if condition_1: statement_block_1 elif condition_2: statement_block_2 else: statement_block_3
while condition: statement_block else: # 無關緊要 statement_block
for <variable> in <sequence>: <statements> else: <statements>
>>> a = list(range(3)) >>> a [0, 1, 2] >>> a = list(range(1, 5, 2)) >>> a [1, 3]
>>> a = [1, 2, 3, 4] >>> it = iter(a) >>> next(it) 1 >>> next(it) 2 >>> next(it) 3 >>> next(it) 4 >>> next(it) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>> it = iter(a) >>> for i in it: ... print(i) ... 1 2 3 4 >>>
class MyNumbers: def __iter__(self): self.a = 1 return self def __next__(self): if self.a <= 5: x = self.a self.a += 1 return x else: raise StopIteration myclass = MyNumbers() myiter = iter(myclass) for i in range(5): print(next(myiter)) for x in myiter: print(x) >>> 1 2 3 4 5
import sys def fibonacci(n): # 生成器函數 - 斐波那契 a, b, counter = 0, 1, 0 while True: if counter > n: return yield a a, b = b, a + b counter += 1 f = fibonacci(10) # f 是一個迭代器,由生成器返回生成 while True: try: print(next(f), end=" ") except StopIteration: sys.exit() >>> 0 1 1 2 3 5 8 13 21 34 55
def function_name(args1, args2): statement return
在 Python 中,strings, tuples, 和 numbers 是不可更改的對象,而 list, dict 等則是能夠修改的對象。html
Python 函數的參數傳遞:python
參數c++
def functionname([formal_args,] *var_args_tuple ): "函數_文檔字符串" function_suite return [expression]
def functionname([formal_args,] **var_args_dict ): "函數_文檔字符串" function_suite return [expression]
匿名函數express
sum = lambda arg1, arg2: arg1 + arg2 print ("相加後的值爲 : ", sum( 10, 20 )) print ("相加後的值爲 : ", sum( 20, 20 )) >>> 相加後的值爲 : 30 相加後的值爲 : 40
vec = [2, 4, 6] [3 * x for x in vec if x > 3] >>> [12, 18] matrix = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ] [[row[i] for row in matrix] for i in range(4)] >>> [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
a = [2, 4, 6] for i, v in enumerate(a): print(i, v) >>> 0 2 1 4 2 6 >>> b = ['sen', 'ius', 'en'] >>> for i, j in zip(a, b): ... print(i, j) ... 2 sen 4 ius 6 en >>> for i in reversed(a): ... print(i) ... 6 4 2 >>> for i in sorted(b): ... print(i) ... en ius sen >>>
參考資料 菜鳥教程函數
獲取更多精彩,請關注「seniusen」! ui