首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >UnboundLocalError:赋值前引用的局部变量“打印”?

UnboundLocalError:赋值前引用的局部变量“打印”?
EN

Stack Overflow用户
提问于 2019-10-30 11:24:44
回答 1查看 644关注 0票数 2

我试图做一个文本为基础的rpg风格的游戏。我遇到的问题是,它正在产生:

UnboundLocalError:赋值前引用的局部变量“打印”

我也不知道为什么。我在网上搜索,发现它通常来自本地使用的全局变量,但我不明白为什么要用print来完成。而且,它一直循环到开始,而不读取print for def option_statue。我正在使用Python 3.7.3:

代码语言:javascript
复制
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() 

错误:

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

发布于 2020-08-29 03:54:33

你的问题就在于这句话:

代码语言:javascript
复制
print:("""The statue appears before you, ...""")
#    ^
#    Specifically here.

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

代码语言:javascript
复制
>>> 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标记为局部变量(没有为其分配任何内容),这就是为什么您看到了“赋值前引用”错误。

解决方案就是去掉冒号:

代码语言:javascript
复制
print("""The statue appears before you, ...""")

由于添加了有趣的信息(嗯,对于“乐趣”的一些奇怪定义),print并没有什么特别之处,您可以通过分配给它来完成各种奇妙的事情:

代码语言:javascript
复制
>>> 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 (请不要在真正的代码中做这样的事情):

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58624332

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档