I started learning python, I don’t understand what’s wrong with the code. Here is the task:

rainbow rainbow rainbow rainbow rainbow rainbow rainbow rainbow rainbow rainbow rainbow rainbow

In short, in 4 attempts using while to find in a string variable the color that will be entered via input

rainbow = "red orange yellow green blue indigo violet" tries = 0 while True: color = input("Try your color: ") tries += 1 if tries == 4: break elif color in rainbow == True: print ("Correct!") break 
  • replace: color in rainbow == True -> color in rainbow.split() - MaxU
  • what does it mean? the course has not yet had a split; apparently, something else is required of me - Anton Zubochenko
  • @AntonZubochenko, as I understand it, it is necessary to break the string into an array of words and consistently compare them with the entered color. - Daniel Chizhevsky
  • @ DaniilChizhevsky yes, but I haven’t passed this yet. In theory, the line color in rainbow == True: should search for a specific word in the line, but for some reason it does not. - Anton Zubochenko

2 answers 2

You need to replace the expression elif color in rainbow == True: with the correct elif color in rainbow:

That is why the code from the question did not work, although at first glance it seemed to be correct:

 rainbow = "red orange yellow green blue indigo violet" color = 'red' # Правильно проверять наличие так: print(color in rainbow) # True # is и == в контексте булевой проверки взаимозаменяемы print(color in rainbow is True) # False print((color in rainbow) is True) # True 

I wondered why it was so googling and found the answer in this source .

According to it, when we write the expression color in rainbow is True , it expands to:

 (color in rainbow) and (rainbow is True) 

And since (rainbow is True) returns False , then the whole expression becomes False . But there will be no such problem if the brackets are placed correctly: (color in rainbow) is True .

And of course, it’s better to write right away:

 color in rainbow 
  • then it is not clear how to make a loop. the program either does not stop at the correct answer, or if you write break it stops at the wrong one. - Anton Zubochenko
  • Replace the incorrect expression elif color in rainbow == True: to the correct elif color in rainbow: If you do not need to immediately exit the cycle, instead of break write continue - gil9red
  • By the way, I wonder why color in rainbow == True gives False ? According to Operator precedence and Comparisons, this should be done from left to right, i.e. I would expect: (color in rainbow) == True ... - MaxU
  • one
    @ gil9red, I decided to deal with this issue ;-) - MaxU
  • one
    @MaxU, looks slim and explains this joke :) - gil9red

It is enough to change one line:

 rainbow = "red orange yellow green blue indigo violet" tries = 0 while True: color = input("Try your color: ") tries += 1 if tries == 4: break elif color in rainbow.split(): print ("Correct!") break