- # -*- coding:utf-8 -*-
-
-
- #初始化变量
- a=100
- b=5
- c=3.1415926
- d='好搞笑'
- e="\t是吗?\n"
- #打印变量值
- print(a)
- print(b)
- print(c)
- print(d)
- print(e)
- print(a*b)
- print(a*c)
- print(a,d,e)
- print("@"*10,"O"*5)
-
- number="789"
- print(float(number))
- print(int(number))
- print(repr(number))
- print(str(number))
- print(eval(number))
-
- #通过ASCII码显示字符,需要使用chr函数进行转换
- print('a')
- print(chr(97))
输出内容:
- 100
- 5
- 3.1415926
- 好搞笑
- 是吗?
-
- 500
- 314.15926
- 100 好搞笑 是吗?
-
- @@@@@@@@@@ OOOOO
- 789.0
- 789
- '789'
- 789
- 789
- a
- a
- name=input("请输入字符:")
- print(name+" 的ASCII码是:",ord(name))
输出内容
- 请输入字符:A
- A 的ASCII码是: 65
- import datetime
- import keyword
-
- print('当前年份:'+str(datetime.datetime.now().year))
- print('当前时间:'+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
-
- print(keyword.kwlist)
输出内容
- 当前年份:2023
- 当前时间:2023-10-02 19:16:32
- ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global',
- 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
- # -*- coding:utf-8 -*-
- #列表
- person=['中国人','美国人','黑人']
- print('输出:{}'.format(person))
- print(person[0])
- print(person[1])
- print(person[2])
- print(person[-1])
- print(person[-2])
- print(person[-3])
- #切片
- print(person[0:2])
- #序列相加
- person2=['中国人2','美国人2','黑人2']
- p_list=person+person2
- print(p_list)
-
- #序列长度
- print(len(p_list))
-
- print('中国人' in person)
- print('中国人' in person2)
- print('中国人' not in person2)
-
- print(list(p_list))
- print(list(range(0,20)))
-
- #删除列表
- del p_list
- #遍历列表
- flower=['玫瑰','牡丹','兰花','菊花']
- for i in flower:
- print(i)
- #输出索引值
- for index,i in enumerate(flower):
- print(index+1,i)
-
- print(flower,len(flower))
-
- flower.append('菊花')
- print(flower,len(flower))
-
- print(flower.count('菊花'))
- print(flower.index('兰花'))
-
-
-
输出内容
- 输出:['中国人', '美国人', '黑人']
- 中国人
- 美国人
- 黑人
- 黑人
- 美国人
- 中国人
- ['中国人', '美国人']
- ['中国人', '美国人', '黑人', '中国人2', '美国人2', '黑人2']
- 6
- True
- False
- True
- ['中国人', '美国人', '黑人', '中国人2', '美国人2', '黑人2']
- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
- 玫瑰
- 牡丹
- 兰花
- 菊花
- 1 玫瑰
- 2 牡丹
- 3 兰花
- 4 菊花
- ['玫瑰', '牡丹', '兰花', '菊花'] 4
- ['玫瑰', '牡丹', '兰花', '菊花', '菊花'] 5
- 2
- 2
- # -*- coding:utf-8 -*-
- import random
-
- #元组
- title=('python3',3,('弥勒','无我'),['爬虫','web'])
- print(title)
- print(title[0])
- print(title[2])
- print(title[2][0])
- print(title[3])
- print(title[3][1])
-
- random_number=(random.randint(10,100) for i in range(10))
- random_number=tuple(random_number)
- print('转化后:',random_number)
输出内容
- ('python3', 3, ('弥勒', '无我'), ['爬虫', 'web'])
- python3
- ('弥勒', '无我')
- 弥勒
- ['爬虫', 'web']
- web
- 转化后: (89, 59, 12, 84, 10, 39, 72, 30, 12, 73)
- # -*- coding:utf-8 -*-
- import random
-
- str1='人生,苦短,潇洒,晚年'
- print(str1[0])
- print(str1[5:])
- print(str1[:4])
- print(str1[2:4])
- print(str1.split(','))
-
- #异常处理
- try:
- print(str1[20])
- except IndexError:
- print('超出索引范围')
-
- i=0
- while i<=6:
- i=i+1
- print(i,'勇闯天涯')
- 人
- ,潇洒,晚年
- 人生,苦
- ,苦
- ['人生', '苦短', '潇洒', '晚年']
- 超出索引范围
- 1 勇闯天涯
- 2 勇闯天涯
- 3 勇闯天涯
- 4 勇闯天涯
- 5 勇闯天涯
- 6 勇闯天涯
- 7 勇闯天涯
- # -*- coding:utf-8 -*-
-
- #创建空字典
- dictionary=dict()
- dictionary={}
- dictionary={'qq':'118951300','name':'海盗'}
- print(dictionary)
-
- #通过映射函数创建字典
- id=['22','55']
- name=['邓小平','江大']
- dictionary=dict(zip(id,name))
- print(dictionary)
-
- # 通过给定的键值对创建字典
- dictionary=dict(夏利 = '上海',张三 = '徐州')
- print(dictionary)
- print(dictionary.get('夏利'))
-
- #遍历字典
- for key,value in dictionary.items():
- print(key,'在',value)
- {'qq': '118951300', 'name': '海盗'}
- {'22': '邓小平', '55': '江大'}
- {'夏利': '上海', '张三': '徐州'}
- 上海
- 夏利 在 上海
- 张三 在 徐州
- # -*- coding:utf-8 -*-
-
- #集合
- set1={2,2,3,4,5}
- set2={'java','python',2,3,('历史','名人')}
-
-
- print(set1)
- print(set2)
-
- set1.add(999)
- set1.pop()
- set1.remove(4)
- print(set1)
- set1.clear()
- print(set1)
-
- #集合的交集、并集、差集
-
- p1=set(['java','js','php'])
- p2=set(['java','python','php'])
-
- print('p1: ',p1)
- print('p2: ',p2)
-
- print('交集: ',p1 & p2)
- print('并集: ',p1 | p2)
- print('差集: ',p1 - p2)
- {2, 3, 4, 5}
- {2, 3, 'python', ('历史', '名人'), 'java'}
- {3, 5, 999}
- set()
- p1: {'js', 'php', 'java'}
- p2: {'python', 'php', 'java'}
- 交集: {'php', 'java'}
- 并集: {'python', 'php', 'js', 'java'}
- 差集: {'js'}
- # -*- coding:utf-8 -*-
-
- #类
- class Animal:
- '''动物类'''
- info='动物'
- __have='having' #私有属性
- def __init__(self,eat,sleep):
- print(Animal.__have)
- print(Animal.info)
- print(eat)
- print(sleep)
- def see(self):
- print('see animal')
-
- class Dog(Animal):
- def __init__(self,eat,sleep):
- super().__init__(eat,sleep)
- print('run')
-
-
- dog_eat='吃'
- dog_sleep='睡'
- dog=Animal(dog_eat,dog_sleep)
- print('私有属性:',dog._Animal__have) #访问私有属性
-
- dog1=Dog(dog_eat,dog_sleep)
- dog1.see()
-
- having
- 动物
- 吃
- 睡
- 私有属性: having
- having
- 动物
- 吃
- 睡
- run
- see animal
- import os
-
- # 遍历目录
- dir_path = r'C:\Windows\Web'
- print('==== os.listdir => str')
- for i in os.listdir(dir_path):
- print(i, type(i), len(i))
-
- print('==== os.scandir => nt.DirEntry')
- for i in os.scandir(dir_path):
- if i.is_dir():
- print('dir', i, type(i), i.name, i.path)
- elif i.is_file():
- print('file', i, type(i), i.name, i.path)
-
- print('====================================================')
- # 遍历目录下的子目录所有文件
- walks = os.walk(dir_path)
- for dir_path, dir_names, files in walks:
- print('发现目录', dir_path, dir_names, files)
- for f in files:
- if f.endswith('.jpg') and f.startswith('img10'):
- print(f)
- import datetime
- import os
- import time
-
- # stat
- dir_path = r'C:\Windows\Web\Screen'
- for i in os.scandir(dir_path):
- print(i.stat())
- print(datetime.datetime.fromtimestamp(i.stat().st_atime),datetime.datetime.fromtimestamp(i.stat().st_mtime))
-
- print(time.ctime(1706708139))
- print(datetime.datetime.fromtimestamp(1706708139))
- import datetime
- import time
-
- # 文件写入读取
- file_path = r'./hello.txt'
- with open(file_path, 'w', encoding='utf-8') as file:
- file.write(str(datetime.datetime.fromtimestamp(time.time())))
- file.write('\n')
- file.write('end')
-
- with open(file_path, 'r', encoding='utf-8') as file:
- print(file.readlines())
- from tempfile import TemporaryFile, TemporaryDirectory
-
- with TemporaryFile('w+') as tmp_file:
- tmp_file.write('大家好12345')
- tmp_file.seek(2)
- print(tmp_file.readlines())
- print(tmp_file.name)
- input('回车即可')
-
- with TemporaryDirectory() as tmp_dir:
- print(tmp_dir)
- input('回车即可')
- import os
-
- path_name = '新建目录'
- if not os.path.exists(path_name):
- os.mkdir(path_name)
- print('已新建:', path_name)
- else:
- print('已存在', path_name)
-
- print('==============================')
-
- path_names = '一/二/三/四/五'
- if not os.path.exists(path_names):
- os.makedirs(path_names)
- print('已新建:', path_names)
- else:
- print('已存在', path_names)
-
-
-
- # input('回车即可')
- import shutil
- # 复制src到dst
- shutil.copy('./hello.txt', 'C:\\')
- with open('C:\\hello.txt') as r:
- print(r.readlines())
- shutil.copytree('./解析库的使用', './一/二/三/四/五/222')
- import shutil
-
- shutil.move('./config.py', './新建目录')
- shutil.move('./一/新建目录', './')
- import os
- import shutil
-
- # 删除文件
- os.remove('./新建目录/config.py')
- # 删除目录
- shutil.rmtree('./一')
- import os
-
- os.rename('./新建目录/hello.txt', 'aa.txt')
-
- os.rename('./新建目录', 'hello')
- import zipfile
-
- # 读取压缩包
- with zipfile.ZipFile('./解析库的使用.zip') as f:
- print(f.namelist())
- for name in f.namelist():
- info = f.getinfo(name)
- print(name, info.file_size, info.compress_size)
- import zipfile
-
- # 解压压缩包
- with zipfile.ZipFile('./解析库的使用.zip', 'r') as zip_obj:
- # zip_obj.extract('解析库的使用/1-1.py', './hello')
- zip_obj.extractall('./hello')
- print(zip_obj.namelist())
- import zipfile
-
- # 创建压缩包
- file_lst = ['hello.txt', 'test.html']
- with zipfile.ZipFile('./demo.zip', 'w') as zip_obj:
- for file in file_lst:
- zip_obj.write(file)
- print(zip_obj.namelist())
- import zipfile
-
- # 添加文件到压缩包
- with zipfile.ZipFile('./demo.zip', 'a') as zip_obj:
- zip_obj.write('aa.txt')
- print(zip_obj.namelist())