作业是制作猜谜游戏,其中参数是答案。最后如果这个人说得对,它会打印一个祝贺声明并返回它所尝试的次数,如果他们输入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
当我运行它时,无论我放入它,只是一直问我猜测。
答案 0 :(得分:3)
因为你调用变量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
答案 1 :(得分:-1)
代码是否正确缩进? 您定义的函数的主体由缩进级别决定。
在您粘贴的示例中,由于def之后的行具有较少的缩进,因此该函数的主体是空的'。
Indenting code is important in python
此外,要为变量分配一个值,您必须使用单个' =',所以:
tries == -1
应该是
tries = -1
如果要将-1值分配给该变量。