In [ ]:
#练习 1:仿照求$ \sum_{i=1}^mi + \sum_{i=1}^ni + \sum_{i=1}^ki$的完整代码,写程序,可求m!+n!+k!
In [ ]:
def compute_product(end):
i = 1
product = 1
while i < end:
i = i + 1
product = product * i
return product
n = int(input('请输入第一个整数,回车结束。'))
m = int(input('请输入第二个整数,回车结束。'))
k = int(input('请输入第三个整数,回车结束。'))
print('最终的和是:', compute_product(n) + compute_product(m) + compute_product(k))
In [ ]:
#练习 2:写函数可返回1 - 1/3 + 1/5 - 1/7...的前n项的和。在主程序中,分别令n=1000及100000,打印4倍该函数的和。
In [1]:
def compute_sum(end):
i = 1
n = 0
total = 1
while i <= end:
i = i + 2
n = n + 1
total=total + (-1)**n*(1/i)
return total
print('最终的和是:', 4*compute_sum(1000))
print('最终的和是:', 4*compute_sum(100000))
In [ ]:
#练习 3:将task3中的练习1及练习4改写为函数,并进行调用。
In [ ]:
def constellation(date):
if 3.21<=date<=4.19:
print(name,',你是非常有个性的白羊座')
elif 4.20<=date<=5.20:
print(name,',你是非常有个性的金牛座')
elif 5.21<=date<=6.21:
print(name,',你是非常有个性的双子座')
elif 6.22<=date<=7.22:
print(name,',你是非常有个性的巨蟹座')
elif 7.23<=date<=8.22:
print(name,',你是非常有个性的狮子座')
elif 8.23<=date<=9.22:
print(name,',你是非常有个性的处女座')
elif 9.23<=date<=10.23:
print(name,',你是非常有个性的天秤座')
elif 10.24<=date<=11.22:
print(name,',你是非常有个性的天蝎座')
elif 11.23<=date<=12.21:
print(name,',你是非常有个性的射手座')
elif 12.22<=date<=1.19:
print(name,',你是非常有个性的魔蝎座')
elif 1.20<=date<=2.18:
print(name,',你是非常有个性的水瓶座')
else:
print(name,',你是非常有个性的双鱼座')
name = input('请输入你的名字')
date = float(input('请输入你的出生月份和日期,以xx.xx形式,如3.09:'))
return constellation(data)
In [5]:
def verb_change(a):
if a.endswith('o') or a.endswith('s') or a.endswith('x')or a.endswith('ch') or a.endswith('sh'):
print (a,'es',sep='')
elif a.endswith('y'):
if a[:-1].endswith('a')or a[:-1].endswith('e') or a[:-1].endswith('i') or a[:-1].endswith('o') or a[:-1].endswith('u') :
print(a,'s',sep='')
else:
print (a[:-1],'ies',sep='')
else:
print(a,'s',sep='')
a=input("请输入一个可数英文名动词的单数形式")
verb_change(a)
In [ ]:
#挑战性练习:写程序,可以求从整数m到整数n累加的和,间隔为k,求和部分需用函数实现,主程序中由用户输入m,n,k调用函数验证正确性。
In [ ]:
def sum_total( m, n, k):
i = m
sum = 0
while i <= n:
sum = sum + i
i = i + k
return sum
m = int(input('请输入整数m的值:'))
n = int(input('请输入整数n的值:'))
k = int(input('请输入整数k的值:'))
print(sum_total(m,n,k))