[英]Python, I have a guessing game and want to add the number of guesses
在猜谜游戏中,我希望计数是猜谜变量的数量,并在您赢得游戏时打印出值。 每当我尝试在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
count
变量是在使用它的函数之外声明的。 您可以在函数内部声明它是全局的:
global count
或在每次调用guessing()
时将其作为参数传递,因为它是递归函数:
def guessing(count):
另外,问题中发布的代码不会显示实际的count
变量在哪里递增。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.