Jetbrains系列软件常用快捷键及Python编程从入门到实践

发布于 2021-01-05  159 次阅读


一、Jetbrains系列软件常用快捷键

代码的格式化:Ctrl+Alt+L
调出快速搜索框:两次Shift
打开的文件中查找:Ctrl+F
全局查找快捷键默认:Ctrl+Shift+F (如果不可以就是与搜狗输入法的冲突了)
Getter和Setter封装:Alt+Insert
自动补全代码:Alt+/
注释代码:Ctrl+/
撤销:Ctrl+Z
撤销返回:Ctrl+Shift+Z
复制本行代码到下一行:Ctrl+D
删除光标所在行的代码:Ctrl+Y
自动注释代码:Ctrl+Shift+/
万能的快捷键:Alt+Enter
测试接口的类:在要测试的上Ctrl + shift + t
快速展开/折叠全部方法:Ctrl + Shift + +/-
向上插入一行空格:CTRL+Enter
向下插入一行空格:Shift+Enter
上端或下端插入一空行:shift+Alt+方向键
快速给代码加上组合语句try/catch等:CTRL+ALT+T
多行相同的代码一起修改或者删除:Ctrl+Shift+Alt 或者 按住鼠标的滚轮向下拉 也可!
运行编写的py文件:Ctrl+Shift+F10

二、《Python 编程从入门到实践》P1~P200 学习总结

1.基本数据类型的运算

print("Python针对于字符串的大小写和去除空白")
message = "\tpython xue xi\t"
# 每个单词的首字母大写的写法
print(message.title())
# 单词全部大写的写法
print(message.upper())  
#  单词全部小写的写法
print(message.lower())  
# 去除字符串前面的空白
print(message.lstrip())
# 去除字符串后面的空白
print(message.rstrip())
# 去除字符串两边的空白
print(message.strip())

print("\nPython的加减乘除混合运算和幂运算")
print(3 + 2)
print(3 - 2)
print(3 * 2)
print(3 / 2)
print(3 ** 2 + 3)
print(0.1 + 2)
print(0.1 + 0.2)
print(0.1 * 2)
print((1 + 2 - 1) * 4 / 4)

print("\n使用函数str()避免类型的错误")
age = 20
print("我今年的年龄是" + str(age) + "岁\n")

print("Python的列表和访问元素和元素的大小写以及去除空格")
shenghuo = ["chifan", "xuexi", "shuijiao", " shangban"]
print(shenghuo)
print(shenghuo[0].title())  #首字母大写
print(shenghuo[1].upper())        #全部字母大写
print(shenghuo[2].lower())        #全部字母小写
print(shenghuo[3].lstrip())        #去除字符串前面的空白
# 访问列表的元素于去除空格和拼接字符的混合使用
print(shenghuo[-1])
print(shenghuo[-2])
print("一天中要先" + shenghuo[0] + "然后再" + shenghuo[-1].lstrip() + "继续再" + shenghuo[1] + "最后再" + shenghuo[-2])

# 修改 添加 删除 元素
che = ["motuo", "qiche", "zixingche", 'huoche']
print(che)
# 修改
che[0] = "kache"
print(che)
# 添加
che.append("danche")
print(che)

#定义一个空列表
aihao = []
aihao.append("chifan")
aihao.append("shuijiao")
aihao.append("dadoudou")
print(aihao)

# 在列表中插入元素
aihao.insert(1, "xuexi")
print(aihao)

# 删除
del aihao[2]
print(aihao)
del aihao[-1]
print(aihao)

# pop删除列表中最后元素并使用删除的最后元素
shanzuihou = aihao.pop()
print(shanzuihou)
print("现在我唯一的爱好是" + shanzuihou.title())
shanchu = aihao.pop(0)
print(shanchu)
print("我每天都要" + shanchu.title())

# 根据值移除元素
che = ["motuo", "qiche", "zixingche", 'huoche']
che.remove("huoche")
print(che)
che.remove("motuo")
print(che)

# 组织列表 sort() 永久性排序 abcde正向或逆向顺序排序
che = ["motuo", "qiche", "zixingche", 'huoche']
# 正向的排序
che.sort()
print(che)
# 反向的排序
che.sort(reverse=True)
print(che)

# 组织列表 sorted() 临时性排序  abcde正向或逆向顺序排序
# 临时正向排序
print(sorted(che))
# 临时反向排序
print(sorted(che, reverse=True))

# 倒着打印列表  永久性的修改顺序 也可以随时改回来
che = ["motuo", "qiche", "zixingche", 'huoche']
# 倒着打印
che.reverse()
print(che)
# 再次倒着改回
che.reverse()
print(che)

# 确认列表的长度 结果为4
che = ["motuo", "qiche", "zixingche", 'huoche']
print(len(che))

# for循环遍历整个列表   for 变量名 in 遍历的列表变量名:
che = ["motuo", "qiche", "zixingche", 'huoche']
for che1 in che:
    print(che1)

# 在for循环中执行更多的操作 Python 对于缩进是极为的严格
for che2 in che:
    print(che2.title() + '都是交通工具!')
print("出门的时候都可以使用!")

# 直接的在for循环中创建打印列表
for wenzi in ["你好", "我也好"]:
    print(wenzi)

# 创建数字列表
for shuzi in range(1, 5):
    print(shuzi)

# 将1-4 输出为一个数列表
number = list(range(1, 5))
print(number)
# 将numer中的列表通过for循环遍历出来
for num in number:
    print(num)

# 打印10以内的偶数 从第一个数 2开始不断的加2
oushu = list(range(2, 10, 2))
print(oushu)

# 1-10每个整数的平方组成一个列表
liebiaos = []
for value in range(1, 11):
    liebiaos.append(value ** 2)
print(liebiaos)
print(liebiaos[-1])

# 对数字列表进行简单的统计 最大值,最小值,求和
number = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(max(number))
print(min(number))
print(sum(number))

# 对数字列表解析 列表中每个数的平方赋值给message
message = [value ** 3 for value in range(1, 11)]
print(message)

# 列表的一部分 切片
che = ["motuo", "qiche", "zixingche", 'huoche']
print(che[0:2])
print(che[1:-1])
print(che[:4])  # 没有指定一个开头的索引,默认从0开始
print(che[0:])  # 没有指定一个结尾的索引,默认到最后结束

