Python,我有一个猜谜游戏,并希望添加猜测的数量

时间:2013-09-26 16:38:33

标签: python function variables

在猜谜游戏中,我希望计数是猜测变量的数量,并在您赢得游戏时打印该值。每当我尝试在else部分下添加count = count + 1行代码时,我就会遇到大量错误。

import random

from random import randint

secret = randint(0,11)
count = 1

def guessing():

    print ("Guessing easy: The secret number will stay the same every turn")
    guess = int(input("Guess a number from 1 to 10 "))

    if secret == guess:
        print ("Your guess was", guess)
        print ("Well done, you win")
        print ("It took you", count, "guessing to win")
        startgame()
    else:
        print ("Your guess was",guess)
        print ("Sorry, your guess was wrong. Please try again""\n")
        guessing()

def guessinghard():
    print ("Guessing hard: The secret number will change every turn")
    secret = randint(0,11)
    guess = int(input("Guess a number from 1 to 10 "))

    if secret == guess:
        print ("Your guess was", guess)
        print ("Well done, you win")
        print ("It took you ", count, " guessing to win")
        startgame()
    else:
        print ("Your guess was", guess)
        print ("Sorry, your guess was wrong. Please try again")
        guessinghard()

def startgame():
    game = input("Would you like to play easy or hard ")

    if game == "easy":
        guessing()
    elif game == "hard":
        guessinghard()
    else:
        print("Please choose easy or hard")
        startgame()

startgame()

我得到的错误是:

Traceback (most recent call last):
  File "H:/Modules (Year 2)/Advanced programming/Python/Week 2 - Review and Arrays/
Iteration Exercise -  Secret Number.py", line 52, in <module>
    startgame()

  File "H:/Modules (Year 2)/Advanced programming/Python/Week 2 - Review and Arrays/
Iteration Exercise -  Secret Number.py", line 45, in startgame
    guessing()

  File "H:/Modules (Year 2)/Advanced programming/Python/Week 2 - Review and Arrays/
Iteration Exercise -  Secret Number.py", line 21, in guessing
    count = count + 1

UnboundLocalError: local variable 'count' referenced before assignment

1 个答案:

答案 0 :(得分:1)

count变量是在使用它的函数之外声明的。您可以在函数内声明它是全局的:

global count

或者每次调用guessing()时将其作为参数传递,因为它是一个递归函数:

def guessing(count):

此外,问题中发布的代码并未显示实际count变量的增加位置。