python 语法教程讲义文档格式.docx

上传人:b****7 文档编号:21734781 上传时间:2023-02-01 格式:DOCX 页数:18 大小:24.20KB
下载 相关 举报
python 语法教程讲义文档格式.docx_第1页
第1页 / 共18页
python 语法教程讲义文档格式.docx_第2页
第2页 / 共18页
python 语法教程讲义文档格式.docx_第3页
第3页 / 共18页
python 语法教程讲义文档格式.docx_第4页
第4页 / 共18页
python 语法教程讲义文档格式.docx_第5页
第5页 / 共18页
点击查看更多>>
下载资源
资源描述

python 语法教程讲义文档格式.docx

《python 语法教程讲义文档格式.docx》由会员分享,可在线阅读,更多相关《python 语法教程讲义文档格式.docx(18页珍藏版)》请在冰豆网上搜索。

python 语法教程讲义文档格式.docx

While:

Foriinrange(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'

delbicycle[1]

print(bicycle

['

'

2)、删除任意位置元素

bicycle=['

lastBicycle=bicycle.pop

(1)

print(lastBicycle)

['

fgtgh

3)、根据值删除元素

bicycle.remove('

注:

remove只能删除第一个指定值的元素,需要循环判断;

4.5、元素处理

1)、对元素永久性排序

按字母排序:

bicycle.sort()

按字母排反序:

bicycle.sort(reverse=True)

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

bicycle=['

newB=sorted(bicycle)

newB=sorted(bicycle,reverse=True)

print(newB)

4.6、列表信息

Len(bicycle)

4.7、操作列表

4.7.1、遍历列表

bicycles=['

forbicycleinbicycles:

print(bicycle)

regr

uyu

4.7.2、创建数字列表

1)、使用range

ui=range(2,6)

forbinrange(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**2forvalueinrange(1,9)]

print(squre)

4.7.3、使用列表一部分

1)、切片

squre=list(range(1,9))

num=squre[2:

7]

print(num)

[3,4,5,6,7]

2)、复制列表

num=squre[:

4.8、元组

不可变的列表称为元组

4.8.1、定义元组

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

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

5、控制语句

5.1、if语句

Ifxxx:

Xxx

Else:

xxxxxxxx

1)、python比较不区分大小写;

2)、使用and和or判断多个条件

3)、使用

num=['

er'

vf'

fbrb'

hyt'

if'

innum:

print('

OK'

检测是否包含在列表中

notinnum:

ifxxx:

xxx

elifxxx

5.2、while循环

5.2.1、使用break立即退出循环

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

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

listnew=['

de'

gtg'

rfrf'

hyh'

vtvt'

whilelistnew:

print(listnew)

listnew.pop()

6、字典

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

6.1、创建字典

client={'

color'

:

'

green'

size'

5}

print(client['

]+'

****'

+str(client['

])

6.2、添加键值对

client={'

client['

ui'

]='

new'

size0'

]=9

])+'

**'

+client['

***'

]))

6.3、删除键值对

delclient['

6.4、遍历字典

forkey,valueinclient.items():

print('

key:

+key+'

-value:

+str(value))

排序遍历

forkey,valueinsorted(client.items(),reverse=True):

只遍历值

forvalueinclient.values():

print(value)

遍历时过滤表中重复的元素

forvalueinset(client.values()):

7、函数:

定义:

Defadd(x,y):

Return(x+y)

调用:

add(1,2)

1)、input函数

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

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

