一.制作exe程序
python脚本如果在没有安装python的机器上不能运行,所以将脚本打包成exe文件,降低脚本对环境的依赖性,同时运行更加迅速,还有为了防止代码被盗
(一)安装第三方模块pyinstaller
pip install pyinstaller
(二)图标
在阿里巴巴矢量图标库寻找自己喜欢的图标
在线图片格式转换网站将图片格式转化为.ico
(三)生成.exe
pyinstaller -F -i temper.ico 温度转换.py # -i制定图标 -F将依赖性文件一起打包
注意位置,我这里将图标放在和代码一块
二.内置数据结构简介
字符串str:单引号,双引号,三引号引起来的字符信息。三重引号也可以进行多行注释
数组array:存储同种数据类型的数据结构。[1, 2, 3], [1.1, 2.2, 3.3]
列表list:打了激素的数组, 可以存储不同数据类型的数据结构. [1, 1.1, 2.1, 'hello']
元组tuple:带了紧箍咒的列表, 和列表的唯一区别是不能增删改。
集合set:不重复且无序的。 (交集和并集)
字典dict:{“name”:"westos", "age":10
# 1. 字符串str
字符串或串(String)是由数字、字母、下划线组成的一串字符
s1 = 'hello'
s2 = "hello"
s3 = """
*********************** 学生管理系统 ************************
"""
print(type(s1), type(s2), type(s3))
# 2. 列表List
li1 = [1, 2, 3, 4]
print(li1, type(li1))
li2 = [1, 2.4, True, 2e+5, [1, 2, 3]]
print(li2, type(li2))
# 3. 元组tuple
# 易错点: 如果元组只有一个元素,一定要加逗号。
t1 = (1, 2.4, True, 2e+5, [1, 2, 3])
print(t1, type(t1))
t2 = (1,)
print(t2, type(t2))
# 4. 集合set(无序,不重复)
set1 = {1, 2, 1, 2, 3, 1, 20}
print(set1) # 不重复{1, 2, 20}
set2 = {1, 2, 3}
set3 = {2, 3, 4}
print("交集:", set2 & set3)
print("并集:", set2 | set3)
# 5. 字典dict: {“name”:"westos", "age":10}
# key和value, 键值对, 通过key可以快速找到value值。
user = {"name":'westos', 'age':10}
print(user, type(user))
print(user['name'])
print(user['age'])
三.字符串
字符串或串(String)是由数字、字母、下划线组成的一串字符.Python 里面最常见的类型.可以简单地通过在引号间(单引号,双引号和三引号)包含字符的方式创建它.
转义符号:一个反斜线加一个单一字符可以表示一个特殊字符,通常是不可打印的字符,常用的主要是\n \t
删除字符和字符串:字符串是不可变的,只能通过赋一个空字符串或者使用 del 语句来清空或者删除一个字符串.
但是没有必要显示的删除字符串,定义这个字符串的代码结束时会自动释放这些字符串
四.字符串的基本特性
# 1. 连接操作符和重复操作符:连接符( + ), 重复操作符( * ),计算长度 len()
连接操作符: 从原有字符串获得一个新的字符串
重复操作符: 创建一个包含了原有字符串的多个拷贝的新字符串
name = 'westos'
print('hello ' + name)
# 1元 + 1分 = 1元 + 0.01元 = 1.01元
print('hello' + str(1))
print("*" * 30 + '学生管理系统' + '*' * 30)
# 2. 成员操作符(in ,not in)
成员操作符用于判断一个字符或者一个子串(中的字符)是否出现在另一个字符串中。出现则返回 True,否则返回 False.
s = 'hello westos'
print('westos' in s) # True
print('westos' not in s) # False
print('x' in s) # False
# 3. 正向索引和反向索引
索引(s[i] ): 获取特定偏移的元素
索引的分类: 正向索引, 反向索引
s = 'WESTOS'
print(s[0]) # 'W'
print(s[3]) # 'T'
print(s[-3]) # 'T'
# 4. 切片
回顾:
range(3):[0, 1, 2]
range(1, 4): [1, 2, 3]
range(1, 6, 2): [1, 3, 5]
切片: 切除一部分的内容
s[start:end:step]
s[:end]:
s[start:]:
(1)切片S[i:j]提取对应的部分作为一个序列:
(2)如果没有给出切片的边界,切片的下边界默认为0,上边界为字符串的长度;扩展的切片S[i:j:k],其中i,j含义同上,k为递增步长;
(3)s[:]获取从偏移量为0到末尾之间的元素,是实现有效拷贝的一种方法;
(4)s[::-1]是实现字符串反转的一种方法;
总结:
s[:n]: 拿出前n个元素
s[n:]: 除了前n个元素, 其他元素保留
s[:]:从头开始访问一直到字符串结束的位置
s[::-1]: 倒序输出
s = 'hello world'
print(s[1:3]) # 'el'
print(s[:3]) # 'hel'
print(s[:5]) # 拿出字符串的前5个字符
print(s[1:]) # 'ello world'
print(s[2:]) # 'llo world'
print(s[:]) # 拷贝字符串
print(s[::-1])
# 5. for循环访问
s = 'world'
count = 0
for item in s:
count += 1
print(f"第{count}个字符:{item}")
# 练习:用户输入一个字符串, 判断该字符串是否为回文字符串
# eg: "aba"是回文字符串, "abba"也是回文字符串。 "abc"不是回文字符串
while True:
s = input('输入字符串:')
result = "回文字符串" if s == s[::-1] else "不是回文字符串"
print(s + "是" + result)
五.字符串内建方法
(一)字符串的判断与转换
# 1. 类型判断
s = 'HelloWORLD'
print(s.isalnum()) # True
print(s.isdigit()) # Flase
print(s.isupper()) # False
# 2. 类型的转换
print('hello'.upper())
print('HellO'.lower())
print('HellO WOrld'.title())
print('HellO WOrld'.capitalize())
print('HellO WOrld'.swapcase())
# 需求: 用户输入Y或者y都继续继续代码
# yum install httpd
choice = input('是否继续安装程序(y|Y):')
if choice.lower() == 'y':
print("正在安装程序......")
(二)字符串的开头和结尾匹配
# startswith
url = 'http://www.baidu.com'
if url.startswith('http'):
# 具体实现爬虫,感兴趣的话可以看request模块。
print(f'{url}是一个正确的网址,可以爬取网站的代码')
# endswith:
# 常用的场景: 判断文件的类型
filename = 'hello.png'
if filename.endswith('.png'):
print(f'{filename} 是图片文件')
elif filename.endswith('mp3'):
print(f'{filename}是音乐文件')
else:
print(f'{filename}是未知文件')
(三)字符串的数据清洗
数据清洗的思路:
lstrip: 删除字符串左边的空格(指广义的空格: \n, \t, ' ')
rstrip: 删除字符串右边的空格(指广义的空格: \n, \t, ' ')
strip: 删除字符串左边和右边的空格(指广义的空格: \n, \t, ' ')
replace: 替换函数, 删除中间的空格, 将空格替换为空。replace(" ", )
>>> " hello ".strip()
'hello'
>>> " hello ".lstrip()
'hello '
>>> " hello ".rstrip()
' hello'
>>> " hel lo ".replace(" ", "")
'hello'
(四)字符串的位置调整
>>> "学生管理系统".center(50)
' 学生管理系统 '
>>> "学生管理系统".center(50, "*")
'**********************学生管理系统**********************'
>>> "学生管理系统".center(50, "-")
'----------------------学生管理系统----------------------'
>>> "学生管理系统".ljust(50, "-")
'学生管理系统--------------------------------------------'
>>> "学生管理系统".rjust(50, "-")
'--------------------------------------------学生管理系统'
(五)字符串的搜索,统计
>>> s = "hello world"
>>> s.find("llo")
2
>>> s.index("llo")
2
>>> s.find("xxx")
-1
>>> s.index("xxx")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
# find如果找到子串, 则返回子串开始的索引位置。 否则返回-1
# index如果找到子串,则返回子串开始的索引位置。否则报错(抛出异常).
>>> s.count("xxx")
0
>>> s.count("l")
3
>>> s.count("o")
2
(六)字符串的分离与拼接
>>> ip = "172.25.254.100"
# 分离
>>> ip.split('.')
['172', '25', '254', '100']
>>> items = ip.split('.')
>>> items
['172', '25', '254', '100']
# 拼接
>>> items
['172', '25', '254', '100']
>>> # 需求: 将四个数字用'-'拼接起来
>>> "-".join(items)
'172-25-254-100'
练习
"""
# 需求: 生成100个验证码, 每个验证码由2个数字和2个字母组成。
import random #调用随机模块
random.choice("0123456789")
'6'
random.choice("0123456789") + random.choice('0123456789') + random.choice('abcdef')
'16b'
import string #调用字符串模块
string.digits
'0123456789'
string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
random.sample(string.ascii_letters, 4)
['z', 'N', 'u', 't']
"".join(random.sample(string.ascii_letters, 4)) #拼接
'aMUF'
"".join(random.sample(string.digits, 2)) + "".join(random.sample(string.ascii_letters, 4)) #连接
'95sGFj'
"""
import random
import string
for i in range(100):
print("".join(random.sample(string.digits, 2)) + "".join(random.sample(string.ascii_letters, 4)))
"""
设计一个程序,用来实现帮助小学生进行算术运算练习,
它具有以下功能:
提供基本算术运算(加减乘)的题目,每道题中的操作数是随机产生的,
练习者根据显示的题目输入自己的答案,程序自动判断输入的答案是否正确
并显示出相应的信息。最后显示正确率。
1+2=?
3*6=?
"""
import random
count = int(input("请输入题数"))
right_count = 0
for i in range(count):
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
symbol = random.choice(["+", "-", "*"])
result = eval(f"{num1}{symbol}{num2}")
question = f"{num1} {symbol} {num2} = ?"
print(question)
user_answer = int(input("Answer:"))
if user_answer == result:
print("Right")
right_count += 1
else:
print("Error")
print("Right percent: %.2f%%" %(right_count/count*100))
while True:
i = 0
j = 0
move = str(input("请输入移动顺序:"))
move1=move.upper()
for s in move1:
if s == "R":
i += 1
elif s == "L":
i -= 1
elif s == "U":
j += 1
elif s == "D":
j -= 1
else:
print("输入有误")
break
else:
if i == 0 and j==0:
print("true")
else:
print("false")
while True:
s = input('请输入字符串:')
s1=s.lower()
s2=s1.replace(" ","")
s3=s2.split(',')
s4="".join(s3)
s5=s4.split(":")
s6="".join(s5)
result="是回文串" if s6 == s6[::-1] else "不是回文字符串"
print(s+result)