![]() |
Infinite loop/ only half working - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: Infinite loop/ only half working (/thread-12704.html) |
Infinite loop/ only half working - anclark686 - Sep-08-2018 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 RE: Infinite loop/ only half working - Gribouillis - Sep-08-2018 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 RE: Infinite loop/ only half working - anclark686 - Sep-08-2018 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! RE: Infinite loop/ only half working - buran - Sep-09-2018 (Sep-08-2018, 10:52 PM)anclark686 Wrote: added commas for separationI think Griboullis suggest to make it a list/tuple/set RE: Infinite loop/ only half working - gitiya - Sep-09-2018 also the break after the first if statement needs not be there, because if True, then the loop runs, with break it stops RE: Infinite loop/ only half working - buran - Sep-09-2018 (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 stopsthat is the idea - break out of the loop if color in rainbow... |