gpt4 book ai didi

python - 我是一个初学者程序员,我需要查询return语句

转载 作者:行者123 更新时间:2023-12-01 04:18:21 25 4
gpt4 key购买 nike

所以我在制作一个猜谜游戏功能时遇到了一些麻烦,该功能可以记录您正确的次数。我目前有两个问题:

  1. 代码导致函数激活两次,有没有办法既打印函数的返回值并为其分配变量?
  2. 变量“score”永远不会超过 1,因为如果您猜测的数字错误,该函数将不返回任何内容并返回到 0

这是我的代码,一团糟:

def GuessingGame(score):

rng = random.Random()
numbertoguess = rng.randrange(1,10)
guess = int(input ("What is your guess for a number between 1 and 10?"))
if numbertoguess == guess:
print ("Great guess! You're correct.")
int (score = score + 1)
return score
else:
print ("Wrong, the number was "+str(numbertoguess)+".")

playagain = "yes"

score = 0

while playagain == "yes":

print ("The score is now "+str(GuessingGame(score))+".")
score = GuessingGame(score)
playagain = input ("Play again? (yes or no)")
if playagain != "yes":
print ("Goodbye")
else:
pass

最佳答案

这行实际上是调用函数:

print ("The score is now "+str(GuessingGame(score))+".")

你应该只使用:

print ("The score is now "+ str(score) +".")

score 是一个变量,可以这样使用

要回答第二个问题,您不会在 else: 子句中return

而不是这个:

if numbertoguess == guess:
print ("Great guess! You're correct.")
int (score = score + 1)
return score
else:
print ("Wrong, the number was "+str(numbertoguess)+".")

您可以在这两种情况下返回分数,如下所示:

if numbertoguess == guess:
print ("Great guess! You're correct.")
int (score = score + 1)
else:
print ("Wrong, the number was "+str(numbertoguess)+".")
return score

此外,此行可能不会执行您想要的操作:

int (score = score + 1)

没有理由cast这个,只需使用这一行:

score = score + 1

或者:

score += 1

最后一点是 GuessingGame 的样式会更好,如下所示:

guessing_game

根据PEP8

关于python - 我是一个初学者程序员,我需要查询return语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34048255/

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