Python函数和代码复用(第5周)
作者:互联网
随机密码生成
- 以整数17为随机数种子,获取用户输入整数N为长度,产生3个长度为N位的密码,密码的每位是一个数字。每个密码单独一行输出。
import random
def genpwd(length):
a = 10**(length-1)
b = 10**length - 1
return "{}".format(random.randint(a, b))
length = eval(input())
random.seed(17)
for i in range(3):
print(genpwd(length))
连续质数计算
-
获得用户输入数字N,计算并输出从N开始的5个质数,单行输出,质数间用逗号,分割。
-
注意:需要考虑用户输入的数字N可能是浮点数,应对输入取整数;最后一个输出后不用逗号。
def prime(m):
for i in range(2,m):
if m % i == 0:
return False
return True
n = eval(input())
a = int(n)
a = a+1 if a < n else a
count = 5
while count > 0:
if prime(a):
if count > 1:
print(a, end=",")
else:
print(a, end="")
count -= 1
a += 1
七段数码管绘制
import turtle, time
def drawGap(): #绘制数码管间隔
t.penup()
t.fd(5)
def drawLine(draw): #绘制单段数码管
drawGap()
t.pendown() if draw else t.penup()
t.fd(40)
drawGap()
t.right(90)
def drawDigit(d): #根据数字绘制七段数码管
drawLine(True) if d in [2,3,4,5,6,8,9] else drawLine(False)
drawLine(True) if d in [0,1,3,4,5,6,7,8,9] else drawLine(False)
drawLine(True) if d in [0,2,3,5,6,8,9] else drawLine(False)
drawLine(True) if d in [0,2,6,8] else drawLine(False)
t.left(90)
drawLine(True) if d in [0,4,5,6,8,9] else drawLine(False)
drawLine(True) if d in [0,2,3,5,6,7,8,9] else drawLine(False)
drawLine(True) if d in [0,1,2,3,4,7,8,9] else drawLine(False)
t.left(180)
t.penup()
t.fd(20)
def drawDate(date):
t.pencolor("red")
for i in date:
drawDigit(eval(i))
def main():
t.setup(800, 350, 200, 200)
t.penup()
t.fd(-300)
t.pensize(5)
drawDate(time.strftime('%Y%m%d',time.gmtime()))
t.done()
main()
科赫雪花小包裹
import turtle
def koch(size, n):
if n == 0:
turtle.fd(size)
else:
if angle in [0, 60, -120, 60]:
turtle.left(angle)
koch(size/3, n-1)
def main(level):
turtle.setup(600,600)
turtle.penup()
turtle.goto(-200, 100)
turtle.pendown()
turtle.pensize(2)
koch(400,level)
turtle.right(120)
koch(400, level)
turtle.right(120)
koch(400, level)
turtle.hideturtle()
turtle.done()
try:
level = eval(input("请输入科赫曲线的阶: "))
main(level)
except:
print("输入错误")
任意累积
def cmul(a, *b):
m = a
for i in b:
m *= i
return m
print(eval("cmul({})".format(input())))
# 无限制数量函数定义的方法,其中b在函数cmul中表达除了a之外的所有输入参数
斐波那契数列计算
def fbi(n):
if n == 1 or n == 2:
return 1
else:
return fbi(n-1)+fbi(n-2)
n = eval(input())
print(fbi(n))
汉诺塔实践
steps = 0
def hanoi(src, des, mid, n):
global steps
if n == 1:
steps += 1
print("[STEP{:>4}] {}->{}".format(steps, src, des))
else:
hanoi(src, mid, des, n-1)
steps += 1
print("[STEP{:>4}] {}->{}".format(steps, src, des))
hanoi(mid, des, src, n-1)
N = eval(input())
hanoi("A", "C", "B", N)
标签:turtle,False,Python,代码,复用,else,drawLine,print,def 来源: https://blog.csdn.net/Nicole_678/article/details/116120574