python - 是否可以使用变量然后重新定义它?
问题描述
我正在为学校制作一个项目,这是一个骰子游戏。我的这段代码就像一个catch 22。
我需要定义一个变量,否则它会标记,所以我这样做但是每次运行按钮时它都会将值更改为零而不是增加它。
if Rollnop1 == 0 :
Userscore1 = Randomnumber
print ("User 1 ",Userscore1 )
Rollnop1 = Rollnop1+1 #But this changes it so it will go to the next players roll, every
#time the button is pressed it changes the variable back to 0
def gamerun():
global Player
global usernamestr
global passwordstr
global usernamestr2
global passwordstr2
Rollnop1 = 0
def roll2():
Rollnop2 = 0
Randomnumber = random.randint(2,12)
print ("Console: Random Number 2 = ",Randomnumber)
if Rollnop2 == 0 :
Userscore2 = Randomnumber
print ("User 2 ",Userscore2 )
def roll1():
Rollnop1 = 0 #Need to define this here otherwise It wont work
Randomnumber = random.randint(2,12)
print ("Console: Random Number = ",Randomnumber)
if Rollnop1 == 0 :
Userscore1 = Randomnumber
print ("User 1 ",Userscore1 )
Rollnop1 = Rollnop1+1 #But this changes it so it will go to the next players roll, every
#time the button is pressed it changes the variable back to 0
else:
roll2()
actdicegame = Tk()
gamerunl0 = Label(actdicegame, text = usernamestr, fg = "black")
gamerunl0.pack()
gamerunl1 = Label(actdicegame, text = "Roll The Dice", fg = "black")
gamerunl1.pack()
gamerunb1 = Button(actdicegame, text="ROLL",fg="Black", command=roll1)#Register Butto
gamerunb1.pack()
actdicegame.geometry("350x500")
print ("Console: GUI RUNNING 1")
actdicegame.mainloop()
解决方案
这可以回答您的问题:外部函数中的嵌套函数更改变量不起作用。基本上,您需要在游戏运行中分配 Rollnop1 = 0 和 Rollnop2 = 0 并在尝试更改它们的值之前在 roll1 和 roll2 中将它们声明为非本地。
– DarrylG 非常感谢您以及所有提供帮助的人。
更多here 嵌套函数更改变量在外部函数不起作用
推荐阅读
- reactjs - ComponentDidMount 是否不适用于反应钩子?
- yocto - Yocto:do_rootfs 失败,因为找不到我正在构建的包
- matlab - 如何从颜色阈值函数批处理创建蒙版?
- python - 具有 classmethod 的本地类不起作用,但导入的版本有效
- python - 如何沿numpy数组的给定轴索引最大值的每次出现?
- testing - 当我手动创建实体但不是在开玩笑测试中时,Nestjs 管道可以工作
- vue.js - 在子组件中查看属性不起作用
- java - 如何设置 org.apache.tomcat.websocket.BLOCKING_SEND_TIMEOUT?
- javascript - 在 GAS 中重新运行的函数
- sqlite - 数据库中的最大数量