(一)函数的定义
1 def hello(): 2 print("Hoddy!") 3 print("Hoddy!!") 4 hello() 5 hello()View Code
输出结果:
Hoddy! Hoddy!! Hoddy! Hoddy!!View Code
(二)带有参数的函数
1 def hello(name): 2 print("Hello " + name) 3 hello('sara')View Code
输出结果:
Hello sara
(三)返回值和返回语句
返回语句包含:return关键字和返回值或者表达式
1 mport random 2 def getAnswer(answerNumber): 3 if answerNumber ==1: 4 return 'It is certain' 5 elif answerNumber == 2: 6 return 'It is decidedly so' 7 elif answerNumber == 3: 8 return 'Yes' 9 r = random.randint(1,4) 10 fortune = getAnswer(r) 11 print(fortune)View Code
print(getAnswer(random.randint(1, 9)))
注意:表达式由值和表达式组成,函数的调用可以使用表达式,因为它计算结果为它的返回值
(四)空值(The None value)
>>>spam = print('Hello!')
Hello
>>>None == spam
True
(五)关键字参数和print()
print('Hello')
print('world')
Hello
world
print('Hello',end='')
print('world')
输出:Helloworld
>>>print('cats','dogs','mice')
cats dogs mice
>>>print('cats','dogs','mice',sep=',')
cats,dogs,mice
(六)全局变量和局部变量
1)局部变量不能用于全局范围
1 def spam(): 2 eggs = 3313 3 spam() 4 print(eggs)View Code
2)局部作用域不能使用其他局部作用域中的变量
1 def spam(): 2 eggs = 3313 3 bacon() 4 print(eggs) 5 def bacon(): 6 ham =101 7 eggs =0 8 spam()View Code
3)局部作用域可以读取全局变量
1 def spam(): 2 print(eggs) 3 eggs=43 4 spam() 5 print(eggs)View Code
4)全局和局部作用域中可以使用相同的变量名称
(七)全局声明
1 def spam(): 2 global eggs 3 eggs = 'spam' 4 def bacon(): 5 eggs = 'bacon' 6 7 def ham(): 8 print(eggs) 9 10 eggs=43 11 spam() 12 print(eggs)View Code
输出结果:
spam