if else语句没有正确遵循elif

时间:2013-03-11 21:21:07

标签: python loops if-statement

我被赋予了一个程序来制作一个程序,它接受用户输入(温度),如果温度是摄氏温度转换为华氏温度,反之亦然。

问题是,当你输入类似35:C的东西时,程序会使用if myscale ==“F”而不是elif myscale ==“C”,即使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")

2 个答案:

答案 0 :(得分:2)

以下内容:

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

应为:

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

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

或(如果你的Python最近足以支持set literals):

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

同样如此
    elif: myscale == "c" or "C":

此外,elif之后还有一个无关的冒号。

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

答案 1 :(得分:0)

这是你的问题:

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

请注意:

后的elif

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