mahabub alam
mahabub alam

Reputation: 13

Problem with conditional inside while loop

i'm doing exercise 7-4 from "Python Crash Course", which is about writing a while loop to prompt customers to input pizza toppings until they type "quit". While i'm running the following code it prints once every third time and breaks after typing "quit" twice. Can someone please point out what i'm doing wrong. Thank you.

prompt = "Enter your topping: "

while True: 
  topping = input(prompt)
  if input(prompt) == "quit":
    break
  else:
    print(f"{input(prompt)} is added")

Here is an example of it running:

>>> Enter your topping: pepperoni
>>> Enter your topping: pepperoni
>>> Enter your topping: cheese
cheese is added
>>> Enter your topping: quit
>>> Enter your topping: quit

Upvotes: 1

Views: 179

Answers (2)

Chad Miller
Chad Miller

Reputation: 1475

You're asking for input twice. First time, you store the value in topping, and you never do anything with it again.

Then, you ask for input again, after the "if" in if input(prompt), and then you do something based on what it returns and tests against "quit".

You should be doing something with the topping variable instead of asking again. Since you're learning, I am not going to tell you what to do.


The bigger thing you need to understand is that function calls do something. That topping = input(prompt) is not like a mathematical expression of equality where you can thus substitute input(prompt) for all the places you mean topping. The topping represents some constant value in the form of an object. The prompt() is a set of instructions that the interpreter is going to go do and put the result of those instructions in place in the code. That "=" is not an equality assertion. It's an assignment of one value to a name.

Upvotes: 0

Abhishek Bhagate
Abhishek Bhagate

Reputation: 5766

You probably must be using this - if topping == "quit":

In your code, you are using if input(prompt) == "quit": which is asking for input twice and this is where you are going wrong.

Also, I don't know what you are doing in the last line, but the last line should be something like this - print("topping is added") OR print(topping+"topping is added") if you want to display the topping which user inputted as well.

Once you have taken input using input(prompt), there's no need to call the same expression again and again as it will take input again (which is not what we want). Instead use topping which has already stored the input that user has given.

Hope it clears where you where going wrong.

Upvotes: 3

Related Questions