首页 > 解决方案 > 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()

(此代码只是代码行的一部分,但我认为问题应该在这里)

我还尝试了在答案周围使用其他类型的括号的答案,但没有,只是为了确保不是这样

我对编码有点陌生,所以我觉得我的代码有问题,我看不到

标签: python

解决方案


您在代码中错误地使用了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()

推荐阅读