Step 2: Create a Function to Get User Input
A text adventure is full of choices. Most of the time, you'll want the user to select from a limited amount of options. Instead of rewriting the code to print the question and answers constantly, you'll want to make a function to do it. Here's how to build an all-purpose, fail-safe function for that purpose.
We'll start out by creating an outline for our function.
def ask(question,answers):
# Print the question.
# Loop through answers and print "number: answer" for each one.
# Ask the user to enter the number of an option.
# Check that the user's response is valid.
# If the answer is valid, return it.
# Otherwise, ask the user again.
Then, we'll fill it in. Here's the completed code.
01 def ask(question,answers):
02 print(question)
03 for i in range(0,len(answers)):
04 print("%s: %s" %(i + 1,answers[i]))
05
06 while True:
07 number = input("Enter an option's number:")
08 try:
09 int(number,10)
10 except:
11 print("Please enter a positive whole number.")
12 continue
13
14 option = int(number,10)
15 if option < 1 or len(answers) < option: # -------------------------- Group 3
16 print("Please enter a number between 1 and %s." %(len(answers))) # Group 3
17 continue # ------------------------------------------------------- Group 3
18 else: # ------------------------------------------------------------ Group 3
19 return option # -------------------------------------------------- Group 3
That's a lot of code! Here's the explanation of each step:
Line 1 defines the ask function.
Line 2 prints the question.
Line 3 begins a for loop:
Line 6 defines a while loop that runs forever (or until a break command is placed):
Line 7 asks the user to enter an option's number.
Line 8 begins a try ... except block.
Line 9 attempts to turn the user's input into an integer.
If it produces an error, the except block (lines 10 - 12) is executed:
If it doesn't produces an error, the code on lines 14 - 19 is run:
Next, let's learn how to create the rest of our text adventure.