1,函数体外的变量,为全局变量,可以在函数体内调用
t = 1
def f1():
print(t)
f1()
输出结果
E:\software\work\python\python.exe "E:/Project/Python/Math Adventures with Python/test.py"
1
Process finished with exit code 0
2,当函数体内定义了一个相同变量名的变量时,优先调用函数内的变量
t = 1
def f1():
t = 200
print(t) # 访问的是函数体内的变量
f1()
print(t) #访问的是函数体外的变量
输出
E:\software\work\python\python.exe "E:/Project/Python/Math Adventures with Python/test.py"
200
1
Process finished with exit code 0
3,如果在函数体内声明了全局变量,则函数体外的同名变量也会修改
t = 1
def f1():
global t
t = 200
print(t)#函数内可以访问外部变量,但函数内的变量,函数外不可以访问
f1()
print(t)
输出:
E:\software\work\python\python.exe "E:/Project/Python/Math Adventures with Python/test.py"
200
200
Process finished with exit code 0
4,声明全局变量应对局部变量声明.即,在函数体外声明全局变量没有效果,因为函数体外的变量是全局变量
global t
t = 1
def f1():
t = 200
print(t)#函数内可以访问外部变量,但函数内的变量,函数外不可以访问
f1()
print(t)
结果:
E:\software\work\python\python.exe "E:/Project/Python/Math Adventures with Python/test.py"
200
1
Process finished with exit code 0
5,如果在迭代中,想要有一个函数内的变量可以在迭代过程中可以实现累次运算,
那么就要声明成全局变量.
这里以i的累次求和为例
i= 0
def f(n):
global i
if n == 1 :
return 1
else:
i += 1
return n+f(n-1)
print(f(3))
print(i)
输出:
E:\software\work\python\python.exe "E:/Project/Python/Math Adventures with Python/test.py"
6
2
Process finished with exit code 0
6,在调用函数时,函数应该在调用语句之前定义,而不是之后,否则会报错.
Python中函数的定义必须在调用的前面,但是在函数的内部调用一个函数,不用考虑顺序,只要被调用的函数被定义了即可
'''
随机生成一个1-100的整数,程序来猜测数是多少,每次猜错后,会告诉程序应该猜大点还是猜小点
'''
from random import randint
# def average(a,b): #返回a,b的平均数
# return (a+b)//2
number = randint(1,100) # 生成的随机数
a = 1
b = 100
i = 1
guss_num = average(a,b)
while guss_num != number:
if b-a == 1: # 如果a,b 是相邻的数,而目标数是b,那么没有这条语句就结束不了.例如:number=100
guss_num += 1
continue
if guss_num > number:
print('应该猜小点',guss_num)
b = average(a,b)
guss_num =average(a,b)
i += 1
else:
print('应该猜大点',guss_num)
a = average(a,b)
guss_num = average(a,b)
i += 1
def average(a,b): #返回a,b的平均数
return (a+b)//2
print('生成的随机数是%d,共猜测%d步'%(average(a,b),i))
print(number)
其中,average()函数定义在这之前调用了average()函数,这样会报错
E:\software\work\python\python.exe "E:/Project/Python/Math Adventures with Python/3章-条件语句/猜数游戏(自己写的).py"
Traceback (most recent call last):
File "E:\Project\Python\Math Adventures with Python\3章-条件语句\猜数游戏(自己写的).py", line 11, in
guss_num = average(a,b)
NameError: name 'average' is not defined
Process finished with exit code 1
显示average()函数未定义.
正确的代码:
'''
随机生成一个1-100的整数,程序来猜测数是多少,每次猜错后,会告诉程序应该猜大点还是猜小点
'''
from random import randint
def average(a,b): #返回a,b的平均数
return (a+b)//2
number = randint(1,100) # 生成的随机数
a = 1
b = 100
i = 1
guss_num = average(a,b)
while guss_num != number:
if b-a == 1: # 如果a,b 是相邻的数,而目标数是b,那么没有这条语句就结束不了.例如:number=100
guss_num += 1
continue
if guss_num > number:
print('应该猜小点',guss_num)
b = average(a,b)
guss_num =average(a,b)
i += 1
else:
print('应该猜大点',guss_num)
a = average(a,b)
guss_num = average(a,b)
i += 1
# def average(a,b): #返回a,b的平均数
# return (a+b)//2
print('生成的随机数是%d,共猜测%d步'%(average(a,b),i))
print(number)