1.程序的循环结构:
要注意其中for/while+else这种用法
2.异常处理:和VB.NET一样,有try+except,但需要注意的是另一种方式:
try:
#语句1
except:
#语句2
else:
#语句3
finally:
#语句4
##如果语句1发生错误那么运行语句2和语句4,如果没有发生错误就
##运行语句3和语句4.也就是说,else是语句没问题的时候执行,
##finally是不管有没有错误都执行
3.函数的定义方式:
def test(m,n):
s = 1
for i in range(1,m)
s=i
return m+n
4.指定参数类型的函数定义方式:
def test(text:'str',max:'int > 0' = 100,min:'int > 0')->str
##不仅限定了参数类型,还限定了传参范围,下面这种方式也可以:
def test(a:str,b:int,c:float)->str
但是需要注意:当我们违背了预设的返回值类型的时候,只会提出警告而不报错。python是动态而灵活的。
5.复杂的类型限定:可以自己定义一个类型,类似structure
from typing import Dict, Tuple, Sequence
ConnectionOptions = Dict[str, str]
Address = Tuple[str, int]
Server = Tuple[Address, ConnectionOptions]
def broadcast_message(message: str, servers: Sequence[Server]) -> None:
...
# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
message: str,
servers: Sequence[Tuple[Tuple[str, int], Dict[str, str]]]) -> None:
...
):
...
6.可选参数传递:
def test(n,m=1): #m为可选参数
s = 1
for i in range(1,n+1):
s *= i
print(s//m)
test(10)
test(10,2)
7.可变参数传递:
def test(n,*args):#args为可变参数,接收到的是一个tuple
s = 1
for i in range(1,n+1):
s += i
for item in args:
s += item
print(s)
test(10,3)
test(10,3,1,5)
8.tuple和dict类型的可变参数传递:使用的时候必须把"*args"放在"**kwargs"前面
def test(*args,**kwargs):
print("args =",args)
print("kwargs =",kwargs)
print("----------------------------------")
if __name__ == '__main__':
test(1,5,94,564)
test(a=1,b=2,c=3)
test(1,2,3,4,a=1,b=2,c=3)
test('I love python',1,None,a=1,b=2,c=3)
函数执行结果:
9.lambda函数:lambda函数是一种匿名函数,即没有名字的函数;lambda函数用于定义简单的、能够在一行内表示的函数。
g = lambda x,y:x*y
print(g(4,5))
引用了:https://www.cnblogs.com/wenwei-blog/p/10592541.html和https://www.cnblogs.com/linkenpark/p/11676297.html