练习 1:仿照求 ∑mi=1i+∑ni=1i+∑ki=1i∑i=1mi+∑i=1ni+∑i=1ki 的完整代码,写程序,可求m!+n!+k!
In [1]:
def product_sum(end):
i = 1
total_n = 1
while i < end:
i += 1
total_n *= i
return total_n
m = int(input("请输入第1个整数,以回车结束:"))
n = int(input("请输入第2个整数,以回车结束:"))
k = int(input("请输入第3个整数,以回车结束:"))
print("最终的和是:",product_sum(m)+product_sum(n)+product_sum(k))
练习 2:写函数可返回1-1/3+1/5-1/7...的前n项的和。在主程序中,分别令n=1000及100000,打印4倍该函数的和。
In [1]:
def sum(n):
i = 1
total_n = 0
while i <= n:
total_n += (-1)**(n-1)*(1.0/(2*n-1))
i += 1
return total_n
print(4*sum(1000))
print(4*sum(100000))
练习 3:将task3中的练习1及练习4改写为函数,并进行调用。
In [1]:
#练习1
def star():
name = input("please enter your name:")
date = input("please enter your date of birth:")
date=float(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 1.20 <= date <= 2.18:
print(name,",你是非常有性格的水瓶座!")
elif 2.19 <= date <= 3.20:
print(name,",你是非常有性格的双鱼座!")
else:
print(name,",你是非常有性格的摩羯座!")
star()
In [1]:
#练习4
def conversion():
word = input("please enter a word:")
if word.endswith("x"):
print(word,"es",sep = "")
elif word.endswith("sh"):
print(word,"es",sep = "")
else:
print(word,"s",sep = "")
conversion()
挑战性练习:写程序,可以求从整数m到整数n累加的和,间隔为k,求和部分需用函数实现,主程序中由用户输入m,n,k调用函数验证正确性。
In [1]:
def sum():
i = m
total = 0
while i <= n:
total += i
i += k
return total
m = int(input("please enter an integer:"))
n = int(input("please enter a biger integer:"))
k = int(input("please enter interval between two numbers:"))
print("最终的和是:",sum())
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]: