多个Python if-statments?

tas*_*had 0 python python-3.x

我通常不用Python开发,但我有一些IDE和代码编辑器,我经常使用和切换.为了让自己更方便,我想我会制作一个快速的Python程序,根据输入启动我的IDE/Editor.问题是,每次运行程序时,第一个if-statment总是验证为true并运行该操作.

这是我的代码:

import os

#NOTE: I have trimmed the root directories here to save space. Just removed the subfolder names, but the programs are the same. 

notepadPlusPlusLaunch = "C:\\Notepad++\\notepad++.exe"
bracketsLaunch = "C:Brackets\\Brackets.exe"
aptanaLaunch = "C:Aptana Studio\\AptanaStudio3.exe"
devCppLaunch = "C:Dev-Cpp\\devcpp.exe"
githubLaunch = "C:GitHub,  Inc\\GitHub.appref-ms"
androidLaunch = "C:android-studio\\bin\\studio64.exe"
ijLaunch = "C:bin\\idea.exe"
pycharmLaunch = "C:JetBrains\\PyCharm  4.0.5\\bin\\pycharm.exe"
sublimeLaunch = "C:Sublime Text 3\\sublime_text.exe"

def launcherFunction(command):
    os.startfile(command)

launchCommand = input("")

if launchCommand == "notepad" or "npp" or "n++" or "n":
    launcherFunction(notepadPlusPlusLaunch)

elif launchCommand == "brackets" or "b":
    launcherFunction(bracketsLaunch)

elif launchCommand == "aptana" or "as" or "webide":
    launcherFunction(aptanaLaunch)

elif launchCommand == "dcpp"or "c++":
    launcherFunction(devCppLaunch)

elif launchCommand == "gh" or "github" or "git" or "g":
    launcherFunction(githubLaunch)

elif launchCommand == "android" or "a" or "as":
    launcherFunction(androidLaunch)

elif launchCommand == "java" or "ij" or "idea" or "j":
    launcherFunction(ijLaunch)

elif launchCommand == "python" or "pc" or "p":
    launcherFunction(pycharmLaunch)

elif launchCommand == "code" or "sublime" or "html" or " " or "s" or "php" or "css" or "js" or "jquery":
    launcherFunction(sublimeLaunch)

elif launchCommand == "help":
        print(notepadPlusPlusLaunch, "\n", bracketsLaunch, "\n", aptanaLaunch, "\n", devCppLaunch, "\n",githubLaunch, "\n", androidLaunch, "\n", ijLaunch, "\n",     pycharmLaunch, "\n", sublimeLaunch, "\n", musicLaunch,"\n")

else: 
    print("Invalid Entry")
Run Code Online (Sandbox Code Playgroud)

我没有收到任何错误,但每次运行时,第一个if-statment总是验证为true.所以从这段代码开始,它一直在启动Notepad ++.谁能说出我做错了什么?先感谢您!

Ben*_*ueg 7

if launchCommand == "notepad" or launchCommand == "npp" or launchCommand == "n++" or launchCommand == "n":
Run Code Online (Sandbox Code Playgroud)

甚至更好

if launchCommand in ("notepad", "npp", "n++", "n"):
Run Code Online (Sandbox Code Playgroud)

您的原始if语句将始终求值为,True因为它等效于:

if (launchCommand == "notepad") or ("npp") or ("n++") or ("n"):
Run Code Online (Sandbox Code Playgroud)

和非空字符串True在逻辑操作中被转换为.

看到:

  • 如果你添加一个解释为什么`launchCommand =="notepad"或者launchCommand =="npp"或者launchCommand =="n ++"或者launchCommand =="n"`总是评估为"True",那就太好了. (3认同)