我是一名初学程序员,我需要查询返回语句

时间:2015-12-02 16:45:16

标签: python python-3.x

所以我在制作一个猜谜游戏功能方面遇到了一些麻烦,这个功能可以保持你得到正确数字的次数。我目前有两个问题:

  1. 代码导致函数激活两次,是否有任何方法可以打印函数的返回值并为其分配变量?
  2. 变量"得分"永远不会超过1,因为如果您猜测的数字是错误的,则该函数返回none并返回0
  3. 这是我的代码,它是一团糟:

    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
    

1 个答案:

答案 0 :(得分:2)

这一行实际上是在调用函数:

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

你应该使用:

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

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

要回答第二个问题,您不是return else:条款。

而不是:

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