文章目录
- 4.基本数据类型
- 判断奇偶数
- 公倍数
- 判断平闰年
- 天天向上的力量第一问
- 天天向上的力量第二问
- 天天向上的力量第三问
- 天天向上的力量第四问
- 拼接最大字符
- 删除字符
- 插入字符
- 回文字符串
- 统计词量
- 你中无我
- 时间格式化
- 文本进度条
- 5.程序的控制结构
- 大小写转换
- 判断位数并打印各位的值
- 地铁车票
- 考试评级
- 判断星期
- 身体质量指数BMI
- 阶乘
- 水仙花数
- 猴子摘桃
- 素数
- 随机密码生成
- 圆周率的计算
- 求pi的近似值
- 篮球弹跳
- 猜数字
- 6.函数和代码复用
- 打招呼函数
- 能否组成三角形
- 转换秒为时间
- 最大公约数
- 简单计算器实现
- 杨辉三角
- 七段数码管绘制
- 斐波那契数列计算
- 汉诺塔实践
- 科赫雪花小包裹
- 合法的用户名
- 密码的强度
- 藏头诗
- 统计字符出现次数
- 文件扩展名
- 7.组合数据类型
- 创建水果列表
- 删除水果
- 添加水果
- 计算总分和平均分
- 添加用户
- 模拟用户登录
4.基本数据类型
判断奇偶数
num=int(input("请输入一个整数"))
if num%2==0:
print("even")
else:
print("odd")
公倍数
num=int(input())
if num%5==0 and num%7==0:
print("yes")
else:
print("no")
判断平闰年
year=int(input())
if (year%4==0) and (year%100!=0) or (year%400==0):
print("leap year")
else:
print("common year")
天天向上的力量第一问
dayup=pow(1.001,365)
daydown=pow(0.999,365)
print("向上:{:.2f},向下:{:.2f}".format(dayup,daydown))
天天向上的力量第二问
dayfactor=0.005
dayup=pow(1+dayfactor,365)
daydown=pow(1-dayfactor,365)
print("向上:{:.2f},向下:{:.2f}".format(dayup,daydown))
天天向上的力量第三问
dayup=1.0
dayfactor=0.01
for i in range(365):
if i%7 in[6,0]:
dayup=dayup*(1-dayfactor)
else:
dayup=dayup*(1+dayfactor)
天天向上的力量第四问
def dayUP(df):
dayup=1
for i in range(365):
if i%7 in [6,0]:
dayup=dayup*(1-0.01)
else:
dayup=dayup*(1+df)
return dayup
dayfactor=0.01
while dayUP(dayfactor)<37.78:
dayfactor+=0.001
print("工作日的努力参数是:{:.3f}".format(dayfactor))
拼接最大字符
string1=input()
string2=input()
str1=list(string1)
str2=list(string2)
str=""
for i in range(len(string1)):
if str1[i]>=str2[i]:
str=str+str1[i]
else:
str=str+str2[i]
print(str)
删除字符
string = 'abcdefghijklmnopqrstuvwxyz'
begin=int(input())
length=int(input())
str1=list(string)
del str1[begin:begin+length]
for i in range(len(str1)):
print(str1[i],end="")
插入字符
s = 'abcdefghijklmnopqrstuvwxyz'
sub=input()
pos=int(input())
str1=list(s)
str1.insert(pos,sub)
for i in range(len(str1)):
print(str1[i],end="")
回文字符串
s=input()
s1=list(s)
s1.reverse()
s2=list(s)
if s1==s2:
print("yes")
else:
print("no")
统计词量
def word_len(text):
return len([i for i in text.split(' ') if i])
def main():
text=str(input("请输入字符串: "))
len=word_len(text)
print(len)
main()
你中无我
s1=input()
s2=input()
for i in s1:
if i not in s2:
print(i,end="")
时间格式化
import time
t=time.gmtime()
time.strftime("%Y-%M-%D %H:%M:%S",t)
文本进度条
import time
scale=50
print("执行开始".center(scale//2,"-"))
start=time.perf_counter()
for i in range(scale+1):
a="*"*i
b="-"*(scale-i)
c=(i/scale)*100
dur=time.perf_counter()-start
print("\r{:^3.0f}%[{}->{}]{:.2f}s".format(c,a,b,dur),end="")
time.sleep(0.1)
print("\n"+"执行结束".center(scale//2,'-'))
5.程序的控制结构
大小写转换
char=input("输入一个英文字母")
if ord(char)>=ord('A') and ord(char)<=ord('Z'):
print(chr(ord(char)+32))
else:
print(chr(ord(char)-32))
判断位数并打印各位的值
num=str(input("输入一个数字"))
lens=len(num)
if len(num)==1:
print("一")
elif len(num)==2:
print("二")
elif len(num)==3:
print("三")
elif len(num) == 4:
print("四")
elif len(num) == 5:
print("五")
i=0
while i<len(num):
print(num[i],end=" ")
i+=1
地铁车票
per_num=int(input("乘坐的人数"))
sta_num=int(input("站数"))
if per_num<=0 or sta_num<=0:
print("error")
elif sta_num<=4 and sta_num>=1:
print(per_num*3)
elif sta_num <= 9 and sta_num >= 5:
print(per_num*4)
elif sta_num >= 9:
print(per_num*5)
考试评级
score = int(input('请输入考试成绩: '))
if 0<=score<=59:
print('E')
elif 60<=score<=69:
print('D')
elif 70<=score<=79:
print('C')
elif 80<=score<=89:
print('B')
elif 90<=score<=100:
print('A')
判断星期
chars = input()
if chars=='mo':
print("monday")
elif chars=='tu':
print("tuesday")
elif chars=='we':
print("wednesday")
elif chars=='th':
print("thursday")
elif chars=='fr':
print("friday")
elif chars=='sa':
print("saturday")
elif chars=='su':
print("sunday")
else:
print("error")
身体质量指数BMI
height = float(input())
weight = float(input())
BMI=weight/pow(height,2)
print(f"BMI数值为:{BMI:.2f}")
A='s'
B='s'
if BMI<18.5:
A=B='偏瘦'
elif 18.5<=BMI<25:
A='正常'
elif 25<=BMI<30:
A='偏胖'
elif BMI>=30:
A='肥胖'
if 18.5<=BMI<24:
B='正常'
elif 24<=BMI<28:
B='偏胖'
elif BMI>=28:
B='肥胖'
print(f"BMI指标为:国际'{A}',国内'{B}'")
阶乘
num=int(input())
i=1
res=1
while i<=num:
res*=i
i+=1
print(res)
水仙花数
num = int(input('请输入一个三位数: '))
s=100
while s<=num:
ge=s%10
shi=s//10%10
bai=s//100
if pow(ge,3)+pow(shi,3)+pow(bai,3)==s:
print(s)
s+=1
猴子摘桃
day = int(input('请输入一个天数: '))
i=2
res=2
while i<=day:
res=2*res+1
i+=1
print(res)
素数
num = int(input('请输入一个整数: '))
for i in range(2,num+1):
fg=0
for j in range(2,i-1):
if i%j==0:
fg=1
break
if fg==0:
print(i)
随机密码生成
import random
import string
a=string.octdigits
key=[]
def genpwd(length):
key=random.sample(a,length)
keys="".join(key)
return keys
length=eval(input())
random.seed(17)
for i in range(3):
print(genpwd(length))
圆周率的计算
from random import random
from time import perf_counter
DARTS = 1000 * 1000
hits = 0.0
start = perf_counter()
for i in range(1,DARTS+1):
x,y = random(),random()
dist = pow(x ** 2 + y ** 2,0.5)
if dist <= 1.0:
hits = hits + 1
pi = 4 * (hits / DARTS)
print("圆周率值是:{}".format(pi))
print("运行时间是:{:.5f}s".format(perf_counter() - start))
求pi的近似值
e = float(input())
x=-1
n=2
result=1
while(1/(2*n-3)>=e):
result = result+x*(1/(2*n-1))
x=x*(-1)
n=n+1
count=4*result
print(count)
篮球弹跳
num=int(input("请输入弹跳的次数: "))
result=10
for i in range(0,num):
result=result/2
print(result)
猜数字
import random
num = random.randint(1, 100)
guess_chances = 7
print('您只有7次猜数字的机会哦!')
for i in range(1, guess_chances + 1):
print('这是第' + str(i) + '次猜数字')
6.函数和代码复用
打招呼函数
"""
练习:打招呼函数
要求:
1. 定义函数 say_hello
2. 有 1 个参数 name 表示要给谁打招呼
3. 实现函数功能,即在控制台打印:`你好,,认识你很高兴!`(注:name 是函数的参数)
"""
def say_hello(name):
print(f"你好,{name},认识你很高兴!")
name="Jack"
say_hello(name)
能否组成三角形
"""
编写 is_triangle 函数,此函数有 3 个参数,分别为3个数字,
判断这3个数字所代表的边长能否组成一个三角形
"""
def is_triangle(a, b, c):
if a<=0 or b<=0 or c<=0:
return -1
if a+b>c and a+c>b and b+c>a and a-b<c and a-c<b and b-c<a:
return 1
else:
return 0
a=3
b=4
c=5
print(is_triangle(a,b,c))
转换秒为时间
def convert_from_seconds(seconds):
a=seconds//86400
b=seconds%86400//3600
c=seconds%3600//60
d=seconds%60
list=[]
list.append(a)
list.append(b)
list.append(c)
list.append(d)
return list
最大公约数
def common_divisor(num1,num2):
if num1>num2:
smaller=num2
else:
smaller=num1
for i in range(1,smaller+1):
if((num1%i==0) and (num2%i)==0):
res=i
return res
result = common_divisor(24, 16)
print(result)
简单计算器实现
def addition(num1, num2):
return num2+num1
def subtraction(num1, num2):
return num1-num2
def multiplication(num1, num2):
return num1*num2
def division(num1, num2):
return num1/num2
杨辉三角
def pascal_triangle(num):
r=[1]
for i in range(1,num):
r.insert(0,0)
for j in range(i):
r[j]=r[j]+r[j+1]
return r
print(pascal_triangle(3))
七段数码管绘制
import turtle as t
import time
def drawgap():
t.pu()
t.fd(5)
def drawline(draw):
t.pendown() if draw else t.penup()
t.fd(40)
drawgap()
t.right(90)
def drawdigit(digit):
drawline(True) if digit in [2,3,4,5,6,8,9] else drawline(False)
drawline(True) if digit in [0,1,3,4,5,6,7,8,9] else drawline(False)
drawline(True) if digit in [0,2,3,5,6,8,9] else drawline(False)
drawline(True) if digit in [0,2,6,8] else drawline(False)
t.left(90)
drawline(True) if digit in [0,4,5,6,8,9] else drawline(False)
drawline(True) if digit in [0,2,3,5,6,7,8,9] else drawline(False)
drawline(True) if digit in [0,1,2,3,4,7,8,9] else drawline(False)
t.left(180)
t.pu()
t.fd(20)
def drawdate(date):
t.pencolor("green")
for i in date:
if i == '年':
t.write('年',font = ("Arial",18,"normal"))
t.pencolor("blue")
t.fd(40)
elif i == "月":
t.write('月',font = ("Arial",18,"normal"))
t.pencolor("yellow")
t.fd(40)
elif i == "日":
t.write('日',font = ("Arial",18,"normal"))
t.pencolor("red")
else:
drawdigit(eval(i))
def main(date):
t.setup(1500,650,20,20)
t.pu()
t.fd(-600)
t.pensize(5)
drawdate(time.strftime("%Y年%m月%d日",time.gmtime()))
t.fd(40)
t.color("red")
drawdate(date)
t.hideturtle()
t.done()
main(input("请输入一个年月日,例:2019年01月22日:\n"))
斐波那契数列计算
def fbi(num):
list=[1,1,""]
for i in range(2,num):
list[i]=list[i-1]+list[i-2]
list.append(list[i])
return list[num]
print(fbi(4))
汉诺塔实践
count = 0
def hanoi (n, src, dst, mid):
global count
if n == 1:
print("{}: {}->{}".format(1, src, dst))
count += 1
else:
hanoi(n-1,src,mid,dst)
print("{}: {}->{}".format(n, src, dst))
hanoi(n-1,mid,dst,src)
hanoi(3, "A", "C", "B")
print(count)
科赫雪花小包裹
import turtle
def koch(size, n):
if n==0:
turtle.fd(size)
else:
for 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()
try:
level = eval(input("请输入科赫曲线的阶: "))
main(level)
except:
print("输入错误")
合法的用户名
"""
实现 check_username 函数,检查 username 是否有效
username 长度在 6-18 位之间,返回 True,否则返回 False
"""
def check_username(username):
length=len(username)
if 6<=length<=18:
return True
else:return False
user=input()
print(check_username(user))
密码的强度
"""
实现密码强度计算函数:
1. 实现函数 passworld_strength 返回 0-10 的数值,表示强度,数值越高,密码强度越强
2. 密码长度在 6 位及以上,强度 +1,
在 8 位及以上,强度 +2,
在 12 位及以上,强度 +4
3. 有大写字母,强度 +2
4. 除字母外,还包含数字,强度 +2
5. 有除字母、数字以外字符,强度 +2
"""
import string
def password_strength(pwd):
strong=0
length=len(pwd)
if length>=12:
strong+=4
elif length>=8:
strong+=2
elif length>=6:
strong+=1
flag1=False
for i in pwd:
if i in string.ascii_uppercase:
strong+=2
break
for i in pwd:
if i in string.ascii_letters:
flag1=True
break
flag2=False
for i in pwd:
if i in string.digits and flag1:
strong+=2
flag2=True
break
for i in pwd:
if i not in string.digits and i not in string.ascii_letters and flag2:
strong+=2
break
return strong
password=input()
print(password_strength(password))
藏头诗
poem1 = [
"芦花丛中一扁舟",
"俊杰俄从此地游",
"义士若能知此理",
"反躬难逃可无忧"
]
poem2 = [
"我画蓝江水悠悠",
"爱晚亭上枫叶愁",
"秋月溶溶照佛寺",
"香烟袅袅绕经楼"
]
def acrostic(poem):
newstr=[]
for i in range(len(poem)):
str1=poem[i]
rstr=list(str1)
newstr.append(rstr[0])
str1=""
newstr1=''.join(newstr)
return newstr1
print(acrostic(poem1))
print(acrostic(poem2))
统计字符出现次数
"""
统计字符串 string 中出现字符 char 的次数,并返回;
char 是长度为 1 的字符串。
"""
def sum_char(string, char):
str1=list(string)
count=0
for i in range(len(string)):
if str1[i] == char:
count+=1
return count
str2=str(input())
char1=str(input())
print(sum_char(str2, char1))
文件扩展名
"""
获取文件扩展名
说明:实现 file_ext 函数,该函数接受一个表示文件名的字符串参数 filename,返回它的扩展名
"""
def file_ext(filename):
str1=list(filename)
for i in range(len(filename)):
if str1[i]!=".":
continue
elif str1[i]==".":
str2=str1[i+1:]
str3=''.join(str2)
return str3
break
else:
return "error"
filename1=input()
print(file_ext(filename1))
7.组合数据类型
创建水果列表
fruits = []
fruits.append("苹果")
fruits.append("草莓")
fruits.append("香蕉")
fruits.append("梨")
fruits.append("百香果")
删除水果
fruits = ['苹果', '草莓', '香蕉', '梨', '百香果']
fruits.remove(fruits[1])
fruits.remove(fruits[3])
添加水果
fruits = ['苹果', '香蕉', '梨']
fruits.append("西瓜")
fruits.append("葡萄")
计算总分和平均分
scores = [95, 69, 98, 74, 64, 72, 53, 92, 83]
total_score=0
avg_score=0
for i in range(len(scores)):
total_score+=scores[i]
print(total_score)
avg_score=total_score/len(scores)
print(avg_score)
添加用户
users = {
"alpha": "alpha123",
"beta": "betaisverygood",
"gamma": "1919191923",
"zhangsan":"zs123456",
"lisi":"si123456"
}
模拟用户登录
users = {
"alpha": "alpha123",
"beta": "betaisverygood",
"gamma": "1919191923",
"zhangsan": "123456",
"lisi": "123456",
"admin": "ADMIN",
"root": "Root123"
}
username = input()
password = input()
if username not in users.keys():
print("not found")
elif username in users.keys() and users.get(username)==password:
print("success")
else:print("password error")