If you run the code below you should see a program that reacts and responds to user input:
Ctrl + Enter to run the code.
This code will ask your name. It uses selection to say
Snap! if you type in “
chatty” which it thinks is its name too.
The code them asks how old you are. It uses selection again to react to your age.
Start by running the code and testing it with a variety of different answers to the questions.
- Change it so that if the user leaves their name blank the program will say “
Don't be shy“
You’ll need another if statement to check if name is equal to an empty string (
Be careful with indentation: your if statement should be all the way to the left but the line underneath should be indented to the right
- Extend it so that if the user says they’re over
100years old, the program says “
I don't believe you“
Find the code that says
if age < 5:and the two
Under these lines but above the line that says
else:add a line that says
elif age > 100:
elifmeans “Else, if”. You can use it under any
ifstatement as long as it’s perfectly lined up (in terms of indentation from the left of the screen)
- Adapt the code so that even if the user says their name is
Chattyit still says “
You can convert strings to lowercase letters by putting
.lower()after the name of the variable that stores a string. You can also use
.upper()to convert to uppercase letters.
Find the line that checks if the variable called
namestores a string that is equal to “
chatty” and change
On the next page you’ll get some code with some common errors that you can use to practise debugging.