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:


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...

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:

Now think how you would write code to check if the variable key_press is 'y' or if the variable key_press is 'n'. Here we can use the '==' operator to check for equality*:


if key_press == "y":
    print("silly sentence")
if 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" 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!")
    if 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

			

Code Examples

Resources