1
+ #!/usr/bin/python
2
+ #coding:utf-8
3
+ def sayHi ():
4
+ print 'hi' ;
5
+
6
+ sayHi ();
7
+
8
+ # 只有在形参表末尾的那些参数可以有默认参数值,
9
+ # 即你不能在声明函数形参的时候,
10
+ # 先声明有默认值的形参而后声明没有默认值的形参。
11
+ def greet (name , word = 'hi' ): # word is optional
12
+ print word + ',' + name ;
13
+
14
+ greet ('joel' , 'hello' );
15
+ greet ('jack' );
16
+
17
+ print 10 * '*' , '返回值' , 10 * '*' ;
18
+ def returnNone ():
19
+ pass ;
20
+
21
+ print returnNone (); # None
22
+
23
+ def returnNone2 ():
24
+ 1 + 3 ;
25
+
26
+ print returnNone2 (); # None
27
+
28
+ def returnNone3 ():
29
+ return None ;
30
+
31
+ print returnNone3 (); # None
32
+
33
+ def add (a , b ):
34
+ return a + b ;
35
+
36
+ print add (3 ,5 ); # 8
37
+
38
+
39
+ print 10 * '*' , '变量的作用域' , 10 * '*' ;
40
+ x = 3 ;
41
+
42
+ def func ():
43
+ x = 5 ;
44
+
45
+ func (); # not change global x
46
+ print 'x is still' , x ; #3
47
+
48
+ def func2 ():
49
+ global x ;# tell it's the global x
50
+ x = 10 ;
51
+
52
+ func2 (); # change global x
53
+ print 'x change to' , x ; #10
54
+
55
+ print 20 * '*' ;
56
+ x = 0 ;
57
+ def func3 ():
58
+ x = 1 ;
59
+ y = 'y~~~' ;
60
+ def func4 ():
61
+ print x ; # 0, global is put before this line
62
+ global x ; # always the outest.
63
+ x = 2 ;
64
+ print y ;# can read from outerside
65
+ print x ; #1
66
+ func4 ();
67
+ print x ; #1
68
+
69
+ func3 ();
70
+ print 'x change to' , x ; # 2
71
+
72
+ # 如果你的某个函数有许多参数,
73
+ # 而你只想指定其中的一部分,
74
+ # 那么你可以通过命名来为这些参数赋值——这被称作 关键参数
75
+ # ——我们使用名字(关键字)而不是位置(我们前面所一直使用的方法)来给函数指定实参。
76
+ print 10 * '*' , '关键参数' , 10 * '*' ;
77
+ def keyParamFunc (a , b = 5 , c = 10 ):
78
+ print 'a is' , a , 'and b is' , b , 'and c is' , c
79
+
80
+ keyParamFunc (3 , 7 )
81
+ keyParamFunc (25 , c = 24 )
82
+ keyParamFunc (c = 50 , a = 100 )
83
+
84
+
85
+ print 10 * '*' , '函数文档' , 10 * '*' ;
86
+ def printMax (x , y ):
87
+ '''函数描述: Prints the maximum of two numbers.
88
+
89
+ The two values must be integers.'''
90
+ x = int (x ) # convert to integers, if possible
91
+ y = int (y )
92
+
93
+ if x > y :
94
+ print x , 'is maximum'
95
+ else :
96
+ print y , 'is maximum'
97
+
98
+ printMax (3 , 5 )
99
+ print printMax .__doc__
0 commit comments