Python Forum
Program: Input the correct color
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Program: Input the correct color
#1
# [ ] 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"

while True:
    rainbow = "red orange yellow green blue indigo violet"
    try1 = input("try color: ")
    try2 = input("try color: ")
    try3 = input("try color: ")
    try4 = input("try color: ")
    if try1 in rainbow:
        print("You guessed the colour!")
    elif try2 in rainbow:
        print("You guessed the colour!")
    elif try3 in rainbow:
        print("You guessed the colour!")
    elif try4 in rainbow:
        print("You guessed the colour!")    
    else:
        print("Better luck next time!")
I assume that this is not optimal solution. I at first tried with if try1 or try2 or try3 or try4 in rainbow: but that doesn't work. Advice is appreciated.
Reply
#2
I don't think asking for input four times in each iteration is what the task demands. Besides, this loop will just run forever. Instead you would be better off making a counter (variable), incrementing it after each (wrong) guess attempt. One guess attempt should be in one loop iteration, and after correct guess or four wrong guesses, the loop should break, thus exiting the program.

Edit: Task description is quite ambiguous, so what you did may be fine, I am not sure anymore.
Reply
#3
Are you sure you are required to use while True? Because that is a really dumb requirement on this assignment.

Either way, you should only be asking for input one time each run through your loop.
An example of the basic idea (needs additional code):
rainbow = "red orange yellow green blue indigo violet"
tries = 0
while True:
    color = input("Try color: ")
    tries += 1
    if tries == 4:
        break
Note that this would be greatly improved if you are allowed to write:
while tries < 4:
And in fact would be even better with a for loop and no while loop at all:
for _ in range(4):
Reply
#4
Mekire, the answer to your question is - yes, this is edx tutorial requirement.
I don't quite understand what did you mean with your code. It doesn't test if input matches with one from variable rainbow.
Reply
#5
Quote:It doesn't test if input matches with one from variable rainbow.
No, it doesn't. It shows you how to write a loop which asks once per loop and exits after four tries. You need to add the rest.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  User input numpy array with color mapping & mouse click events imakeathepi 0 3,300 Aug-15-2017, 10:33 AM
Last Post: imakeathepi

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020