我是一个初学者程序员,我需要询问返回语句

2024-09-27 23:20:12 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我在制作一个猜谜游戏函数时遇到了一些麻烦,这个函数可以记录你正确的次数。我现在有两个问题:

  1. 代码导致函数激活两次,有没有方法既打印函数的返回值,又给它赋值?你知道吗
  2. 变量“score”永远不会超过1,因为如果您猜测的数字是错误的,则函数将返回none并返回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

Tags: 函数numberinputifiselseyesint
1条回答
网友
1楼 · 发布于 2024-09-27 23:20:12

此行实际上是在调用函数:

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

您只需使用:

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

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

要回答第二个问题,您不是在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

相关问题 更多 >

    热门问题