gpt4 book ai didi

python - 每次函数运行时增加计数

转载 作者:太空宇宙 更新时间:2023-11-03 12:36:03 27 4
gpt4 key购买 nike

我刚开始学习 Python。我正在阅读一本书并制作一个基于文本的游戏。

所以我有一个房间。如果他/她进入房间 3 次但不知道该怎么做,我想让他/她死。

def spawn():
count = 0
count += 1
print(count)
print("You dropped down nearly to the magma.")
print("There are four doors around you.")
print("Which one do you take?")
ch = input("Top, bottom, left or right? > ")
if count = 4:
dead("You wandered around too much and died.")
else:
print()

我试图通过打印来跟踪数字,但我无法让它增加。我做错了什么?

编辑:当我将 count 放在它给出的函数之外时:

Traceback (most recent call last):
File "ex.py", line 147, in <module>
spawn()
File "ex.py", line 14, in spawn
count += 1
UnboundLocalError: local variable 'count' referenced before assignment

最佳答案

好吧,在函数中,您每次都将一个局部变量设置为0,这意味着函数完成后,该变量不再存在。

诀窍是使用在函数存在后保持“事件”状态的变量。例如,函数外部的变量,或者您可以将 属性 添加到您递增的函数中。后者的好处是更明确这是和功能相关的东西,比如:

def spawn():
<b>spawn.count += 1</b>
print(<b>spawn.count</b>)
print("You dropped down nearly to the magma.")
print("There are four doors around you.")
print("Which one do you take?")
ch = input("Top, bottom, left or right? > ")
if <b>spawn.count</b> == 4:
dead("You wandered around too much and died.")
else:
print()

<b>spawn.count = 0</b>

请注意,您还忘记了对 if 语句(相等检查与赋值)使用双等号 (==)。

关于python - 每次函数运行时增加计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52567324/

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