Подскажите, как сделать чтобы при каждом цикле менялось значение переменной (хочу сделать "систему попыток")
недавно начал изучать Python и решил сегодня потренироваться, после того, как почитал пару книг. Поэтому, сразу говорю мои знания минимальные. Хочу сделать, так сказать, систему попыток, но не могу додуматься каким образом сделать так, чтобы с X вычиталось 1 и при каждом цикле оставалось все меньше и меньше попыток.
capital = "London"
running = True
x = 4
while running:
guess = input('Enter Capital of the Great Britain: ')
att = 4
if guess == capital:
print('Congratulations!')
running = False
else:
att = x-1
print("No, you have yet", att, "attempts")
print('Game: Countries - END')
Ответы (3 шт):
Автор решения: CrazyElf
→ Ссылка
Тут проще всего через цикл for:
capital = "London"
for attempt in range(3, -1, -1):
guess = input('Enter Capital of the Great Britain: ')
if guess == capital:
print('Congratulations!')
break
if attempt:
print("No, you have yet", attempt, "attempts")
else:
print("No, and you have no more attempts, sorry")
print('Game: Countries - END')
Автор решения: gil9red
→ Ссылка
Вариант через while:
attempts = 5
capital = "London"
while attempts > 0:
guess = input('Enter Capital of the Great Britain: ')
if guess == capital:
print('Congratulations!')
break
attempts -= 1
if attempts:
print(f"No, you have yet {attempts} attempts")
else:
print("No, and you have no more attempts, sorry")
print('Game: Countries - END')
Или через while True:
attempts = 5
capital = "London"
while True:
guess = input('Enter Capital of the Great Britain: ')
if guess == capital:
print('Congratulations!')
break
attempts -= 1
if attempts <= 0:
print("No, and you have no more attempts, sorry")
break
print(f"No, you have yet {attempts} attempts")
print('Game: Countries - END')
Автор решения: vadim vaduxa
→ Ссылка
или через рекурсию
def func(question, answer, failed_attempts=1):
guess = input(question)
if guess == answer:
print('Congratulations!')
return True
elif failed_attempts:
print(f"No, you have yet {failed_attempts} attempts")
return func(question, answer, failed_attempts - 1)
print("No, and you have no more attempts, sorry")
answer_results = [
func('Enter Capital of the Great Britain: ', "London"),
func('Enter Capital of the Great Russia: ', "Moscow"),
func('Enter Capital of the Great USA: ', "Washington"),
]
print(f'Game: Countries - END. Правильных ответов: {answer_results.count(True)} из {len(answer_results)}')
# Enter Capital of the Great Britain: London
# Congratulations!
# Enter Capital of the Great Russia: 2
# No, you have yet 1 attempts
# Enter Capital of the Great Russia: 1
# No, and you have no more attempts, sorry
# Enter Capital of the Great USA: Washington
# Congratulations!
# Game: Countries - END. Правильных ответов: 2 из 3