[Tutor] Coding for a Secret Message in a Game

Steven D'Aprano steve at pearwood.info
Fri Dec 13 12:00:02 CET 2013


On Thu, Dec 12, 2013 at 11:10:31PM -0500, Sky blaze wrote:

> Here's the code I currently have so far:
> print("===INSTRUCTIONS===")
> input(">> ")

Are you using Python 3? Is so, that's fine, but in Python 2 you should 
use raw_input instead.

> print("When you see a \'>>\', hit Enter to advance the text.")

There's no need for the backslashes to escape the quotes. Python uses 
two different quotes especially so you can put one sort inside the 
other:

"Here you don't need to escape the single quote."
'He turned to me and said, "Is that a fact?"'


> start = False #This is the start screen check
> print("Type \"start\" to begin.") #Command message to start the game
> start_prompt = input("> ") #Command prompt to start the game
> while start != True: #Infinite loop that doesn't end until "start" is typed
>     if start_prompt == "start":
>         start = True #Continues from the title screen

First off, let me show you how I would do this command prompt without 
changing the message.

answer = ""
while answer != 'start':
    print("Type 'START' to begin.")
    # Ignore leading and trailing spaces, and UPPER/lower case.
    answer = input("> ").strip().lower()


That will loop forever, or until the user types "start", regardless of 
case. "StArT" or any other combination will be accepted, as will spaces 
at the start or end of the word.

How do we add a changing prompt? We need to know when to change the 
prompt, and to do that, we need to count how many times we've been 
around the loop. Here's my first version, which changes the prompt only 
once:

answer = ""
prompt = "Type 'START' to begin."
count = 0
while answer != 'start':
    count += 1
    if count == 10:
        prompt = "Y U NO TYPE 'START'???"
    print(prompt)
    # Ignore leading and trailing spaces, and UPPER/lower case.
    answer = input("> ").strip().lower()


That's okay for what it is, but what if you wanted more than two 
different prompts? Here's a third version which uses a function that 
returns the required prompt.


def get_prompt(loop_number):
    if loop_number == 1:
        return "Enter 'START' to begin the game."
    if 2 <= loop_number < 5:
        return ("I'm sorry, I don't know that response."
                " Enter 'START' to begin the game.")
    if 5 <= loop_number < 10:
        return "Type the word 'START' then press the Enter key."
    return "Y U NO TYPE 'START'???"


answer = ""
count = 0
while answer != 'start':
    count += 1
    print(get_prompt(count))
    # Ignore leading and trailing spaces, and UPPER/lower case.
    answer = input("> ").strip().lower()



-- 
Steven


More information about the Tutor mailing list