1、跑马灯效果
'''
跑马灯
'''
import os
import time
def main():
content='人生苦短,我用python....'
while True:
os.system('cls')
print(content)
time.sleep(0.2)
content=content[1:]+content[0]
#if __name__=='__main__':
main()
2、录入员工姓名及联系方式,并根据姓名进行查询
zd = {}
name = '请输入您的姓名:'
phone= '请输入您的电话:'
while True:
user_name = str(input(name))
user_phone = str(input(phone))
zd[user_name]=user_phone
ok = str(input('是否录入完成?[Y/N]'))
if ok == 'y' or ok == 'Y' or ok == '':
break
#查询用户
print('接下来是查询用户的电话号码!')
while True:
user_name = str(input(name))
if user_name in zd:
print('员工'+user_name+'的电话为:'+zd[user_name])
ok = str(input('是否查询完毕?[Y/N]'))
if ok == 'y' or ok == 'Y' or ok == '':
break
else:
print('当前用户不存在,请重新输入!')
3、查询列表或元组中的最大值
age = (15,25,35,40,24)
def maxage():
num1 = 0
for i in age:
if num1 < i:
num1 = i
return (num1)
print(maxage())
4、根据姓名查询业绩
ks = {'张三':'80','李四':'90','王五':'85'}
def a1():
tishi = '请输入要查询的姓名:'
name = input(tishi)
if name in ks.keys():
print(ks[name])
else:
print('当前用户不存在!')
a1()
5、使用用户输入的数字,计算由1到所输入数字的累加结果
def a2():
sum1=0
x = int(input('请输入一个数字:'))
for i in range(1,x+1):
sum1 += i
print(sum1)
a2()
6、使用函数计算列表除了最大数和最小数的数值总和
def a1():
a2 = ['80', '70', '75', '76', '36', '29', '86', '96']
sum1 = 0
for i in a2:
if i < max(a2) and i > min(a2):
sum1+=int(i)
print(sum1)
a1()
7、九九乘法表
def jiujiu():
for i in range(1,10):
for n in range(1,i+1):
print('%d x %d = %d' %(n,i,n*i),end =' ')
print(' ')
jiujiu()
8、面向对象编程
1)
'''
面向对象编程
1、定义类:关键字class
2、创建对象:对象名=类名(可能需要传递参数列表)
3、调用对象的方法:用对象名.方法
'''
class Dog():
'''模拟宠物狗'''
def __init__(self, name, age):
'''初始化'''
self.name = name
self.age = age
def sit(self):
'''模拟蹲下的动作'''
print(self.name.title() + "is sitting.")
def roll_over(self):
'''模拟狗狗打滚'''
print(self.name.title() + "rolled over.")
def woof(self):
'''模拟狗狗叫'''
print(self.name + '正在叫')
def life(self):
'''模拟表示旺财被常威被打死了'''
print(self.name + '被打死了')
# 基于类创建对象(实例)
my_dog = Dog(name="ssss", age=3)
my_dog.roll_over()
my_dog.sit()
my_dog.woof()
Dog('旺财', 5).life()
2)
class Car():
def __init__(self, brand, year):
self.a = '一汽大众'
self.b = brand
self.c = year
def info(self):
print("汽车的制造商是:" + self.a, ";品牌是:" + self.b, ";生产年份是:" + self.c)
car_info = Car(brand="宝来", year="2019-12-12")
car_info.info()
Baoma_info=Car(brand='宝马',year="2017-07-07")
Baoma_info.a="德国"
Baoma_info.info()
3)判断用户账号密码的登录信息是否正确
class User():
def __init__(self, user_name, password):
self.name = user_name
self.pwd = password
def check_user(self):
log = {'张三': '123', '李四': '456'}
if self.name in log.keys():
mima = log[self.name]
else:
print('该用户不存在!')
exit(1)
if self.name in log.keys() and self.pwd == mima:
print("登录成功!!" + "您的账号是:" + self.name, ",您的密码是:" + self.pwd)
else:
print("密码输入错误,登录失败!")
s_name = str(input("请输入用户名:"))
s_pwd = str(input("请输入密码:"))
login = User(s_name, s_pwd)
login.check_user()
4)
from time import sleep
class Clock(object):
'''数字时钟'''
def __init__(self,hour=0,minute=0,second=0):
'''初始化方法
:param hour: 时
:param minute:分
:param second:秒
'''
self._hour = hour
self._minute=minute
self._second=second
def run(self):
"""走字"""
self._second +=1
if self._second == 60:
self._second=0
self._minute +=1
if self._minute==60:
self._minute=0
self._hour+=1
if self._hour == 24:
self._hour=0
def show(self):
"""显示时间"""
return '%02d:%02d:%02d' % \
(self._hour,self._minute,self._second)
def main():
clock=Clock(23,59,58)
while True:
print(clock.show())
sleep(1)
clock.run()
if __name__ == '__main__':
main()
9、时钟
from time import sleep
class Clock(object):
'''数字时钟'''
def __init__(self,hour=0,minute=0,second=0):
'''初始化方法
:param hour: 时
:param minute:分
:param second:秒
'''
self._hour = hour
self._minute=minute
self._second=second
def run(self):
"""走字"""
self._second +=1
if self._second == 60:
self._second=0
self._minute +=1
if self._minute==60:
self._minute=0
self._hour+=1
if self._hour == 24:
self._hour=0
def show(self):
"""显示时间"""
return '%02d:%02d:%02d' % \
(self._hour,self._minute,self._second)
def main():
clock=Clock(23,59,58)
while True:
print(clock.show())
sleep(1)
clock.run()
if __name__ == '__main__':
main()
10、父类与子类
一个.py文件就是一个模块;
模块===》类===》方法====》代码块 #这就是封装
基于父类创建子类:
1、子类必须和父类写在同一个文件中;
2、子类的类名后括号中要填写父类的类名;
3、子类的init()函数中必须调用父类的init()函数
4、使用子类实例化对象,这个对象自动继承父类所拥有的属性和方法
5、对于子类特有的属性和方法,我们可以在子类中任意定义。
6、方法重写(重载):子类方法名与父类的方法名相同,内容由自己来控制
7、使用实例做属性,就是提取出一些属性,封装到一个类中
8、当子类继承了父类以后,就可以调用父类中的函数,即使子类没有这些函数。
'''
父类与子类的定义与调用
'''
class Pet():
'''宠物父类'''
def __init__(self, name, sex):
self.name = name
self.sex = sex
def get_info(self):
print('宠物' + str(self.name) + '是' + str(self.sex) + '的')
class Dog(Pet):
'''狗子类'''
def __init__(self, name, sex, age):
self.age = age
super().__init__(name, sex)
def get_info(self):
print('宠物' + str(self.name) + '是' + str(self.sex) + '的,年龄是' + str(self.age) + '岁!')
class Qie(Pet):
def __init__(self, name, sex, age):
self.age = age
super().__init__(name, sex)
def get_info(self):
print('宠物' + str(self.name) + '是' + str(self.sex) + '的,年龄是' + str(self.age) + '岁!')
if __name__ == '__main__':
dog = Dog('李四', '女', '5')
dog.get_info()
qie = Qie('付嘉豪', '男', '18')
qie.get_info()
============= 读取文件以及判断 ===================
11、读取文件
'''
拷贝图片:读取二进制文件,生成新的文件。
'''
def copy_pri():
try:
with open('a.png','rb') as pri1:
old_pri=pri1.read()
with open('bb.png','wb') as pri2:
pri2.write(old_pri)
except (FileExistsError,FileNotFoundError,IOError,Exception):
print('文件不存在!')
else:
print('图片读取成功!')
finally:
print('程序退出!')
if __name__ == "__main__":
copy_pri()
12:
1、加法运算
提示用户提供数值输入时,常出现的一个问题是,用户提供的是文本而不是数字。在这种情况下,当你尝试将输入转换为整数时,将引发ValueError异常。编写一个程序,提示用户输入两个数字,再将它们相加并打印结果。在用户输入的任何一个值不是数字时都捕获ValueError异常,并打印一条友好的错误消息。对你编写的程序进行测试:先输入两个数字,再输入一些文本而不是数字。
def jiafa_sum():
try:
num1=int(input('请输入第一个数:'))
num2=int(input('请输入第二个数:'))
print('{0}+{1}={2}'.format(num1,num2,num1+num2))
except ValueError:
print('你输入的不是数字!')
if __name__ == "__main__":
jiafa_sum()
13、读两个文件
def showname(filename):
try:
with open(filename, 'r', encoding='utf-8') as dogs:
data = dogs.read()
print(filename + '的内容如下:')
print(data)
except FileNotFoundError:
pass
if __name__ == '__main__':
showname('dogs.txt')
showname('cats.txt')
14、json文件的读取与写入
import json
nums = [1, 2, 3, 4, 5, 6, 7, 7, 8, ]
filename = 'num.json'
with open(filename, 'w') as f_obj:
json.dump(nums, f_obj)
with open(filename, ) as f_obj:
numbers = json.load(f_obj)
print(numbers)
15、保存和读取用户生成的数据
json文件读取和写入的合并
import json
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
username = input('请输入用户名:')
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
print('我们记住您了,欢迎' + username + '再回来!')
else:
print("欢迎回来," + username + '!')
16、获取疫情实时图
import requests
import json
from pyecharts.charts import Map
from pyecharts import options as opts
def get_info():
# 1.从原始网站获取疫情数
url = 'https://interface.sina.cn/news/wap/fymap2020_data.d.json'
result = requests.get(url).text
html = json.loads(result)
# 2.数据分析
data = list()
for provice in html['data']['list']:
data.append((provice['name'], provice['value']))
# print(data)
# 3.页面渲染
yq_news = Map()
yq_news.set_global_opts(title_opts=opts.TitleOpts(title='疫情实时图-----' + html['data']['times']),
visualmap_opts=opts.VisualMapOpts(max_=1000))
yq_news.add('确诊', data, maptype='china')
# 4.生成html文件
yq_news.render('ncov.html')
if __name__ == '__main__':
get_info()
17、获取网站PV量及UV量
#!/usr/local/python38/bin/python3
#-*- coding:UTF-8 -*-
from __future__ import print_function
ips = []
with open('access.log') as f:
for line in f:
ips.append(line.split()[0])
print('PV is {0}'.format(len(ips)))
print('UV is {0}'.format(len(set(ips))))
18、获取磁盘信息
#!/usr/bin/env python3
# -*- conding:utf-8 -*-
from __future__ import print_function
from collections import namedtuple
disk = namedtuple('Disk', 'major_number minor_number device_name'
' read_count read_merged_count read_sections'
' time_spent_reading write_count write_merged_count'
' write_sections time_spent_write io_requests'
' time_spent_doing_io weighted_time_spent_dong_io')
def get_disk_info(device):
with open('/proc/diskstats') as f:
for line in f:
if line.split()[2] == device:
return disk(*(line.split()))
raise RuntimeError('设备({0})没找到。。。'.format(device))
def main():
disk_info = get_disk_info('sda1')
print(disk_info)
if __name__ == '__main__':
main()