0

How can I create a while loop that asks a user a fruit and if the fruit is 5 or less characters print i like (the fruit) otherwise print i do not like (the fruit), and when Stop is entered the program stops.

user_input = input("Enter a fruit ")

while user_input != "Stop":
  if user_input == "Stop":
    print("Goodbye")

  elif len(user_input) <= 5: 
    print("I like ", user_input)

  elif len(user_input) > 5: 
    print("I do not like ", user_input) 

This is what I tried but the loop is continuous and does not stop until it times out. How can I easily fix this with the code I have already written?

1
  • You don't give a way for the user to enter another input. Commented Sep 9, 2022 at 14:14

3 Answers 3

2

You never modify input inside the loop.

Either add another input() call at the end of the loop, or use an infinite loop with input() as the first statement in the loop:

# Infinite loop
while True:
    user_input = input("Enter a fruit (or Stop to end): ")

    if user_input == "Stop":
        print("Goodbye")
        # Break out of the loop
        break

    elif len(user_input) <= 5: 
        print("I like ", user_input)

    elif len(user_input) > 5: 
        print("I do not like ", user_input) 
Sign up to request clarification or add additional context in comments.

Comments

0

You need ask the user again at the end of the while loop to update the user_input variable, otherwise it will not be updated

user_input = input("Enter a fruit ")

while user_input != "Stop":

if user_input == "Stop": print("Goodbye")

elif len(user_input) <= 5: print("I like ", user_input)

elif len(user_input) > 5: print("I do not like ", user_input)

user_input = input("Enter a fruit ")

Comments

0

Usually with a repetitive loop situation like this, usually you want to use a "while True:" scenario and then utilize a "break" statement to exit the "while" loop. Following is a snippet of code you might analyze.

while True:

    user_input = input("Enter a fruit ")

    if user_input == "Stop":
        print("Goodbye")
        break
        
    elif len(user_input) <= 5:
        print("I like", user_input)
        
    else:
        print("I do not like", user_input)

This provides a graceful exit after allowing the user to enter an indeterminant number of fruits.

@Una:~/Python_Programs/Fruit$ python3 Fruit.py 
Enter a fruit apple
I like apple
Enter a fruit pear
I like pear
Enter a fruit grapes
I do not like grapes
Enter a fruit Stop
Goodbye

Give that a try.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.