Python Forum

Full Version: Infinite loop/ only half working
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all - I'm auditing a MOOC, and have to create code for the following question:
# [ ] use a while True loop (forever loop) to give 4 chances for input of a correct color in a rainbow
# rainbow = "red orange yellow green blue indigo violet"

When I enter a color that isn't in "rainbow" it causes an infinite loop. If I enter one that is in "rainbow" it performs as it should. Any help is greatly appreciated!

Here's my code:

rainbow = "red orange yellow green blue indigo violet"
color = input("Guess a color of the rainbow: ")
counter = 0

while True:
    if color.lower() in rainbow:
        print("Correct!", color.capitalize(), "is a color in the rainbow!")
        break
    elif counter < 4:
        if color.lower() in rainbow == False:
            counter += 1
            print("Sorry that color is not in the rainbow.")
    else: 
        break 
The question for the user needs to be in the loop, otherwise it can only be asked once.

There is another minor issue, note that
>>> rainbow = "red orange yellow green blue indigo violet"
>>> "ange yel" in rainbow
True
Hi, thank you for this! I moved the question into the loop, and added commas for separation. I believe my problem had to do with the counter location, but I think I figured it out. Thank you!
(Sep-08-2018, 10:52 PM)anclark686 Wrote: [ -> ]added commas for separation
I think Griboullis suggest to make it a list/tuple/set
also the break after the first if statement needs not be there, because if True, then the loop runs, with break it stops
(Sep-09-2018, 07:19 AM)gitiya Wrote: [ -> ]also the break after the first if statement needs not be there, because if True, then the loop runs, with break it stops
that is the idea - break out of the loop if color in rainbow...