python - 简单的 Python 温度转换器

标签 python python-2.x string-parsing temperature

我是编程新手,我决定从 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)

关于python - 简单的 Python 温度转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32772567/

相关文章:

python - Tkinter 跟踪和值错误 : invalid literal for int() with base 10: ''

python - 线程条件变量 : un-acquired lock

python - 如何在配置文件中存储格式化字符串?

python - 如何使用多个参数在python中加入url

python - 如何将一个 Sphinx 角色转换为另一个角色?

c++ - rdbuf 对比 getline 对比 ">>"

c - 将字符串解析为单独的元素

javascript - 搜索数字字符串

python - 并发 future 以非阻塞方式将任务提交到进程池

python - 将 txt 文件转换为 int 数组