每次函数运行时计数都会增加

时间:2018-09-29 10:11:17

标签: python

我刚刚开始学习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

2 个答案:

答案 0 :(得分:9)

在函数中,每次将 local 变量设置为0,这意味着之后函数完成,该变量不再存在

诀窍是使用一个在函数存在后仍保持“活动”状态的变量。例如,函数外部的变量,或者您可以在要递增的函数中添加属性。后者的优点是更清楚地表明这与功能有关,例如:

def spawn():
    spawn.count += 1
    print(spawn.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 spawn.count == 4:
        dead("You wandered around too much and died.")
    else:
        print()

spawn.count = 0

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

答案 1 :(得分:1)

或者您可以这样做:

def spawn():
    if not hasattr(spawn, 'count'):
        spawn.count = 0
    spawn.count += 1
    print(spawn.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 spawn.count == 4:
        dead("You wandered around too much and died.")
    else:
        print()