python练习题-原创 难度从小到中到大~欢迎评论交流
- 编写100以内逢7拍手游戏(含7和7倍数的数用@替换)。
for i in range(1, 101):
# 把i转成字符串,使用find方法(字符串中不包含时,返回-1)
include = str(i).find("7")
# 判断条件:既不包含7,也不是7的倍数
if include == -1 and int(i) % 7 != 0:
# 输出,去掉了换行符,加了、
print(i, end="、")
# 如果包含7 输出*
elif include != -1 or int(i) % 7 == 0:
print("*", end='、')
- 输入100以内整数,5次机会猜此数。
import random
print("猜数字游戏,输入一个1-100以内的数字")
random_num = random.randint(1, 100)
# print(random_num) # 打开注释可查看生成的随机数
for frequency in range(1,6):
number = input("请输入一个数字:")
if number.isdigit() is False:
print('请输入一个正确的数字')
elif int(number) < 0 or int(number) > 100:
print("请输入1-100范围的数字")
elif random_num == int(number):
print("恭喜你用了%d次猜对了" % frequency)
break
elif random_num > int(number):
print("很遗憾,你猜小了")
else:
print("很遗憾,你猜大了")
if frequency == 5:
print("很遗憾,%d次机会已用尽,游戏结束,答案为%d" %
(frequency, random_num))
- 列表中存放若干商品的价格,输入价格区间上限和下限,输出该区间所有价格。
num = [399, 4369, 539, 288, 109, 749, 235, 190, 99, 1000]
a = int(input("请输入最大价格:"))
b = int(input("请输入最小价格:"))
c = input('''1.价格降序排序
2.价格升序排序
请选择...:''')
num1 = []
for i in num:
if i >= b and i <= a:
num1.append(i)
if c == '1':
d = sorted(num1, reverse=True)
print(d)
if c == '2':
num1.sort()
print(num1)
- 列表(namel)中存放若干老师姓名,嵌套列表(officelJ, L. OI)三个子列表(办公室)随机存储name中各老师姓名,输出office内容。
import random
teachers=['A','B','C','D','E','F','G','H']
offices=[[],[],[]]
for name in teachers:
num=random.randint(0,2)
offices[num].append(name)
i=0
for i in offices:
m=len(i)
print(m)
print(offices)
- 编写函数:输入两个数和运算符输出运算结果。
a = int(input("请输入第一个数:"))
b = int(input("请输入第二个数:"))
symbol = input("请输入四则运算符号:(+-*/%)")
if symbol == "+":
print("%s%s%s=%s"%(a,symbol,b,a+b))
elif symbol == "-":
print("%s%s%s=%s"%(a,symbol,b,a-b))
elif symbol == "*":
print("%s%s%s=%s"%(a,symbol,b,a*b))
elif symbol == "/":
if b == 0:
print("除数不能为零")
else:print("%s%s%s=%s"%(a,symbol,b,a/b))
elif symbol=="%":
print("%s%s%s=%s"%(a,symbol,b,a%b))
else:
print("符号输入有误,请重新输入!!!")
- 编写函数:输出20项斐波那契数列项。
listnum = []
for x in range(1, 21):
if x == 1 or x == 2:
listnum.append(x)
else:
listnum.append(listnum[x-2]+listnum[x-3])
print(listnum)
- 设计编写长方体类,输入长、宽和高,输出面积和体积。
import math
import decimal
class Rect(object):
def __init__(self,l,h,z):
self.l = l
self.h = h
self.z = z
def length(self):
return 2*(self.l+self.h)
def area(self):
return self.l*self.h
class Cubic(Rect):
def __init__(self,l,h,z):
super(Cubic,self).__init__(l,h,z)
#表面积
def area(self):
return 2*(self.l*self.h) + 2*(self.h*self.z) + 2* (self.l*self.z)
#体积
def tj(self):
return super(Cubic,self).area() * self.z
def show(self):
print('{} {}'.format(decimal.Decimal(self.area()).quantize(decimal.Decimal('0.00')),decimal.Decimal(self.tj()).quantize(decimal.Decimal('0.00'))),end=' ')
if __name__ == '__main__':
while True:
a = float(input('请输入长:'))
b = float(input('请输入宽:'))
c = float(input('请输入高:'))
if a <= 0 or b <= 0 or c <= 0:
print('0.00 0.00 0.00 0.00')
else:
m = Cubic(a, b, c)
m.show()
- 设计编写动物类Animal,属性、函数自定义;子类鸟Bird,属性继承父类属性,函数完成属性值的输出。编写代码执行子类函数。
class Animal(object):
"""定义动物类"""
name = ""
time = 0
def __init__(self, name, time):
self.setName(name)
self.setTime(time)
def setName(self, name):
self.name = name
def setTime(self, time):
if not isinstance(time, int):
print('必须是整数')
self.time = time
def tell(self):
print("动物名称: " + self.name)
print("喂食次数: " + str(self.time))
class brid(Animal):
"""定义猫类"""
color = ""
def __init__(self, name, time, color):
Animal.__init__(self, name, time)
self.color = color
def tell(self):
Animal.tell(self)
print("动物颜色: " + self.color)
def feed(self):
self.time += 1
if __name__ == "__main__":
Brid1 = brid("小鸟1号", 0, "花色")
Brid1.tell()
Brid1.feed()
Brid1.tell()
- 登陆mysql数据库的用户名密码自定义,数据库名为mydb。数据表为login,包含uname、upassword字段。要求完成注册和登陆功能,
- 注册:输入用户名和密码,如果login表无此用户则插入到login中否则显示'用户已存在;
⑵登陆:输入用户名和密码,如果login表有此用户则'登陆成功'否则显示'登陆失败'。
"""
mysql
1.创建数据库
create database python charset=uft8;
2.创建表
create table py_users(
id int unsigned auto_increment not null primary key,
uname varchar(20) not null,
upwd char(40) not null,
);
"""
# 注册
import pymysql, pymongo, os
def login():
"""
登录
:return:
"""
try:
# 接收输入用户名、密码
uname = input('请输入用户名:')
upwd = input('请输入密码:')
print(uname+upwd)
# 根据用户名查询密码
# 先到mongodb上查,没有再到mysql上查
#client = pymongo.MongoClient('localhost', 27017)
# 连接数据库
#db = client.py3
# 连接py_users集合
#result = db.py_users.find_one({'uname': uname})
# 如果集合中的数据为空,在mysql中查询
#if result is None:
conn = pymysql.connect(host='localhost', port=3306, database='mydb2', user='root', password='wzh123sal',
charset='utf8')
if conn:
print('connect successful')
cur = conn.cursor()
sql = 'select * from py_users where uname=%s and upwd=%s;'
sql1 = "select * from py_users ;"
params = [uname, upwd]
#cur.execute(sql)
cur.execute(sql,params)
if cur:
print('cur successful')
result = cur.fetchone()
if result :
print(result[0]+':'+result[1])
print('登录成功')
show_stu()
else:
print('用户名不存在')
#else:
# print('登录成功')
except:
print("用户名未注册,请先注册")
sel = input("是否需要注册:1:注册 2:退出")
if sel == '1':
registered()
else:
os._exit(0)
def show_stu():
try:
conn = pymysql.connect(host='localhost', port=3306, database='mydb2', user='root', password='wzh123sal',
charset='utf8')
if conn:
print('connect successful')
cur = conn.cursor()
sql = "select * from student2;"
cur.execute(sql)
if cur:
print('cur successful')
results = cur.fetchall()
print('studentid'+' '+'studentname'+' '+'age'+' '+'gender')
print('-' * 30)
for row in results:
# studentid = row[0]
# studentname = row[1]
# age = row[2]
# gender = row[3]
print(f'{row[0]}',end='\t')
print(f'{row[1]}',end='\t')
print(f'{row[2]}',end='\t')
print(f'{row[3]}')
print('-'*30)
except:
print("no such tables!")
def registered():
"""
注册
:return:
"""
uname = input('请输入用户名:')
upwd = input('请输入密码:')
sql = 'select upwd from py_users where uname=%s'
params = [uname]
# 打开与数据库的连接
try:
conn = pymysql.connect(host='localhost', port=3306, database='mydb2', user='root', password='wzh123sal',
charset='utf8')
cur = conn.cursor()
# 判断用户名是否存在
sql = 'select count(*) from py_users where uname=%s'
params = [uname]
cur.execute(sql, params)
result = cur.fetchone()
if result[0] == 1:
print('用户名已经存在,注册失败')
else:
# 用户名不存在
sql = 'insert into py_users(uname,upwd) values(%s,%s)'
params = [uname, upwd]
result = cur.execute(sql, params)
conn.commit()
if result == 1:
print('注册成功')
else:
print('注册失败')
cur.close()
except Exception as e:
print('注册失败,原因是:%s' % e)
finally:
conn.close()
def main():
# 打印菜单
print('————功能选择——————')
print('1.登录')
print('2.注册')
sel = input("登录(1)or 注册(2)?")
try:
if sel == '1':
login()
elif sel == '2':
registered()
except Exception as e:
print('程序错误,%s'%e)
if __name__ == '__main__':
main()
- 点赞
- 收藏
- 关注作者
评论(0)