python - 获取“NameError:名称'room_path'未定义”
问题描述
这是我遇到问题的代码。我正在使用 Python 3.6。
def room():
room_path=["1","2"]
user_choice = ""
print ("If you decide to ditch Todd and go to the campfire alone, enter 1")
print ("If you decide to drag Todd with you to the campfire, enter 2")
user_choice = input("your option number")
if user_choice == room_path [1]:
print ("yes")
elif user_choice == room_path [2]:
print ("no")
当我运行代码并输入一个数字时,这是我得到的错误:
if user_choice == room_path [1]:
NameError: name 'room_path' is not defined
解决方案
发生错误是因为名称room_path
是在函数范围内声明的
room
,因此无法从该函数外部调用。
这是一个很好的链接,解释了 Python 中变量的范围:
http://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html
要解决此问题,您可以在函数room_path
之外声明room
,您可能还想使用user_choice
并完全删除该room
函数。
您的代码将如下所示:
room_path=["1","2"]
user_choice = ""
print ("If you decide to ditch Todd and go to the campfire alone, enter 1")
print ("If you decide to drag Todd with you to the campfire, enter 2")
user_choice = input("your option number")
if user_choice == room_path [1]:
print ("yes")
elif user_choice == room_path [2]:
print ("no")
推荐阅读
- python - Imshow/Matshow 在轴内收缩
- javascript - Nodejs 串口不能同时运行两个代码
- c# - 我在制作脚本以淡入/淡出 Unity c# 中的精灵列表时遇到问题
- java - 如何使用 https 将 spring-config-server 与 vertx 一起使用?
- elasticsearch - 提升 word2vec 相关词以改善 ElasticSearch 结果
- arrays - 获取数组的值而不是索引
- node.js - 配置 NbAuthJWTInterceptor 以正确格式化 JWT 令牌的问题
- netlogo - NetLogo,映射一个多维变量数组
- wordpress - 我想更改侧边栏中的图标
- javascript - 为什么 ParseInt() 在 Microsoft Edge 上返回 NaN?