Python 简易温度转换器
我对编程相当陌生,并已决定以Python作为入门。无论如何,我似乎不明白为什么我写的这个温度转换脚本没有运行Python 简易温度转换器,python,python-2.x,string-parsing,temperature,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
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()
它返回一个TypeError:
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'
回溯(最近一次呼叫最后一次):
文件“C:/Users/Brandon/PycharmProjects/IntroTo/Ch1/Exercises.py”,第32行,在
转换()
文件“C:/Users/Brandon/PycharmProjects/IntroTo/Ch1/Exercises.py”,第24行,转换为
转换为华氏温度(cels)
文件“C:/Users/Brandon/PycharmProjects/IntroTo/Ch1/Exercises.py”,第8行,转换为华氏温度
f=c*9/5+32
TypeError:/:“str”和“int”的操作数类型不受支持
一个问题是,您将和字符串传递给前两个函数,但希望它是一个浮点。您可以通过将从字符串获得的值转换为浮点值来解决此问题。你应该这么做
c = float(celcius)
在第一个函数中,以及
f = float(farenheit)
在第二个
另一个问题是需要在
(c,f)
和(f,c)
之间加上括号,以便%
正常工作
您可能还想做的另一件事是询问用户是否希望将cel转换为far或其他方式。如果符合以下条件,则可以使用
:
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)
您可能应该包含运行程序时遇到的异常。如果你知道问题出在哪里,也写下来。对不起,我是新来的。我得到了“TypeError:unsupported operation type for/:'str'和'int'”,很高兴您添加了关于您的问题的更多信息!不过,最好的方式是编辑你的帖子。太好了,现在你有一个好问题。获得一个向上的投票:)为了更喜欢(OP),允许他们输入一个单位为“33摄氏度”、“-4.6华氏度”的温度。然后解析单元并调用相应的转换函数。只有他们忘记了单位,才提示他们输入哪些单位?@smci是的,这很好,但让我们把实现这一点留给OP:)我肯定会搞砸的。谢谢你的帮助@xponent:当你有工作代码并且想要对风格、分解、清晰性、好的习惯用法、简洁性等进行全面的回顾时,使用姐妹网站