- 程序控制结构
- 大小写转换
- 判断位数并打印各位的值
- 地铁车票
- 考试评级
- 判断星期
- 身体质量指数BMI
- 阶乘
- 水仙花数
- 猴子摘桃
- 素数
- 随机密码生成
- 圆周率计算
- 求pi近似值
- 篮球弹跳
- 猜数字
- 函数
- 打招呼函数
- 能否组成三角形
- 转换秒为时间
- 最大公约数
- 简单计算器
- 杨辉三角
- 斐波那契数列计算
- 汉诺塔实践
- 科赫雪花小包裹
- 合法的用户名
- 密码的强度
- 藏头诗
- 统计字符出现的次数
- 文件拓展名
- 组合数据类型
- 创建水果列表
- 删除水果
- 添加水果
- 计算总分和平均奶粉
- 添加用户
- 模拟用户登录
程序控制结构
大小写转换
char=input("")
if ord(char)>=65 and ord(char)<97:
print(chr(ord(char)+32))
else:
print(chr(ord(char)-32))
判断位数并打印各位的值
num=int(input())
num1=str(num)
num_list=list(num1)
n=len(num1)
if n==1:
print("一")
print(num)
elif n==2:
print("二")
for i in range(n):
print(num_list[i],end=" ")
elif n==3:
print("三")
for i in range(n):
print(num_list[i],end=" ")
elif n==4:
print("四")
for i in range(n):
print(num_list[i],end=" ")
elif n==5:
print("五")
for i in range(n):
print(num_list[i],end=" ")
地铁车票
per_num=int(input())
sta_num=int(input())
if per_num<=0 or sta_num<=0:
print("error")
else:
if 1<=sta_num<=4:
pm=3
if 5<=sta_num<=9:
pm=4
if sta_num>9:
pm=5
count=pm*per_num
print(count)
考试评级
score = int(input('请输入考试成绩: '))
if score>=0 and score<60:
print("E")
elif score>=60 and score<70:
print("D")
elif score>=70 and score<80:
print("C")
elif score>=80 and score<90:
print("B")
elif score>=90 and 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/(height*height)
print("BMI数值为:{:.2f}".format(BMI))
if BMI<18.5:
print("BMI指标为:国际'偏瘦',国内'偏瘦'")
elif BMI>=25 and BMI<30:
print("BMI指标为:国际'偏胖',国内'偏胖'")
阶乘
num = int(input())
a = 1
for i in range(1, num+1):
a = a*i
print(a)
水仙花数
num=eval(input())
for num in range(100,num):
a=num//100
b=(num//10)%10
c=num%10
if num==(a*a*a+b*b*b+c*c*c):
print(num)
猴子摘桃
day = int(input('请输入一个天数: '))
n=2
for i in range(2,day+1):
n=2*n+1
print(n)
素数
num = int(input('请输入一个整数: '))
for i in range(2,num+1):
flg = 0
for j in range(2,i):
if not(i%j):
flg = 1
break
if(flg == 0):
print(i)
随机密码生成
import random
def genpwd(length):
length = eval(input())
random.seed(17)
for i in range(3):
print(genpwd(length))
圆周率计算
import time
import random
count = 0
t = time.perf_counter()
n = 1000*1000
for i in range(n):
x,y = random.random(),random.random()
if pow(x**2+y**2,0.5) <= 1:
count = count + 1
pi = 4*(count/n)
t =time.perf_counter()-t
print("圆周率为{}".format(pi))
print("运行时间为{}".format(t))
求pi近似值
e = float(input().strip())
n,s,t,pai=1,1,1,0.0
while True:
t=1/(2*n-1)
pai+=s*t
if t<e:
break
n+=1
s=-s
pai*=4
print(pai)
篮球弹跳
num = int(input('请输入弹跳的次数: '))
height=10
for i in range(num):
height=height/2
print(height)
猜数字
import random
num = random.randint(1,100)
guess_chances = 7
print('您只有7次猜数字的机会哦!')
for i in range(1,guess_chances + 1):
print('这是第'+ str(i) + '次猜数字')
guess = input('请输入数字:')
if guess.isdigit():
guess = int(guess)
if guess < num:
print('您输入的数字太小了,您还有' + str(guess_chances - i)+'次机会,请重新输入:')
elif guess > num:
print('您输入的数字太大了,您还有' + str(guess_chances - i)+'次机会,请重新输入:')
elif guess == num:
print('恭喜您猜对了')
break
elif guess == 'q':
print('退出游戏!')
break
else:
print('输入的内容必须为整数,请重新输入:')
while (guess_chances - i) == 0:
print('您输入已经超过7次,游戏结束!')
break
函数
打招呼函数
"""
练习:打招呼函数
要求:
1. 定义函数 say_hello
2. 有 1 个参数 name 表示要给谁打招呼
3. 实现函数功能,即在控制台打印:`你好,,认识你很高兴!`(注:name 是函数的参数)
"""
def say_hello(name):
n=name
print("你好,{},认识你很高兴!".format(n))
name="张三"
say_hello(name)
能否组成三角形
"""
编写 is_triangle 函数,此函数有 3 个参数,分别为3个数字,
判断这3个数字所代表的边长能否组成一个三角形
"""
'''a=int(input())
b=int(input())
c=int(input())
'''
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=1
b=2
c=3
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))
斐波那契数列计算
def fbi(num):
if num==1 or num==2:
return 1
else:
return fbi(num-1)+fbi(num-2)
汉诺塔实践
count = 0
def hanoi (n, src, dst, mid):
global count
if n == 1:
print("{}: {}->{}".format(1, src, dst))
count += 1
else:
...
hanoi(3, "A", "C", "B")
print(count)
科赫雪花小包裹
import turtle
def koch(size, n):
...
def main(level):
turtle.setup(600,600)
turtle.penup()
turtle.goto(-200, 100)
turtle.pendown()
turtle.pensize(2)
...
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))
组合数据类型
创建水果列表
fruits = ['苹果','草莓','香蕉','梨','百香果']
删除水果
fruits = ['苹果', '草莓', '香蕉', '梨','百香果']
'''
del fruits[1]
del fruits[3]
'''
fruits.remove('草莓')
fruits.remove('百香果')
添加水果
fruits = ['苹果', '香蕉', '梨']
fruits.append('西瓜')
fruits.append('葡萄')
计算总分和平均奶粉
scores = [95, 69, 98, 74, 64, 72, 53, 92, 83]
total_score=0
c=len(scores)
for i in range(c):
total_score+=scores[i]
print(total_score)
avg_score=0
avg_score=total_score/c
print(avg_score)
添加用户
users = {
"alpha": "alpha123",
"beta": "betaisverygood",
"gamma": "1919191923",
"zhangsan":"zs123456",
"lisi":"si123456"
}
'''
dict["zhangsan"] = "zs123456"
dict["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")