python 语法教程讲义

发布时间:2019-01-10 17:22:28   来源:文档文库   
字号:

Python 语法教程讲义

------

第一章、python基础

1python的源程序,

1.1python的源程序,本质上就是一个特殊格式的文本可以使用任意文本编辑软件python开发扩展名为.py

1.2、第一个小程序

Print(“hello python”)

Print(“hello word”)

linux中运行python源程序:python 01-hellopython.py

1.3执行python程序的三种方式:

1.3.1python/python 3解释器/其他解释器

Python xxx.py;

Python3 xxx.py

1.3.2)、交互式运行python程序

也就是在终端中,直接运行解释器,而不需要传入文件名,在python shell中,直接输入终端命令

优点:适合验证局部代码;缺点:不能保存代码,不适合大量代码文件。

操作:linux下,直接输入python进入python\python3的解释器shell,输入python程序。

1.01365次方: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集成开发环境,可以在windowlinuxmacos中使用,

2、算术运算

+、减-、乘*、除/、取整//、取余%、取幂**

3变量

数据类型

数字型:整数、浮点数、布尔值、复数;

非数字型:字符串、列表、元组、字典

Python2.x版本整型包括:intlongType(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+/

3.1数据类型转换

字符串转int

num='21'

int1=int(num)

print(int1)

4列表

列表是一系列按特定顺序排列的元素组成,可以创建包含任何没有关联的元素。

4.1、创建列表

Bicycle=[‘trek’’rgtg’‘cec’]

Print[bicycle]

4.2、访问、使用列表元素

bicycle=['efer','cec','c']

print(bicycle[0].title())

4.3添加元素

末尾添加元素:.append(‘efvrf’)

支持动态添加数据:

bicycle=[]

bicycle.append('ecece')

print(bicycle)

支持动态插入数据:.insert(1,’eded’)

4.4删除元素

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只能删除第一个指定值的元素,需要循环判断;

4.5元素处理

1)、对元素永久性排序

按字母排序:bicycle.sort()

按字母排反序:bicycle.sort(reverse=True)

2)、对元素排序且不影响原数据:

bicycle=['regr','uyu','fgtgh']

newB=sorted(bicycle)

newB=sorted(bicycle,reverse=True)

print(bicycle)

print(newB)

4.6、列表信息

Len(bicycle)

4.7操作列表

4.7.1、遍历列表

bicycles=['regr','uyu','fgtgh']

for bicycle in bicycles:

print(bicycle)

regr

uyu

fgtgh

4.7.2创建数字列表

1)、使用range

ui=range(2,6)

for b in range(1,9):

print(b)

print(ui)

2)、使用listrange转换为列表、指定步长

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)

4.7.3使用列表一部分

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[:]

4.8、元组

不可变的列表称为元组

4.8.1定义元组

与列表不一样的是需要使用括号来定义元组

num=(2,3,5,6,7,5,3,9)

5、控制语句

5.1if语句

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

5.2while 循环

5.2.1、使用break立即退出循环

5.2.2、使用continue跳到开头继续判断执行

5.2.3、使用while判断列表是否为空

listnew=['de','gtg','rfrf','hyh','vtvt']

while listnew:

print(listnew)

listnew.pop()

6字典

字典包括一系列的键值对,通过键可以访问值,值可以是数字、字符串甚至字典

6.1创建字典

client={'color':'green','size':5}

print(client['color']+'****'+str(client['size'])

6.2、添加键值对

client={'color':'green','size':5}

client['ui']='new'

client['size0']=9

print(client['color']+'****'+str(client['size'])+'**'+client['ui']+'***'+str(client['size0']))

6.3、删除键值对

del client['color']

6.4遍历字典

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()):

7、函数:

定义:

Def add(x,y):

Return (x+y)

调用:

add(1,2)

注:1)、input函数

让用户输入参数存储在变量中

可以添加信息提示用户输入

num=input('请输入:')

print(num)

2)、方法split() 以空格为分隔符将字符串分拆成多个部分, 并将这些部分都存储到一个列表中。

7.1、关键字实参定义:

Def add(x,y):

Return (x*80+y)

调用:

add(x=1,y=2)

7. 2、形参默认值:

def addInt(x=20,y=1):

7.3、实参可选

def addInt(x=20,y=1,z=''):

return (x+y*199)

print(addInt(x=100,y=0))

7.4、返回字典

def build_person(first_name, last_name):

❶ person = {'first': first_name, 'last': last_name}

❷ return person

7.5字典做参数

def greet_users(names):

for name in names:

msg = "Hello, " + name.title() + "!"

print(msg)

