Coding Curriculum - Python

Worksheet 3

In this worksheet, we will try to achieve the following:

  1. Ask what subject to study
  2. List the subjects available
  3. Get an input
  4. Decide if answer is valid
  5. If answer is not valid, print an error message
  6. Get an input again

Step 1. Print the Menu

It's always nice to display a welcome message to anyone who use your programme.

def yourFunction():
print "Your friendly welcome message"
print "Your question"
print "Option 1"
print "Option 2"
print "Option 3"

Step 2. Get an Answer

To keep it simple, we will ask for a number answer.

yourVariable = int(raw_input())

Step 3. Decide if an answer is valid

Use conditional statement like if and else to decide if the answer is valid.

if yourVarible == 1:
anotherVariable = True
elif yourVarible == 2:
anotherVariable = True
elif yourVarible == 3:
anotherVariable = True
else:
print "An error message for invalid answer"

Step 4. Get another Answer for Invalid Answer (Loop)

What if you enter an invalid answer? You don't want the program to end, you want it to give you a chance to enter another answer.

To achieve this, we can use a while loop. This loop use a variable validAnswer to determine if the program should request for another input. The variable is set as False. It will be change to True if a valid answer is enter and the loop will end.

anotherVariable = False
while not anotherVariable:
yourVariable = int(raw_input())
if yourVariable == 1:
anotherVariable = True
elif yourVariable == 2:
anotherVariable = True
elif yourVariable == 3:
anotherVariable = True
else:
print "An error message for invalid answer"

The Complete Code

def decideTopic():
print "Welcome to the Word Search Quiz"
print "What do you want to study?"
print "1. Math"
print "2. Chemistry"
print "3. Physics"
validAnswer = False
while not validAnswer:
answer = int(raw_input())
if answer == 1:
entries = mathEntries
validAnswer = True
elif answer == 2:
entries = chemistryEntries
validAnswer = True
elif answer == 3:
entries = physicsEntries
validAnswer = True
else:
print "I am sorry but that was not a valid answer, try again"
return entries

Well, this is the end of this worksheet. Congratulations!