In [1]:
def total (m):
i=0
ntotal=0
while i<m:
i+=1
ntotal+=i
return ntotal
m=int(input('please enter an integer. '))
n=int(input('please enter an integer. '))
k=int(input('please enter an integer. '))
sum=total(n)+total(m)+total(k)
print(sum)
练习 1:仿照求$ \sum_{i=1}^mi + \sum_{i=1}^ni + \sum_{i=1}^ki$的完整代码,写程序,可求m!+n!+k!
In [2]:
def total (m):
i=0
result=1
while i<m:
i+=1
result*=i
return result
m=int(input('please enter an integer. '))
n=int(input('please enter an integer. '))
k=int(input('please enter an integer. '))
print('The result of ',m,'!+',n,'!+',k,'! is :',total(m)+total(n)+total(k))
练习 2:写函数可返回1 - 1/3 + 1/5 - 1/7...的前n项的和。在主程序中,分别令n=1000及100000,打印4倍该函数的和。
In [3]:
def sum (n):
i=0
total=0
while i<n:
i+=1
if i%2==0:
total-=1/(2*i-1)
else:
total+=1/(2*i-1)
return total
n=int(input('please enter an integer. '))
m=int(input('please enter an integer. '))
print('resoult is :',4*sum(n))
print('resoult is :',4*sum(m))
练习 3:将task3中的练习1及练习4改写为函数,并进行调用。
In [8]:
def find_star ( n,name):
if 321<=n<=419 :
print('Mr',name,'你是白羊座')
elif 420<=n<=520 :
print('Mr',name,'你是非常有个性的金牛座!')
elif 521<=n<=621 :
print('Mr',name,'你是双子座')
elif 622<=n<=722 :
print('Mr',name,'你是巨蟹座')
elif 723<=n<=822 :
print('Mr',name,'你是狮子座')
elif 823<=n<=922 :
print('Mr',name,'你是处女座')
elif 923<=n<=1023 :
print('Mr',name,'你是天枰座')
elif 1024<=n<=1122 :
print('Mr',name,'你是天蝎座')
elif 1123<=n<=1221 :
print('Mr',name,'你是射手座')
elif 1222<=n<=1231 or 101<=n<=119 :
print('Mr',name,'你是摩羯座')
elif 120<=n<=218 :
print('Mr',name,'你是水平座')
else :
print('Mr',name,'你是双鱼座')
print('what is your name ?')
name=input()
print('when is your birthday ?for example 3 月 4日 以如下格式输如:304')
dat=int(input())
find_star(n,name)
In [11]:
def change(word):
if word.endswith('sh') or word.endswith('ch') or word.endswith('x') or word.endswith('s'):
print(word,'es',sep='')
else:
print(word,'s',sep='')
word=input('please enter a word :')
change(word)
挑战性练习:写程序,可以求从整数m到整数n累加的和,间隔为k,求和部分需用函数实现,主程序中由用户输入m,n,k调用函数验证正确性。
In [5]:
def sum (m,n,k):
i=m
total=m
while i<n and i+k<=n :
i+=k
total+=i
return total
m=int(input('please enter the from integer :'))
n=int(input('please enter the to integer : '))
k=int(input('please enter the gap :'))
print('The result :',sum(m,n,k))
In [ ]: