gpt4 book ai didi

python - 未使用变量

转载 作者:太空宇宙 更新时间:2023-11-04 04:26:08 25 4
gpt4 key购买 nike

这将是我在这里的第一个问题,所以如果我做错了什么,请不要生气。我得到了猜测密码的作业,我不得不在其中实现 Tkinter。问题是计数器不工作,因为变量计数器没有被使用。我明白了,但我很难按应有的方式对其进行编码,但它看起来不像。对于另一个问题,下面是我再次使用 IF 的 else 语句,这样可以吗,还是您练习不同的代码。

    import Tkinter
import random
import tkMessageBox

secret_number = random.randint(1, 10)

window = Tkinter.Tk()

greeting = Tkinter.Label(window, text="Welcome to the game " + "guess the secret number".upper() + ". You have 5 tries.\n Select a number between 1 and 10:")
greeting.pack()


guess = Tkinter.Entry(window)
guess.pack()


def check_guess():
counter = 0
if int(guess.get()) == secret_number:
counter = counter + 1 #here it states "variable not used"
result_text = "You guessed correctly! Secret number is %s! " % secret_number
elif int(guess.get()) > secret_number:
counter = counter + 1
result_text = "Wrong. Your number is to HIGH! This was your %s try." % counter
else:
counter = counter + 1
result_text = "Wrong. Your number is to LOW! This was your %s try." % counter
if counter == 5 and guess != secret_number:
print "Secret number was %s!" % secret_number

tkMessageBox.showinfo("Result", result_text)


submit = Tkinter.Button(window, text="Try your luck", command=check_guess) # check_guess, not check_guess()
submit.pack()

window.mainloop()

最佳答案

每次调用该函数时,counter 都将设置为 0,这意味着它永远不会等于 5。一个简单的解决方法是改用全局变量。改为在函数外设置 counter = 0,并从函数中删除该行。相反,在函数的第一行写入 global counter。像这样:

counter = 0
def check_guess():
global counter
if int(guess.get()) == secret_number:
...

关于python - 未使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53462165/

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