I train to work with the for loop: Does not iterate over the list, performs the first iteration ('Yes'), regardless of whether there is a name in the list or not. Help please, the answer is not found in the internet.

name = input("Π’Π²Π΅Π΄ΠΈΡ‚Π΅ имя для ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΊΠΈ: ") names = ["Kate", "Elena", "Sergej", "Oleg", "Vasya"] for name in names: if name in names: print('Yes') else: print('No') 
  • The loop variable rewrites the β€œname” variable declared above - MaxU
  • What is the right way then? - Oleg Butkevich
  • one
    That's right without a cycle =) but if you really want a cycle - see the answer - Vladimir Klykov
  • one
    input ("Enter a name for verification:") in names - S. Nick

2 answers 2

Here is the working code:

 name = input("Π’Π²Π΅Π΄ΠΈΡ‚Π΅ имя для ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΊΠΈ: ") names = ["Kate", "Elena", "Sergej", "Oleg", "Vasya"] if name in names: print ("yes") else: print ("no") 

The problem is that in and so it runs through the array itself to check the entry. And you did how:

  1. Assigned the name variable as a name.
  2. The loop was made for the same variable, that is, the name you already had was an array of each element
  3. And then I checked whether the name in the array.

That is, you have overwritten and looked far from it.

  • Thank you) So I can, here in the video I looked at the for cycle I decided to pervert, thanks anyway. - Oleg Butkevich
  • IN and so runs through the array itself. If the task is to check availability, then my option is faster. - mepihindeveloper
  • I agree, the simple is better than the complex, if I quote the founder correctly - Oleg Butkevich
  • @mepihindeveloper did not notice your answer when your rules +) returned everything to sleep =) - Vladimir Klykov
  • @ OlegButkevich names = ["Kate", "Elena", "Sergej", "Oleg", "Vasya"] result = input("Π’Π²Π΅Π΄ΠΈΡ‚Π΅ имя для ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΊΠΈ: ") in names - mepihindeveloper

If you really want a cycle:

 namein = input("Π’Π²Π΅Π΄ΠΈΡ‚Π΅ имя для ΠΏΡ€ΠΎΠ²Π΅Ρ€ΠΊΠΈ: ") names = ["Kate", "Elena", "Sergej", "Oleg", "Vasya"] for name in names: if namein == name: print('Yes') else: print('No') 
  • Thank you, I didn’t quite understand what the chip is, I will search - Oleg Butkevich
  • Look at how the condition is written and the difference in the namein and name names - Vladimir Klykov
  • I understood it, and why namein? Is it an in operator? I am engaged less than a month, in many respects I swim for what - Oleg Butkevich
  • No, just an abbreviation for NameInput can call it as you like, the main thing is that the variable names do not match. for name in names: here in this statement, each time in the name variable, the next element from the names written. - Vladimir Klykov
  • Thank you) Yes, it is more logical without a cycle, I teach further)) - Oleg Butkevich