python - UnboundLocalError:分配前引用了局部变量'print'?
问题描述
我正在尝试制作基于文本的 rpg 风格的游戏。我遇到的问题是它提出了:
UnboundLocalError:分配前引用的局部变量“打印”
我不知道为什么。我在网上搜索过,发现通常是来自本地使用的全局变量,但我不明白为什么要使用print
. 此外,它会不断循环回到开头而不读取print
for 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
解决方案
您的问题在于这一行:
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
推荐阅读
- python - Django自定义后端导致登录错误
- python - 为 jira lib 手动安装 python
- r - 在 R 中绘制横跨绘图边缘的两点之间的线,即环绕的边缘
- c++ - 将 BGR 转换为 HSV 以查找特定颜色
- php - 您如何正则表达式匹配除变量内容之外的所有内容(PHP)
- java - 如何使用 Mockito 模拟 Lamda 表达式
- java - 如何使用 Spring Boot 配置 JPA + HIBERNATE
- r - R 与点 (".")、"~" 和管道 (%>%) 运算符的组合
- fluent-nhibernate - 在 Fluent NHibernate 中映射多到 MapObject 到多关系的问题
- excel - VBA Excel 仅在某些值前插入 0