1. 程式人生 > >Python3學習筆記4-函式,全域性變數&區域性變數,內建函式

Python3學習筆記4-函式,全域性變數&區域性變數,內建函式

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

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()