温度转换

2024-04-18 10:08:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图编写一个python函数,它可以在摄氏度和farenheit之间进行转换,然后编写一个程序,首先提示输入温度刻度(c或f),然后再输入温度值,然后再转换成另一个。到目前为止我所拥有的:

def convert_temp( source_temp, scale):
    if scale == 'c':
        return(tmp-32.0)*(5.0/9.0)
    elif scale == 'f':
        return(tmp*(9.0/5/0))+32

source_temp = int(input)'Key in temp:'))
scale = input('(c) or (f)?')
y = conv(source_temp,scale)
print(tmp, 'in ',scale,"='s",y)

但是,当我试图运行这个程序时,我收到了很多回溯和语法错误。我做错什么了??在


Tags: 函数in程序sourceconvertinputreturndef
3条回答

替换此项:

9.0/5/0        # you will get ZeroDivisionError

收件人:

^{pr2}$

替换此项:

source_temp = int(input)'Key in temp:')) # there should be opening bracket after input

收件人:

source_temp = int(input('Key in temp:'))

替换此项:

y = conv(source_temp,scale)

收件人:

y = conv_temp(source_temp,scale)

更改您的打印声明:

print(source_tmp, 'in ',scale,"='s",y)       # here tmp was not defined, its source_tmp

此语句中括号不平衡至少是问题的一部分:

source_temp = int(input)'Key in temp:'))

试试这个:

^{pr2}$

另外:conv()convert_temp()不同,raw_input()而不是{},被零除等等

你的代码中有很多问题。在

def convert_temp( source_temp, scale):
    if scale == 'c':
        return(tmp-32.0)*(5.0/9.0)
    elif scale == 'f':
        return(tmp*(9.0/5/0))+32

首先,tmp在此范围内未定义。您的参数名为source_temp,而不是tmp。更改函数定义将修复该错误。另外,你在你的一个表达式中打错了字,用斜杠代替了一个点。此功能将正常工作:

^{pr2}$

接下来,您在程序主体中出现了一些语法错误:

source_temp = int(input)'Key in temp:'))

这一行的括号不匹配。应该是的

source_temp = int(input('Key in temp:'))

再往下看:

y = conv(source_temp,scale)

conv()不是函数。相反,您应该使用您定义的convert_temp()函数

y = convert_temp(source_temp,scale)

最后

print(tmp, 'in ',scale,"='s",y)

tmp现在未定义。使用您定义的source_temp变量,如下所示:

print(source_temp, ' in ',scale," ='s ",y)

相关问题 更多 >