K
K
Konstantin Omelyan2016-03-16 15:25:56
Python
Konstantin Omelyan, 2016-03-16 15:25:56

Why is the for loop not working properly?

The problem is that there are 5 attempts to find out if the hidden word contains the letter that the user indicated or not.
if this is the code:

import random 

WORDS =("питон", "анаграмма", "простая", "сложная", "ответ", "подстаканник")
word = random.choice(WORDS)
i = 5
dor = input('Назовите вашу букву ')
while i!=0:
  for item in word:
      if item == dor:
          print('Да')
  i -= 1
  dor = input('Назовите вашу букву ')

It works fine if there is such a letter in the word it writes "yes", but if there is no pass and again a question,

Say your letter a
Say your letter o
Yes
Say your letter p
Yes
Say your letter and
Yes
Say your letter s

what if the code is like this:
import random 

WORDS =("питон", "анаграмма", "простая", "сложная", "ответ", "подстаканник")
word = random.choice(WORDS)
i = 5
dor = input('Назовите вашу букву ')
while i!=0:
  for item in word:
      if item == dor:
          print('Да')
      else:
          print('Нет')
  i -= 1
  dor = input('Назовите вашу букву ')

That output will be like this:

What is your letter o
Yes
No
No
No
No
What is your letter

I can’t understand why when adding else or elif the for loop behaves in a way that is not clear to me.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nirvimel, 2016-03-16
@Sipatyj

import random 

WORDS =('питон', 'анаграмма', 'простая', 'сложная', 'ответ', 'подстаканник')
word = random.choice(WORDS)
dor = input('Назовите вашу букву: ')
print('Да' if dor[0] in word else 'Нет')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question