【问题标题】:Python Function to convert temperature does not work properly [duplicate]转换温度的Python函数无法正常工作[重复]
【发布时间】:2020-08-28 10:42:16
【问题描述】:

我是 Python 的新手,我正在做一个练习,我应该从摄氏转换为华氏,反之亦然。我正在尝试通过一个应该处理用户输入并将其转换的函数来做到这一点。不幸的是,我被卡住了,因为它只是部分起作用,我不明白问题出在哪里。这是我的代码:

Temperature = int(input("Give an int as temperature"))

Unit = input("insert 'C' or 'F' as unit")

Mix_input = [(Temperature, Unit)] 



def convert_f_c(x):
    for t, u in x:
        if u == "C" or "c":
            F = round((1.8 * t) + 32)
            print("Converted Temp:{}F".format(F))
        elif u == "F" or "f":
            C = round((t-32)/ 1.8)
            print("Converted Temp:{}C".format(C))
        else:
            print("You typed something wrong")


convert_f_c(Mix_input)

如果我输入摄氏温度,它会按预期工作:

Give an int as temperature 60
insert 'C' or 'F' as unit c
Converted Temp:140F

但是在华氏温度下,我得到一个错误的输出:

Give an int as temperature 45
insert 'C' or 'F' as unit F
Converted Temp:113F

小写也会出现这种情况:

Give an int as temperature 45
insert 'C' or 'F' as unit f
Converted Temp:113F

预期的输出是:

Give an int as temperature 45
insert 'C' or 'F' as unit f
Converted Temp:7.2C

此外,如果我输入不同的内容,我不会收到错误消息:“您输入了错误的内容”,正如预期的那样,但是:

Give an int as temperature 145
insert 'C' or 'F' as unit r
Converted Temp:293F

【问题讨论】:

  • 你可以改成这样if u.lower() == 'c'

标签: python function input


【解决方案1】:

你做到了:

if u == "C" or "c":

elif u == "F" or "f":

由于operator priority,这些工作实际上是:

if (u == "C") or "c":

elif (u == "F") or "f":

由于所有非空字符串在python中都是真的,这些条件总是满足的。为避免这种情况,您可以这样做:

if u == "C" or u == "c":

if u in ["C", "c"]:

if u.lower() == "c":

(与elif 相同)。 in是会员,lower把str转成小写。

【讨论】:

    【解决方案2】:

    u == "C" or "c" 更改为if u == "C" or u== "c"

    or "c" 永远是真实的,这就是你得到错误的原因(elif u == "F" or "f" 也是如此)

    【讨论】: