3 回答
TA贡献1946条经验 获得超4个赞
使用for循环及其else子句。else只有当您没有跳出循环时,循环的子句才会运行。
首先让您的函数返回一个值来指示用户是否猜对了。否则将很难与之交互:
def check_guess():
letter = "d"
guess = input("What is your guess: ")
if not guess.isalpha():
print("This is invalid")
return False
guess = guess.lower()
if guess == letter:
print("that is correct")
return True
if guess > letter:
print("This too high")
else:
print("this is too low")
return False
现在您可以准确地调用该函数 3 次,或者直到用户猜对为止,以先到者为准:
for _ in range(3):
if check_guess():
break
else:
print('you failed')
当check_guess返回True表示成功时,我们break跳出循环,确保else子句不被触发。如果三个迭代完成并且用户从未做出正确的猜测,则触发该子句。
TA贡献1873条经验 获得超9个赞
def check_guess():
letter = "d"
guess = input("What is your guess: ")
if guess.isalpha() == False:
print("This is invalid")
return False
elif guess.lower() > letter:
print("This too high")
return False
elif guess.lower() < letter:
print("this is too low")
return False
else:
print("that is correct")
return True
for i in range(0,3):
status = check_guess()
If status:
print(“success”)
break
else:
print(“fail”)
TA贡献1719条经验 获得超6个赞
如果用户是对的,您需要返回,如果不是,则增加一个计数器。这样的事情应该工作:
count = 0
while count < 3:
if check_guess():
# he's right
break
else:
# he's wrong
count += 1
if count >= 3:
print("You lose !")
else:
print("You win !")
添加回答
举报