gpt4 book ai didi

python - 我的 while 循环永远不会到达条件语句并不断循环

转载 作者:行者123 更新时间:2023-12-01 03:20:58 27 4
gpt4 key购买 nike

任务是做一个猜谜游戏,其中参数就是答案。最后,如果用户答对了,它会打印一条祝贺语句并返回尝试的次数,如果他们输入 quit,它会显示答案并尝试 == -1。除此之外,它会一直循环,直到他们得到正确的答案。

def guessNumber(num):
tries = 1
while tries > 0:
guess = input("What is your guess? ")
if guess == num:
print ("Correct! It took you" + str(tries)+ "tries. ")
return tries
elif guess == "quit":
tries == -1
print ("The correct answer was " + str(num) + ".")
return tries
else:
tries += 1

当我运行它时,无论我放入什么,它都会不断询问我的猜测。

最佳答案

由于您调用了变量 num 所以我猜测它是一个整数,因此您正在检查整数和字符串之间的相等性,因此它永远不是 True。比较时尝试将 num 更改为 str(num),因此:

def guessNumber(num):
tries = 1
while tries > 0:
guess = input("What is your guess? ")
if guess == str(num):
print ("Correct! It took you {0} tries. ".format(tries))
return tries
elif guess == "quit":
tries = -1
print ("The correct answer was {0}.".format(num))
return tries
else:
tries += 1

关于python - 我的 while 循环永远不会到达条件语句并不断循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41924390/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com