【问题标题】:if else statment not following the elif correctly [duplicate]if else 语句未正确遵循 elif [重复]
【发布时间】:2013-03-11 21:21:06
【问题描述】:

我的任务是编写一个程序,该程序接受用户输入(温度),如果温度是摄氏温度,则转换为华氏温度,反之亦然。

问题在于,当您键入类似 35:C 的内容时,即使 myscale 是 C 我的代码,程序也会使用 if myscale == "F" 而不是 elif myscale == "C":

mytemp = 0.0
while mytemp != "quit":
    info = raw_input("Please enter a temperature and a scale. For example - 75:F " \
                       "for 75 degrees farenheit or 63:C for 63 degrees celcius "\
                       "celcious. ").split(":")
    mytemp = info[0]
    myscale = str(info[1])

    if mytemp == "quit":
        "You have entered quit: "
    else:
        mytemp = float(mytemp)
        scale = myscale
        if myscale == "f" or "F":
            newtemp = round((5.0/9.0*(mytemp-32)),3)
            print "\n",mytemp,"degrees in farenheit is equal to",newtemp,"degrees in 
            celcius. \n" 
        elif: myscale == "c" or "C":
            newtemp = 9.0/5.0*mytemp+32
            print "\n",mytemp,"degrees in celcius is equal to",newtemp,"degrees in 
            farenheit. \n"
        else:
            print "There seems to have been an error; remember to place a colon (:) 
                  between "\
                  "The degrees and the letter representing the scale enter code here. "
raw_input("Press enter to exit")

【问题讨论】:

    标签: python loops if-statement


    【解决方案1】:

    以下内容:

        if myscale == "f" or "F":
    

    应改为:

        if myscale == "f" or myscale == "F":
    

        if myscale in ("f", "F"):
    

    或者(如果你的 Python 足够新,可以支持集合文字):

        if myscale in {"f", "F"}:
    

    同样的道理

        elif: myscale == "c" or "C":
    

    另外,elif 后面还有一个多余的冒号。

    你现在拥有的东西在语法上是有效的,但做的事情与预期的不同。

    【讨论】:

    • 具体来说,条件解析与(myscale=="f") or "F"相同,而"F"——作为非空字符串——将始终评估为真。
    【解决方案2】:

    这是你的问题:

    elif: myscale == "c" or "C":
    

    注意elif后面的:

    如其他答案所述,您还应该使用 in

    【讨论】: