6、输出100以内的质数
for i in range(2, 101):
for j in range(2, i//2+1):
if i % j == 0:
break
else:
print(i)
7、定义函数,判断用户名是否合法(至少包含一个大写字母,一个数 字)
import string
numbers = string.digits
upper = string.ascii_uppercase
name = "csdvvscADA2521s"
def check(name):
num = 0
upp = 0
for i in name:
if i in numbers:
num = 1
if i in upper:
upp = 1
if num == upp == 1:
return True
else:
return False
if check(name):
print("合法")
else:
print("不合法")
8、使用递归,输出指定目录中所有的jpg文件
import os
dirname = input("请输入路径:")
def selectjpg(dirpatth):
items = os.listdir(dirpatth)
for item in items:
item=os.path.join(dirpatth, item)
if os.path.isdir(item):
selectjpg(item)
elif os.path.isfile(item):
if item.endswith(".jpg"):
print(os.path.basename(item))
selectjpg(dirname)
9、异常处理:处理"123"+4的异常
a = "123"
b = 4
try:
c = a + b
except TypeError:
print("类型错误")
10、图书管理系统,要保存的图书信息包 括:图书编号、书名、价格、库存量。键盘输入3本书的信息,分别以三种方式存储并完成输出。如果书名超过4个字,只显示4个字,其余 加‘.…’ 方式一:使用元组存储一本书的信息,元组列表存储所有图书 方式二:使用字典存储所有图书信息,键为图书编号,值为“书名_价格库存量” 方式三:定义图书类(使用property封装属性),使用对象列表存储所有图书
class book():
@property
def __init__(self, id, name, price, number):
self.id = id
self.name = name
self.price = price
self.number = number
@property
def show(self):
return self.id, self.name, self.price, self.number
tu = tuple()
dic = {}
ls = []
for i in range(3):
id = input("请输入图书编号:")
name = input("请输入书名:")
price = int(input("请输入价格:"))
number = int(input("请输入库存:"))
if i == 0:
tu = (id, name, price, number)
elif i == 1:
dic[id] = [name, price, number]
elif i == 2:
ls.append(book(id, name, price, number))
def sl(bookname):
if len(bookname) > 4:
name = bookname[0:4] + "***"
print('名字', name)
else:
print('名字', bookname)
print('图书编号', tu[0])
sl(tu[1])
print('价格', tu[2])
print('库存', tu[3])
for id, value in dic.items():
print('图书编号', id)
sl(value[0])
print('价格', value[1])
print('库存', value[2])
for i in ls:
print('图书编号', i.id)
sl(i.name)
print('价格', i.price)
print('库存', i.number)
11、使用多态模拟:宠物医生:给宠物看病宠物:狗狗生病了,就打针吃药;小鸟生病了,就包扎疗养
class Animal_doctor():
def ill(self):
print("给宠物看病")
class Dog(Animal_doctor):
def ill(self):
print("狗生病,打针吃药")
class Bird(Animal_doctor):
def ill(self):
print("小鸟生病,包扎疗养")
doctor = Animal_doctor()
dog = Dog()
bird = Bird()
def fun(obj):
obj.ill()
12、文件读写: 1)随机产生10个4位数字组成的验证码,存储在code.txt文件中(一个验证码一行) 2)从code.txt中读出所有内容输出
import string
import random
a = string.digits + string.ascii_letters
def yanz():
code = ""
for i in range(4):
code += random.choice(a)
return code
with open('code.txt','w') as f:
for i in range(10):
f.write(yanz()+'\r')
with open('code.txt','r') as f:
print(f.read())
13、使用爬虫下载图片
import requests
url = "https://pic.netbian.com/uploads/allimg/211109/221532-163646733295cd.jpg"
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:90.0) Gecko/20100101 Firefox/90.0"}
respones = requests.get(url,headers = headers)
print("正在下载")
with open("E://"+'picture1.jpg','wb') as f:
f.write(respones.content)
print("下载完成")
|