首页 > 解决方案 > 嵌套的 if 语句无法正常工作(python)

问题描述

这是我的代码:

#Greeting
print('\n---Automatic Troubleshooter---\n')

#UserInput
userInput = input('Are you having issues with your Wi-Fi?: ')

#QuestionAnswer
if (userInput == 'Yes' or userInput == 'yes'):
    print('\nReboot the computer and try to connect.')
    userInput = input('Did that fix the problem?: ')
    if (userInput == 'No' or userInput == 'no'):
        print('\nReboot the router and try to connect.')
        userInput = input('Did that fix the problem?: ')
        if (userInput == 'No' or userInput == 'no'):
            print('\nMake sure the cables between the router & modem are plugged in firmly.')
            userInput = input('Did that fix the problem?: ')
            if (userInput == 'No' or userInput == 'no'):
                print('\nMove the router to a new location and try to connect.')
                userInput == input('Did that fix the problem?: ')
                if (userInput == 'No' or userInput == 'no'):
                    print('\nGet a new router.')
                else:
                    print('\nExiting program...\n')
else:
    print('\nExiting program...\n')

每当我到达最后一个 if 语句时,无论我输入什么,它总是打印“获取新路由器”。起初,我没有第一个 else 和最后一个 else;我刚刚在外面有“退出程序......”,在我看来,它应该有效。如果问题得到解决,它不应该继续其余的并打印'Exiting program...' 另外,当我改变它的工作条件时。因此,当我将最后一个 if 语句的条件从“否”和“否”更改为其他内容时,它就起作用了。

标签: pythonif-statementnested

解决方案


在最后一次之前,if您没有分配给userInput变量-您有 a==而不是 a =。因此,它将保留先前输入的“否”或“否”,并始终转到if分支。

替换为===你应该没问题:

userInput = input('Did that fix the problem?: ')
# Here ---^

推荐阅读