# 【python基础】3-函数

2018-02-27 11:14:50来源:https://www.jianshu.com/p/fc17f347094e作者:王诗翔人点击

def：定义函数
print 函数
range 函数
type 函数

def：定义函数
``#!/usr/bin/python3# ----- function without arguments -----def greeting():    print("-----------------------------")    print("         Hello World         ")    print("-----------------------------")greeting()# ----- 带参数的函数 -----def sum_two_numbers(num1, num2):    total = num1 + num2    print("{} + {} = {}".format(num1, num2, total))sum_two_numbers(3, 4)# ----- 带返回值的函数 -----def num_square(num):    return num * nummy_num = 3print(num_square(2))print(num_square(my_num))``

`def`关键字用于定义函数

Python文档 - 编码风格

`format`包含在下一个主题中
``\$ ./functions.py-----------------------------         Hello World-----------------------------3 + 4 = 749``

``#!/usr/bin/python3# ----- function with default valued argument -----def greeting(style_char='-'):    print(style_char * 29)    print("         Hello World         ")    print(style_char * 29)print("Default style")greeting()print("/nStyle character *")greeting('*')print("/nStyle character =")greeting(style_char='=')``

``\$ ./functions_default_arg_value.pyDefault style-----------------------------         Hello World-----------------------------Style character ******************************         Hello World*****************************Style character ==============================         Hello World=============================``

``def num_square(num):    """    returns square of number    """    return num * num``

Python文档 - 定义函数
Python文档 - 内置函数

print函数

``>>> print("hi")hi>>> print("hi", end='')hi>>>>>> print("hi", end=' !!/n')hi !!>>>``

help函数可以用来从解释器获取函数的快速使用帮助
`q`从帮助页面退出
``>>> help(print)Help on built-in function print in module builtins:print(...)    print(value, ..., sep=' ', end='/n', file=sys.stdout, flush=False)    Prints the values to a stream, or to sys.stdout by default.    Optional keyword arguments:    file:  a file-like object (stream); defaults to the current sys.stdout.    sep:   string inserted between values, default a space.    end:   string appended after the last value, default a newline.    flush: whether to forcibly flush the stream.``

``>>> a = 5>>> b = 2>>> print(a+b, a-b)7 3>>> print(a+b, a-b, sep=' : ')7 : 3>>> print(a+b, a-b, sep='/n')73``

``>>> greeting = 'Hello World'>>> print(greeting)Hello World>>> num = 42>>> print(num)42>>> print(greeting + '. We are learning Python')Hello World. We are learning Python>>> print(greeting, '. We are learning Python', sep='')Hello World. We are learning Python>>> print("She bought " + num + " apples")Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: Can't convert 'int' object to str implicitly>>> print("She bought " + str(num) + " apples")She bought 42 apples``

``>>> print("She bought", num, "apples")She bought 42 apples>>> items = 15>>> print("No. of items:", items)No. of items: 15>>> print("No. of items:", items, sep='')No. of items:15``

``>>> import sys>>> print("Error!! Not a valid input", file=sys.stderr)Error!! Not a valid input``

`str.format()`可以用来设定字符串的风格，处理多个字符串时比粘连方式更优雅
``>>> num1 = 42>>> num2 = 7>>> '{} + {} = {}'.format(num1, num2, num1 + num2)'42 + 7 = 49'# 或者将格式保存为一个变量然后在需要的地方使用>>> op_fmt = '{} + {} = {}'>>> op_fmt.format(num1, num2, num1 + num2)'42 + 7 = 49'>>> op_fmt.format(num1, 29, num1 + 29)'42 + 29 = 71'# 在print函数内部使用也当然没问题>>> print('{} + {} = {}'.format(num1, num2, num1 + num2))42 + 7 = 49``

``>>> num142>>> num27>>> print("{0} + {1} * {0} = {2}".format(num1, num2, num1 + num2 * num1))42 + 7 * 42 = 336``