# for循环遍历切片 并让单词的首字母大写
che = ["motuo", "qiche", "zixingche", 'huoche']
for che3 in che[:2]:
    print(che3.title())

# 复制列表  以及验证列表是两个列表
che = ["motuo", "qiche", "zixingche", 'huoche']
gongju = che[:]
print(che)
print(gongju)
# 验证复制的列表是两个列表
che.append("kache")
print(che)
gongju.append("daba")
print(gongju)

# 元组:Python将不能修改的值称为不可变的,而不可变的列表被称为元组! 不能修改的是元素,而变量是可以修改的
# 定义元组  遍历元组中的所有的值
yuanzu = (100, 50)
print(yuanzu[0])
print(yuanzu[1])

# for遍历元组的所有值
yuanzu = (100, 20, 30)
for bianli in yuanzu:
    print(bianli)

# for修改元组变量
yuanzu = (100, 50)
for bianli in yuanzu:
    print(bianli)
yuanzu = (200, 300)
for bianli in yuanzu:
    print(bianli)

# if语句的使用 不是根据条件顺序输出,而是根据列表的排列顺序和条件输出
che = ["motuo", "qiche", "zixingche", 'huoche']
for che1 in che:
    if che1 == 'qiche':
        print(che1.upper())  # 全部大写  QICHE
    else:
        print(che1.title())  # 首字母大写   Motuo Zixingche Huoche

# 检查特定值是否包含在列表中 或者 是否不包含在列表中
che = ["motuo", "qiche", "zixingche", 'huoche']
baohan = 'huoche1'
if baohan in che:
    print(baohan + '包含在列表中')
else:
    print((baohan + "不包含在列表中"))
if baohan not in che:
    print(baohan.title() + '不包含在列表中')

# 简单的条件判断语句的使用 if if-else if_elif-else
a = 18
if a > 17:
    print('a的值大于17')
if a > 19:
    print('a的值大于19')
else:
    print('a的值小于19')
if a > 19:
    print('a的值大于19')
elif a == 18:  # Java中的 else if 在Python 中就是elif
    print('a的值是18')
else:
    print('a的值小于19')

2.Python之禅

import this

ZJV_42KHJLQNO46OPG336ca32af899c57b.png

3.Python关键字

# 输出Python 中的关键字
# ['False', 'None', 'True', 'and', 'as', 'assert', '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']
import keyword
print(keyword.kwlist)

4.Python ()[]{}区别

() 表示元组

# 元组:Python将不能修改的值称为不可变的,而不可变的列表被称为元组! 不能修改的是元素,而变量是可以修改的
# 定义元组  遍历元组中的所有的值
yuanzu = (100, 50)
print(yuanzu[0])
print(yuanzu[1])
# for遍历元组的所有值
yuanzu=(100,20,30)
for bianli in yuanzu:
    print(bianli)
# for修改元组变量
yuanzu = (100, 50)
for bianli in yuanzu:
    print(bianli)
yuanzu=(200,300)
for bianli in yuanzu:
    print(bianli)

[]表示列表

# 组织列表 sort() 永久性abcde正向或逆向排序
che = ["motuo", "qiche", "zixingche", 'huoche']
# 正向的排序
che.sort()
print(che)
# 反向的排序
che.sort(reverse=True)
print(che)
# 组织列表 sorted() 临时性abcde 正向或逆向排序
# 临时正向排序
print(sorted(che))
print(sorted(che, reverse=True))

{}大括号表示字典

# Python字典{} 相当于Java中的键值对
che = {"motuo":'motuoche', 'huoche':5}
print(che['motuo'])
print(che['huoche'])

5.字典和列表(嵌套)使用

# Python字典{} 键-值对
che = {"motuo": 'motuoche', 'huoche': 5}
print(che['motuo'])
print(che['huoche'])

# 字典添加键-值对
che = {"motuo": 'motuoche', 'huoche': 5}
che['kache'] = 1
che['qiche'] = 3
print(che)

# 创建一个空字典 添加、修改、删除键-值对
che1 = {}
che1['kache'] = 'green'
che1['motuo'] = '1'
che1['huoche'] = '2'
che1['qiche'] = '3'
che1['daba'] = 'red'
print(che1)

# 修改字典中的值
che2 = {'kache': 'green'}
print(che2)
che2['kache'] = 'yellow'
print(che2)

# 删除键-值对
che1 = {'kache': 'green', 'motuo': '5', 'huoche': '2', 'qiche': '3', 'daba': 'red'}
print(che1)
del che1['huoche']
print(che1)
che1['huoche'] = '4'  # 重新添加回删除的键-值对
print(che1)
print('kache交通工具的颜色:' + che1['kache'].title() + '\t' + 'daba交通工具的颜色是' + che1['daba'].upper())
# for 循环遍历 打印出键值对中所有的键
for key in che1.keys():
    print(key.title())
# for 循环遍历 打印出键值对中的所有的值
for value in che1.values():
    print(value)
# for 循环遍历打印出 键值对中所有的键 并 按照顺序排序
for key in sorted(che1.keys()):
    print(key.upper().lower().title())  # 将 打印出来的键的值先全部大写 之后小写 然后在把首字母大写输出
# for 循环遍历出键值对中所有的值 并 按照顺序排列
for value in sorted(che1.values()):
    print(str(value.upper().lower().title()))

# 在列表中存储字典 组合 打印出每一个键值对的字典 或者 列表中所有的字典
che1 = {'kache': '5', 'motuo': '10'}
che2 = {'huoche': '20', 'qiche': '15', }
che3 = {'gongjiao': '30', 'daba': '25'}
che = [che1, che2, che3]
for gongju in che:
    print(gongju)
# 打印显示列表中的 前两个 字典键值对
for gongju2 in che[:2]:
    print(gongju2)
# 复制前两个键值对的列表 并在里面添加新的键值对 并查看原来的和复制之后的字典组成的列表 / 在列表中存储字典
che4 = che[:]
a = {'mache': '35', 'luche': '40'}
che4.append(a)
print(che)
print(che4)
print(str(len(che4)))  # 显示列表中总共有多少个字典

