一.定义函数 在Python中可以使用`def`关键字来定义函数,和变量一样每个函数也有一个响亮的名字,而且命名规则跟变量的命名规则是一致的。在函数名后面的圆括号中可以放置传递给函数的参数,这一点和数学上的函数非常相似,程序中函数的参数就相当于是数学上说的函数的自变量,而函数执行完成后我们可以通过`return`关键字来返回一个值,这相当于数学上说的函数的因变量。
二.代码示例
1
def Pjz():
c = 0
sum = 0
while 1:
print('Enter an integer, the input ends if it is 0: ',end="")
shu = input()
if shu != '0' :
sum = sum + float(shu)
c +=1
else:
break
ave = float(sum/c)
return ave
ave=Pjz()
print('平均值是%f' %ave)
输出样例:
2
def doa(y):
for i in range(14):
y = y+ y * 0.05
if i== 9:
print(y)
print(y)
doa(10000)
输出样例:
3
def Shu(m,n):
hang = 0
for i in range(m,n):
if i % 5 == 0 and i % 6 ==0:
print(i,end=" ")
hang +=1
if hang % 10 == 0:
print()
Shu(100,1000)
输出样例:
4
def XZ():
n= 0
while n**2 < 12000:
n += 1
print(n)
XZ()
输出样例:
In [89]:
def DZ():
n = 0
while n**3 < 12000:
n += 1
print(n-1)
DZ()
输出样例:
5
def DK():
la = 10000
ny = 5
y = 5
for i in range(24):
M = la * ny / 100
T = 12 * M * y
print(ny,'%','月利率',M,'总和',T)
if ny == 5.25:
print('.....')
ny += 1/8
DK()
输出样例:
6
def Zh():
ac = 0
for i in range(50000,0,-1):
ac += 1/i
print(ac)
Zh()
输出样例:
def Ch():
res = 0
for i in range(1,50001,1):
res += 1/i
print(res)
Ch()
输出样例:
7
def Zh():
res = 0
for i in range(1,98,2):
res +=i/(i+2)
print(res)
Zh()
输出样例:
8
def M(a,b):
ac= 0
for i in range(a,b):
ac += 4*((-1)**(i+1)/(2*i-1))
print (ac)
M(1,100000)
输出样例:
9
def ZH():
for i in range(1,10000):
acc = 0
for j in range(1,i):
if i % j == 0:
acc += j
if i == acc:
print(i)
ZH()
输出样例:
10
def LS():
m = 0
for i in range(1,8,2):
for j in range(2,8):
if i != j:
print(i,j)
m += 1
LS()
输出样例: