python基础4----调用函数

Python内置了很多有用的函数,我们可以直接调用。

要调用一个函数,需要知道函数的名称和参数,可以直接从Python的官方网站查看文档:

http://docs.python.org/3/library/functions.html#abs

也可以在交互式命令行通过help(函数名)查看函数的帮助信息。

下面来简单介绍几种函数的使用方法:

 = hex(1)  #将整数转换为十六进制
print(a)
>>>0x1

b = abs(-2)  #求绝对值,只能有一个参数
print(b)
>>>2

c = max(1,-2,4,0,10)  #取最大值
print(c)
>>>10

d = int(2.12)   #转换为整型
print(d)
>>>2

e = float(1)   #转换为浮点型
print(e)
>>>1.0

f = str(6.8)   #转换为字符串类型
print(f)
>>>6.8

g = bool()   #转换为布尔值
print(g)
>>>True

h = bool(1)   #转换为布尔值
print(h)
>>>Flase

调用函数

调用函数的时候,如果传入的参数数量不对,会报TypeError的错误,并且Python会明确地告诉你:abs()有且仅有1个参数,但给出了两个:

>>> abs(1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: abs() takes exactly one argument (2 given)

如果传入的参数数量是对的,但参数类型不能被函数所接受,也会报TypeError的错误,并且给出错误信息:str是错误的参数类型:

>>> abs('a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for abs(): 'str'

max函数max()可以接收任意多个参数,并返回最大的那个:

>>> max(1, 2)
2
>>> max(2, 3, 1, -5)
3
数据类型
转换

Python内置的常用函数还包括数据类型转换函数,比如int()函数可以把其他数据类型转换为整数:

>>> int('123')
123
>>> int(12.34)
12
>>> float('12.34')
12.34
>>> str(1.23)
'1.23'
>>> str(100)
'100'
>>> bool(1)
True
>>> bool('')
False

函数名其实就是指向一个函数对象的引用,完全可以把函数名赋给一个变量,相当于给这个函数起了一个“别名”:

a = hex   #变量a增向hex函数
print(a(1))   #所以也可以通过a调用hex函数
>>>0x1

注:此为学习笔记

原文地址:https://www.cnblogs.com/hm-baobao/p/7060737.html