usernames = ['hannah', 'ty', 'margot']

greet_users(usernames)

7.6列表的副本传递给函数

可以像下面这样做:

function_name(list_name[:])

7.7传递任意多实参

def make_pizza(*toppings):

"""打印顾客点的所有配料"""

print(toppings)

make_pizza('pepperoni')

make_pizza('mushrooms', 'green peppers', 'extra cheese')

7.8结合使用位置实参和任意数量实参

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')

7.9使用任意数量的关键字实参

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)

7.10、将函数导入模块中

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')

8、类

8.1创建类

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!")

8.2创建类的实例

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()

8.3、属性赋予默认值

def __init__(self, make, model, year):

"""初始化描述汽车的属性"""

self.make = make

self.model = model

self.year = year

❶ self.odometer_reading = 0 //赋予默认值

8.4继承

❶ 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.")

8.4.1重写父类方法

对于父类的方法, 只要它不符合子类模拟的实物的行为, 都可对其进行重写。 为此, 可在子类中定义一个这样的方法, 即它与要重写的父类方法同名。 这样, Python将不会考虑这

个父类方法, 而只关注你在子类中定义的相应方法

假设Car 类有一个名为fill_gas_tank() 的方法, 它对全电动汽车来说毫无意义, 因此你可能想重写它。 下面演示了一种重写方式:

def ElectricCar(Car):

def fill_gas_tank():

print("This car doesn't need a gas tank!")

8.4.2将实例用作属性

不断给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()

:一个类里面可以包括多个类

8.5导入类

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()

8.5.1、导入模块中的某个类

单个.py文件可以包括多个类,导入模块时可以只导入我们需要的类

from car import ElectricCar

my_tesla = ElectricCar('tesla', 'model s', 2016)

print(my_tesla.get_descriptive_name())

8.5.2在一个模块中导入多个类

from car import ElectricCar

my_tesla = ElectricCar('tesla', 'model s', 2016)

print(my_tesla.get_descriptive_name())

8.5.3导入整个模块

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())

8.5.4、导入模块每个类

❶ import car import *

8.5.5将一个类存储在几个模块

主模块: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

8.6使用python标准库

下面来看模块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() + ".")

9、文件和异常

9.1读取整个文件

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() 删除(剥除) 字符串末尾的空白

9.1.1、文件路径

file_path = 'C:\Users\ehmatthes\other_files\text_files\filename.txt'

with open(file_path) as file_object:

9.2、逐行读取

filename = 'pi_digits.txt'

with open(filename) as file_object:

for line in file_object:

print(line)

9.3、使用列表存储文件

filename = 'pi_digits.txt'

with open(filename) as file_object:

lines = file_object.readlines()

for line in lines:

print(line.rstrip())

readlines() 从文件中读取每一行, 并将其存储在一个列表中; 接下来, 该列表被存储到变量lines

9.4、写入文件

filename = 'programming.txt'

with open(filename, 'w') as file_object:

file_object.write("I love programming.")

9.4.1写入多行

filename = 'programming.txt'

with open(filename, 'w') as file_object:

file_object.write("I love programming.")

file_object.write("I love creating new games.")

9.4.2附加到文件末尾

如果你要给文件添加内容, 而不是覆盖原有的内容, 可以附加模式 打开文件

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' 以便将内容附加到文件末尾, 而不是覆盖文件原来的内容

9.5、异常

9.5.1使用try-except 代码块

当你认为可能发生了错误时, 可编写一个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)

9.5.2失败时直接跳过

有时候你希望程序在发生异常时一声不吭, 就像什么都没有发生一样继续运行。

try:

--snip--

except FileNotFoundError:

pass

else:

--snip

9.6存储数据

9.9.1使用json.dump() json.load()

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)

10代码测试

Python准库中的模块unittest 提供了码测试工具 单元测试 用于核实函数的某个方面没有问题; 测试用例 一组单元测试 这些单元测试一起核实函数在各种情形下的行为都符合要求。 良好的测试用例考虑到了函数可能收到的各种输入, 包含针对所有这些情形的测试。 全覆盖式测试 用例包含一整套单元测试 涵盖了各种可能的函数使用方式。 对于大型项目, 要实现全覆盖可能很难。 通常, 最初只要针对代码的重要行为编写测试即可, 等项目被广泛使用时再考虑全覆盖

本文来源:https://www.2haoxitong.net/k/doc/290e06a959f5f61fb7360b4c2e3f5727a4e92403.html

《python 语法教程讲义.doc》
将本文的Word文档下载到电脑,方便收藏和打印
推荐度:
点击下载文档

文档为doc格式