1

在猜谜游戏中,我希望计数是猜测变量的数量,并在您赢得游戏时打印该值。每当我尝试在 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
4

1 回答 1

1

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

global count

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

def guessing(count):

此外,问题中发布的代码没有显示实际count变量的递增位置。

于 2013-09-26T16:46:36.753 回答