# 在字典中存储列表 通过遍历打印出来所有列表中的值
che1 = {'kache': 'dakache',
        'motuo': ['xiaomotuo', 'damotuo'],
        }
for motuo1 in che1['motuo']:
    print(motuo1)
print("拉货用" + che1['kache'] + '\t' + "摩托车是" + motuo1)
# 在字典中存储字典 并且访问每一级字典中的键 和 值的数据
che5 = {'che6': {'kache': '5', 'huoche': '6'}}
for key, value in che5.items():
    print(key)
    print(value)
    b=value
    print(b.keys())
    print(b.values())

6.用户输入和while循环

# 用户输入和while循环 函数input()
message = input('用户请输入:')
print("输出了用户输入的:\t" + message)

# 使用Input输出一句名言 并拼接输出一句完整的话
qian = "说做过的,"
hou = '做说过的!'
name = input('请输入这是谁说的话:')
print(qian + hou + '\n' + '\t\t\t' + '————' + name)

# 求模运算 根据用户输入的数字 判断用户输入的是奇数还是偶数!
number = input("请任意输入一个不为0的整数:")
number = int(number)
if number % 2 == 0:
    print('用户输入的这个数为' + str(number) + '是一个偶数!')
else:
    print('用户输入的这个数为' + str(number) + '是一个是奇数!')

# 让用户自己选择何时退出 只要用户输入的数据不等于jieshu 就会一直让用户输入数据 当用户输入jieshu直接退出循环
message=''
while message!='jieshu':
    message=input('请输入:') #输入jieshu 直接终止程序
    if message!='jieshu':  #使用if语句可以减少最后的jieshu的打印 message不等于jieshu的时候才打印 否则反之!
        print(message)
# while 让用户选择何时推出循环 while 循环默认的是True 默认执行的是循环并输出信息 只有当用户输入的是tuichu的时候Active 才是False 就会结束!
xinxi='请输入信息:'
active=True
while active:
    message=input(xinxi)
    if message=='tuichu':
        active=False
    else:
        print(message)

# 如果用户输入的是 tuichu则使用break跳出循环
xinxi='请输入信息:'
active=True
while active:
    message=input(xinxi)
    print(message)
    if message=='退出':
        break
    else:
        print("I love You"+message)

# 在循环中使用 continue 输出1~10数字的奇数
shuzi = 0
while shuzi < 10:
    shuzi += 1
    if shuzi % 2 == 0:
        continue
    print(shuzi)

# 使用while 循环来处理 列表 字典
unconfirmed_users=['alice','brian','candace']
confirmed_users=[]
while unconfirmed_users:
    current_user=unconfirmed_users.pop()
    print(current_user.title())
    confirmed_users.append(current_user)

# 删除包含特定值的列表元素
che = ["motuo", "qiche", "zixingche", 'huoche'];
print(che)
# 移除qiche
while 'qiche' in che:
    che.remove('qiche')
print(che)

# 使用用户输入来填充字典 让用户自己决定是否继续调查 默认为True
responses={}
active=True
while active:
    name=input('\n你叫什么名字?请输入:')
    respons=input('从哪里来?请输入:')
    responses[name]=respons
    repeat=input('还有人要参与调查吗?(yes/no)')
    if repeat=='no':
        active=False
for name,response in responses.items():
    print(name+'\t'+response)

7.函数

