流程控制语句:
# Fibonaacci series: # the sum of two elements defines the next a,b = 0,1 while b<100: print(b,) a,b=b,a+b | # range() 函数 print(range(10)) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] range(0, 10, 3) #[0, 3, 6, 9] a = ['北京', '上海', '深圳', '天津', '南京', '苏州'] for i in range(len(a)): print(i, a[i]) |
# if语句 x = int(input("Please enter an integer:")) if x < 0: x = 0 print("Negative changed to zero") elif x==0: print('Zero') elif x==1: print('Single') else: print('More') #pytohn循环体是缩进的: 缩进是python组织语句的方法。 不提供集成的行编辑功能,所以要为每一个缩进提供Tab/空格。 | # break, continue, break语句 import re def searchtext(): print('''Search the text in str''') try: line = '_testcodes' mstchobj = re.search(r'.*test.*', line) print(mstchobj.group()) except: print('not found') else: print('found success!') finally: print('Done') |
# for 语句 words = ['defenestrate', 'cat', 'window'] for w in words[:]: if len(w) > 6: words.insert(0,w) print(words) | #continue for i in range(2, 10): if i%2 == 0: print('found an even number', i) else: print('found a number', i) for i in range(2, 10): if i%2 == 0: print('found an even number', i) continue print('found a number', i) |
#pass class MyEmptyClass: pass def initlog(*args): pass |
函数体:
#定义函数:def def fib(n): """Print a fibonacci series up to n.""" a,b = 0,1 while a<n: print(a) a,b = b,a+b fib(10) def fib2(n): """Return a list containing the Fibonacci series up to n.""" result = [] a,b = 0,1 while a < n: result.append(a) a,b = b,a+b return result f100 = fib2(100) print(f100) | #默认值只被赋值一次。。 #eg下面的函数在后续调用过程中会累积(前面)传给它的参数: def f(a, L = []): L.append(a) return L #print(f(3)) #若不想在随后的调用中共享默认值,可以这样写: def f1(a, L = None): if L is None: L = [] L.append(a) return L print(f1(1)) print(f1(2)) print(f1(3)) |
参数:
#关键字参数 def parrot(voltage, state='a stiff', action = 'voom', type) def parrot(voltage, state='a stiff', action = 'voom', type= 'Norwegian Blue'): print("--This parrot wouldn't", action,) print("if you put", voltage, "volts through it.") print("--Lovely plumage, the", type) print("--It's", state, "!") | #接受一个必选参数以及三个可选参数 parrot(100) parrot(100, "a smart worker") |
def cheeseshop(kind, *arguments, **keywords): print("--Do you have any", kind, "?") print("--I'm sorry, we're all out of", kind) for arg in arguments: print(arg) print("-" * 40) keys = sorted(keywords.keys()) for kw in keys: print(kw, ":", keywords[kw]) cheeseshop("Limburger", "It's very runny, sir.", "It's really very, VERY runny, sir.", shopkeeper = 'Michael Palin', Client = 'John Cleese', sketch = 'Cheese Shop Sketch') | #引入一个形如**name的参数时,它接收一个字典,组合使用形如*name的形式参数,它接收一个元组,包含了所有没有出现在形式参数列表中的参数值。*name必须在**name之前出现 |
# 可变参数列表\ def write_multiple_items(file, separator, *args): file.write(separator.join(args)) with open("result.txt", 'w') as file: write_multiple_items(file, "operate", "test", "performance") | |
#参数列表的分拆 list(range(3, 6)) print(list(range(3, 6))) # normal call with separate arguments args = [3, 6] print(list(range(*args))) # call with arguments unpacked from a list | |
#用**操作符分拆关键字参数为字典 def parrot1(voltage, state='a stiff', action = 'voom'): print("--This parrot wouldn't", action,) print("if you put", voltage, "volts through it.") print("--It's", state, "!") d = {"voltage":"four million", "state":"bleedin'demised", "action":"VOOM"} parrot1(**d) | |
#Lambda形式 #使用lambda表达式返回一个函数 def mi(n): return lambda x: x+n f = mi(30) print(f(3)) print(f(5)) | |
#将一个小函数作为参数传递 pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] pairs.sort(key = lambda pair: pair[0]) print(pairs) | |
#文档字符串 """ this is.... only to document""" |