Python 不知道如何打破循环
我有一个字母猜测游戏要用Python完成。用户可以选择的字母是“a、b、c和d”。我知道如何尝试五次,但当我猜到一个正确的字母时,我无法打破循环并祝贺玩家Python 不知道如何打破循环,python,loops,out,Python,Loops,Out,我有一个字母猜测游戏要用Python完成。用户可以选择的字母是“a、b、c和d”。我知道如何尝试五次,但当我猜到一个正确的字母时,我无法打破循环并祝贺玩家 g = 0 n = ("a", "b", "c", "d") print("Welcome to the letter game.\nIn order to win you must guess one of the\ncorrect numbers.") l=input('Take a guess:
g = 0
n = ("a", "b", "c", "d")
print("Welcome to the letter game.\nIn order to win you must guess one of the\ncorrect numbers.")
l=input('Take a guess: ');
for g in range(4):
if l == n:
break
else:
l=input("Wrong. Try again: ")
if l == n:
print('Good job, You guessed one of the acceptable letters.')
if l != n:
print('Sorry. You could have chosen a, b, c, or d.')
首先,你把一个字母和一个元组进行比较。例如,当你做
如果l==n
,你说的是如果'a'==(“a”,“b”,“c”,“d”)
我想你想要的是一个while
循环
guesses = 0
while guesses <= 4:
l = input('Take a guess: ')
if l in n: # Use 'in' to check if the input is in the tuple
print('Good job, You guessed one of the acceptable letters.')
break # Breaks out of the while-loop
# The code below runs if the input was wrong. An "else" isn't needed.
print("Wrong. Try again")
guesses += 1 # Add one guess
# Goes back to the beginning of the while loop
else: # This runs if the "break" never occured
print('Sorry. You could have chosen a, b, c, or d.')
猜测=0
虽然猜测这会保留大部分代码,但会重新排列以满足您的目标:
n = ("a", "b", "c", "d")
print('Welcome to the letter game. In order to win')
print('you must guess one of the correct numbers.\n')
guess = input('Take a guess: ');
for _ in range(4):
if guess in n:
print('Good job, You guessed one of the acceptable letters.')
break
guess = input("Wrong. Try again: ")
else:
print('\nSorry. You could have chosen a, b, c, or d.')
我们并不真正关心循环变量的值,为了明确这一点,我们使用“”来代替变量。请修复缩进