9 月 162020
 
PS C:\Users\harveymei> python
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> def fahrenheit_converter(C):
...     fahrenheit = C * 9 / 5 + 32
...     return str(fahrenheit) + 'F'
...
>>> fahrenheit_converter(30)
'86.0F'
>>> C = 40
>>> fahrenheit_converter(C)
'104.0F'
>>> exit()
PS C:\Users\harveymei> 

#自定义函数,摄氏度转换为华氏度
#Celsius 2 Fahrenheit
def fahrenheit_converter(C):
    fahrenheit = C * 9 / 5 + 32
    return str(fahrenheit) + 'F'
# 变量fahrenheit为float数值,与字符串F合并,需要使用str()函数转换
# 以下开始调用函数
# 摄氏温度35度,使用转换函数并赋值给变量C2F
C2F = fahrenheit_converter(35)
#打印C2F值
print(C2F)
PS C:\Users\harveymei> & C:/Users/harveymei/AppData/Local/Programs/Python/Python38/python.exe c:/Users/harveymei/hello.py
95.0F
PS C:\Users\harveymei> 
不使用str()函数处理的float数值与字符串合并异常
PS C:\Users\harveymei> & C:/Users/harveymei/AppData/Local/Programs/Python/Python38/python.exe c:/Users/harveymei/hello.py
Traceback (most recent call last):
  File "c:/Users/harveymei/hello.py", line 9, in <module>
    C2F = fahrenheit_converter(35)
  File "c:/Users/harveymei/hello.py", line 5, in fahrenheit_converter
    return fahrenheit + 'F'
TypeError: unsupported operand type(s) for +: 'float' and 'str'
PS C:\Users\harveymei>

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)