mrm
mrm

Reputation: 69

How do I structure a while-loop to not include an empty-string or quit entry in a print statement?

In my program, the user is supposed to enter a pizza-topping, then press 'enter', at which time a message is printed that says 'We'll add (topping) to your pizza.'

In the case of the user entering an empty string, I want to print the message "Please enter a topping.".

In the case of the user entering 'quit' I want to exit the while-loop.

Currently, if the user enters an empty-string, or 'quit' the program prints the message 'We'll add to your pizza.' Or, We'll add quit to your pizza.', respectively.

prompt = "\nPlease enter the topping you want and press 'enter'"
prompt += "\nType 'quit', then press 'enter' when you're finished:"
active = True
while active:

    topping = raw_input(prompt)
    if topping == '':
        print("Please enter a topping.")

    elif topping == 'quit':
        print("\nThank you.")
        active = False

    else:
        print("\n We'll add {} to your pizza.".format(topping))

I'm sure there is a simple problem with my structure, I just can't seem to find it. Any help is appreciated!

Upvotes: 0

Views: 246

Answers (1)

Shanard
Shanard

Reputation: 131

Your code works fine, and you're likely running into an issue with trailing characters like @Blupper mentioned. If you wanted to implement a simple way of sanitizing your inputs you could refactor topping as:

topping = raw_input(prompt).strip()

The strip would remove any trailing characters.

Upvotes: 1

Related Questions