正在看书自学中,贴出自己的作业,欢迎大家交流指正,一起进步~
实现isOdd()函数,参数为整数,奇数返回True,偶数返回False
def isOdd(n):
if n%2:
return True
else:
return False
print(isOdd(10))
实现isNum()函数,参数为字符串,如果属于整数、浮点数或复数,返回True,否则返回False
def isNum(n):
try:
t=type(eval(n))
if t==int or t==float or t==complex:
return True
except ValueError:
return False
except NameError:
return False
print(isNum('a'))
实现multi()函数,参数个数不限,返回所有参数的乘积
def multi(*num):
if num:
if not all(num):
return 0
else:
mul = 1
for i in num:
mul = mul*i
return mul
else:
return None
print(multi(1,2,3))
实现isPrime()函数,参数为整数,要有异常处理。如果为质数返回True,否则返回False
def isPrime(n):
try:
idx = 0
if n==0 or n==1:
return False
else:
for i in range(2,n):
if (n%i)==0:
idx += 1
return False
if idx == 0:
return True
except ValueError:
return False
print(isPrime(16))
使用datetime库,对自己生日输出不少于10种日期格式
#coding=utf-8
from datetime import datetime as dt
DOB = dt(1996,1,1,17,0,0)
print(DOB.strftime("%Y-%m-%d %H:%M:%S"))
print(DOB.strftime("%Y,%B,%d %H:%M:%S"))
print(DOB.strftime("%Y-%b-%d %H:%M:%S"))
print(DOB.strftime("%Y年%m月%d日 %H时%M分%S秒"))
print(DOB.strftime("%Y-%m-%d %I%p"))
print(DOB.strftime("%Y年%m月%d日 %A"))
print(DOB.strftime("%Y年%m月%d日 %a"))
汉诺塔问题。要求输入层数,输出整个移动流程
count = 0
def hanoi(n, src, dst, mid):
global count
if n == 1:
print(f"{1}: from {src} to {dst}")
count += 1
else:
hanoi(n-1, src, mid, dst)
print(f"{n}: from {src} to {dst}")
count += 1
hanoi(n-1, mid, dst, src)
hanoi(2,'A','C','B')