Python Touch is designed for students to write python code on a tablet computer
Features:
# use print to display messages print("Hello world")
# import turtle drawing module import turtle print "Click on Drawing Canvas to see turtle graphics" draw = turtle.Turtle() draw.penup() # draw text draw.color("#3978AE") draw.goto(0,20) draw.write("Python") draw.color("#FFD344") draw.goto(0,0) draw.write("Touch") # draw shape draw.goto(-30, -20) draw.pendown() draw.color("black") for i in range(2): draw.forward(100) draw.left(90) draw.forward(70) draw.left(90)
# Template for a chatbot - a simple program that asks you questions and responds print("Hello! My name is chatbot") name = input("What's your name?") print("Hi " + name) age = int(input("How old are you?")) if age > 100: print("Really? That's pretty old!") else: difference = 100 - age print("You'll be 100 in " + str(difference) + " years") # add your own questions here
These samples are designed to cover the AQA GCSE Computer Science (from 2016)
These resources are not affiliated to or endorsed by AQA in any way.
print """ integers are whole numbers (not fractions or decimals) """ print("These are integers (whole numbers)") print(1) print(10) print(33)
print """ Real numbers can contain decimal places (e.g. 3.141) Python calls reals floats or floating point numbers """ print("These are reals (floating point or decimal numbers)") print(1.45) print(3.1412) print(1.0)
print """ Boolean means either True or False - nothing else. """ print("These are booleans") print(True) print(False)
print """ A character is one letter or symbol In python there's no difference between the data type that stores one character or lots of characters: they're both stored in strings. """ print("These are characters (single letters or digits)") # Note that you can use either single quotes ' or double quotes " as long as you use the same one either side of the character. print("A") print("1") print("*") print('"')
print """ A string is one or more letter or symbol In python there's no difference between the data type that stores one character or lots of characters: they're both stored in strings. """ print("These are strings (one or more characters)") print("Hello") print("Howdi") # notice that this next one is still a string even though it looks like a number. It's a string because it's surrounded by quotation marks. print("12345")
print """ Variables store data that might change while the program runs. Variables in python should be given a suitable name that describes the data stored inside. Choosing variable names carefully (rather than variable1 or thingy) makes your code easier to understand. You should follow the PEP8 convention for choosing variable names: lowercase_words_separated_by_underscores """ # integer variable age = 8 # real variable top_speed = 4.32 # boolean variable hungry = True # character variable key_to_quit = "Q" # string variable user_name = "Bob" # display the variables print "Integer variable:", age print "Real variable:", top_speed print "Boolean variable:", hungry print "Character variable:", key_to_quit print "String variable:", user_name
print """ Constants store data that you set in your code and never change while the program runs. Constants in python should be given a suitable name that describes the data stored inside. Choosing constant names carefully (rather than variable1 or thingy) makes your code easier to understand. You should follow the PEP8 convention for choosing constant names: UPPERCASE_SEPARATED_BY_UNDERSCORES """ # integer constant AGE = 8 # real constant TOP_SPEED = 4.32 # boolean constant HUNGRY = True # character constant KEY_TO_QUIT = "Q" # string constant USER_NAME = "Bob" # display the constants print "Integer constant:", AGE print "Real constant:", TOP_SPEED print "Boolean constant:", HUNGRY print "Character constant:", KEY_TO_QUIT print "String constant:", USER_NAME
print """ Assignment means setting the value of a variable. This means that the variable stores that value so it can be used or changed later. """ # Assign (store) the real number 3.141 into a constant called PI PI = 3.141 # assign the integer number 10 to a variable called radius radius = 10 # calculate the area (pi times radius squared) and assign it to a variable called area area = PI * radius * radius print area
print """ Iteration means looping through each of multiple values Definite iteration means you know in advance exactly how many times the loop will repeat. """ # Display each letter of the alphabet for letter in "abcdefghijklmnopqrstuvwxyz": print letter # Display each number between 1 and 10 for i in [1,2,3,4,5,6,7,8,9,10]: print i # Display each number between 1 and 100 for i in range(100): print i
print """ Iteration means looping (repeating) multiple times Indefinite iteration means you don't know in advance exactly how many times the loop will repeat """ # keep looping until the user types "exit" while raw_input("Type exit to quit") != "exit": print("OK, I'll keep looping")
# iteration means repeating some code multiple times. # Nested iteration means having a loop within a loop # make a list containing each day of the week days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] # outer loop: iterate through days of the week for day in days: # inner loop: iterate through each of the hours in a day for hour in range(24): print day, hour, ": 00"
print """ Selection happens when your program makes a choice between doing one thing or another. In python, "if" lets you run code based on the answer to a question / condition. """ # choose a random number import random random_number = str(random.randint(1,10)) # let the user guess guess = raw_input("I've chosen a random number between 1 and 10. Guess what it is") # does the user's guess match the random number? if random_number == guess: print "Correct!" else: print "Wrong: I guessed " + random_number
print """ Selection means making your code only run if a condition is met. Nested selection means an if statement inside an if statement - checking to see if two conditions are met. """ str_number = raw_input("Please enter a number over 100") if str_number.isdigit(): int_number = int(str_number) # nested selection: "if" inside an "if" if int_number > 100: print "Thank you" else: print "The number must be over 100" else: print "You must type in a number"
print """ A subroutine is a section of code that you can re-use more than once. This makes your code more efficient as you end up writing less code. You have to give each subroutine a name. This can help your code be more readable. """ # import the turtle module to draw shapes import turtle t = turtle.Turtle() # define a procedure (subroutine) called draw_square def draw_square(x, y, size): # move to x, y t.penup() t.goto(x,y) t.pendown() # draw the square for i in range(4): t.forward(size) t.right(90) # call the subroutine to draw a square at (0,0) draw_square(0, 0, 10) # call the subroute again, drawing a square at (100,100) draw_square(100,100, 30)
print """ An identifier name is the name of a variable, constant, function or procedure. In order to make your code consistent and easy to understand / maintain, you should name your variables / constants in a way that describes the data that they store Similarly, you should name procedures or functions in a way that describes what those subroutines do. For further info, read the Python Style Guide (PEP8): https://www.python.org/dev/peps/pep-0008/ """ # bad examples: variable1 = "Hello" n = "Bob" number = 27 # better examples, but not in line with PEP8 EnglishGreeting = "Hello" Name = "Bob" ageOfPerson = 27 # advised way of doing things according to PEP8 english_greeting = "Hello" name = "Bob" age_of_person = 27
print """ An operator lets perform an action (or operation) on some data An arithmetic operator means performing an addition / subtraction / multiplication or division on some numbers """ # addition print "+ is the addition operator" answer = 10 + 100 print "10 plus 100 = ", answer # subtraction print "- is the subtraction operator" answer = 100 - 10 print "100 minus 10 = ", answer # multiplication print "* is the multiplication operator" answer = 10 * 10 print "10 times 10 = ", answer # real division print "/ is the division operator" answer = 50.0 / 7.0 print "50 divided by 7 = ", answer # integer division print "% is the modulo operator (used to find the remainder after an integer division)" answer = 50 / 7 remainder = 50 % 7 print "50 divided by 7 is", answer, "with a remainder of", remainder
print """ An operator lets perform an action (or operation) on some data A relational operator means comparing two pieces of data This sample asks the user to type in a number and then compares that number to the number 10 """ # ask the user to type in a number user_number = int(raw_input("Please enter a number")) # equal to if user_number == 10: print "Your number is equal to 10" # not equal to if user_number != 10: print "Your number is not equal to 10" # less than if user_number < 10: print "Your number is less than 10" # greater than if user_number > 10: print "Your number is greater than 10" # less than or equal to if user_number <= 10: print "Your number is less than or equal to 10" # greater than or equal to if user_number >= 10: print "Your number is greater than or equal to 10"
print """ An operator lets perform an action (or operation) on some data Boolean data is either something that is True or False. A boolean operator can combine or change boolean data (and / or / not) This sample asks the user if they are hungry and/or thirsty then analyses the answers """ # ask the user if they're hungry hungry = raw_input("Please type yes if you're hungry") # check if they type in "yes" bool_hungry = hungry == "yes" # Check if the user is thirsty bool_thirsty = raw_input("Please type yes if you're thirsty") == "yes" # show results print "Hungry:", bool_hungry print "Thirsty", bool_thirsty # NOT print "NOT hungry:", not bool_hungry print "NOT thirsty:" , not bool_thirsty # AND print "Hungry AND thirsty:", bool_hungry and bool_thirsty # OR print "Hungry OR thirsty:", bool_hungry or bool_thirsty
print """ A list in python is an array: it can stores more than one pieces of data in order. A one dimensional array is a single list. A two dimensional array is a list of different lists """ # list of animals animals = ["dog", "cat", "donkey", "chicken"] # loop through each item in list for animal in animals: print "Old McDonald had a farm, E-i-e-i-oh" print "And on that farm he had a", animal, "e-i-e-i-oh" # You can think of strings as an array of characters. # e.g. "dog" is pretty much the same as ["d", "o", "g"] print "The first letter of the first animal is:", animals[0][0] print "The first letter of the last animal is", animals[-1][0] print "The 2nd letter of the 3rd animal is", animals[1][2]
print """ A dictionary in python is a record: it can structure data in a way so that linked data is stored together A dictionary works with pairs of keys and values: you look up a key to find a value. This works the same way as an old fashioned paper dictionary: you look up a word (key) to find its meaning (value) """ # create a dictionary for each animal dog = {"name": "dog", "noise": "woof"} cat = {"name": "cat", "noise": "miaow"} donkey = {"name": "donkey", "noise": "eee-or"} chicken = {"name": "chicken", "noise": "cluck"} # list of animals animals = [dog, cat, donkey, chicken] # loop through each dictionary in list for animal in animals: print "Old McDonald had a farm, E-i-e-i-oh" print "And on that farm he had a", animal["name"], "e-i-e-i-oh" print "With a", animal["noise"], animal["noise"], "here and a", animal["noise"], animal["noise"], "there" print "Here a", animal["noise"], "there a", animal["noise"], "everywhere a", animal["noise"], animal["noise"] print "Old McDonald had a farm, E-i-e-i-oh" print
print """ Most programs need to ask the user questions and let them type in their answers. This sample asks the user what their name is and responds by saying hello """ # ask question and save answer into variable called name name = raw_input("What is your name?") # display greeting print "Hello", name
print """ Most programs need to display text or data to the screen. This sample shows how to display text and the contents of a variable """ # create a variable called hello and save the string "Bonjour" to it hello = "Bonjour" # display the string "hello" print "hello" # display the contents of the variable called hello print hello
print """ The data stored in variables is lost when a program stops running. Saving data to a file allows your program to store is so that it can read next time it runs. This sample asks the user a question and shows what they typed in last time they ran the program """ try: # open data.txt in read mode input_file = open("data.txt", "r") previous_answer = input_file.read() input_file.close() except: previous_answer = "Could not open data.txt. Perhaps this is the first time you've run this program?" # ask for highligh of the day this_answer = raw_input("What's been the highlight of your day today?") # save answer output_file = open("data.txt", "w") output_file.write(this_answer) output_file.close() print "Thank you. Your answer has been saved. Last time you ran the program you said the highlight of your day was:" print previous_answer
print """ Python can write data to CSV files which can be easily imported into a spreadsheet (e.g. Excel) This sample exports a file called fruit.csv with the colours of different fruit. """ # Store data in a 2D list (a list of lists) data = [["Fruit", "Colour"], ["Tomato", "Red"], ["Lemon", "Yellow"]] # import comma separated values module import csv # open file in binary write mode file_object = open("fruit.csv", "wb") # create csv writer object writer = csv.writer(file_object) # write data to file writer.writerows(data) # close file file_object.close()
print """ Python can read data from CSV files which can be easily exported from a spreadsheet (e.g. Excel) This sample loads data from a file called fruits.csv (Check samples to create a sample of this file). """ # import comma separated values module import csv # open file in binary read mode file_object = open("fruit.csv", "rb") # create csv reader object reader = csv.reader(file_object) # loop through each line in the file for row in reader: print row # close file file_object.close()
print """ A string is one or more characters (letters or symbols) in order, usually in a way that spells out a word or sentence, but it can store any text. The length of a string is the number of characters. E.g. the length of "hello" is 5 because there are 5 characters This sample asks the user to type in a string. It then counts how many characters are in that string. """ # ask user to type in a string user_string = raw_input("Type in anything here:") # calculate the length length = len(user_string) # display the result print "The length of the string you typed in is:", length
print """ A string is one or more characters (letters or symbols) in order, usually in a way that spells out a word or sentence, but it can store any text. This sample asks the user to type in a string containing the letter "a". It then displays where the letter "a" is first found in the string that the user entered. """ # ask user to type in a string user_string = raw_input("Type in anything here that contains the letter 'a':") # calculate the first position of 'a' position = user_string.index('a') # display the result print "The letter a first appears as character in position", position
print """ A string is one or more characters (letters or symbols) in order, usually in a way that spells out a word or sentence, but it can store any text. A substring is some of the characters that makes up part of a string. E.g. "hell" is a substring of "hello" This sample asks the user to choose the first and last characters of a nursery rhyme. It then displays the substring between the first and last characters that they choose """ rhyme = """Jack and Jill went up the hill To fetch a pail of water. Jack fell down and broke his crown, And Jill came tumbling after""" length = len(rhyme) print "Here's a nursery rhyme that is", length, "characters long:" print rhyme start = int(raw_input("Choose substring start number:")) end = int(raw_input("Choose substring end number:")) print "Here's your substring:", rhyme[start:end]
print """ A string is one or more characters (letters or symbols) in order, usually in a way that spells out a word or sentence, but it can store any text. Concatenation means joining together. E.g. concatenating the strings "im" and "possible" makes the string "impossible" This sample chooses 10 random letters and joins them together to make a secure password """ # make a string with all the possible characters in characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXVZ1234567890!$%^&*()" # import the random module import random # start with an empty password password = "" # loop 10 times, using the variable i to count from 0 to 9 for i in range(10): # concatenate (add on) a random character on to the end of the password password = password + random.choice(characters) print "A random 10 digit password for you to us is:", password
print """ Characters are single letters, digits or symbols. Each character in the US alphabet is stored as an ASCII number. E.g. The character "A" is the decimal ASCII number 65 and "a" is the decimal ASCII number 97 You can use ord() and chr() to convert between characters and ASCII numbers This sample lets the user convert to and from characters / ascii numbers """ number = int(raw_input("Please enter a number between 0 and 127 to convert to a character:")) character = chr(number) print "The ASCII number", number, "represents the character", character character = raw_input("Please enter a single character:") number = ord(character) print "This character", character, "is represented by the ASCII number", number
print """ A string is data made up of one or more characters e.g. "hello" This sample converts strings to integers / real (float) data types and vice versa. """ string_number = "100" print "When you multiply the string '100' by two you get", string_number * 2 # convert from string to int int_number = int(string_number) print "When you multiply the integer 100 by two you get", int_number * 2 # convert from string to real float_number = float(string_number) print "When you multiply the float / real number 100.00 by 2.00 you get", float_number * 2.0 print "You can convert any data type to a string using the str() function" # convert to string print "Here are some examples: ", str(2.0), str(1), str(True)
print """ Getting a completely logical machine such as a computer to choose a random number is a surprisingly complex task. Thankfully, Python has a random module that makes it really easy. This sample shows how to choose a random number between a minimum and maximum value """ # load random module import random print "Random number between 1 and 10:" print random.randint(1,10) print "Random number between 0.5 and 0.75:" print random.uniform(0.5, 0.75)
print """ A procedure is a section of code that has been given a name that you can re-use. They can make your code easier to read (because you give sections of code a descriptive name) They can make your code more efficient (because you can re-use sections of code) This sample uses a procedure that displays a random insult to the user. """ # load random module import random # define the insult procedure def show_insult(): # make lists used to generate random insult adjectives = ['fat', 'funny', 'silly', 'wobbly', 'smelly', 'stinky', 'big', 'small'] nouns = ['face', 'nose', 'ears', 'arms', 'belly', 'toes', 'hair', 'breath'] # display insult print random.choice(adjectives), random.choice(nouns) # show insult print "Here's a random insult:" show_insult() print "Here's another" show_insult() # show 10 more print "Here's 10 more:" for i in range(10): show_insult()
print """ A procedure is a section of code that has been given a name that you can re-use. A parameter is a variable that you give to the procedure that determines what it does or how it works. Parameters let you customise procedures so that they can be used for more than one purpose. This sample uses a procedure that displays a set number of random insults to the user. """ # load random module import random # define the insult procedure def show_insult(how_many_times): # make lists used to generate random insult adjectives = ['fat', 'funny', 'silly', 'wobbly', 'smelly', 'stinky', 'big', 'small'] nouns = ['face', 'nose', 'ears', 'arms', 'belly', 'toes', 'hair', 'breath'] # display insult print "Here are your", how_many_times, "insults:" for i in range(how_many_times): print random.choice(adjectives), random.choice(nouns) # show 3 insults show_insult(3) # show 10 insults show_insult(10)
print """ A procedure is a section of code that has been given a name that you can re-use. A function is like a procedure but it returns a value that you can then use later in your program. Functions can take parameters just like procedures This sample uses a function to let the user choose one of a set number of options """ # define a function that lets the user choose from a list of options def choose_from(prompt, options): # keep looping until the user chooses a valid option while True: # use a dictionary to keep track of which number each of the options are number_options = {} # display the prompt message print prompt # loop through and display each option with its own number count = 1 for option in options: print count, ":", option # add to dictionary: pair up the number with the option number_options[str(count)] = option # increase count by one count += 1 # ask user to choose an option user_choice = raw_input("Which option?") # check if they typed in an option longhand if user_choice in options: # return what the user return user_choice # check if they typed in a number if user_choice in number_options: # return the option the user chose with their number return number_options[user_choice] # ask the user to choose between potatoes and carrots. Save the return value into veg veg = choose_from("What's your favourite vegetable?", ("Potatoes", "Carrots")) # ask the user to choose between oranges, apples and pineapples. Save the return value into fruit fruit = choose_from("What's your favourite fruit?", ("Orange", "Apple", "Pineapple")) # display their choices print "You chose", fruit, "and", veg
Python touch is created by P. Dring primarily for use by students at Manor CE Academy in York
Python touch uses Skulpt which is released under the MIT License
The text editor uses Ace which is released under the BSD license
Python touch also uses jQuery Mobile which is released under the MIT License
The ability to load / save code hidden in an image uses the steganography library by Peter Eigenschink which is released under the MIT and Beerware licence.
# import turtle drawing module import turtle print "Click on Drawing Canvas to see turtle graphics" draw = turtle.Turtle() draw.penup() # draw text draw.color("#3978AE") draw.goto(0,20) draw.write("Python") draw.color("#FFD344") draw.goto(0,0) draw.write("Touch") # draw shape draw.goto(-30, -20) draw.pendown() draw.color("black") for i in range(2): draw.forward(100) draw.left(90) draw.forward(70) draw.left(90)