Jetbrains系列软件常用快捷键 及《Python编程从入门到实践》袁国忠 译 P1~P200
之前两天在学习时做的笔记总结 在这里也记录一下,方便以后查阅,同时也希望能帮助到更多的童鞋!
一、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)
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)
che = ["motuo", "qiche", "zixingche", 'huoche']
che.sort()
print(che)
che.sort(reverse=True)
print(che)
print(sorted(che))
print(sorted(che, reverse=True))
che = ["motuo", "qiche", "zixingche", 'huoche']
che.reverse()
print(che)
che.reverse()
print(che)
che = ["motuo", "qiche", "zixingche", 'huoche']
print(len(che))
che = ["motuo", "qiche", "zixingche", 'huoche']
for che1 in che:
print(che1)
for che2 in che:
print(che2.title() + '都是交通工具!')
print("出门的时候都可以使用!")
for wenzi in ["你好", "我也好"]:
print(wenzi)
for shuzi in range(1, 5):
print(shuzi)
number = list(range(1, 5))
print(number)
for num in number:
print(num)
oushu = list(range(2, 10, 2))
print(oushu)
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 = [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])
print(che[0:])
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)
yuanzu = (100, 50)
print(yuanzu[0])
print(yuanzu[1])
yuanzu = (100, 20, 30)
for bianli in yuanzu:
print(bianli)
yuanzu = (100, 50)
for bianli in yuanzu:
print(bianli)
yuanzu = (200, 300)
for bianli in yuanzu:
print(bianli)
che = ["motuo", "qiche", "zixingche", 'huoche']
for che1 in che:
if che1 == 'qiche':
print(che1.upper())
else:
print(che1.title())
che = ["motuo", "qiche", "zixingche", 'huoche']
baohan = 'huoche1'
if baohan in che:
print(baohan + '包含在列表中')
else:
print((baohan + "不包含在列表中"))
if baohan not in che:
print(baohan.title() + '不包含在列表中')
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:
print('a的值是18')
else:
print('a的值小于19')
2.Python之禅
import this
3.Python关键字
import keyword
print(keyword.kwlist)
4.Python ()[]{}区别
() 表示元组
yuanzu = (100, 50)
print(yuanzu[0])
print(yuanzu[1])
yuanzu=(100,20,30)
for bianli in yuanzu:
print(bianli)
yuanzu = (100, 50)
for bianli in yuanzu:
print(bianli)
yuanzu=(200,300)
for bianli in yuanzu:
print(bianli)
[]表示列表
che = ["motuo", "qiche", "zixingche", 'huoche']
che.sort()
print(che)
che.sort(reverse=True)
print(che)
print(sorted(che))
print(sorted(che, reverse=True))
{}大括号表示字典
che = {"motuo":'motuoche', 'huoche':5}
print(che['motuo'])
print(che['huoche'])
5.字典和列表(嵌套)使用
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 key in che1.keys():
print(key.title())
for value in che1.values():
print(value)
for key in sorted(che1.keys()):
print(key.upper().lower().title())
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循环
message = input('用户请输入:')
print("输出了用户输入的:\t" + message)
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) + '是一个是奇数!')
message=''
while message!='jieshu':
message=input('请输入:')
if message!='jieshu':
print(message)
xinxi='请输入信息:'
active=True
while active:
message=input(xinxi)
if message=='tuichu':
active=False
else:
print(message)
xinxi='请输入信息:'
active=True
while active:
message=input(xinxi)
print(message)
if message=='退出':
break
else:
print("I love You"+message)
shuzi = 0
while shuzi < 10:
shuzi += 1
if shuzi % 2 == 0:
continue
print(shuzi)
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)
while 'qiche' in che:
che.remove('qiche')
print(che)
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.函数
def greet_user():
'''输出一句话'''
print("输出一句话")
greet_user()
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('小型')
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)
def person1(name,sex,age=''):
person1={'n':name,'s':sex}
if 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)
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)
che = ["motuo", "qiche", "zixingche", 'huoche']
gongju=[]
while che:
che3=che.pop()
print('gongu:'+che3)
gongju.append(che3)
for che4 in sorted(gongju):
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.make_pizza(15,'wuai')
pizza.make_pizza(18,'wuai','po','jie')
2.导入特定的函数
making_pizzas.py from 模块名 import 函数名
from pizza import 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
mp(15,'wuai')
mp(18,'wuai','po','jie')
4.使用as 给模块指定别名
making_pizzas.py import 模块名 as 别名
import pizza as pi
pi.make_pizza(15,'wuai')
pi.make_pizza(18,'wuai','po','jie')
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():
'''一次模拟小狗的简单测试'''
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()
my_dog.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()
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()
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()
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
my_car = Car('汽车', '火车')
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) + '年!')
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['che'] = 'qiche'
favorivte_languages['che1'] = 'mache'
favorivte_languages['che2'] = 'huoche'
favorivte_languages['che3'] = 'kache'
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())
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())
file_path = 'pi_digits.txt'
with open(file_path) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
2.使用文件的内容 读取/拼接/长度
pi_string.py
file_path = 'pi_digits.txt'
with open(file_path) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip()
print(pi_string)
print(len(pi_string))
3.读取一个百万位的大型文件
pi_string.py
file_path = 'pi_digits.txt'
with open(file_path) as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip()
print(pi_string[:9]+'...')
print(len(pi_string))
4.写入到空文件(多行)/附加/读取
pi_string.py
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:
file_object.write('rj正在学习Python' + '\n')
file_object.write('rj正在学习Python1' + '\n')
with open(file_path, 'a') as file_object:
file_object.write('rj正在学习Python' + '\n')
with open(file_path, 'r') as file_object:
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:
message = input('请输入您的名字:')
file_object.write(message)
division.py
print(5/0)
'''try-except 的代码块包裹快捷键是 Ctrl+Alt+T'''
try:
print(5/0)
except ZeroDivisionError:
print('你的被除数不能为零!')
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 = [2, 3, 4, 5, 7, 11, 13]
filename = 'number.json'
with open(filename, 'w') as f_obj:
json.dump(number, f_obj)
print('数据存储到' + filename + '完成!')
filename = 'number.json'
with open(filename, 'r') as f_obj:
numbers = json.load(f_obj)
print(numbers)
for number in numbers:
print(number)
remember_me.py 保存和读取用户输入的数据
import json
username = input("请输入您的名字:")
filename = 'username.json'
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
print('这个人的名字叫:' + username)
filename = 'username.json'
with open(filename, 'r') as f_obj:
username = json.load(f_obj)
print('在文件中读取到的信息是:' + username)
import json
filename = 'username.json'
try:
with open(filename, 'r') as f_obj:
username = json.load(f_obj)
print('在文件中读取到的信息是:' + username)
except FileNotFoundError:
username = input("请输入您的名字:")
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
print('这个人的名字叫:' + username)
else:
print('欢迎你:' + username + '!')
6.重构
remember.py
import json
def greet_user():
'''问候用户,并指出其名字'''
filename = 'username.json'
try:
with open(filename, 'r') as f_obj:
username = json.load(f_obj)
print('在文件中读取到的信息是:' + username)
except FileNotFoundError:
username = input("请输入您的名字:")
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
print('这个人的名字叫:' + username)
else:
print('欢迎你:' + username + '!')
greet_user()
remember.py
import json
def get_stored_username():
'''问候用户,并指出其名字'''
filename = 'username.json'
try:
with open(filename, 'r') as f_obj:
username = json.load(f_obj)
print('在文件中读取到的信息是:' + username)
except FileNotFoundError:
return None
else:
return username
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
def get_stored_username():
'''问候用户,并指出其名字'''
filename = 'username.json'
try:
with open(filename, 'r') as f_obj:
username = 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
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
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)
self.assertNotEqual(a,b)
self.assertTrue(x)
self.assertFalse(x)
self.assertIn(item,list)
self.assertNotIn(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
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 test_store_single_response(self):
'''测试单个答案会被妥善的存储'''
question = 'what language did you first learn to speak?'
my_survey = AnonymousSurvey(question)
my_survey.store_response('English')
self.assertIn('English', my_survey.responses)
if __name__ == '__main__':
unittest.main()
test_survey.py for遍历测试类中的答案列表 方法 setUp()
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)
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':
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文件单独拿出来放在任何的位置都可以运行。