练习1:
In [2]:
def compute_sum(end):
i = 0
total_n = 1
while i < end:
i = i + 1
total_n = total_n * i
return total_n
n = int(input('请输入第1个整数,以回车结束。'))
m = int(input('请输入第2个整数,以回车结束。'))
k = int(input('请输入第3个整数,以回车结束。'))
print('最终的和是:', compute_sum(m) + compute_sum(n) + compute_sum(k))
练习2:
In [2]:
def compute(end):
pro = 1
num = 1
i = 1.0
j = 1.0/i
total_m = 0
while num <= end:
j = 1.0/i * pro
total_m = total_m + j
pro = pro * (-1)
i = i + 2
num = num + 1
return total_m
n1 = int(input('请输入一个整数,以回车结束:'))
print('最终和的四倍是:',compute(n1) * 4.0)
n2 = int(input('请输入一个整数,以回车结束:'))
print('最终和的四倍是:',compute(n2) * 4.0)
练习3(第一小题):
In [21]:
name=input('请输入你的名字:')
def your_sex(s):
if s==1:
sex='Miss'
else:
sex='Mr'
return sex
def birthday(birthday_month,birthday_data):
if birthday_month==1:
if birthday_data>=20:
xinzuo='水瓶'
else:
xinzuo='摩羯'
elif birthday_month==2:
if birthday_data>=19:
xinzuo='双鱼'
else:
xinzuo='水瓶'
elif birthday_month==3:
if birthday_data>=21:
xinzuo='白羊'
else:
xinzuo='双鱼'
elif birthday_month==4:
if birthday_data>=20:
xinzuo='金牛'
else:
xinzuo='白羊'
elif birthday_month==5:
if birthday_data>=21:
xinzuo='双子'
else:
xinzuo='金牛'
elif birthday_month==6:
if birthday_data>=22:
xinzuo='巨蟹'
else:
xinzuo='双子'
elif birthday_month==7:
if birthday_data>=23:
xinzuo='狮子'
else:
xinzuo='巨蟹'
elif birthday_month==8:
if birthday_data>=23:
xinzuo='处女'
else:
xinzuo='狮子'
elif birthday_month==9:
if birthday_data>=23:
xinzuo='天秤'
else:
xinzuo='处女'
elif birthday_month==10:
if birthday_data>=24:
xinzuo='天蝎'
else:
xinzuo='天秤'
elif birthday_month==11:
if birthday_data>=23:
xinzuo='射手'
else:
xinzuo='天蝎'
elif birthday_month==12:
if birthday_data>=22:
xinzuo='摩羯'
else:
xinzuo='射手'
return xinzuo
ni=int(input('如果你是女性,输入1,如果你是男性,输入2:'))
birthday_month=int(input('你的生日月份是:'))
birthday_data=int(input('你的生日日期是:'))
print('你好,',your_sex(ni),name,'你是',birthday(birthday_month,birthday_data))
练习3(第二小题):
In [42]:
def add(word):
if word.endswith('s') or word.endswith('x') or word.endswith('ch') or word.endswith('sh') or word.endswith('o'):
end='加es'
elif word.endswith('ay')==0 and word.endswith('ey')==0 and word.endswith('iy')==0 and word.endswith('oy')==0 and word.endswith('uy')==0 and word.endswith('yy')==0 and word.endswith('y'):
end='变y为i再加es'
elif word=='have':
end='变为has'
else:
end='直接加s'
return end
verb=input('请输入一个动词的原型:')
print('它的变化规则是:',add(verb))
挑战性练习:
In [9]:
def compute_sum(star,end,tap):
i = star
total_n = 0
while i <= end:
total_n = total_n + i
i = i + tap
return total_n
m = int(input('请输入开始整数,以回车结束。'))
n = int(input('请输入结束整数,以回车结束。'))
k = int(input('请输入间隔整数,以回车结束。'))
print('最终的和是:', compute_sum(m,n,k))