首页 > 解决方案 > UnboundLocalError:分配前引用了局部变量'print'?

问题描述

我正在尝试制作基于文本的 rpg 风格的游戏。我遇到的问题是它提出了:

UnboundLocalError:分配前引用的局部变量“打印”

我不知道为什么。我在网上搜索过,发现通常是来自本地使用的全局变量,但我不明白为什么要使用print. 此外,它会不断循环回到开头而不读取printfor def option_statue。我正在使用 Python 3.7.3:

import time
import random

answer_A = ["A", "a"]
answer_B = ["B", "b"]
answer_C = ["C", "c"]
yes = ["Y", "y", "yes"]
no = ["N", "n", "no"]
required = ("\nUse only A, B, or C\n")


hp = 30
sword = 0
flower = 0




goblin_damage = random.randint(1,5)


def intro():
    print("You wake with a start, cold mountain air fills your lungs as a bird cry shatters the serenity of the early morning.")
    print("You rise to your feet and observe your surroundings,it is clear that you are in a forest of some sort, the tall oaken arms of nearby trees strech into the sky")
    print(",they cast a soft shadow on you, and combined with the damp grass beneath your feet, results in a brisk morning awakening")
    time.sleep(1)
    print("How or why you are here remains unknown")
    time.sleep(1)
    print("What will you do now?")
    time.sleep(1)
    print("""A. Look around
B. Sit back down""")


    choice = input (">>> ")
    if choice in answer_A:
        option_lookaround()
    elif choice in answer_B:
        print("\nYou sit back down.\nWell that was fun")
        time.sleep(3)
        print("After lying down for a while, chewing grass and contemplating why you are here, you eventually decide to do something")
        time.sleep(1)
        option_lookaround()
    else:print (required)
    intro()


def option_lookaround():
    print("As you blink the sleep from your eyes, you realize that you are in a grove, in the centre, lies the broken remains of a statue")
    print("to your left you see a small stream and to your right appears to be the glow of a campfire. Will you:")
    print("""A. Explore the statue
B. Walk towards the stream
C. Investigate the campfire""")

    choice = input (">>> ")
    if choice in answer_A:
        option_statue()
    elif choice in answer_B:
        option_stream()
    elif choice in answer_C:
        option_campfire()
    else:
        print (required)
        option_lookaround()

def option_statue():
    global hp
    print:("""The statue appears before you, a grand monument to its era, now faded into obscurity,
it appeared to have been a humanoid of some sort, yet the eons of weather have worn the features to a near unrecognizable state""")
    hp = (hp- goblin_damage)
    print("You now have" ,hp, "health points")


intro() 

错误:

Traceback (most recent call last):
  File "/home/pi/Python/Text story adventure.py", line 79, in <module>
    intro()
  File "/home/pi/Python/Text story adventure.py", line 39, in intro
    option_lookaround()
  File "/home/pi/Python/Text story adventure.py", line 61, in option_lookaround
    option_statue()
  File "/home/pi/Python/Text story adventure.py", line 76, in option_statue
    print("You now have" ,hp, "health points")
UnboundLocalError: local variable 'print' referenced before assignment

标签: python

解决方案


您的问题在于这一行:

print:("""The statue appears before you, ...""")
#    ^
#    Specifically here.

看看下面的文字记录,它在一个较小的代码片段中显示了您的问题:

>>> def fn():
...     print:("Hello there.")
...     print(42)
...
>>> fn()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in fn
UnboundLocalError: local variable 'print' referenced before assignment

print:("Hello")实际上是 Python 类型提示(注释)的一种形式,看起来这只是标记print为局部变量(没有为其分配任何内容),这就是为什么您会看到“分配前引用”错误的原因。

解决办法就是去掉冒号:

print("""The statue appears before you, ...""")

作为添加的有趣信息(好吧,对于“有趣”的一些奇怪定义),没有什么特别print,你可以通过分配它来做各种美妙的事情:

>>> print(7)
7
>>> print = 42
>>> print(7)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

或者强迫它做一些非预期的事情,比如42尽管你给它输出(请不要在真实代码中做这样的事情):

def newprint(*args):
    global oldprint, print
    try:
        oldprint
    except:
        oldprint = print
        print = newprint
    oldprint(42)

print(7)                         # 7
newprint(7)                      # 42
print(7)                         # 42
print("Hello", "from", "pax")    # 42

推荐阅读