design, write and debug programs that accomplish specific goals, including controlling or simulating physical systems; solve problems by decomposing them into smaller parts.
use logical reasoning to explain how some simple algorithms work and to detect and correct errors in algorithms and programs
5.1b
LO: To use conditional statements with user input.
We're going to return to responding to user input, as we started in year 4, but this time reacting to this input using conditional statements. Let's just refresh our memories on our little rules for writing programs:
Introduce the program - tell the user what the program does.
Explain how to use the program - what inputs the program will accept.
Hide the algorithim from the user - the user does not need to know how the program is working, they do not need to see anything apart from the output (the answer they want).
Present the answer in a readable way - if the user is expecting the answer in cm then they should recieve the answer in cm.
We are going to look at using the conditional statement while as a game loop - as long as the game/problem is going on/being solved then the instructions will be carried out. The simple loop will look the same as what we have been using in Reeborg, only this time we will be writing it in IDLE.
while True: #do what you need to do to complete the game/problem else: done()
Let's think of a silly, but simple, game we could play - a program that asks a user their name and then prints out a silly sentence about them everytime if they press a key and then will end if they press another key.
Think about how you would would write this program...
The program must print out an introduction to explain what it does.
The program must ask the user their name.
The program must then start a loop where it checks what key the user presses - one key will print out the silly sentence, the other will end the game.
If the game is ended then the loop must stop.
It can be helpful to write out these requirements for the program and even put them in a rough flow chart so that you can get an overall look of what the program has to do. It may help you spot things you already know how to do...
#What we already know how to do #introduction/explanation print("introduction and explanation...") #get user's name name = input("What is your name? :") #start a game loop while True: #do what you need to do to complete the game/problem else: done() #check what key is pressed if ???: print("silly sentence") if ???: #end the game?
As you can see there is a lot we already know, or have an idea how we might go about it, but there are somethings we still need to learn - let's start with starting and stopping the game loop.
We know that a while loop will check if some condition is True or False - it will loop through it's instructions if it is True or just run some instructions once if it is False (through the else statement). We can use a variable (sometimes known as a flag variable) to be our on and off switch:
play = False***** while play: print("silly sentence") else: print("Game Over!") print("Thanks for playing.")
If the variable play is False then the while loop will not run and the instructions in the else statement will run insead - try typing this out in the IDLE shell (we don't want to try typing this out if play is True because it would loop over and over again with no way to stop it). Let's deal with this problem of looping over and over again - remember that the while loop will run if the variable play is True, we can stop the loop by changing the variable play to False after the loop has printed out the silly sentence:
play = True while play: print("silly sentence") play = False else: print("Game Over!") print("Thanks for playing.")
Try this out in IDLE and you will see that it will only print out the silly sentence once before printing out the else instructions (because play is now False). There is another way of ending the game loop but we'll get to that later.
Let's put together what we know so far:
#declare a flag variable play = True #we say it is True because we want the game to start #introduce print("This game will ask you your name and then print out a silly sentence.") print("") #this is just a blank line to make it look clearer #get name name = input("What is your name? :") #start the game loop while play: print("Press y to print out the sentence.") print("Press n to quit.") key_press = input(": ") #we have to know what keys the user is pressing? else: print("Game Over!") print("Thanks for playing.")
So far this looks like the programs we wrote to solve mathematical problems. A few notes:
The introduction is outside of the game loop - we don't need all the instructions every time.
An empty print() statement is used to give a space between the instructions and getting user input.
In the while loop the instructions are written on seperate lines just for clarity.
The prompt in the input() function consists of just a colon : as the instructions above explain what the user has to do.
Now think how you would write code to check if the variable key_press is 'y' or elif the variable key_press is 'n'. We have used elif (else if) because we are making a choice between "y" and "n", we don't need to check if both are true Here we can use the '==' operator to check for equality*:
if key_press == "y": print("silly sentence") elif key_press == "n": play = False else: print("You need to type in either y or n.")
The if statement will check if the string referenced by the key_press variable is equal to the string "y", if it is then it will print out the silly sentence. If the key_press variable is equal to the string "n" (but not "y" as well - elif) then the play variable is assigned the value False - meaning that the loop will no longer run, ending the game. The else statement is included to catch any errors (pressing the wrong number). Putting this all together we get:
Let's put together what we know so far:
#declare a flag variable play = True #we say it is True because we want the game to start #introduce print("This game will ask you your name and then print out a silly sentence.") print("") #this is just a blank line to make it look clearer #get name name = input("What is your name? :") #start the game loop while play: print("Press y to print out the sentence.") print("Press n to quit.") key_press = input(": ") if key_press == "y": print(name, "is scared of fish!") elif key_press == "n": play = False else: print("You need to type in either y or n.") else: print("Game Over!") print("Thanks for playing.")
* Remember that '=' is used to assign a value as in:
number = 42
'==' is used for equality, what we would use = for in maths.
4 == 4 True
***** As a little extra we could now talk about scope...
Scope can be thought of as 'who can see who' (we are talking about variables).
The variable play is defined and given a value at the 'root' level of the program (it is not inside any functions): this means that it is a global variable - it can be 'seen' from inside other functions in the program.
A variable defined inside a function is called a local variable - it can only be 'seen' inside the function. An example will make this clearer:
#declare an integer variable (a global variable) number1 = 20 #reference the global variable in a function def add_ten(): answer = (number1 + 10) #the global variable can be seen print(answer) return answer #declare a local variable def add_number(): number2 = 42 #define local variable answer = (number1 + number2) #the global variable can be seen print(answer) return answer
- In the function add_ten the variable number1 can be evaluated or 'seen' because it is a global variable - it was declared at the root level of the program (outside any functions)
- In the function add_number the variable number2 can be evaluated or 'seen' because it is a local variable - it was declared inside the current function. The variable number1 can be evaluated or 'seen' because it is a global variable - it was declared at the root level of the program (outside any functions)
Global variable can be 'seen' from inside of functions, local variables can only be seen inside the function that they are declared in:
#declare local variables def add_number(user_input): number = 42 #define local variable answer = (number + user_input) print(answer) return answer #declare local variables def sub_number(user_input): number = 78 #define local variable answer = (user_input - number) print(answer) return answer
- In the function add_number the variables number and answer can only be evaluated or 'seen' inside the function (therefore they can have the same names)
- In the function sub_number the variables number and answer share the same names as those in the function add_number. Because they are local variables they can only be evaluated or 'seen' inside the function (therefore they can have the same names)
Finally, we now know that we can evaluate/'see' global variables from inside functions, but what if we need to change their values - like the variable play from our programme? If we write the name of the global variable inside a function won't Python just think we are declaring a new local variable? - yes:
#declare global variable play = True #define local variable #change global variables def sub_number(user_input): if user_input == 'n': global play #use the 'global' keyword to target the global variable play = False #now you can change it
The global keyword will tell Python that you ar targetting the global variable (not making a new local one).