调用函数

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

要调用一个函数,需要知道函数的名称和参数,比如求绝对值的函数abs,只有一个参数。可以直接从Python的官方网站查看文档:

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

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

调用abs函数:

  1. >>> abs(100)
  2. 100
  3. >>> abs(-20)
  4. 20
  5. >>> abs(12.34)
  6. 12.34

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

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

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

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

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

  1. >>> max(1, 2)
  2. 2
  3. >>> max(2, 3, 1, -5)
  4. 3

数据类型转换

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

  1. >>> int('123')
  2. 123
  3. >>> int(12.34)
  4. 12
  5. >>> float('12.34')
  6. 12.34
  7. >>> str(1.23)
  8. '1.23'
  9. >>> str(100)
  10. '100'
  11. >>> bool(1)
  12. True
  13. >>> bool('')
  14. False

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

  1. >>> a = abs # 变量a指向abs函数
  2. >>> a(-1) # 所以也可以通过a调用abs函数
  3. 1

练习

请利用Python内置的hex()函数把一个整数转换成十六进制表示的字符串:

  1. # -*- coding: utf-8 -*-
  2. n1 = 255
  3. n2 = 1000
  4. print(???)

小结

调用Python的函数,需要根据函数定义,传入正确的参数。如果函数调用出错,一定要学会看错误信息,所以英文很重要!

参考源码

call_func.py