# Python 的函数 相当于是java中的方法
def greet_user():

    输出一句话'''
    print("输出一句话")
greet_user()

# 向函数传递信息 实参:rj  形参:username
def greet_user(username):
    print('这个人叫'+username)
greet_user('rj')

#实参和形参 传递实参 位置实参 多次调用函数
def describe_pet(animal_type,pet_name):
    '''显示宠物的信息'''
    print('宠物的类型是:'+animal_type+'.')
    print('宠物的名字是:'+pet_name.title()+'.\n')
describe_pet('小型','h士奇')
describe_pet('大型','z獒')

# 关键字实参 可以无视顺序:在写实参的时候,不用遵循形参的顺序  多次调用函数验证
def describe_pet(animal_type,pet_name):
    '''显示宠物的信息'''
    print('宠物的类型是:'+animal_type+'.')
    print('宠物的名字是:'+pet_name.title()+'.\n')
describe_pet(animal_type='中型',pet_name='m羊犬')
describe_pet(pet_name='m羊犬',animal_type='中型')

#函数 可以设置形参的默认值
def describe_pet(animal_type,pet_name='s魔灰'):
    '''显示宠物的信息'''
    print('宠物的类型是:'+animal_type+'.')
    print('宠物的名字是:'+pet_name.title()+'.\n')
describe_pet(animal_type='中型')
describe_pet('小型')

#函数的实参和形参,简单的返回值, 多次调用函数复赋值 组成一个列表 for循环遍历列表输出值!
def person(name,age):
    xinxi='这个人叫'+name+','+"年龄是:"+age
    return xinxi
person_xinxi=person('aaa','20岁')
person_xinxi1=person('bbb','21岁')
per_xinxi=[person_xinxi,person_xinxi1]
for pers_xinxi in per_xinxi[:]:
    print(pers_xinxi)
# 函数 往字典中添加一个信息组成一个新字典 for 循环遍历所有的字典的键-值最后输出
def person1(name,sex,age=''):
    person1={'n':name,'s':sex}
    if age:
        person1['a']=age #在上面的person1字典中添加一个 'a':age 的字典
        return person1
xinxi=person1('rj','男',age='20')
'''打印字典的所有信息'''
print(xinxi)
'''打印全部的键-值'''
for key,value in xinxi.items():
    print(key)
    print(value)
'''只打印字典中的键'''
for key in xinxi.keys():
    print(key)
'''只打印字典中的值'''
for value in xinxi.values():
    print(value)

# 结合使用函数和while循环
def mingzi(first_name,last_name):
    '''返回一个全部的名字'''
    full_name=first_name+' '+last_name
    return full_name.title()
'''这是有一个无限循环'''
while True:
    print('请输入您的名字')
    f_name=input("请输入您的First_name:")
    if f_name=='tuichu':
        break
    l_name=input("请输入您的Last_name:")
    if l_name=='quxiao':
        break
    '''调用前面定义的函数'''
    suoyou_name=mingzi(f_name,l_name)
    print(suoyou_name)
# 传递列表
def greet_users(names):
    '''向列表中的每一位用户都发出一条简单的问候'''
    for name in names:
        print('Hi',name.title()+'!')
names=['rj','cj','ft']
greet_users(names)

# 在函数中修改列表 while循环移除数据,可用数据,添加到工具,for循环遍历 移除的可用的数据 并 输出修改后的列表数据
che = ["motuo", "qiche", "zixingche", 'huoche']
gongju=[]
while che:
    che3=che.pop()
    print('gongu:'+che3)
    gongju.append(che3)
for che4 in sorted(gongju): #sorted() 临时性abcde 正向或逆向排序
    print(che4)

#传递任意数量的实参 多次调用函数赋值
def make_pizza(*toppings):
    print(toppings)
make_pizza('wuai')
make_pizza('wuai','po','jie','wuaipo','pojie','wuaipojie')

#传递任意数量的实参 多次调用函数赋值 并且循环遍历实参并输出
def make_pizza(*toppings):
    print('这里要输出循环遍历的名字结果:')
    for topping in toppings:
        print('-'+topping)
make_pizza('wuai')
make_pizza('wuai','po','jie','wuaipo','pojie','wuaipojie')

# 结合使用位置实参和任意数量的实参 还嫌匹配位置实参和关键字实参
def make_pizza(size,*toppings):
    print('总共需要'+str(size)+'这里要输出循环遍历的名字结果:')
    for topping in toppings:
        print('-'+topping)
make_pizza(16,'wuai')
make_pizza(12,'wuai','po','jie','wuaipo','pojie','wuaipojie')

1.导入模块

pizza.py 模块

def make_pizza(size, *toppings):
    print('总共需要' + str(size) + '这里要输出循环遍历的名字结果:')
    for topping in toppings:
        print('-' + topping)

making_pizzas.py import 模块名

import pizza   #导入的模块的名字 pizza
pizza.make_pizza(15,'wuai')
pizza.make_pizza(18,'wuai','po','jie')
2.导入特定的函数

2.导入特定的函数

making_pizzas.py from 模块名 import 函数名

from pizza import make_pizza   #导入特定的函数 make_pizza
make_pizza(15,'wuai')
make_pizza(18,'wuai','po','jie')

3.使用as 给函数指定别名

making_pizzas.py from 模块名 import 函数名 as 别名

from pizza import make_pizza as mp   #导入特定的函数 make_pizza 并且指定别名
mp(15,'wuai')
mp(18,'wuai','po','jie')

4.使用as 给模块指定别名

making_pizzas.py import 模块名 as 别名

import pizza as pi   #导入的模块的名字pizza 并且指定别名pi
pi.make_pizza(15,'wuai')
pi.make_pizza(18,'wuai','po','jie')
5.导入模块中所有的函数

5.导入模块中所有的函数

making_pizzas.py from 模块名 import *

from pizza import *   #导入模块中所有的函数
make_pizza(15,'wuai')
make_pizza(18,'wuai','po','jie')

8.类

1.创建类和使用类

dog.py

class Dog():
    '''一次模拟小狗的简单测试'''
    #init 是一个特殊的方法,开头和结尾都有两个下划线 三个参数 形参self必不可少
    def __init__(self, name, age):
        '''初始化属性name 和 age'''
        self.name = name
        self.age = age

    def sit(self):
        '''模拟小狗被命令时蹲下'''
        print(self.name.title() + 'is now sitting.')

    def roll_over(self):
        '''模拟小狗被命令时打滚'''
        print(self.name.title() + 'rolled over')

2.根据类来创建实例/多个

dog.py

my_dog = Dog('gougou', 6)
you_dog = Dog('xiaogou', 7)
print('我的狗的名字叫:' + my_dog.name.title() + '.')
print('它今年已经:' + str(my_dog.age) + '岁了!')

dog.py #调用方法

my_dog = Dog('gougou', 6)
my_dog.sit() #调用sit蹲下方法
my_dog.roll_over() #调用roll_over打滚方法

3.使用类和实例

che.py 属性指定默认的值 和 修改属性的值(直接和自定义函数) 不允许年份比之前要小

# 在方法中通过自定义修改函数 修改属性的值
class Che():
    def __init__(self, gongjiao, daba):
        self.gongjiao = gongjiao
        self.daba = daba
        self.year = 9

    def dache(self):
        dache1 = self.gongjiao + self.daba
        return dache1

    def nian(self):
        print('这两个大车的年限是:' + str(self.year) + '年!')

    def update(self, nianfen):
        '''使用修改方法 为年限设置 值'''
        self.year = nianfen
        if nianfen >= self.year:
            self.year = nianfen
        else:
            print('不允许年份比现在设置的值要小!')

gongju1 = Che('公交', '大巴')
print(gongju1.dache())
gongju1.update(8)
gongju1.nian()

9. 继承

che.py

# 在方法中通过自定义修改函数 修改属性的值
class Che():
    def __init__(self, gongjiao, daba):
        self.gongjiao = gongjiao
        self.daba = daba
        self.year = 9

    def dache(self):
        dache1 = self.gongjiao + '\t' + self.daba
        return dache1

    def nian(self):
        print('这两个大车的年限是:' + str(self.year) + '年!')

    '''修改属性的值 或 增加属性的值'''

    def update(self, nianfen):
        '''使用修改方法 为年限设置 值'''
        self.year += nianfen
        if nianfen >= self.year:
            self.year = nianfen
        else:
            print('不允许年份比现在设置的值要小!')

gongju1 = Che('公交', '大巴')
print(gongju1.dache())
gongju1.update(10)
gongju1.nian()

# 继承   子类 继承 父类  使用super初始化父类的属性 输出时子类调用父类的函数
class ElectricCar(Che):
    '''还有哪几种车'''

    def __init__(self, gongjiao, daba):
        '''使用super初始化父类的属性'''
        super(ElectricCar, self).__init__(gongjiao, daba)

gongjuzilei = ElectricCar('公交子类', '大巴子类')
print(gongjuzilei.dache()) #子类调用父类的函数 输出

1.给子类定义属性和方法

che.py che为父类 ElectricCar为子类 子类继承父类 即:子类(父类)

# 在方法中通过自定义修改函数 修改属性的值
class Che():
    def __init__(self, gongjiao, daba):
        self.gongjiao = gongjiao
        self.daba = daba
        self.year = 9

    def dache(self):
        dache1 = self.gongjiao + '\t' + self.daba
        return dache1

    def nian(self):
        print('这两个大车的年限是:' + str(self.year) + '年!')

    '''修改属性的值 或 增加属性的值'''

    def update(self, nianfen):
        '''使用修改方法 为年限设置 值'''
        self.year += nianfen
        if nianfen >= self.year:
            self.year = nianfen
        else:
            print('不允许年份比现在设置的值要小!')

gongju1 = Che('公交', '大巴')
print(gongju1.dache())
gongju1.update(10)
gongju1.nian()

# 继承   子类继承父类 使用super初始化父类的属性 输出时子类调用父类的函数 给子类定义属性和方法
class ElectricCar(Che):
    '''还有哪几种车'''

    def __init__(self, gongjiao, daba):
        '''使用super初始化父类的属性'''
        super(ElectricCar, self).__init__(gongjiao, daba)
        self.daxiao=70   #定义一个子类特有的属性
    def chedaxiao(self):
        '''打印一条关于车的大小的信息'''
        print('车的大小是:'+str(self.daxiao)+'米')

#给子类的属性进行赋值 
gongjuzilei = ElectricCar('公交子类', '大巴子类')
print(gongjuzilei.dache()) #子类调用父类的函数 输出
gongjuzilei.chedaxiao()   #在子类中给输出这个子类特有的属性值

2.子类重写父类的方法

che.py che为父类 ElectricCar为子类 子类继承父类 即:子类(父类)

# 在方法中通过自定义修改函数 修改属性的值
class Che():
    def __init__(self, gongjiao, daba):
        self.gongjiao = gongjiao
        self.daba = daba
        self.year = 9

    def dache(self):
        dache1 = self.gongjiao + '\t' + self.daba
        return dache1

    def nian(self):
        print('这两个大车的年限是:' + str(self.year) + '年!')

    '''修改属性的值 或 增加属性的值'''
    def update(self, nianfen):
        '''使用修改方法 为年限设置 值'''
        self.year += nianfen
        if nianfen >= self.year:
            self.year = nianfen
        else:
            print('不允许年份比现在设置的值要小!')

gongju1 = Che('公交', '大巴')
print(gongju1.dache())
gongju1.update(10)
gongju1.nian()

# 继承   子类继承父类 使用super初始化父类的属性 输出时子类调用父类的函数 给子类定义属性和方法
class ElectricCar(Che):
    '''还有哪几种车'''

    def __init__(self, gongjiao, daba):
        '''使用super初始化父类的属性'''
        super(ElectricCar, self).__init__(gongjiao, daba)
        '''新增两条大小和年份的属性'''
        self.daxiao = 70
        self.nianfen=2

    def chedaxiao(self):
        '''打印一条关于车的大小的信息'''
        print('车的大小是:' + str(self.daxiao) + '米')

    def nian(self):
        print('这个大车的使用年份是:' + str(self.nianfen) + '年!')

    def update(self, nianfen):
        '''修改车子的使用年限'''
        self.nianfen = nianfen

# 通过子类来给 属性传递参数
gongjuzilei = ElectricCar('公交子类', '大巴子类')
print(gongjuzilei.dache())  # 子类调用父类的函数 输出
gongjuzilei.chedaxiao()
gongjuzilei.update(12) #给形参传递年份的信息
gongjuzilei.nian() #子类调用年份的函数 传递相关的年份信息

3.导入类/单个类

car.py

# 给属性指定默认的值  定义一个类 在类中定义 几个函数
class Car():
    def __init__(self, qiche, huoche):
        '''初始化描述车的类型'''
        self.qiche = qiche
        self.huoche = huoche
        self.year = 6

    def chexing(self):
        '''定一个车型的函数'''
        message = (self.qiche + '\t' + self.huoche)
        return message.title()

    def nian(self):
        '''定义一个输出车的年份的函数'''
        print('车的年份都是:' + str(self.year) + '年!')

mycar.py

from car import Car # from 文件名 import 类名
# 为类的形参赋值
my_car = Car('汽车', '火车')
# 调用chexing的函数输出
print(my_car.chexing())
# 修改属性的值 并 调用相关的函数输出
my_car.year = 12
my_car.nian()

4.模块中存储多个类/类继承 导入

car.py

# 给属性指定默认的值  定义一个类 在类中定义 几个函数
class Car():
    def __init__(self, qiche, huoche):digits
        '''初始化描述车的类型'''
        self.qiche = qiche
        self.huoche = huoche
        self.year = 6

    def chexing(self):
        '''定一个车型的函数'''
        message = (self.qiche + '\t' + self.huoche)
        return message.title()

    def nian(self):
        '''定义一个输出车的年份的函数'''
        print('车的年份都是:' + str(self.year) + '年!')

# 继承   子类继承父类 使用super初始化父类的属性 输出时子类调用父类的函数 给子类定义属性和方法
# 重写父类的方法 在子类中定义个和父类中同名的方法 Python不会考虑在父类中的方法,只关注在子类中定义的相应方法
class ElectricCar(Car):
    '''还有哪几种车'''

    def __init__(self, gongjiao, daba):
        '''使用super初始化父类的属性'''
        super(ElectricCar, self).__init__(gongjiao, daba)
        self.daxiao = 70
        self.nianfen = 2

    def chedaxiao(self):
        '''打印一条关于车的大小的信息'''
        print('车的大小是:' + str(self.daxiao) + '米')

    # 子类重写父类函数
    def nian(self):
        print('这个大车的使用年份是:' + str(self.nianfen) + '年!')

    # 子类重写父类的函数
    def update(self, nianfen):
        '''修改车子的使用年限'''
        self.nianfen = nianfen

my_electric_car.py 从一个模块中导入多个类 格式:from 模块名 import 类名,类名 或者 *

from car import Car,ElectricCar

# 传递实参的参数给形参 并输出传递的参数
my_tesla = ElectricCar('公交', '大巴')
print(my_tesla.chexing())
# 修改属性的值 并调用函数输出相关的信息
my_tesla.daxiao = 80
print(my_tesla.chedaxiao())
# 修改属性的值,并调用函数输出相关的信息
my_tesla.nianfen = 5
print(my_tesla.nian())

5.导入整个模块/模块中所有的类

my_cars.py import 模块名 from 模块名 import 所有的类

import car
from car import *

6.Python 标准库

字典让你能够和信息关联起来,但是不记录添加键值对的顺序。创建字典并记录键值对中的数据可以使用模块 collections 中的 OrderedDict类。OrderedDict实例几乎与字典相同,区别只是在于记录键-值对的顺序!

from collections import OrderedDict  # 导入一个模块中的函数

favorivte_languages = OrderedDict()  # 将类赋值给favorivte_languages
'''往favorivte_languages中添加字典信息'''
favorivte_languages['che'] = 'qiche'
favorivte_languages['che1'] = 'mache'
favorivte_languages['che2'] = 'huoche'
favorivte_languages['che3'] = 'kache'
# for循环遍历输出类的字典信息
for che, mingzi in favorivte_languages.items():
    print('这些' + che.title() + '\t' + '叫:' + mingzi.title() + '.')

10.文件和异常

1.读取整个文件 read()

pi_digits.txt

3.1415926535
  8979323846
  2643383279

file_reader.py 读取整个文件的格式是: with open(\'文件的名字\') as file_object:

# 相对文件路径 (优先使用)
with open('pi_digits.txt') as file_object:
    contents = file_object.read()
    print(contents.rstrip())  # 多出一个空行的情况下可以使用 rstrip() 来去除字符串后面的空白

# 将文件放在项目文件夹中 相对文件路径  (优先使用)
with open('text_files\pi_digits.txt') as file_object:
    shuchu = file_object.read()
    print(shuchu)

# 将文件放在电脑桌面上  绝对文件路径
file_path = 'C:\\Users\lenovo\Desktop\pi_digits.txt'
with open(file_path) as file_object:
    print(file_object.read())

# 逐行 读取文件的信息
file_path = 'pi_digits.txt'
with open(file_path) as file_object:
    for line in file_object:
        print(line.rstrip())  # 多出一个空行的情况下可以使用 rstrip() 来去除字符串后面的空白

# 逐行 读取文件的信息 使用readlines()
file_path = 'pi_digits.txt'
with open(file_path) as file_object:
    lines = file_object.readlines()
    for line in lines:
        print(line.rstrip())  # 多出一个空行的情况下可以使用 rstrip() 来去除字符串后面的空白

2.使用文件的内容 读取/拼接/长度

pi_string.py

# 逐行 读取文件的信息 使用readlines()
file_path = 'pi_digits.txt'
with open(file_path) as file_object:
    lines = file_object.readlines()  # 读取文件中每行的信息
pi_string = ''  # 创建一个字符串
for line in lines:  # 遍历读取到的文件的每行信息 存储到line中
    pi_string += line.strip()  # 读取到的每行信息+创建的字符串  并用strip()去除两端的空格
print(pi_string)  # 输出拼接之后的信息
print(len(pi_string))  # 输出拼接之后的信息的字符串长度

3.读取一个百万位的大型文件

pi_string.py

# 逐行 读取文件的信息 使用readlines()
file_path = 'pi_digits.txt'
with open(file_path) as file_object:
    lines = file_object.readlines()  # 读取文件中每行的信息
pi_string = ''  # 创建一个字符串
for line in lines:  # 遍历读取到的文件的每行信息 存储到line中
    pi_string += line.strip()  # 读取到的每行信息+创建的字符串  并用strip()去除两端的空格
print(pi_string[:9]+'...')  # 输出拼接之后的信息 只输出列表中的前9位 如果输出百万位 把9改为1000000
print(len(pi_string))  # 输出拼接之后的信息的字符串长度

4.写入到空文件(多行)/附加/读取

pi_string.py

# 写入文件 执行完之后 文件目录中 会生成一个xieru.txt的文件 内容就是‘易瑞杰正在学习Python’
file_path='xieru.txt'
with open(file_path,'w') as file_object:
    file_object.write('rj正在学习Python') 

pi_string.py

# 写入文件 在读取写入的文件内容和文件长度
file_path = 'wenjian.txt'
with open(file_path, 'w') as file_object:  # w:表示写入(Write)到这个文件中
    file_object.write('rj正在学习Python' + '\n')
    file_object.write('rj正在学习Python1' + '\n')
with open(file_path, 'a') as file_object:  # a:表示附加(Attach)到这个文件中
    file_object.write('rj正在学习Python' + '\n')
with open(file_path, 'r') as file_object:  # r:表示读取(read)这个文件的内容
    lines = file_object.readlines()
    for line in lines:
        print(line.strip())
        print(len(line))

pi_string.py

# 提示用户输入自己的姓名 再将用户输入的姓名写入到文件中输出
file_path = 'tishishuru.txt'
with open(file_path, 'w') as file_object:  # w:表示写入(Write)到这个文件中
    message = input('请输入您的名字:')
    file_object.write(message)

division.py

# 异常 division by zero
print(5/0)
# 异常 division by zero(ZeroDivisionError)
'''try-except 的代码块包裹快捷键是 Ctrl+Alt+T'''
try:
    print(5/0)
except ZeroDivisionError:
    print('你的被除数不能为零!')
# 分析文本 拆分字符串 for循环遍历输出
title = "r j study Python"
print(title.split())  #遍历根据空格拆分 输出的是一个列表
fenxi = title.split()  # 以空格为分隔符拆分文本
for wenben in fenxi:  # 遍历根据空格拆分之后的文本 并输出
    print(wenben)

division.py 使用多个文件

# 定义函数 排除异常 读取文件 拆分文件内容 计算内容长度 写入到新的文件中
def count_words(filename):
    try:
        with open(filename, 'r') as file_object:
            contents = file_object.read()
    except FileNotFoundError:
        print('文件' + filename + '是不存在的!')
    else:
        words = contents.split()
        for wenben in words:
            print(wenben)        #遍历输出拆分之后的每条信息
        num_words=(len(words))
        print('这个文件是真是存在的'+filename+'文件中的内容的长度是:'+str(num_words))

filename = 'alice.txt'
count_words(filename)
# 定义函数 排除异常 读取文件(多个文件) 拆分文件内容 计算内容长度 写入到新的文件中
def count_words(filename):
    try:
        with open(filename, 'r') as file_object:
            contents = file_object.read()
    except FileNotFoundError:
        print('文件' + filename + '是不存在的!')
    else:
        words = contents.split()
        for wenben in words:
            print(wenben)
        num_words=(len(words))
        print('这个文件是真是存在的'+filename+'文件中的内容的长度是:'+str(num_words))

'''当其中的某一文件不存在时丝毫不影响,其他的文件'''
filenames = ['alice1.txt','alice2.txt','alice3.txt','alice4.txt']
for filename in filenames:
    count_words(filename)

5.存储数据

number_reader.py json.dump()和json.load()

import json

# 将列表数据存储在number.json 文件中
number = [2, 3, 4, 5, 7, 11, 13]
filename = 'number.json'
with open(filename, 'w') as f_obj:
    json.dump(number, f_obj)  # json.dump用来存储。    number:要存入json文本的数据源.   f_obj:存入到的文件的位置
    print('数据存储到' + filename + '完成!')

# 读取前面写入到number.json文件的数据内容
filename = 'number.json'
with open(filename, 'r') as f_obj:
    numbers = json.load(f_obj)  # json.load用来读取。  f_obj:读取的数据源的位置
    print(numbers)
for number in numbers:  # for循环遍历输出读取到的文件中的每条列表中的数据 并 打印输出
    print(number)

remember_me.py 保存和读取用户输入的数据

import json

# 保存用户输入时生成的数据到json文件中
username = input("请输入您的名字:")
filename = 'username.json'
with open(filename, 'w') as f_obj:
    json.dump(username, f_obj)  # json.dump用来存储。   username:要存入json文本的数据源.   f_obj:存入到的文件的位置 username.json
    print('这个人的名字叫:' + username)

# 读取用户输入存储到json中的数据
filename = 'username.json'
with open(filename, 'r') as f_obj:
    username = json.load(f_obj)  # json.load用来读取。  f_obj:读取的数据源的位置
    print('在文件中读取到的信息是:' + username)
import json

# json.dump()  json.load() try-except-else 的组合使用
# 如果以前存储了用户名就加载它,否则就提示用户输入用户名并存储它
filename = 'username.json'
try:
    with open(filename, 'r') as f_obj:
        username = json.load(f_obj)  # json.load用来读取。  f_obj:读取的数据源的位置
        print('在文件中读取到的信息是:' + username)
except FileNotFoundError:
    # 保存用户输入时生成的数据到json文件中
    username = input("请输入您的名字:")
    with open(filename, 'w') as f_obj:
        json.dump(username, f_obj)  # json.dump用来存储。   username:要存入json文本的数据源.   f_obj:存入到的文件的位置 username.json
        print('这个人的名字叫:' + username)
else:
    print('欢迎你:' + username + '!')

6.重构

remember.py

import json

# json.dump()  json.load() try-except-else 的组合使用
# 如果以前存储了用户名就加载它,否则就提示用户输入用户名并存储它
def greet_user():
    '''问候用户,并指出其名字'''
    filename = 'username.json'
    try:
        with open(filename, 'r') as f_obj:
            username = json.load(f_obj)  # json.load用来读取。  f_obj:读取的数据源的位置
            print('在文件中读取到的信息是:' + username)
    except FileNotFoundError:
        # 保存用户输入时生成的数据到json文件中
        username = input("请输入您的名字:")
        with open(filename, 'w') as f_obj:
            json.dump(username, f_obj)  # json.dump用来存储。   username:要存入json文本的数据源.   f_obj:存入到的文件的位置 username.json
            print('这个人的名字叫:' + username)
    else:
        print('欢迎你:' + username + '!')

greet_user()

remember.py

import json

# json.dump()  json.load() try-except-else 的组合使用
# 如果以前存储了用户名就加载它,否则就提示用户输入用户名并存储它
# 定义函数 get_stored_username 读取已经存在的用户信息
def get_stored_username():
    '''问候用户,并指出其名字'''
    filename = 'username.json'
    try:
        with open(filename, 'r') as f_obj:
            username = json.load(f_obj)  # json.load用来读取。  f_obj:读取的数据源的位置
            print('在文件中读取到的信息是:' + username)
    except FileNotFoundError:
        return None
    else:
        return username

# 读取不到已经存在的信息 使用greet_user函数 提示用户输入信息 并写入到json文件中
def greet_user():
    username = get_stored_username()
    if username:
        print("这个人的名字叫:" + username)
    else:
        username = input('请输出您的名字:')
        filename = 'username.json'
        with open(filename, 'w') as f_obj:
            json.dump(username, f_obj)
            print('用户输入的数据是:' + username)

greet_user()
import json

# json.dump()  json.load() try-except-else 的组合使用
# 如果以前存储了用户名就加载它,否则就提示用户输入用户名并存储它
# 定义函数 get_stored_username 读取已经存在的用户信息
def get_stored_username():
    '''问候用户,并指出其名字'''
    filename = 'username.json'
    try:
        with open(filename, 'r') as f_obj:
            username = json.load(f_obj)  # json.load用来读取。  f_obj:读取的数据源的位置
            print('在文件中读取到的信息是:' + username)
    except FileNotFoundError:
        return None
    else:
        return username

def get_new_username():
    '''提示用户输入姓名'''
    username = input('请输出您的名字:')
    filename = 'username.json'
    with open(filename, 'w') as f_obj:
        json.dump(username, f_obj)
    return username

# 读取到已经存在的信息就调用get_stored_username函数并输出
# 读取不到已经存在的信息 调用get_new_username函数 提示用户输入信息 并写入到username.json文件中
def greet_user():
    username = get_stored_username()
    if username:
        print("这个人的名字叫:" + username)
    else:
        username = get_new_username()
        print('用户输入的数据是:' + username)

greet_user()

11.测试代码

1.测试函数

name_function.py

def get_formatted_name(first, last):
    '''生成整洁的名字'''
    full_name = first + ' ' + last
    return full_name.title()

name.py from 模块名 import 函数名

from name_function import get_formatted_name

# from name_function import *
# from name_function import get_formatted_name as gfn

print('输入‘q’就是退出程序!')
while True:
    first = input('请输入你的第一个名字:')
    if first == 'q':
        break
    last = input('请输入你的最后一个名字:')
    if last == 'q':
        break
    formatted_name = get_formatted_name(first, last)
    print('\t用户输入的两个名字结果是:' + formatted_name)

2.单元测试和测试用例 / 可通过测试 / 添加新测试

name_function.py

def get_formatted_name(first, last):
    '''生成整洁的名字'''
    full_name = first + ' ' + last
    return full_name.title()

test_name_function.py

import unittest
from name_function import get_formatted_name

class NamesTestCase(unittest.TestCase):
    '''测试 name_function.py'''

    def test_first_last_name(self):
        '''看处理的信息 是否断言等于(assertEqual) 预期的输出信息'''
        formatted_name = get_formatted_name('wuai', 'rj')
        self.assertEqual(formatted_name, 'Wuai Rj')

if __name__ == '__main__':
    unittest.main()

添加新测试

name_funciton.py

def get_formatted_name(first, last):
    '''生成整洁的名字'''
    full_name = first + ' ' + last
    return full_name.title()

test_name_function.py

import unittest
from name_function import get_formatted_name

class NamesTestCase(unittest.TestCase):
    '''测试 name_function.py'''

    def test_first_last_name(self):
        '''看处理的信息 是否断言等于(assertEqual) 预期的输出信息'''
        formatted_name = get_formatted_name('wuai', 'rj')
        self.assertEqual(formatted_name, 'Wuai Rj')
    def xin_test_first_last_name(self):
        '''看处理的信息 是否断言等于(assertEqual) 预期的输出信息'''
        formatted_name = get_formatted_name('rj', 'wuai')
        self.assertEqual(formatted_name, 'Rj Wuai')

if __name__ == '__main__':
    unittest.main()

3.测试类

测试中常用的6种的断言方法

        self.assertEqual(a,b)                    #核实a==b
        self.assertNotEqual(a,b)                 #核实a!=b
        self.assertTrue(x)                       #核实x为True
        self.assertFalse(x)                      #核实x为false
        self.assertIn(item,list)                 #核实item在list中
        self.assertNotIn(item,list)              #核实item不在list中

survey.py #一个要测试的类

class AnonymousSurvey():
    '''收集匿名调查问卷的答案'''

    def __init__(self, question):
        '''存储一个问题,并未存储答案做准备'''
        self.question = question
        self.responses = []

    def show_question(self):
        '''显示调查问卷'''
        print(self.question)

    def store_response(self, new_response):
        '''存储单份调查问卷'''
        self.responses.append(new_response)

    def show_results(self):
        '''显示收集到的所有答卷'''
        print('调查的结果是:')
        for response in self.responses:
            print('-' + response)

language_survey.py #一个要使用测试的类的类

from survey import AnonymousSurvey

# 定义一个问题并创建一个表示调查的AnonymousSurvey对象
question = 'what language did you first learn to speak?'
my_survey = AnonymousSurvey(question)

# 显示问题并存储答案
my_survey.show_question()
print("用户输入'q'就可以退出")
while True:
    response = input('Language:')
    if response == 'q':
        break
    my_survey.store_response(response)

# 显示要调查的结果
print('很感谢你参与这个调查!')
my_survey.show_results()

测试AnonymousSurvey类

import unittest
from survey import AnonymousSurvey

# 子类继承父类 父类是测试类
class TestAnonymousSurvey(unittest.TestCase):
    '''针对AnonymousSurvey类的测试'''

    def setUp(self):
        '''创建一个调差对象和一组答案,供使用的测试方法使用'''
        question = 'what language did you first learn to speak?'
        self.my_survey = AnonymousSurvey(question)
        self.response = ['English', 'Spanish', 'Mandarin', 'Chinese']

    def test_store_single_response(self):
        '''测试单个答案会被妥善的存储'''
        self.my_survey.store_response(self.response[0])
        self.assertIn(self.response[0], self.my_survey.responses)  # 核实Englishm是否在my_survey.responses中

    def test_store_three_responses(self):
        '''测试三个答案会被妥善的存储'''
        for response in self.response:
            self.my_survey.store_response(response)
        for response in self.response:
            self.assertIn(response, self.my_survey.responses)

if __name__ == '__main__':
    unittest.main()

12.写一个简单的程序/打包为exe并运行

shuzi.py 创建1~100的一个数字列表,存储在文件shuzi.txt中,并读取显示在控制台!

print('创建1~100的一个数字列表,存储在文件shuzi.txt中,并读取显示在控制台!')

def kaishi():
    message = input('请用户输入开始或者结束(Y/N):')
    if message == 'Y':
        # 创建一个1~100的数字列表 并输出到文件
        print('恭喜你!文件内容输出已成功!')
        number = list(range(1, 101))
        print(number)
        file_name = '1~100.txt'
        with open(file_name, 'w') as file_object:
            for shuzi in number:
                file_object.write(str(shuzi) + '\n')
        with open(file_name, 'r') as file_object:
            line = file_object.readlines()
            for shuzi in line:
                print(shuzi.strip())
    elif message == 'N':
        print('很抱歉,您选择了退出!拜拜!')
    else:
        print('注意!!! 请按照指令输入哦!Y或者N ')
        kaishi()

kaishi()

1.打包教程

打包生成参考链接1 打包生成参考链接2

win+R 输入cmd 进入命令行窗口 执行 pip install Pyinstaller 安装打包的插件

之后cd 到要打包的文件项目的路径下:D:\SoftwareProject\PyCharmProject\peoject1

也可以在文件项目的窗口路径前直接 添加 cmd D:\SoftwareProject\PyCharmProject\peoject1敲回车进入

在cmd 窗口中执行命令 Pyinstaller -F  test(要打包的文件名).py

Pyinstaller -F 文件名.py //打包exe
Pyinstaller -F -w 文件名.py //不带控制台的打包
Pyinstaller -F -i xx.ico 文件名.py //打包指定exe图标打包

出现completed successfully就成功了。

生成的exe文件在dist里,这个exe文件单独拿出来放在任何的位置都可以运行。