python - if 和 elif 问题总是被跳过,不管输入
问题描述
继承人的代码:
L = '?'
ignore_letters = ['!','?','.',',']
print("type 'commands' for list of commands")
name = input('hello what is your name :) ')
def main():
global restart
answer = input('please type your request here '+name+': ')
def answer():
global answer
if 'list' in [answer] and 'take' in [answer]:
print('ok')
i = input('type your list '+name+' ')
l = i.split()
global L
L = l.sort()
main()
elif 'run' in [answer] and 'list' in [answer]:
print('ok sure')
print('here ' + L )
main()
(此代码只是代码行的一部分,但我认为问题应该在这里)
我还尝试了在答案周围使用其他类型的括号的答案,但没有,只是为了确保不是这样
我对编码有点陌生,所以我觉得我的代码有问题,我看不到
解决方案
您在代码中错误地使用了global
关键字。
注意: global 关键字用于从非全局范围(例如在函数内部)更改或创建全局变量。
考虑代码,
def funcA():
varA = 20
def funcB():
global varA
varA = 25
funcB()
print(varA)
funcA()
当您执行上述代码时,20
尽管 的值varA
已更改,但输出仍将是funcB
. 本质上发生的是,您创建了一个名为的全局变量并将varA
其分配给 value 25
,但是当您调用它时,print(varA)
它引用了内部声明的局部变量funcA
。
要解决这个问题,你必须使用nonlocal
关键字,nonlocal 关键字用于处理嵌套函数内部的变量,其中变量不应该属于内部函数。
考虑代码,
def funcA():
varA = 20
def funcB():
nonlocal varA
varA = 25
funcB()
print(varA)
funcA()
现在,当您执行代码时,输出将符合25
预期。
现在,来到你的代码,正确的代码可能看起来像,
L = '?'
ignore_letters = ['!', '?', '.', ',']
print("type 'commands' for list of commands")
name = input('hello what is your name :) ')
def main():
global restart
answer = input('please type your request here ' + name + ': ').split()
def answerFunc():
nonlocal answer
if 'list' in answer and 'take' in answer:
print('ok')
i = input('type your list '+name+' ')
l = i.split()
global L
L = l.sort()
main()
elif 'run' in answer and 'list' in answer:
print('ok sure')
print('here ' + L)
main()
answerFunc()
推荐阅读
- docker - 安装 Hyperledger Fabric docker 映像失败
- mysql - Java 8 java.time 未正确映射到 mysql
- android - Room 无法验证数据完整性。如何在不编写迁移步骤的情况下修复它?
- html - Deck.gl (Mapbox) StaticMap 不调整大小 - 覆盖屏幕上的所有内容
- powershell - 带有安全字符串的管理员密码的框输入
- react-native - 我想在反应原生应用程序中为给定视频生成哈希
- r - 如何在 R 中使用 Dplyr 过滤年初至今的数据?
- bash - 在命令行中找到了 FFMpeg 尾随选项
- flask - 使用 MongoAlchemy 从字典中保存记录
- swift - 错误消息:对成员“withUnsafeBytes”的模糊引用