num=input('

请输入:

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

7.1、关键字实参定义:

Return(x*80+y)

add(x=1,y=2)

7.2、形参默认值:

defaddInt(x=20,y=1):

7.3、实参可选

defaddInt(x=20,y=1,z='

):

return(x+y*199)

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

7.4、返回字典

defbuild_person(first_name,last_name):

❶person={'

first'

first_name,'

last'

last_name}

❷returnperson

7.5、字典做参数

defgreet_users(names):

fornameinnames:

msg="

Hello,"

+name.title()+"

!

"

print(msg)

❶usernames=['

hannah'

ty'

margot'

greet_users(usernames)

7.6、列表的副本传递给函数

可以像下面这样做:

function_name(list_name[:

7.7、传递任意多实参

defmake_pizza(*toppings):

打印顾客点的所有配料"

print(toppings)

make_pizza('

pepperoni'

mushrooms'

greenpeppers'

extracheese'

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

defmake_pizza(size,*toppings):

概述要制作的比萨"

print("

\nMakinga"

+str(size)+

-inchpizzawiththefollowingtoppings:

fortoppingintoppings:

-"

+topping)

make_pizza(16,'

make_pizza(12,'

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

defbuild_profile(first,last,**user_info):

创建一个字典,其中包含我们知道的有关用户的一切"

profile={}❶profile['

first_name'

]=first

profile['

last_name'

]=last

❷forkey,valueinuser_info.items():

profile[key]=value

returnprofile

user_profile=build_profile('

albert'

einstein'

location='

princeton'

field='

physics'

print(user_profile)

7.10、将函数导入模块中

1)、导入整个模块

模块是扩展名为.py的文件,包含要导入到程序中的代码。

importaddIntPrj//导入模块

print(addIntPrj.addInt(2,4))

2)、导入函数

fromaddIntPrjimportaddInt

print(addInt(1,2))

3)、使用as给函数指定别名

frompizzaimportmake_pizzaasmp

mp(16,'

mp(12,'

4)、使用as给模块指定别名

importpizzaasp

p.make_pizza(16,'

p.make_pizza(12,'

5)、导入模块所有函数

frompizzaimport*

8、类

8.1、创建类

Class类名():

成员

classDog():

❸def__init__(self,name,age):

//初始化属性

❹self.name=name//self相当于this

self.age=age

❺defsit(self):

print(self.name.title()+"

isnowsitting."

defroll_over(self):

rolledover!

8.2、创建类的实例

classDog():

❶my_dog=Dog('

willie'

6)//创建类的实例

❷print("

Mydog'

snameis"

+my_dog.name.title()+"

."

)//访问类的属性

❸print("

Mydogis"

+str(my_dog.age)+"

yearsold."

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、继承

❶classCar():

//创建父类

def__init__(self,make,model,year):

self.odometer_reading=0

defget_descriptive_name(self):

long_name=str(self.year)+'

'

+self.make+'

+self.modelreturnlong_name.title()

defread_odometer(self):

Thiscarhas"

+str(self.odometer_reading)+"

milesonit."

defupdate_odometer(self,mileage):

ifmileage>

=self.odometer_reading:

self.odometer_reading=mileage

else:

Youcan'

trollbackanodometer!

defincrement_odometer(self,miles):

self.odometer_reading+=miles

//创建子类

classElectricCar(Car):

❸def__init__(self,make,model,year):

初始化父类的属性"

❹super().__init__(make,model,year)

//创建子类实例

❺my_tesla=ElectricCar('

tesla'

models'

2016)

print(my_tesla.get_descriptive_name())

1)、创建子类时,父类必须包含在当前文件中,且位于子类前面。

2)、方法__init__()接受创建Car实例所需的信息。

3)、super()是一个特殊函数,帮助Python将父类和子类关联起来。

这行代码让Python调用ElectricCar的父类的方法__init__(),让ElectricCar实例包含父类的所有属性。

父类也称为超类(superclass),名称super因此而得名。

4)、给子类定义新的属性

classCar():

classElectricCar(Car):

super().__init__(make,model,year)

❶self.battery_size=70

❷defdescribe_battery(self):

Thiscarhasa"

+str(self.battery_size)+"

-kWhbattery."

8.4.1、重写父类方法

对于父类的方法,只要它不符合子类模拟的实物的行为,都可对其进行重写。

为此,可在子类中定义一个这样的方法,即它与要重写的父类方法同名。

这样,Python将不会考虑这

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

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

下面演示了一种重写方式:

defElectricCar(Car):

deffill_gas_tank():

Thiscardoesn'

tneedagastank!

8.4.2、将实例用作属性

不断给ElectricCar类添加细节时,我们可能会发现其中包含很多专门针对汽车电瓶的属性和方法。

在这种情况下,我们可将这些属性和方法提取出来,放到另一个名为Battery的类中,并将一个Battery实例用作ElectricCar类的一个属性:

classCar():

classBattery():

def__init__(self,battery_size=70):

self.battery_size=battery_size

defdescribe_battery(self):

//电动车独特属性

self.battery=Battery()

my_tesla=ElectricCar('

my_tesla.battery.describe_battery()

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

8.5、导入类

fromcarimportCar//导入类模块

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文件可以包括多个类,导入模块时可以只导入我们需要的类

fromcarimportElectricCar

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

8.5.3、导入整个模块

❶importcar

❷my_beetle=car.Car('

volkswagen'

beetle'

print(my_beetle.get_descriptive_name())

❸my_tesla=car.ElectricCar('

roadster'

8.5.4、导入模块每个类

❶importcarimport*

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

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 工程科技 > 兵器核科学

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1