Python3学习笔记4-函数,全局变量&局部变量,内置函数

来源:互联网 发布:光怪兽普利茨墨淘宝 编辑:程序博客网 时间:2024/05/29 18:04

1 Functions

Keyword, Function name, parameters and body.
函数都以关键词def开头,然后是函数名,需要传递的参数,函数体。最后一般会返回值。
早上的for,while笔记中有 Prime Number Generator 代码,能得到30以内的质数,很适合改写成函数。改写成函数后,可以重复利用代码。

def prime_number(num1,num2):    """Find all prime number between num1 and num2.    Use prime_number(num1,num2) command to run it.    When executed,it will return a list of prime numbers.    """    Prime_number = []    for i in range(num1,num2):        j = 2        counter = 0        while j<i:            if i%j == 0:                counter = 1                j = j +1            else:                j = j + 1        if counter == 0:            Prime_number.append(i)        else:            counter = 0    return Prime_number>>> help(prime_number)Help on function prime_number in module __main__:prime_number(num1, num2)    Find all prime number between num1 and num2.    Use prime_number(num1,num2) command to run it.    When executed,it will return a list of prime numbers.>>> prime_number(2,30)[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]>>> prime_number(100,300)[101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293]

2 global and local variables

Local variables exist in functions.
Global variables was defined outside a function. We can use it anywhere.
函数中定义的变量只能在函数内部使用。
函数外定义的变量哪儿都能用。

3 Built_in functions

Python内部有许多内置函数,比如abs(),dir(),help()等。下面是从https://docs.python.org/3/library/functions.html上复制过来的Python Built_in functions.
https://docs.python.org/3/library/functions.html页面有各个函数的详细说明。

The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order.                            Built-in Functions  abs()           dict()      help()          min()       setattr()all()           dir()       hex()           next()      slice()any()           divmod()    id()            object()    sorted()ascii()         enumerate() input()         oct()       staticmethod()bin()           eval()      int()           open()      str()bool()          exec()      isinstance()    ord()       sum()bytearray()     filter()    issubclass()    pow()       super()bytes()         float()     iter()          print()     tuple()callable()      format()    len()           property()  type()chr()           frozenset() list()          range()     vars()classmethod()   getattr()   locals()        repr()      zip()compile()       globals()   map()           reversed()  __import__()complex()       hasattr()   max()           round()  delattr()       hash()      memoryview()    set()    
原创粉丝点击