``>>> appx_pi = 22 / 7>>> appx_pi3.142857142857143# 在小数点后限制数字的位数# 数值会进行取舍>>> print("{0:.2f}".format(appx_pi))3.14>>> print("{0:.3f}".format(appx_pi))3.143# 对齐>>> print("{0:<10.3f} and 5.12".format(appx_pi))3.143      and 5.12>>> print("{0:>10.3f} and 5.12".format(appx_pi))     3.143 and 5.12# 用0填充>>> print("{0:08.3f}".format(appx_pi))0003.143``

``>>> print("42 in binary = {:b}".format(42))42 in binary = 101010>>> print("42 in octal = {:o}".format(42))42 in octal = 52>>> print("241 in hex = {:x}".format(241))241 in hex = f1# 通过#添加0b/0o/0x前缀>>> print("42 in binary = {:#b}".format(42))42 in binary = 0b101010>>> hex_str = "{:x}".format(42)>>> hex_str'2a'# 也可以使用内置的format函数>>> format(42, 'x')'2a'>>> format(42, '#x')'0x2a'# 将字符串转换为整型>>> int(hex_str, base=16)42>>> int('0x2a', base=16)42``

`r`前缀相似，使用`f`前缀可以用来表示格式化的字符串
Python v3.6引进

`str.format()`相似，在`{}`中指定变量/表达式
``>>> num1 = 42>>> num2 = 7>>> f'{num1} + {num2} = {num1 + num2}''42 + 7 = 49'>>> print(f'{num1} + {num2} = {num1 + num2}')42 + 7 = 49>>> appx_pi = 22 / 7>>> f'{appx_pi:08.3f}''0003.143'>>> f'{20:x}''14'>>> f'{20:#x}''0x14'``

Python文档 - 格式化字符串 - 更多信息和例子
Python docs - f-strings - 更多例子和告诫

range函数

`range(stop)`
`range(start, stop)`
`range(start, stop, step)`

Python文档 - Ranges - 更多信息和例子
``>>> range(5)range(0, 5)>>> list(range(5))[0, 1, 2, 3, 4]>>> list(range(-2, 2))[-2, -1, 0, 1]>>> list(range(1, 15, 2))[1, 3, 5, 7, 9, 11, 13]>>> list(range(10, -5, -2))[10, 8, 6, 4, 2, 0, -2, -4]``

type函数

``>>> type(5)<class 'int'>>>> type('Hi there!')<class 'str'>>>> type(range(7))<class 'range'>>>> type(None)<class 'NoneType'>>>> type(True)<class 'bool'>>>> arr = list(range(4))>>> arr[0, 1, 2, 3]>>> type(arr)<class 'list'>``

``#!/usr/bin/python3def print_num():    print("Yeehaw! num is visible in this scope, its value is: " + str(num))num = 25print_num()``

Python docs - 默认参数值 - 查看默认数值使用的描述
``\$ ./variable_scope_1.pyYeehaw! num is visible in this scope, its value is: 25``

``#!/usr/bin/python3def square_of_num(num):    sqr_num = num * numsquare_of_num(5)print("5 * 5 = {}".format(sqr_num))``

``\$ ./variable_scope_2.pyTraceback (most recent call last):  File "./variable_scope_2.py", line 7, in <module>    print("5 * 5 = {}".format(sqr_num))NameError: name 'sqr_num' is not defined``

``#!/usr/bin/python3def square_of_num(num):    global sqr_num    sqr_num = num * numsquare_of_num(5)print("5 * 5 = {}".format(sqr_num))``

``\$ ./variable_scope_3.py5 * 5 = 25``

``#!/usr/bin/python3sqr_num = 4def square_of_num(num):    sqr_num = num * num    print("5 * 5 = {}".format(sqr_num))square_of_num(5)print("Whoops! sqr_num is still {}!".format(sqr_num))``

``\$ ./variable_scope_4.py5 * 5 = 25Whoops! sqr_num is still 4!``

Python文档 - 作用域示例
Python文档 - global语句