将需要多次执行的代码放在一起,消除代码段复制粘贴的重复
1. def func_name(parameter_list):
2. return value
#!/usr/bin/env python3
# coding=utf-8
import random
def getAnswer(answerNumber):
if answerNumber == 1 :
return 'it is certain'
elif answerNumber == 2:
return 'it is decidedly so'
elif answerNumber == 3:
return 'Yes'
elif answerNumber == 4:
return 'Reply hazy try again'
elif answerNumber == 5:
return 'Ask again later'
elif answerNumber == 6:
return 'Concentrate and ask again'
elif answerNumber == 7:
return 'My reply is no'
elif answerNumber == 8:
return 'Outlook not so good'
elif answerNumber == 9:
return 'Very doubtful'
print(getAnswer(random.randint(1,9)))
None值,NoneType数据类型的唯一值,表示没有值,类似NULL
1. print()的返回值是None
2. 对于没有return语句或不返回值的return语句的函数,python都会在末尾加上return None
>>> a = print('hello')
hello
>>> a == None
True
大多数参数是由它们在函数调用中的位置来识别的,比如randint(1,9),返回[1,9]范围的一个随机整数
关键字参数,由函数调用时加在它们前面的关键字来识别的,常用于可选变元
1. print()的可选变元end–在参数末尾打印什么,默认为换行
2. sep–在参数之间打印什么来分隔,默认为空格
#!/usr/bin/env python3
# coding=utf-8
print('hello')
print('world') #输出两行,因为print()默认换行
print('hello', end=' ') #输出一行,用一个空格替代了换行符
print('world')
print('cats', 'dogs', 'mice') # 输出cats dogs mice
print('cats', 'dogs', 'mice', sep=',') # 输出cats,dogs,mice
一个程序中只有一个全局作用域,在程序开始时创建,程序终止时销毁;一个函数被调用时,就创建了一个局部作用域,函数调用返回时,属于这个局部作用域的变量被销毁
1. 函数的局部作用域:在被调函数内赋值的变元和变量
2. 全局作用域:在所有函数之外赋值的变量
3. 全局作用域的代码不能使用任何局部变量
#!/usr/bin/env python3
# coding=utf-8
def spam():
eggs = 10
spam()
print(eggs) # 执行将报错NameError: name 'eggs' is not defined
#!/usr/bin/env python3
# coding=utf-8
def spam():
print(eggs)
eggs = 10
spam() #输出 10
print(eggs) #输出 10
#!/usr/bin/env python3
# coding=utf-8
def spam():
eggs = 99
bacon()
print(eggs)
def bacon():
eggs = 0 # 这是调用bacon函数的局部作用域
#调用spam()创建一个局部作用域,spam()中调用的bacon函数创建另一个局部作用域
spam() # 输出 99
#!/usr/bin/env python3
# coding=utf-8
def spam():
eggs = 'spam local'
print(eggs) # prints 'spam local'
def bacon():
eggs = 'bacon local'
print(eggs) # prints 'bacon local'
spam()
print(eggs) # prints 'bacon local'
eggs = 'global'
bacon()
print(eggs) # prints 'global'
这个程序中有三个相同名字的不同变量(两个局部,一个全局),执行该脚本输出
bacon local
spam local
bacon local
global
#!/usr/bin/env python3
# coding=utf-8
def spam():
global eggs # global语句,后续使用全局的spam,而不是在局部作用域中创建一个
eggs = 'spam' # this is global
def bacon():
eggs = 'bacon' # this is local
def ham():
print(eggs) # this is global
eggs = 42 # this is global
spam()
bacon()
ham()
四条法则区分变量是局部还是全局:
1. 如果变量在全局作用域中使用(所有函数之外)–全局变量
2. 如果在一个函数中,有针对该变量的global语句 –全局变量
3. 否则,如果该变量用于在函数中的赋值语句–局部变量
4. 但是,如果该变量没有用在赋值语句中–全局变量
#!/usr/bin/env python3
# coding=utf-8
# Python看到spam()函数中有eggs的赋值语句,认为eggs是局部变量,
# 但是在print(eggs)执行之前,局部变量eggs并不存在
def spam():
print(eggs)
eggs = 'spam local'
eggs = 'gloabl'
spam()
语句print(eggs)在执行时会报错:UnboundLocalError: local variable ‘eggs’ referenced before assignment
一个函数中,一个变量要么总是全局变量,要么总是局部变量,没有办法先使用名为eggs的局部变量,稍后又在同一个函数中使用全局eggs变量
惯例是在编写函数时不使用全局变量,通常不必担心函数的代码会与程序的其他部分发生交叉影响
一般程序遇到错误会终止,如果希望程序能检测错误并处理它们–异常处理
1. 可能出错的语句放在try子句中
2. 如果错误发生,程序执行就转到接下来的except子句中进行处理
#!/usr/bin/env python3
# coding=utf-8
def spam(divedBy):
try:
return 42 / divedBy
except ZeroDivisionError:
print('Error: INvalid argument')
print(spam(2))
print(spam(0))
print(spam(1))
执行输出
21.0
Error: INvalid argument
None
42.0
在函数调用的try子句中,发生的所有错误都会被捕捉
#!/usr/bin/env python3
# coding=utf-8
# 由调用者捕捉错误
def spam(divideBy):
return 42 / divideBy
try:
print(spam(2))
print(spam(0)) # 发生除0的错误,直接跳到except子句
print(spam(1)) # 发生异常在except子句处理之后,不会再回try语句块
except ZeroDivisionError:
print('Error: INvalid argument')
#!/usr/bin/env python3
# coding=utf-8
# This is a guess the number game
import random
secretNumber = random.randint(1,20)
print('I am thinking of a number between 1 and 20')
# ask the player to guess 6 times
for guessesTaken in range(1,7):
print('Take a guess')
guessNum = int(input()) #guessNum和guessTaken都是全局的
#没有像c++那样的for语句作用域
if guessNum < secretNumber:
print('Your guess is too low')
elif guessNum > secretNumber:
print('Your guess is too high')
else:
break
if guessNum == secretNumber:
print('Good job, you guess the number in', str(guessesTaken), 'times')
else:
print('Nope. The number I was thinking of was', str(secretNumber))
对任意整数,如果是偶数,那么对它除以2,否则计算它的三倍加一,直到该数最终等于1
#!/usr/bin/env python3
# coding=utf-8
# 让用户输入一个整数,不断调用该函数,直到该函数返回1
def collatz(number):
if number % 2 == 0 :
number = number // 2
else:
number = number * 3 + 1
return number
value_in = int(input('Please input a integer value'))
while value_in != 1:
value_in = collatz(value_in)
print(value_in)