gpt4 book ai didi

Python,我有一个猜谜游戏,想添加猜数

转载 作者:太空宇宙 更新时间:2023-11-03 18:48:02 25 4
gpt4 key购买 nike

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

关于Python,我有一个猜谜游戏,想添加猜数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19033857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com