Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

Click here to view code image


# script0701.py - The Secret Word Validation.
# Written by <your name here>
# Date: <today's date>
#
############ Define Variables ###########
#
max_attempts = 3 #Number of allowed input attempts.
the_word = 'secret' #The secret word.
#
############# Get Secret Word ################
#
for attempt_number in range (1, max_attempts + 1):
secret_word = input("What is the secret word?")
if secret_word == the_word:
print ()
print ("Congratulations! You know the secret word!")
print ()
break # Stops the scripts execution.
else:
print ()
print ("That is not the secret word.")
print ("You have", max_attempts - attempt_number, "attempts left.")
print ()

Watch Out!: Proper Indentation
Remember that when you use a text editor, you need to make sure you do the
indentation properly. If you do not indent the for and the if code blocks
properly, Python will give you an error message. Look back to the section
“Watching for a Few ‘Gotchas,’” earlier this hour, for help on this, if needed.


  1. Write out the modified script you just typed in the text editor by pressing Ctrl+O.
    Press Enter to write out the contents to the script0701.py script.

  2. Exit the nano text editor by pressing Ctrl+X.

  3. Type python3 py3prog/script0701.py and press Enter to run the script.
    The first time you run the script, answer the question correctly by entering secret.
    You should see output similar to that shown in Figure 7.2.


FIGURE 7.2 The script0701.py output with the correct answer.
The script stops after you enter the correct answer because of the break statement.
The break statement causes the loop to terminate. In other words, it lets you “break
out” of the loop.
Free download pdf