Skip to main content
 首页 » 编程设计

python之简单的 Python 温度转换器

2025年05月04日34zfyouxi

我是编程新手,我决定从 Python 入手。无论如何,我似乎无法弄清楚为什么我编写的这个温度转换脚本没有运行。

def convert_to_fahrenheit(celsius): 
 
    c = celsius 
    f = c * 9 / 5 + 32 
    print '%r Celsius, converted to Fahrenheit, is: %r Fahrenheit.' % c, f 
 
 
def convert_to_celsius(fahrenheit): 
 
    f = fahrenheit 
    c = (f - 32) * 5 / 9 
    print '%r Fahrenheit, converted to Celsius, is: %r Celsius.' % f, c 
 
 
def convert(): 
 
    print 'To convert a temperature from Celsius to Fahrenheit:' 
    cels = raw_input('CELSIUS: ') 
    print '' 
    convert_to_fahrenheit(cels) 
 
    print '' 
    print 'To convert a temperature from Fahrenheit to Celsius:' 
    fahr = raw_input('FAHRENHEIT: ') 
    convert_to_celsius(fahr) 
 
 
convert() 

它返回一个类型错误:

Traceback (most recent call last): 
  File "C:/Users/Brandon/PycharmProjects/IntroTo/Ch1/Exercises.py", line 32,     in <module> 
    convert() 
  File "C:/Users/Brandon/PycharmProjects/IntroTo/Ch1/Exercises.py", line 24,     in convert 
    convert_to_fahrenheit(cels) 
  File "C:/Users/Brandon/PycharmProjects/IntroTo/Ch1/Exercises.py", line 8,      in convert_to_fahrenheit 
    f = c * 9 / 5 + 32 
TypeError: unsupported operand type(s) for /: 'str' and 'int' 

请您参考如下方法:

一个问题是您将 and string 传递给前两个函数,但期望它是一个 float 。您可以通过将从字符串获得的值转换为 float 来解决它。你应该这样做

c = float(celcius) 

在第一个函数中,和

f = float(farenheit) 

在第二个。


另一个问题是您需要在 (c, f) 和 (f, c) 两边加上括号,以便 % 正常工作.


您可能还想做的另一件事是询问用户是想将 cel 转换为 far 还是相反。您可以使用 if 来做到这一点:

def convert(): 
 
    user_input = raw_input('From what do you want to convert?: ') 
 
    if user_input == 'celsius': 
        print 'To convert a temperature from Celsius to Fahrenheit:' 
        cels = raw_input('CELSIUS: ') 
        convert_to_fahrenheit(cels) 
 
    elif user_input == 'farenheit': 
        print 'To convert a temperature from Fahrenheit to Celsius:' 
        fahr = raw_input('FAHRENHEIT: ') 
        convert_to_celsius(fahr)