摘要:本文旨在帮助中国药科大学的学生学习必修课《Python与医药大数据处理》,在实验操作题方面给予代码参考。
欢迎各界人士共同讨论Python相关话题,并给予宝贵建议。
目录
PY50201:自定义函数实现不同的功能
要求:(1)自定义函数psum1()包含两个参数,函数的返回值是两个数的平方和;
(2)自定义函数psum2()包含两个参数,函数的返回值是两个数的平方和,调用时如果只给定一个实参,则另一个参数的默认值为整数10;
(3)自定义函数psum3()包含两个参数,函数的返回值是两个数的平方和以及两个数的和;
(4)自定义函数psum4()包含两个参数,函数的返回值是两个数的平方和与全局变量n的乘积
def psum1(a,b):
return a**2+b**2
def psum2(a,b=10):
return a**2+b**2
def psum3(a,b):
return a**2+b**2,a+b
n=2
def psum4(a,b):
global n
return (a**2+b**2)*n
print(psum1(1,2))
print(psum2(1))
print(psum3(1,2))
print(psum4(1,2))
PY50202:自定义函数,根据用户输入返回不同结果
要求:数据处理时经常会要求用户输入整数,为了提高用户体验和代码复用,自定义函数getinput()处理以下通用情况:如果用户输入整数,则直接在屏幕上输出整数并退出;如果用户输入的不是整数,则要求用户重新输入,直至用户输入整数为止
def getinput():
while True:
try:
n=eval(input("Please input a integar:"))
if type(n)==int:
break
except:
print("Non-numeric is inputed,please input a numeric!")
return n
print(getinput())
PY50203:自定义函数,返回所有参数的乘积
要求:自定义函数multi(),函数参数的个数不限,函数返回值为所有参数的乘积。若参数中有非数值信息,在屏幕上输出提示信息
def multi(*args):
fact=1
count=1
for i in args:
if type(i)==type(1) or type(i)==type(1.0):
fact*=i
count+=1
else:
return"第{}项不是一个有效的数值!".format(count)
return fact
print(multi(2,3,1.5,8,6.7))
print(multi(1,2,"str"))
PY50204:提取系统当前时间并以指定格式输出
要求:利用datetime库提取当前系统时间,并采用两种方法以指定格式在屏幕上输出
#特殊条件(一般可省略)
import locale
locale.setlocale(locale.LC_ALL,'en')
locale.setlocale(locale.LC_CTYPE,'chinese')
from datetime import datetime
now=datetime.now()
print("现在是{0:%Y}年{0:%m}月{0:%d}日 {0:%H}:{0:%M}".format(now))
print("现在是"+now.strftime("%Y年%m月%d日 %H:%M"))
PY50205:实现生日的5种格式输出
要求:利用datetime库,根据所给的年份、月份、日期和时间构造一个生日对象,按5种指定格式在屏幕上输出
#特殊条件(一般可省略)
import locale
locale.setlocale(locale.LC_ALL,'en')
locale.setlocale(locale.LC_CTYPE,'chinese')
from datetime import datetime
birt=datetime(2010,1,1,20)
print(birt)
print(birt.strftime("%Y年%m月%d日"))
print(birt.strftime("%Y-%m-%d %a"))
print(birt.strftime("%b.%d %Y"))
if birt.day%10==1 and birt.day!=11:
s="st"
elif birt.day%10==2 and birt.day!=12:
s="nd"
elif birt.day%10==3 and birt.day!=13:
s="rd"
else:
s="th"
print(birt.strftime("%d")+s+birt.strftime(" %b %Y"))
PY50206:采用自定义递归函数实现字符串反转
要求:自定义递归函数reverse(),可实现字符串的反转,即对于用户输入的字符串,调用函数后在屏幕上输出对应的逆序字符串,例如,将"python"反转成"nohtyp"
def reverse(s):
if s=="":
return s
else:
return reverse(s[1:])+s[0]
ss=input("请输入一个字符串:")
print("反转后的字符为:",reverse(ss))
PY50207:自定义递归函数输出斐波那契数列
要求:从键盘输入项数n,通过调用自定义递归函数fib()在屏幕上输出斐波那契数列前n项的值。如果n为负数,则提示“请输入正数”,否则实现前n项的输出
def fib(i):
if i==1 or i==2:
return 1
else:
return fib(i-1)+fib(i-2)
n=int(input("请输入项数n:"))
if n<=0:
print("请输入正数")
else:
print("斐波那契数列前{}项为:".format(n))
for i in range(1,n+1):
print(fib(i),end=" ")