An Introduction to Python for KS4 Python is a modern, typed language - quick to create programs and easily scalable from small, simple programs to those as complex as GoogleApps. IDLE is the editor that comes free with Python. There are other text editors that will work, including Textastic for the ipad. When you start Python on the Mac you get the following window: Notice the warning about TkInter. The above installation had the latest 8.6.1 version of tcltk running. This can occur on some installs on Macs and can have issues with some graphical applications but, for applications up to GCSE level, it is not an issue. The next step to writing your python code is to launch the editor window. Click File>New File and a blank window will open. Print() and Input() Commands Type the following, using the print() command: print ( Hello Cornwall ) Now File>Save and call it Hello.py, saving to desktop. Next, click Run>Run Module and the following should happen. Note that the program runs in the shell window.
Now. Looking at the code we typed: print ( Hello Cornwall ) print Hello Cornwall In Python 2, this would have been written as: In both, you can see that outputted text must be enclosed within quotes. Note that smart quotes fail and so copying and pasting code from a word processor can cause errors. This is really common with students so one to watch out for. Taking the code to the next step, we want to ask the user for their name and then print out a welcome. Edit the code in the editor window to read: name = null name = input ( What is your name? ) print ( Hello,name,. Welcome to Cornwall ) Save the code as HelloName.py and run. You should see the following: Here we have introduced a text variable, name to store the input. Although it is not strictly necessary to declare it at the start, it is a good habit for the students to get into. \n - introduce a line break \t - insert a tab \\ - insert a backslash \ - insert a speech mark There are special characters that we can enter into text to improve flow and presentation.
It is possible to use single speech marks, and so avoid having to \ speech marks. This can be confusing for students, so I wouldn t recommend its introduction early on. print( Hello, he said. ) could be used to replace print( \ Hello\, he said. )
Maths Functions Python can be used like a calculator. This is a good opportunity to introduce integer and floating point variables at the same time. * Multiply If we add an extra line at the start of the program, we can also add more functions, such as trigonometry. import math This brings in a new module. Modules are extra Python commands that can be added and a lot are installed along with the standard Python files. Some useful ones are: math.e Inserts e These extra functions are extremely useful in the GCSE Controlled Assessments. Variables + Add % Modulus - Subtract ** Raise to the power / Divide // Divide (Integer Part) math.sin() Sine of an angle math.floor() Integer part of a decimal math.cos() Cosine of an angle math.sqrt() Square Root math.tan() Tangent of an angle math.pi Inserts Pi To use these functions, we need to be able to define variables. name = null Text String correct = set([ y, yes ]) Sets score = 1 Integer correct = ( y, yes ) Tuple (read-only list) g = 9.81441 Floating Point letters = [ a, b, c ] List Sets, Tuples and Lists have an Index, starting with 0, that can refer to elements in the values. For example: mylist = [ a, b, c ] print (mylist[1]) would print out b, as this is at the second position with index value of 1. A dice randomiser could be of the form: import random throws = ( 1, 2, 3, 4, 5, 6 ) choice = random.randint(1,6) print(throws[choice])
So a simple program involving other variable types might have a form: x = 0 y = 0 m = 0 c = 0 print( For a linear equation of y=mx+c, please enter m and c ) m = int(input( m: )) c = int(input( c: )) print( Now enter the value of x that you want to process ) x = int(input( x: )) y=(m*x)+c print( Y =,y) Note the introduction of the int() conversion. input() always returns a string. We want an integer here. Students often forget the second closing ) so one to watch out for. Try the above code for yourself. The nice thing is that this introduces variables, input, process and output. Now. The above is a little inefficient. It would be nice to calculate a range of y values for a series of x. We can modify the above code like this: x = 0 y = 0 m = 0 c = 0 print( For a linear equation of y=mx+c ) print( please enter m and c ) m = int(input( m: )) c = int(input( c: )) x = -5 while x < 6: y=(m*x)+c print( X:,x,,Y:,y) x+=1 print( Finished ) I have included the code from IDLE to show the handy way that it uses colour to show correct syntax. Note the tabbing for the while loop. This also introduces a condition x < 6 and a simple incremental addition to a variable x+=1. When we used BASIC, we might have written x=x+1 to add one to a counter. A final variable type is the Dictionary. These are another type of list but, this time, you supply the index value. For example: elements = {1: Hydrogen, 2: Helium, 3: Lithium, 4: Beryllium } The index value is called the Key and the item in quotes is called the Value.
Operators > Greater Than < Less Than >= Greater Than or Equal <= Less Than or Equal = Not Equal == Exactly Equal Note how we use a single equal sign to assign a value but a double equal sign to check equivalence. For example: a=1 b=1 while a == b: print ( Equal )
Comments If we use a # tag at the start of a line, the line is not compiled and so is a comment. We use these to annotate a program #define variables a=1 # Start a Loop while a = 0: print(a)
Modules As said earlier, modules bring extra commands. import math This module gives us extended mathematical functions import random math.sin() Sine of an angle math.floor() Integer part of a decimal math.cos() Cosine of an angle math.sqrt() Square Root math.tan() Tangent of an angle math.pi Inserts Pi math.e This module gives us a range of random items to use in other calculations random.randint(a,b) Inserts e Random integer between a and b random.choice(list) random.randrange(start, stop, step) Random string from a list Random number within a range random.random() Random decimal number between 0.0 and 1.0
Selection When we ask a user for an input, it is often useful to define the action, based on their response. For this we use IF statements in programming. In Python we have IF, ELIF and ELSE. For example answer1 = null answer1 = input ( What is your choice? y/n ) if answer1 == y : print( Yes ) else: print( No ) or goodchoices = set([ y, yes ]) answer1 = input ( What is your choice? y/n ) if answer1 in goodchoices: print( Good Choice ) else: print( Bad Choice ) words = ['cat', 'dog', mouse'] for w in words: print ( Word: w,,length:,len(w)) We can also use lists with another selection tool - FOR. Look at this example: This loop would cycle through the list, printing the length of the words in the list, using the len() command. The result would be: Word: cat, Length: 3 Word: dog, Length: 3 Word: mouse, Length: 5
Functions We can make programs more efficient by collecting parts of a program together and turning it into a function. Lets look at this program again: x = 0 y = 0 m = 0 c = 0 print( For a linear equation of y=mx+c ) print( please enter m and c ) m = int(input( m: )) c = int(input( c: )) x = -5 while x < 6: y=(m*x)+c print( X:,x,,Y:,y) x+=1 print( Finished ) x =0 y = [] m = 0 c = 0 counter = 0 #The Function def linear(m,c): counter = 0 x = -5 while counter < 11: y=(m*x)+c print( X:,x,,Y:,y) x+=1 counter+=1 #End of the function print( For a linear equation of y=mx+c ) print( please enter m and c ) m = int(input( m: )) c = int(input( c: )) linear(m,c) print( Finished ) Lets look at this program again. The def command defines the function here. The function is passed the two values of m and c using the function name - note that you cannot use the name of any built in command as a function name.
Menus A simple menu for a choice could use the techniques that we have seen up until now: level = input( Please enter your choice - a, b or c: ) while level = a and level = b and level = c : level = input( Sorry, your choice must be - a, b or c: ) This gives us some sort of validation checking on a menu option. Next we will see some further code examples, all of which have examples useful for GCSE coursework tasks.
Extra lists - adding and removing list elements mylist = ['Bob','Sue','Rita'] index = 0 myextra = 'Null' size = len(mylist) for index in range(0,size): print (index+1,':',mylist[index]) print ("Add names to the list") print ("Type Stop to stop") while myextra = 'Stop': myextra = input("add a name> ") mylist.append(myextra) mylist.remove('stop') index = 0 print ("Your new list of names is") size = len(mylist) for index in range(0,size): print (index+1,':',mylist[index]) import random Making random names. Useful for game characters. FirstNames = ['Bob','Sue','Rita','Sam','George','Degory','Thomasina'] LastNames = ['Smith','Jones','Roberts','Willa','Curnow','Mitchell'] WholeName = "" rounds = int(input("how many names would you like? ")) while rounds > 0: WholeName = random.choice (FirstNames) + " " + random.choice (LastNames) print (WholeName) rounds -= 1 print ( End") Countdown loop with Play Again choice launchagain = True counter = 10 validchoice = set(['y','y','yes','yes']) while launchagain == True: counter = 10 print ("Countdown>",counter) while counter >1: counter -= 1 print ("Countdown>",counter) print ("Launch") launchchoice = input("would you like to launch another rocket? (y/n)") launchagain = launchchoice in validchoice print ("Thanks for launching rockets. )
Random Captain Generator for Sports This code combines all of the elements that we have seen and is a useful demonstration for GCSE Coursework tasks. It also shows effective use of commenting. # Import any functions we need import random # Initialise our variables # Set the captain player number to 0 captain = 0 # Set the number of players to 0 players = 0 # Set the While loop value to True playagain = True # Define any functions we need # The function is called 'captainizer'. This is fed the number of players (players) when called def captainizer (players): # Create a random integer between 1 and the number of players. captain = random.randint(1,players) # Return the number of the captain using the variable name 'captain' return captain # Print a welcome message to the users print (""" Welcome Which sport would you like? 1 Football 2 Rugby 3 Double's Tennis """) # Begin the body of the programme. The While statement continues until False while playagain: # We are going to give users a choice of sports. This is in case people do not know how many should be on a team # This can be expanded easily with more sports. # Ask the user which sport they would like sportchoice = input ("Choose your sport, 1,2 or 3") # Sport Choice Sections # Check for sport and initialise variable with number of players, call the captainizer function and output the value to the screen # Whilst this code could be simplified, this method makes adding new sports very quick. # Choice 1 if sportchoice == "1": players = 11 captain = captainizer (players) print ("Out of ",players,", your Captain is player number ",captain) #Choice 2 elif sportchoice == "2": players = 15
captain = captainizer (players) print ("Out of ",players,", your Captain is player number ",captain) #Choice 3 elif sportchoice == "3": players = 2 captain = captainizer (players) print ("Out of ",players,", your Captain is player number ",captain) #Trap if no valid choice is made. else: print ("You didn't choose a valid sport") # Output the results to a file try: #Open a file with name "captain.txt" and place in append mode captainfile = open("captain.txt", "a") try: # Text String captainfile.write("your Captain is player number ") # Note that you cannot output numbers without turning them into a text string captainfile.write(str(captain)) #T ext String captainfile.write(" out of ") # Note that you cannot output numbers without turning them into a text string captainfile.write(str(players)) # Text String captainfile.write(" players") # Text String captainfile.write("\n") finally: # Close the file captainfile.close() except IOError: pass # Now we test for whether the user wants another go # Set the while look value to True, just to be sure. playagain = True # Ask the user if they want to play again playagain = input("do you want to choose another captain? (y/n)") # never assume they will do as they are told. Strip out all capitals and allow y and yes to be valid answers to play again playagain = playagain.strip().lower() in ('y','yes') # Now we say goodbye print ("Thank you for playing") quit