Creating a simple while loop

Viewed 38

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?

3 Answers

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) 

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 ")

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.

Related