------
1.1、python的源程序,本质上就是一个特殊格式的文本,可以使用任意文本编辑软件做python开发扩展名为.py。
1.2、第一个小程序
Print(“hello python”)
Print(“hello word”)
在linux中运行python源程序:python 01-hellopython.py;
1.3、执行python程序的三种方式:
1.3.1)、python/python 3解释器/其他解释器
Python xxx.py;
Python3 xxx.py
1.3.2)、交互式运行python程序
也就是在终端中,直接运行解释器,而不需要传入文件名,在python 的shell中,直接输入终端命令。
优点:适合验证局部代码;缺点:不能保存代码,不适合大量代码文件。
操作:linux下,直接输入python进入python\python3的解释器shell,输入python程序。
1.01的365次方:1.01**365 //退出解释器:exit()或者ctrl+d
交互式执行python程序时,推荐使用ipython,通常是我们首选的shell:
优点:自然后动补全、自动缩进、支持bash shell、内置了许多功能和函数、支持很多linux命令
操作:linux下,直接输入ipython\i python3进入python的解释器shell,输入python程序。
1.3.3)、集成开发环境IDE(集成了开发环境需要的所有命令);
pycham是一款非常优秀的python集成开发环境,可以在window、linux、macos中使用,
加+、减-、乘*、除/、取整//、取余%、取幂**;
数据类型:
数字型:整数、浮点数、布尔值、复数;
非数字型:字符串、列表、元组、字典
Python2.x版本整型包括:int、long。Type(z**89);3.0以后不区分,都为int;
注:type函数可以查看数据类型;
循环的语法:
If :
Else :
While :
For i in range(3):
命名规范:1、只能包括字母、数字、下划线;2、只能以字母或者下划线开头;3、不能包括空格;4、不能与关键字冲突;
字符串:用单引号、双引号括起来的,都是字符串;
Print(“fvr”+str(age)+”fvrv”),使用str()来转换为字符串;
注:1)、变量名.title(),将变量名的首字母转换成大写字母;使用+来拼接字符串;\n\t换行退格;
2)、删除空格,.rstrip();
3)、print可以使用多个,分离,连续输出,但是使用,会添加空格。Print(‘scdc’,mr)
4)、print("第{0}天体重为:{1}".format(day,height))
5)、注释单行/多行代码:选中+ctrl+/
字符串转int:
num='21'
int1=int(num)
print(int1)
列表是一系列按特定顺序排列的元素组成,可以创建包含任何没有关联的元素。
Bicycle=[‘trek’,’rgtg’,‘cec’]
Print[bicycle]
bicycle=['efer','cec','c']
print(bicycle[0].title())
末尾添加元素:.append(‘efvrf’)
支持动态添加数据:
bicycle=[]
bicycle.append('ecece')
print(bicycle)
支持动态插入数据:.insert(1,’eded’)
1)、删除任意位置元素
bicycle=['regr','uyu','fgtgh']
del bicycle[1]
print(bicycle
['regr', 'fgtgh']
2)、删除任意位置元素
bicycle=['regr','uyu','fgtgh']
lastBicycle=bicycle.pop(1)
print(bicycle)
print(lastBicycle)
['regr', 'uyu']
fgtgh
3)、根据值删除元素
bicycle=['regr','uyu','fgtgh']
bicycle.remove('uyu')
print(bicycle)
注:remove只能删除第一个指定值的元素,需要循环判断;
1)、对元素永久性排序
按字母排序:bicycle.sort()
按字母排反序:bicycle.sort(reverse=True)
2)、对元素排序且不影响原数据:
bicycle=['regr','uyu','fgtgh']
newB=sorted(bicycle)
newB=sorted(bicycle,reverse=True)
print(bicycle)
print(newB)
Len(bicycle)
bicycles=['regr','uyu','fgtgh']
for bicycle in bicycles:
print(bicycle)
regr
uyu
fgtgh
1)、使用range
ui=range(2,6)
for b in range(1,9):
print(b)
print(ui)
2)、使用list将range转换为列表、指定步长
number=list(range(1,9,2))
print(number)
3)、统计列表
max(number)
min(number)
sum(number)
4)、使用列表解析创建列表
squre=[value**2 for value in range(1,9)]
print(squre)
1)、切片
squre=list(range(1,9))
num=squre[2:7]
print(squre)
print(num)
[3, 4, 5, 6, 7]
2)、复制列表
squre=list(range(1,9))
num=squre[:]
不可变的列表称为元组
与列表不一样的是需要使用括号来定义元组
num=(2,3,5,6,7,5,3,9)
If xxx :
Xxx
Xxx
Else:
Xxx
Xxx
xxxxxxxx
注:1)、python比较不区分大小写;
2)、使用and 和or判断多个条件
3)、使用
num=['er','vf','fbrb','hyt']
if 'vf' in num:
print('OK')
检测是否包含在列表中
num=['er','vf','fbrb','hyt']
if 'vf' not in num:
print('OK')
if xxx:
xxx
elif xxx
xxx
listnew=['de','gtg','rfrf','hyh','vtvt']
while listnew:
print(listnew)
listnew.pop()
字典包括一系列的键值对,通过键可以访问值,值可以是数字、字符串甚至字典
client={'color':'green','size':5}
print(client['color']+'****'+str(client['size'])
client={'color':'green','size':5}
client['ui']='new'
client['size0']=9
print(client['color']+'****'+str(client['size'])+'**'+client['ui']+'***'+str(client['size0']))
del client['color']
client={'color':'green','size':5}
client['ui']='new'
client['size0']=9
for key,value in client.items():
print('key:'+key+'-value:'+str(value))
排序遍历
for key,value in sorted(client.items(),reverse=True):
print('key:'+key+'-value:'+str(value))
只遍历值
for value in client.values():
print(value)
遍历时过滤表中重复的元素
for value in set(client.values()):
定义:
Def add(x,y):
Return (x+y)
调用:
add(1,2)
注:1)、input函数
让用户输入参数,存储在变量中,
可以添加信息提示用户输入:
num=input('请输入:')
print(num)
2)、方法split() 以空格为分隔符将字符串分拆成多个部分, 并将这些部分都存储到一个列表中。
Def add(x,y):
Return (x*80+y)
调用:
add(x=1,y=2)
def addInt(x=20,y=1):
def addInt(x=20,y=1,z=''):
return (x+y*199)
print(addInt(x=100,y=0))
def build_person(first_name, last_name):
❶ person = {'first': first_name, 'last': last_name}
❷ return person
def greet_users(names):
for name in names:
msg = "Hello, " + name.title() + "!"
print(msg)
❶ usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
可以像下面这样做:
function_name(list_name[:])
def make_pizza(*toppings):
"""打印顾客点的所有配料"""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
def make_pizza(size, *toppings):
"""概述要制作的比萨"""
print("\nMaking a " + str(size) +
"-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
def build_profile(first, last, **user_info):
"""创建一个字典, 其中包含我们知道的有关用户的一切"""
profile = {}❶ profile['first_name'] = first
profile['last_name'] = last
❷ for key, value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile('albert', 'einstein',
location='princeton',
field='physics')
print(user_profile)
1)、导入整个模块
模块 是扩展名为.py的文件, 包含要导入到程序中的代码。
import addIntPrj //导入模块
print(addIntPrj.addInt(2,4))
2)、导入函数
from addIntPrj import addInt
print(addInt(1,2))
3)、使用as 给函数指定别名
from pizza import make_pizza as mp
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')
4)、使用as给模块指定别名
import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese'
5)、导入模块所有函数
from pizza import *
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
Class 类名():
成员
class Dog():
❸ def __init__(self, name, age): //初始化属性
❹ self.name = name //self相当于this
self.age = age
❺ def sit(self):
print(self.name.title() + " is now sitting.")
def roll_over(self):
print(self.name.title() + " rolled over!")
class Dog():
❶ my_dog = Dog('willie', 6) //创建类的实例
❷ print("My dog's name is " + my_dog.name.title() + ".") //访问类的属性
❸ print("My dog is " + str(my_dog.age) + " years old.")
my_dog.sit() //调用方法
my_dog.roll_over()
def __init__(self, make, model, year):
"""初始化描述汽车的属性"""
self.make = make
self.model = model
self.year = year
❶ self.odometer_reading = 0 //赋予默认值
❶ class Car():
//创建父类
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.modelreturn long_name.title()
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
self.odometer_reading += miles
//创建子类
class ElectricCar(Car):
❸ def __init__(self, make, model, year):
"""初始化父类的属性"""
❹ super().__init__(make, model, year)
//创建子类实例
❺ my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
1)、创建子类时, 父类必须包含在当前文件中, 且位于子类前面。
2)、方法__init__() 接受创建Car 实例所需的信息。
3)、super() 是一个特殊函数, 帮助Python将父类和子类关联起来。 这行代码让Python调用ElectricCar 的父类的方法__init__() , 让ElectricCar 实例包含父类的所有属性。 父类也称为超类 (superclass) , 名称super因此而得名。
4)、给子类定义新的属性
class Car():
class ElectricCar(Car):
def __init__(self, make, model, year):
super().__init__(make, model, year)
❶ self.battery_size = 70
❷ def describe_battery(self):
print("This car has a " + str(self.battery_size) + "-kWh battery.")
对于父类的方法, 只要它不符合子类模拟的实物的行为, 都可对其进行重写。 为此, 可在子类中定义一个这样的方法, 即它与要重写的父类方法同名。 这样, Python将不会考虑这
个父类方法, 而只关注你在子类中定义的相应方法;
假设Car 类有一个名为fill_gas_tank() 的方法, 它对全电动汽车来说毫无意义, 因此你可能想重写它。 下面演示了一种重写方式:
def ElectricCar(Car):
def fill_gas_tank():
print("This car doesn't need a gas tank!")
不断给ElectricCar 类添加细节时, 我们可能会发现其中包含很多专门针对汽车电瓶的属性和方法。 在这种情况下, 我们可将这些属性和方法提取出来, 放到另一个名为Battery 的类中, 并将一个Battery 实例用作ElectricCar 类的一个属性:
class Car():
class Battery():
def __init__(self, battery_size=70):
self.battery_size = battery_size
def describe_battery(self):
print("This car has a " + str(self.battery_size) + "-kWh battery.")
//电动车独特属性
class ElectricCar(Car):
def __init__(self, make, model, year):
super().__init__(make, model, year)
self.battery = Battery()
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
注:一个类里面可以包括多个类
from car import Car //导入类模块
my_new_car = Car('audi', 'a4', 2016) //创建类实例
print(my_new_car.get_descriptive_name())
my_new_car.odometer_reading = 23
my_new_car.read_odometer()
单个.py文件可以包括多个类,导入模块时可以只导入我们需要的类
from car import ElectricCar
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
from car import ElectricCar
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
❶ import car
❷ my_beetle = car.Car('volkswagen', 'beetle', 2016)
print(my_beetle.get_descriptive_name())
❸ my_tesla = car.ElectricCar('tesla', 'roadster', 2016)
print(my_tesla.get_descriptive_name())
❶ import car import *
主模块:car.py
class Car():
--snip—
分部模块:electric_car.py
from car import Car
class Battery():
--snip--
class ElectricCar(Car):
--snip—
使用模块:
from car import Car
from electric_car import ElectricCar
下面来看模块collections 中的一个类——OrderedDict
from collections import OrderedDict
favorite_languages = OrderedDict()
favorite_languages['jen'] = 'python'
favorite_languages['sarah'] = 'c'
favorite_languages['edward'] = 'ruby'
favorite_languages['phil'] = 'python'
for name, language in favorite_languages.items():
print(name.title() + "'s favorite language is " +
language.title() + ".")
with open('111.txt') as file_object: //使用with,可以在结束时自动关闭文件
contents = file_object.read()
print(contents)
相比于原始文件, 该输出唯一不同的地方是末尾多了一个空行。 为何会多出这个空行呢? 因为read() 到达文件末尾时返回一个空字符串, 而将这个空字符串显示出来时就是一
个空行。 要删除多出来的空行, 可在print 语句中使用rstrip():
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())
rstrip() 删除(剥除) 字符串末尾的空白
file_path = 'C:\Users\ehmatthes\other_files\text_files\filename.txt'
with open(file_path) as file_object:
filename = 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line)
filename = 'pi_digits.txt'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
readlines() 从文件中读取每一行, 并将其存储在一个列表中; 接下来, 该列表被存储到变量lines 中
filename = 'programming.txt'
with open(filename, 'w') as file_object:
file_object.write("I love programming.")
filename = 'programming.txt'
with open(filename, 'w') as file_object:
file_object.write("I love programming.")
file_object.write("I love creating new games.")
如果你要给文件添加内容, 而不是覆盖原有的内容, 可以附加模式 打开文件
filename = 'programming.txt'
with open(filename, 'a') as file_object:
file_object.write("I also love finding meaning in large datasets.\n")
file_object.write("I love creating apps that can run in a browser.\n")
我们打开文件时指定了实参'a' , 以便将内容附加到文件末尾, 而不是覆盖文件原来的内容
当你认为可能发生了错误时, 可编写一个try-except 代码块来处理可能引发的异常。
try:
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
可以使用else代码块一起使用
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't divide by 0!")
else:
print(answer)
有时候你希望程序在发生异常时一声不吭, 就像什么都没有发生一样继续运行。
try:
--snip--
except FileNotFoundError:
pass
else:
--snip—
import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json' //指定了要将该数字列表存储到其中的文件的名称。
with open(filename, 'w') as f_obj: //以写入模式打开这个文件, 让json 能够将数据写入
json.dump(numbers, f_obj) //使用函数json.dump() 将数字列表存储到文件numbers.json中。
import json
filename = 'numbers.json'
with open(filename) as f_obj: //读取方式打开这个文件, 因为Python只需读取这个文件
numbers = json.load(f_obj)
print(numbers)
Python标准库中的模块unittest 提供了代码测试工具。 单元测试 用于核实函数的某个方面没有问题; 测试用例 是一组单元测试, 这些单元测试一起核实函数在各种情形下的行为都符合要求。 良好的测试用例考虑到了函数可能收到的各种输入, 包含针对所有这些情形的测试。 全覆盖式测试 用例包含一整套单元测试, 涵盖了各种可能的函数使用方式。 对于大型项目, 要实现全覆盖可能很难。 通常, 最初只要针对代码的重要行为编写测试即可, 等项目被广泛使用时再考虑全覆盖
本文来源:https://www.2haoxitong.net/k/doc/290e06a959f5f61fb7360b4c2e3f5727a4e92403.html
文档为doc格式