Python -- 上

一、变量

1、变量的命名和使用

  

2、使用方法修改字符串的大小写

  ①以首字母大写的方式显示每个单词,使用 title() 方法

message="this is I study Python first day"
print(message.title())

 

  ②将字符串全部修改为大写或者小写,使用方法 upper() 和 lower()

message="this is I study Python first day"
print(message.upper())
print(message.lower())

  

3、拼接字符串

  python使用加号(+)来拼接字符串。

name="zhangsan"
address="beijing"
message=name+"-"+address
print(message)

message=name+" "+address
print(message)

 

  简单问候语

first_name="ada"
last_name="lovelace"
full_name=first_name+" "+last_name
print(full_name)
print("Hello,"+full_name.title()+"!")

 

  可以使用拼接来创建信息,再把整条消息都存储在一个变量中

first_name="ada"
last_name="lovelace"
full_name=first_name+" "+last_name
message="Hello,"+full_name.title()+",happy!"
print(message)

 

  4、使用制表符或换行符来添加空白

  在编程中,空白泛指任何非打印字符,如空格、制表符和换行符。可使用空白来组织输出,使其更易读。

  要在字符串中添加制表符,可使用字符组合 \t

print("Python")
print("\tpython")

 

  要在字符串中添加换行符,使用字符组合 \n

print("Linux\nPython\nMySQL")

 

5、删除空白

   删除字符串末尾的空白,使用方法 rstrip()

message="Python  "
message

 

message.rstrip()

 

  要永久删除这个字符串中的空白,必须将删除操作的结果返回到变量中

message=message.rstrip()
message

  删除字符串开头的空白,使用方法 lstrip()

message=" Python   "
message.lstrip()

 

  删除字符串两端的空白,使用方法 strip()

message=" Python   "
message.strip()

 

6、使用字符串避免语法错误

  ①一对双引号中存在单引号可以正常输出,一对单引号中存在双引号可以正常输出。

  ②一对单引号中存在单引号会报错,一对双引号中存在双引号会报错,因为python会将第一对单引号或双引号视为字符串,其余的文本视为python代码,从而引发错误。

 7、函数str()

  将python中的非字符串表示为字符串,如果不进行转换会报错。

age=25
message="happy "+str(age)+"rd birthday"
print(message)

 Python之禅:在Python终端会话中执行命令import this。

二、列表简介

  列表是由一系列按特定顺序排列的元素组成,可以创建包含字母表中的所有字母,数字0~9或所有家庭成员姓名的列表,也可以将任何东西加入列表中,其中的元素之间可以没有任何关系。

  在Python中,用方括号([ ])表示列表,并用逗号来分割其中的元素。

#列表包含几类自行车
bicycles = ['trek','cannondale','redline','specialized'] print(bicycles)

 

  如果让python将列表打印出来,python将打印列表的内部所有,包括方括号。

1、列表是有序集合,因此要访问列表的任何元素,只需将该元素的位置或索引告诉python即可,要访问列表元素,可指出列表的名称,再指出元素的索引,并将其放在方括号内。

#提取第一款自行车
bicycles = ['trek','cannondale','redline','specialized']
print(bicycles[0])

 

  当请求获取列表元素时,Python只返回该元素,而不包括方括号和引号。

#输出第一款自行车,首字母大写,使用title()方法
bicycles = ['trek','cannondale','redline','specialized']
print(bicycles[0].title())

 

2、索引从0而不是1开始

  在python中,第一个列表元素的索引是0而不是1,第二个列表元素的索引是1,按照这种计算方式,要访问列表的任何元素,都可将其位置减1

#访问索引1和3处的自行车,返回列表中的第二个和第四个元素
bicycles = ['trek','cannondale','redline','specialized']
print(bicycles[1])
print(bicycles[3])

 

3、Python访问最后一个列表元素提供了一种特殊语法,通过索引指定为 -1 ,可让Python返回最后一个列表元素。

bicycles = ['trek','cannondale','redline','specialized']
print(bicycles[-1])

 

  索引 -2 返回倒数第二个列表元素,索引 -3 返回倒数第三个列表元素,以此类推。

 4、使用列表中的各个值

  可像使用其他变量一样使用列表中的各个值,可以使用拼接根据列表中的值创建信息。

bicycles = ['trek','cannondale','redline','specialized']
message="my first bicycle was "+bicycles[0].title()+"."
print(message)

 

5、修改、添加和删除元素

  创建的大多数列表都将是动态的,列表将随着程序的运行增删元素。

  ①修改列表元素的语法与访问列表元素的语法类似,要修改列表元素,可指定列表名和要修改的元素的索引,再指定该元素的新值。

#修改第一个人物的名字为"赵信"
student=['锐雯','盖伦','亚索','璐璐']
print(student)
student[0]="赵信"
print(student)

 

  可以修改任何列表元素的值。

  ②在列表中添加元素

  在列表末尾添加元素,使用 append() 方法

#在列表末尾添加一个人物”剑圣“
student=['锐雯','盖伦','亚索','璐璐']
print(student)
student.append('剑圣')
print(student)

 

  可以先创建一个空列表,再使用 append() 方法去添加

figure=[]
figure.append('诺手')
figure.append('木木')
figure.append('狼人')
print(figure)

 

   在列表的任何位置插入元素 -- insert()

#在索引2处添加一个人物”拉克丝“
student=['锐雯','盖伦','亚索','璐璐']
print(student)
student.insert(2,'拉克丝')
print(student)

 

  ③从列表中删除元素 -- del

#删除索引位置0的人物
student=['锐雯','盖伦','亚索','璐璐']
print(student)
del student[0]
print(student)

 

  ④使用方法 pop() 删除元素

  有时候需要将元素从列表中删除, 并接着使用它的值,方法 pop() 可删除列表末尾的元素,并让你能够接着使用它。

  术语弹出(pop)源自这样的类比:列表就像一个栈,而删除列表末尾的元素相当于弹出栈顶元素。

#删除列表最后一个元素,并继续使用其值
student=['锐雯','盖伦','亚索','璐璐']
print(student)
figure=student.pop()
print(student)
print(figure)

 

  ⑤使用 pop() 方法弹出任何位置处的元素。

  可以使用pop() 来删除列表中任何位置的元素,只需在括号中指定要删除的元素的索引即可。

#删除索引位置2的人物
student=['锐雯','盖伦','亚索','璐璐']
figure=student.pop(2)
print(figure)
print("I like use a figure is"+figure)

 

  ※如果要从列表中删除一个元素,且不再以任何方式使用它就用 del 语句;如果要在删除元素后还继续使用,就使用方法 pop()

 ⑥根据值删除元素

  不知道列表中删除值的所处位置,知道想删除元素的值,可以使用 remove() 方法。

#从列表中删除“亚索‘
student=['锐雯','盖伦','亚索','璐璐']
print(student)
student.remove("亚索")
print(student)

 

  ※方法 remove() 只删除列表中第一个指定的值,如果要删除的值在列表中出现多次,就需要使用循环来判断是否删除了所有这样的值。

6、组织列表

  元素的排列顺序常常是无法预测的,需要特定的顺序呈现信息。

  ①使用方法 sort() 对列表进行永久性排序

#对自行车按照字母顺序排序
bicycles = ['trek','cannondale','redline','specialized']
bicycles.sort()
print(bicycles)

 

  方法 sort() 永久性的修改了列表元素的排列顺序,无法恢复到原来的排列顺序。

  ②反向排序,向 sort() 方法传递参数 reverse=True

#将自行车按照反向按照字母排序
bicycles = ['trek','cannondale','redline','specialized']
bicycles.sort(reverse=True)
print(bicycles)

 

  ③使用函数 sorted() 对列表进行临时排序

  要保留列表元素原来的排列顺序,同时以特定的顺序呈现他们,可使用函数 sorted() ,函数 sorted() 能够按照特定顺序显示列表元素,同时不影响它们在列表中的原始排列顺序。

#对自行车按照字母临时排序
bicycles = ['trek','cannondale','redline','specialized']
print(bicycles)
print(sorted(bicycles))
print(bicycles)

 

  按与字母顺序相反的顺序显示列表,可向函数 sorted() 传递参数 reverse=True

bicycles = ['trek','cannondale','redline','specialized']
print(bicycles)
print(sorted(bicycles,reverse=True))

 

  ④倒着打印列表

  要反转列表元素的排列顺序,使用方法 reverse()

#倒着打印列表
student=['锐雯','盖伦','亚索','璐璐']
student.reverse()
print(student)

 

  reverse() 不是指按与字母顺序相反的顺序排列列表元素,只是反转列表元素的排列顺序。

  reverse() 方法可以永久性的修改元素的排列顺序,但可随时恢复到原来的排列顺序,为此只需对列表再次调用reverse() 即可

7、确定列表的长度

  使用 len() 可快速获悉列表的长度

student=['锐雯','盖伦','亚索','璐璐']
len(student)

 

三、操作列表

1、for 循环

figure=['锐雯','盖伦','亚索','璐璐']
for item in figure:
    print("I Like use "+item+"!")

 

  for 循环后面,没有缩进的代码都执行一次,而不会重复执行。

figure=['锐雯','盖伦','亚索','璐璐']
for item in figure:
    print("I Like use "+item+"!")
print("Do you like play LOL?")

 

2、创建数值列表

  ①使用函数 range()

for item in range(1,5):
    print(item)

 

  range() 前闭后开。

  ②range()创建数字列表

  要创建数字列表,可使用函数 list() 将 range() 的结果直接转换为列表,如果将 range() 作为 list() 的参数,输出将作为一个数字列表

number = list(range(1,6))
print(number)

 

  使用函数 range() 时,可指定步长。

number = list(range(1,10,2))
print(number)

 

  使用函数range() 几乎能够创建任何需要的数字集

#将前10个整数的平方加入到一个列表中
number = []
for item in range(1,11):
    total=item ** 2
    number.append(total)
print(number)

 

#为了使代码简洁,可不使用临时变量total
number = []
for item in range(1,11):
    number.append(item**2)
print(number)

 

  ③专门对数字列表执行统计计算的函数

  min -- 显示列表中的最小值

  max -- 显示列表中的最大值

  sum -- 统计列表中数值的总和

number = list(range(0,21))
print(number)
print(min(number))
print(max(number))
print(sum(number))

 

3、列表解析

  列表解析只需编写一行代码就能生成这样的列表,列表解析将 for 循环和创建新元素的代码合并成一行,并自动附加新元素。

number = [item ** 2 for item in range(1,11)]
print(number)

 

4、切片

  切片可以处理列表的部分元素,创建切片要指定使用的第一个元素和最后一个元素的索引。与函数range() 一样,Python在到达指定的第二个索引前面的元素停止,要输出列表中的前三个元素,需要指定索引0~3,这将分别输出0、1、2的元素。

figure=['锐雯','盖伦','亚索','璐璐','剑姬','安妮','盲僧']
print(figure[0:4])

 

#如果没有指定第一个索引,Python将自动从列表开头开始
figure=['锐雯','盖伦','亚索','璐璐','剑姬','安妮','盲僧']
print(figure[:6])

 

#让切片从列表的某个索引到列表末尾
figure=['锐雯','盖伦','亚索','璐璐','剑姬','安妮','盲僧']
print(figure[2:])

 

  负数索引可以返回离列表末尾相应距离的元素。

#输出最后三个人物的名字
figure=['锐雯','盖伦','亚索','璐璐','剑姬','安妮','盲僧']
print(figure[-3:])

 

5、遍历切片

  遍历列表中的部分元素,可在for循环中使用切片。

figure=['锐雯','盖伦','亚索','璐璐','剑姬','安妮','盲僧']
for item in figure[:5]:
    print(item)

 

6、复制列表

  复制列表可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引(:),这让python创建一个始于第一个元素,终止于最后一个元素的切片,即复制整个列表。

figure = ['锐雯','盖伦','亚索','璐璐','剑姬','安妮','盲僧']
student = figure[:]
print(figure)
print(student)

 

7、元组

  列表非常适合用于存储在程序运行期间可能变化的数据集。列表是可以修改的,有时候需要创建一系列不可修改的元素,元组可以满足这种修改,Python将不可修改的值称为不可变的,而不可变的列表称为元组。 

  元组看起来犹如列表,但是使用圆括号而不是方括号来标识。定义元组后,就可以使用索引来访问其元素,就像访问列表元素一样。

figure = ('亚索','锐雯','卡特')
print(figure)

 

  元组不允许修改元素的值

  ①遍历元组中的所有值

  像列表一样,也可以使用for循环来遍历元组的所有值

figure = ('亚索','锐雯','卡特')
for item in figure:
    print(item)

 

  ②修改元组变量

  虽然不能修改元组的元素,但可以给存储元组的变量赋值。

figure = ('亚索','锐雯','卡特')
print(figure)

figure = ('赵信','盖伦','剑圣','诺手')
print(figure)

 

  相比于列表,元组是更简单的数据结构,如果需要存储的一组值在程序的整个生命周期内都不变,可使用元组。

四、if 语句

  在Python中,if语句能够检查程序的当前状态,并据此采取相应的措施。

#遍历列表,如果是”trek“,字母全部大写,其他的都是首字母大写
bicycles = ['trek','cannondale','redline','specialized']
for item in bicycles:
    if item == 'trek':
        print(item.upper())
    else:
        print(item.title())

 

  每条 if 语句的核心都是一个值为 True 或 False 的表达式,这种表达式称为条件测试。Python 根据条件测试的值为 True 还是 False 来决定是否执行 if 语句中的代码,如果条件测试的值为 True,Python 就执行紧跟在 if 语句后面的代码;如果为 False,Python就忽略这些代码。

  ①大多数条件测试都将一个变量的当前值和特定值进行比较,最简单的条件测试检查变量的值是否与特定值相等。

bicycle = 'trek'
bicycle == 'trek'

 

bicycle = 'trek'
bicycle == 'redline'

       

  两个大小写不相同的值会被视为不相等。

  如果大小写无关紧要,只是想检查变量的值,可将变量的值转换为小写再进行比较。

bicycle = 'TREK'
bicycle.lower() == 'trek'

 

  ②检查是否不相等

  要判断两个值是否不等,可结合使用叹号和等号(!=),叹号表示不

bicycles = ['trek','cannondale','redline','specialized']
for item in bicycles:
    if item != 'apple':
        print('这不是自行车')

 

  ③比较数字

 

1、检查多个条件

  需要两个条件都为 true 时才执行的操作或只要求一个条件为 true 时就执行相应的擦欧总,需要用到 and 和 or

  ①使用 and 检查多个条件,两边都为 true 才返回 true,有一个为 false 则返回 false

age = 20
age_1 = 25
age == 20 and age_1 == 25

 

  ②使用 or 检查多个条件,两边有一个是 true 则返回 true,两边都为 false 才返回 false

age = 20
age_1 = 25
age == 20 or age_1 == 100

  

2、检查特定值是否包含在列表中,使用 in

  执行操作前检查列表中是否包含特定的值,要判断特定值是否已经在列表中,可使用关键字 in

bicycles = ['trek','cannondale','redline','specialized']
'trek' in bicycles

 

3、检查特定值是否不包含在列表中,使用 not in

bicycles = ['trek','cannondale','redline','specialized']
figure = 'monkey'
if figure not in bicycles:
    print(figure+"is an animal")

 

4、布尔表达式

  布尔表达式是条件测试的别名,与条件表达式一样,布尔表达式的结果要么为 True,要么为 False

  布尔表达式通常用于记录条件,如游戏正在运行,或用户是否可以编辑网站的特定内容。

game_active = True
can_edit = False

  ※else是一条包罗万象的语句,只要不满足任何 if 或 elif 中的条件测试,其中的代码就会执行,这可能会引入无效甚至恶意的数据,如果知道最终要测试的条件,应考虑使用一个elif代码块来代替else代码块,这样就可以肯定,仅当满足相应的条件时,代码才会执行。

  ※if-elif-else结构功能强大,且仅适合用于一个条件满足的情况,遇到通过了的测试,Python就跳过余下的测试。

  ※单独使用代码块时,如果关心每个条件,就需要用一系列的 if

figure = ('亚索','锐雯','盲僧')
if "亚索" in figure:
    print("亚索是中单")
if "锐雯" in figure:
    print("锐雯是上单")
if "盲僧" in figure:
    print("盲僧是打野")

 

  单独的代码块如果使用 if-elif 结构,那么满足第一个条件就跳出

figure = ('亚索','锐雯','盲僧')
if "亚索" in figure:
    print("亚索是中单")
elif "锐雯" in figure:
    print("锐雯是上单")
elif "盲僧" in figure:
    print("盲僧是打野")

 

  如果是在 for 循环中使用 if-elif-else 可以,都使用 if 也可以

figure = ('亚索','锐雯','盲僧')
for item in figure:
    if item == '亚索':
        print(item+"是中单")
    elif item == '锐雯':
        print(item+"是上单")
    else:
        print(item+"是打野")

 

5、检查特殊元素

figure = ('亚索','锐雯','盲僧')
for item in figure:
    if item == '亚索':
        print(item+" this hero was select")
    else:
        print("you select hero is "+item)

 

6、确定列表不是空的

  在运行 for 循环前确定列表是否为空。

figure = []
if figure:
    for figure in figure:
        print("use "+figure)
    print("begin game")
else:
    print("don't select a hero")

 

  在 if 语句中将列表名用在条件表达式中时,Python 将在列表至少包含一个元素时返回 True,并在列表为空时返回 False,如果列表不为空,就运行与前一个示例相同的 for 循环。

figure = ['亚索','锐雯']
if figure:
    for figure in figure:
        print("use "+figure)
    print("begin game")
else:
    print("don't select a hero")

 

  使用多个列表

figure = ['盖伦','锐雯','亚索','泰隆','剑姬']
user_figure = ['盖伦','拉克丝','锐雯']
for user_figure in user_figure:          #user_figure 列表自己遍历自己的元素
    if user_figure in figure:            #每遍历一个元素判断是否在 figure 列表中
        print('The user select hero is '+user_figure)
    else:
        print("Sorry,The user can't select "+user_figure)

 

五、字典

  字典可存储的信息量几乎不受限制。

1、一个简单的字典

alien = {'color':'green','points':5}
print(alien['color'])
print(alien['points'])

 

2、使用字典

  在Python中,字典是一系列的键值对,每个键都与一个值相关联,可以使用键来访问与之关联的值。与键相关联的值可以是数字、字符串、列表乃至字典。事实上,可将任何 Python 对象用作字典中的值。

  在Python中,字典用放在花括号 { } 中的一系列键值对表示。

  键值对是两个相关联的值,指定键时,Python将返回与之相关联的值。键和值之间用冒号分割,而键值对之间用逗号分割,在字典中,想存储多少个键值对都可以。

alien = {'color':'green','points':5}

  要获取与键相关联的值,可依次指定字典名和放在方括号内的键

alien = {'color':'green'}
print(alien['color'])

 

alien = {'color':'green','points':5}
new_alien = alien['points']
print("You just earned "+str(new_alien)+" points")

 

3、添加键值对

  字典是一种动态结构,可随时在其中添加键值对。要添加键值对,可依次指定字典名、用方括号括起来的键和相关联的值。

  ①添加键值对

fruit = {'apple':'red','banana':'yellow'}
fruit['peach'] = 'pink'
print(fruit)

 

  ②创建空字典在添加键值对

fruit = {}
fruit['apple'] = 'red'
print(fruit)

 

  ③修改字典中的值

  修改字典中的值,依次指定字典名、用方括号括起来的键以及与该键相关联的新值。

fruit = {'apple':'red'}
print("The apple color is "+fruit['apple'])
fruit['apple'] = 'green'
print("now,The apple color is "+fruit['apple'])

 

number = {'a':1,'b':2,'c':3}
if number['a'] == 1:
    x = 1
elif number['a'] == 2:
    x = 2
else:
    x = 3
number['a'] = x + number['a']
print("the number a is "+str(number['a']))

 

4、删除键值对

  对于字典中不需要的信息,可使用 del 语句将相应的键值对彻底删除。使用 del 语句时,必须指定字典名和要删除的键

fruit = {'apple': 'red', 'banana': 'yellow', 'peach': 'pink'}
print(fruit)
del fruit['peach']
print(fruit)

 

5、由类似对象组成的字典

  可以使用字典来存储众多对象的同一信息。对于较长的字典,可采用如下方法

fruit = {'apple': 'red',
         'banana': 'yellow', 
         'peach': 'pink',
         'orange':'orange',
         'kiwi':'green'
        }
print("the apple color is "+fruit['apple'].title())

 

 6、遍历字典:

#使用 items() 方法将返回一个键值对列表。
fruit = {'apple':'red','banana':'yellow','peach':'pink'} for key,value in fruit.items(): print("key: "+key) print("value: "+value+"\n")

 

  ①遍历字典中的所有键 -- keys()

fruit = {'apple':'red','banana':'yellow','peach':'pink'}
for key in fruit.keys():
    print("The key is "+key)

 

  ②按顺序遍历字典中的所有键

fruit = {'apple':'red','banana':'yellow','peach':'pink','pear':'yellow'}
for item in sorted(fruit.keys()):
    print(item)

 

  字典总是明确的记录键和值之间的关联关系,但获取字典元素时,获取顺序是不可预测的,如果按顺序输出,使用函数 sorted() 来获得按特定顺序排列列表的副本。

  ③遍历字典中的所有值 -- values(),返回一个值列表,不包含任何键

fruit = {
    'apple':'red',
    'banana':'yellow',
    'peach':'pink',
    'pear':'yellow'
}
for item in fruit.values():
    print(item)

 

  ④去除重复项 -- set()

fruit = {
    'apple':'red',
    'banana':'yellow',
    'peach':'pink',
    'pear':'yellow'
}
for item in set(fruit.values()):
    print(item)

 

7、嵌套

  将一系列字典存储在列表中,或将列表作为值存储在字典中,称为嵌套。可以在列表中嵌套字典、在字典中嵌套列表或在字典中嵌套字典。

  ①在列表中嵌套字典

fruit_1 = {'apple':'red'}
fruit_2 = {'banana':'yellow'}
fruit_3 = {'peach':'pink'}
fruit_4 = {'pear':'yellow'}
fruit = [fruit_1,fruit_2,fruit_3,fruit_4]
print(fruit)
for item in fruit:
    print(item)

 

  ②在字典中嵌套列表

fruit = {
    'orange':'orange',
    'apple':['red','green']
}
print("The fruit orange's color is "+fruit['orange']+"\n")
for item in fruit['apple']:
    print("The fruit apple's color is "+item)

    

  ③在字典中存储字典

#将每位用户的信息存储在一个字典中,对于每位用户,存储其三项信息:名、姓和居住地,遍历所有用户名,并访问每个用户相关联的信息字典。
users = {
    'W':{
        'first':'wang',
        'last':'_A'
    },
    'L':{
        'first':'li',
        'last':'_B'
    }
}
for username,user_info in users.items():
    print("\nUsername: "+username)
    full_name = user_info['first']+user_info['last']
    print("Full_name:"+full_name.title())

 

#字典存储列表
favorite_places = {'zhangsan':['beijing','shanghai'],'lisi':['hunan','guangzhou','xizang'],'wangwu':['guizhou','neimeng']} for name,place in favorite_places.items(): print("\n"+name+"喜欢去的地方是:") for item in place: print(item.title())

 

# 创建一个名为cities 的字典,其中将三个城市名用作键;对于每座城市,都创建一个字典,并在其中包含该城市所属的国家、人口约数以及一个有关该 城市的事实。在表示每座城市的字典中,
应包含country 、population 和fact 等键。将每座城市的名字以及有关它们的信息都打印出来。 cities
= { 'China':{ 'country':'beijing', 'population':'2153.6 million', 'fact':'capital' }, 'USA':{ 'country':'New York', 'population':'870 million', 'fact':'sports' }, 'Japan':{ 'country':'Tokyo', 'population':'1394 million', 'fact':'hot' } } for country,info in cities.items(): print("Select city is "+country) print("The city's country is "+info['country']) print("The city's population is "+info['population']) print("The city's fact is "+info['fact']+"\n")

 

六、用户输入和while循环

  函数 input() 可以接收用户输入的内容。

  ①函数 Input() 的工作原理

  函数 Input() 让程序暂停运行,等待用户输入一些文本,获取用户输入后,Python将其存储在一个变量中,方便之后使用。

message = input("please input a tel number:")
print(message)

 

  每当使用 input() 函数时,都应该指定清晰而易于明白的提示,有时候提示超过一行,可将提示存储在一个变量中,再将变量传递给函数 input() 。

message = "This is a long message."
message += "\nplease input your number"

tel = input(message)
print(tel)

 

  使用函数 input() 时,Python 将用户输入解读为字符串

age = input("please input your age:")
age

 

  当进行数字比较时,此时会报错,因为无法将字符串和数字进行比较。

  函数 int() 将Python的输入视为数值,

age = input("please input your age:")
age = int(age)
if age < 30:
    print("your are so young")

 age = int(input("please input your age:"))
 if age < 30:
 print("your are so young")

 

1、求模运算符

  求模运算符将两个数相除并返回余数,不会指出一个数是另一个数的多少倍,而指出余数是多少。

number = int(input("please input a number: "))
if number % 2 == 0 :
    print("The number "+str(number)+" is even")
else:
    print("The number "+str(number)+" is odd")

 

#判断一个数是不是100的整数
number = input("please input a number: ")
number = int(number)
if number % 100 == 0:
    print("This "+str(number)+" is an integer multiple of 100")
else:
    print("This "+str(number)+" is not an integer multiple of 100")

 

2、while循环简介

  for 循环用于针对集合中的每个元素的一个代码块,而 while 循环不断的运行,直到指定的条件不满足为止。

#使用循环来数数
number = 1
while number <= 5:
    print(number)
    number += 1

 

message_a = input("please input a str: ")
while message_a != 'quit':
    message_a = input("please input a str: ")
    if message_a == 'quit':
        print("over")
    else:
        print("continue")

 

#添加一个标志,将这个标志命名为 active,可以将标志命名为任何名称。用于判断程序是否应该继续执行。
active = True while active: message_a = input("please input a str: ") if message_a == 'quit': active = False else: print("continue")

 

  将程序变量 active 设置为 True,让程序处于活动状态,这样简化了while语句,不需要做任何比较,将变量 active 变为 True,循环将继续执行。将变量 active 设置为 False,这将导致 while 循环不再执行。

1、使用 break 退出循环

  要立即退出 while 循环,不再运行循环中余下的代码,也不管条件测试的结果如何,可使用 break 语句,break 语句用于控制程序流程,可使用它来控制哪些代码行执行,哪些代码行不执行。

city = "Please enter according to the prompt,"
city += "\nPlease input a city name:"
while True:
    message = input(city)
    if message == 'quit':
        break
    else:
        print("I love city is "+message+"\n")

 

  在任何Python循环中都可使用break语句,可使用break语句来退出遍历列表或字典的for循环。

2、在循环中使用continue

  要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句,它不像break语句那样不再执行余下的代码并退出整个循环。

number = 0
while number < 10:
    number += 1
    if number % 2 == 0:
        continue
    print(number)

 

message = "please input a fruit: "
while True:
    fruit = input(message)
    if fruit == 'quit':
        break
    else:
        print("I Like eat fruit is "+fruit+"\n")

 

3、使用 while 循环来处理列表和字典

  for 循环是一种遍历列表的有效方式,但在 for 循环中不应修改列表,否则将导致 Python 难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用 while 循环,通过将 while 循环同列表和字典结合使用,可收集、存储并组织大量输入,供以后查看和显示。

在列表之间移动元素

fruit = ['apple','banana','peach']
fruit_new = []
while fruit:
    fruit_A = fruit.pop()
    print("I like this fruit: "+fruit_A)
    fruit_new.append(fruit_A)
for item in fruit_new:
    print(item.title())

 

  ①删除包含特定值的所有列表元素

pets = ['cat','dog','rabbit','cat','pig','cat']
print(pets)
while 'cat' in pets:
    pets.remove("cat")
print(pets)

 

  ②使用用户输入来填充字典

question = {}
active = True
while active:
    name = input("What's your name: ")
    ques = input("How do you like fruit: ")
    question[name] = ques
    
    resp = input("Have another person?(yes/no): ")
    if resp == 'yes':
        continue
    elif resp == 'no':
        active = False
        print("\nOver")
    else:
        print("please input right option")
        continue
for name,ques in question.items():
    print(name.title()+" like fruit is "+ques.title())

 

七、函数

  函数是带名字的代码块,用于完成具体的工作。

  要执行函数定义的特定任务,可调用该函数,需要在程序中多次执行同一项任务时,无需反复编写该任务的代码,只需要调用执行该任务的函数。

  定义函数,使用 def 定义函数

def number():
    '''定义一个简单的函数'''
    print("Hello World")
number()

 

  函数i调用让Python执行函数的代码,要调用函数,可依次指定函数名以及用括号括起的必要信息。

1、向函数传递信息

def greet_user(username):
    print("Hello, "+username.title() + "!")
greet_user('Jerry')

 

  在函数定义 greet_user() 的括号内添加 username ,通过在这里添加 username ,就可让函数接受你给 username 的任何值,函数调用时给 username 指定一个值,调用 greet_user() 时,可将一个名字传递给它。

2、实参和形参

  在函数 greet_user() 的定义中,变量 username 是一个形参,形参是函数完成其工作所需的一项信息,在代码 greet_user('Jerry') 中,值 'Jerry' 是一个实参,实参是调用函数时传递给函数的信息。

  我们调用函数时,将要让函数使用的信息放在括号内,在greet_user('Jerry')中,将实参‘Jerry’ 传递给了函数 greet_user(),这个值被存储在形参 username 中。

3、传递实参

  函数定义中可能包含多个形参,因此函数调用中也可能包含多个实参。向函数传递实参的方式很多,可使用位置实参,这要求实参的顺序与形参的顺序相同,也可使用关键字实参,其中每个实参都由变量名和值组成,还可使用列表和字典。

  ①位置实参

  Python必须将函数调用中的每个实参都关联到函数定义中的一个形参,最简单的关联方式是基于实参的顺序,这种关联方式被称为位置实参。

def fruit(fruit_name,fruit_color):
    print("I like fruit name is "+fruit_name+",and It's color is "+fruit_color)
fruit('apple','green')

 

  ②可以调用函数多次

def fruit(fruit_name,fruit_color):
    print("I like fruit name is "+fruit_name+",and It's color is "+fruit_color)
fruit('apple','green')
fruit('peach','pink')

 

  在函数中,根据需要使用任意数量的位置实参,Python将按顺序将函数调用中的实参关联到函数定义中相应的形参。

 4、关键字实参

  关键字实参是传递给函数的名称---值对,直接在实参中将名称和值关联起来了,因此向函数传递实参时不会混淆,关键字实参无需考虑函数调用中的实参顺序,清楚的指出了函数调用中各个值的用途。

def fruit(fruit_name,fruit_color):
    print("I like fruit name is "+fruit_name+",and It's color is "+fruit_color)
fruit(fruit_name='apple',fruit_color='green')
fruit(fruit_color='pink',fruit_name='peach')

 

5、默认值

  编写函数时,可给每个形参指定默认值,在调用函数中给形参提供了实参时,Python将使用指定的实参值,否则,将使用形参的默认值,给形参指定默认值后,可在函数调用中省略相应的实参。

def fruit(fruit_name,fruit_color='red'):
    print("I Like fruit is "+fruit_name+",It's color is "+fruit_color)
fruit(fruit_name='apple')
fruit(fruit_name='banana',fruit_color='yellow')
fruit('orange')

 

6、返回值

  函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值。函数返回的值被称为返回值。

  在函数中,可使用 return 语句将值返回到调用函数的代码行,返回值能够将程序的大部分繁重工作移到函数中去完成,从而简化主程序。

def fruit(fruit_name,fruit_color):
    full_name = fruit_name+' '+fruit_color
    return full_name.title()
message = fruit('apple','color')
print(message)

 

  调用返回值的函数时,需要提供一个变量,用于存储返回的值,才能整洁输出,不提供变量返回的将是带引号的

  ①让实参变成可选的

  有时候需要让实参变成可选的,这样使用函数的人只需在必要时才能提供额外的信息,可使用默认值让实参变成可选的。

def get_formatted_name(first_name,last_name,middle_name=''):
    if middle_name:    #判断middle_name 是否有值,有的人没有中间名
        full_name = first_name+'-'+middle_name+'-'+last_name
        return full_name.title()
    else:
        full_name = first_name+'-'+last_name
        return full_name.title()
message = get_formatted_name('Stephen','Curry','Waddell')
print(message)

message = get_formatted_name('LeBron','James')
print(message)

 

  ②返回字典

  函数可返回任何类型的值,包括列表和字典等较复杂的数据结构。

def fruit(fruit_name,fruit_color):
    fruit_full = {'name':fruit_name,'color':fruit_color}
    return fruit_full
message = fruit('apple','red')
print(message)

 

def name(first_name,last_name,age=''):
    person = {'first':first_name,'last':'last_name'}
    if age:
        person['age'] = age
    return person
message = name('Wang','_A')
print(message)

message = name('L','_B',age=24)
print(message)

 

7、结合使用函数和while循环

def fruit(fruit_name,fruit_color):
    fruit_full_name = fruit_name+'-'+fruit_color
    return fruit_full_name.title()

while True:
    print("\n请输入你喜欢的水果的名称和颜色")
    f1 = input("Fruit's name: ")
    l1 = input("Fruit's color: ")
    message = fruit(f1,l1)
    print("I Like fruit is "+message)

 

def fruit(fruit_name,fruit_color):
    fruit_full_name = fruit_name+'-'+fruit_color
    return fruit_full_name.title()

while True:
    print("\n请输入你喜欢的水果的名称和颜色")
    f1 = input("Fruit's name: ")
    l1 = input("Fruit's color: ")
    if f1 == 'q' and l1 == 'q':
        break
    message = fruit(f1,l1)
    print("I Like fruit is "+message)

 

def fruit(fruit_name,fruit_color):
    full_fruit = {fruit_name:fruit_color}
    return full_fruit
while True:
    fruit_n = input("please input fruit's name: ")
    fruit_c = input("please input fruit's color: ")
    if fruit_n == 'quit' and fruit_c == 'quit':
        break
    message = fruit(fruit_n,fruit_c)
    for name,color in message.items():
        print(name+"'s color is"+color)

 

#可选形参
def fruit(fruit_name,fruit_color,fruit_count=''):
    fruit_full = {'fruit_name':fruit_name,'fruit_color':fruit_color}
    if fruit_count:
        fruit_full['fruit_count'] = fruit_count
    return fruit_full
while True:
    fruit_n = input("input fruit's name: ")
    if fruit_n == 'quit':
        break
    fruit_c = input("input fruit's color: ")
    if fruit_c == 'quit':
        break
    fruit_co = input("input fruit's count: ")
    if fruit_co == 'quit':
        break
    message = fruit(fruit_n,fruit_c,fruit_co)
    print(message)

 

8、传递列表

  向函数传递列表,列表包含的可能是名字、数字或更复杂的对象(如字典),将列表传递给函数后,函数就能直接访问其内容。

def greet_users(names):
    for name in names:
        print("Hello,"+name.title()+"!")
username = ['Tom','Jerry','Hardon']
greet_users(username)

 

  ①在函数中修改列表

  列表传递给函数后,函数可对其进行修改,在函数中对这个列表所作的任何修改都是永久性的,能够高效的处理大量数据。

def fruit(fruit_name,fruit_full):
    while fruit_name:
        fruit_a = fruit_name.pop()
        print("弹出的元素是:"+fruit_a)
        fruit_full.append(fruit_a)

def fruit_new(fruit_full):
    for item in fruit_full:
        print("元素:"+item)
fruit_name = ['apple','banana','pear','orange']
fruit_full = []
fruit(fruit_name,fruit_full)
fruit_new(fruit_full)

  ②禁止函数修改列表

  切片表示法[:] 可以创建副本的形式操作,而原列表不发生变化

#name是列表
修改列表:fruit(name,color)
使用副本,不修改列表:fruit(name[:],color)

 9、传递任意数量的实参 -- *

  预先不知道函数需要接受多少个实参,Python允许函数从调用语句中收集任意数量的实参。

def fruit(*fruit_name):
    print(fruit_name)
fruit('apple')
fruit('apple','banana','orange')

 

  使用 * 号让形参可以接受多个参数。

def fruit(*fruit_name):
    for item in fruit_name:
        print(item)
fruit('apple','banana','orange')

 

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

  如果让函数接收不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后,Python先匹配位置关键字和关键字实参,再将余下的实参都收集到最后一个形参中。

def fruit(fruit_name,*fruit_color):
    print("The Fruit is "+fruit_name)
    for item in fruit_color:
        print("- " +item)
fruit('orange','orange')
fruit('apple','red','green','yellow')

 

  Python将收到的第一个值存储在形参 fruit_name 中,并将其他的所有值都存储在元组 fruit_color 中。

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

  需要接受任意数量的实参,但是预先不知道传递给函数的会是什么样的信息,这种情况下,可将函数编写能够接受任意数量的键值对,调用语句提供了多少就接受多少。

def fruit(fruit_name,fruit_color,**fruit_info):
    profile = {}
    profile['fruit_name'] = fruit_name
    profile['fruit_color'] = fruit_color
    for key,value in fruit_info.items():    #遍历字典fruit_info的键值对,并将每一个键存储到字典profile中。
        profile[key] = value
    return profile
fruit_full = fruit('apple','red',location='Beijing',count=20)
print(fruit_full)

 

12、将函数存储在模块中

  函数的优点之一是,使用他们可将代码块与主程序分离,通过给函数指定描述性名称,可让主程序容易理解的多。

  可以将函数存储在称为模块的独立文件中,再将模块导入到主程序中,import 语句允许再当前运行的程序文件中使用模块中的代码。

  ①导入整个模块

  要让函数导入,需要先创建模块,模块是扩展名为 .py 的文件,包含要导入到程序中的代码,例,创建一个包含 make_pizza() 的模块,保存在 pizza.py中。

def make_pizza(size,*toppings):
    '''概述要制作的披萨'''
    print("\nMaking a "+str(size)+
          "-inch pizza with the following toppings:")
    for topping in toppings:
        print("- "+ topping)

 

  在 pizza.py 所在的目录中创建另一个名为 making_pizzas.py 的文件,这个文件导入刚刚创建的模块并进行调用。

import pizza
pizza.make_pizza('12','pepperoni')
pizza.make_pizza('16','mushrooms','green peppers','extra cheese')

 

  调用 pizza.py 模块后得出的结果,在making_pizzas.py 中可以使用 pizza.py 定义的所有函数。

 

#使用 import 就可以导入函数,导入后的使用方法
module_name.function_name()

  ②导入特定的函数

from module_name import function_name

  通过用逗号分割函数名,可根据需要从模块中导入任意数量的函数

from module_name import function_0,function_1.function_2

  对于前面的making_pizza.py 示例,如果只想导入想要的函数,可以使用类似下面

from pizza import make_pizza

  ③使用as给函数指定别名

  如果导入的函数名称与程序现有的名称冲突,或者函数的名称太长,可指定简短而独一无二的别名 -- 函数的另一个名称。

from pizza import make_pizza as mp
mp(16,'pepperoni')
mp(12,'mushrooms','green peppers','extra cheese')

 

  ④使用as给模块指定别名

import pizza as p
p.make_pizza(16,'pepperoni')
p.make_pizza(12,'mushrooms','green peppers','extra cheese')

 

  ⑤导入模块中的所有函数

  使用星号(*)运算符可让Python导入模块中的所有函数

from pizza import *
make_pizza(16,'pepperoni')
make_pizza(12,'mushrooms','green peppers','extra cheese')

 

八、类

  首字母大写的名称指的是类。

  在面向对象编程中,表示显示世界中的事物和情景的类,并基于这些类来创建对象,编写类时,定义一大类对象都有的通用行为。

  基于类创建对象时,每个对象都自动具备这种通用行为,然后可根据需要赋予每个对象独特的个性。

  根据类来创建对象被称为实例化,能够用类的实例。

1、创建和使用类

  例:编写一个表示小狗的简单类Dog,不是特定的小狗,而是任何小狗,大多数小狗都有名字和年龄,还会蹲下和打滚。由于大多数小狗都具备上述两项信息和两种行为,这个类让Python知道如何创建小狗的对象,编写这个类后再使用它来创建表示特定小狗的实例。

#创建Dog类
#根据Dog类的每个实例都将存储名字和年龄,赋予每条小狗蹲下(sit()) 和 打滚 (roll_over()) 的能力
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!")

  ①方法 __init__()

  前面学到的有关函数的一切都适用于方法。__init__() 是一个特殊的方法,每当根据Dog()类创建实例时,Python都会自动运行它,在这个方法的名称中,开头和末尾各有两个下划线,避免Python默认方法与前面普通方法发生名称冲突。

  上面Dog()例子中,将方法__init__() 定义成了包含三个形参:self、name、age,在这个方法的定义中,形参 self 必不可少,还必须位于其他形参的前面,Python 调用这个 __init__() 方法来创建 Dog 实例时将自动传入实参 self。每个类相关联的方法调用都自动传递实参 self,它是一个指向实例本身的引用,让实例能够访问类中的属性和方法。

  Python 调用Dog类的方法 __init__(),通过实参向 Dog() 传递名字和年龄;self 会自动传递,因此不需要传递它,每当根据Dog类创建实例时,都只需给最后两个形参(name 和 age)提供值。

  以self为前缀的变量都可供类中的所有方法使用,还可以通过类的任何实例来访问这些变量。self.name = name 获取存储在形参 name 中的值,并将其存储到变量中,然后该变量被关联到当前创建的实例。

   Dog 类定义的另外两个方法,sit() 和 roll_over() ,这些方法不需要额外的信息,如名字或年龄,因此它们只有一个形参self。

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!")
my_dog = Dog('naonao',6)
print("My Dog's name is "+my_dog.name+" ,and it's age is "+str(my_dog.age))  #my_dog.name 访问小狗名字

 

  ②访问属性

  要访问实例的属性,可使用句点表示法:如  my_dog.name、my_dog.age

  ③调用方法

  根据 Dog 类创建实例后,就可以使用句点表示法调用 Dog 类中定义的任何方法

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!")
my_dog = Dog('naonao',6)
my_dog.sit()
my_dog.roll_over()

 

  ④创建多个实例

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!")
my_dog = Dog('naonao',6)
my_dog.sit()
your_dog = Dog('niuniu','8')
your_dog.roll_over()
print("My Dog's name is "+my_dog.name+",and it's age is "+str(my_dog.age))
print("My Dog's name is "+your_dog.name+",and it's age is "+str(your_dog.age))

 

#创建一个名为Restaurant 的类,其方法__init__() 设置两个属性:restaurant_name 和cuisine_type 。创建一个名 为describe_restaurant() 的方法和一个名为open_restaurant() 的方法,其中前者打印前述两项信息,而后者打印一条消息,指出餐馆正在营业。 根据这个类创建一个名为restaurant 的实例,分别打印其两个属性,再调用前述两个方法
class Restaurant():
    def __init__(self,restaurant_name,cuisine_type):
        self.restaurant_name = restaurant_name
        self.cuisine_type = cuisine_type

    def describe_restaurant(self):
        print("restaurant name is "+self.restaurant_name+",cusine type is "+self.cuisine_type)

    def open_restaurant(self):
        print("餐馆正常营业")
restaurant = Restaurant('python','⭐⭐⭐⭐⭐')
print("Look! "+restaurant.restaurant_name+",and it;s type is "+restaurant.cuisine_type)
restaurant.describe_restaurant()
restaurant.open_restaurant()

  

class User():
    def __init__(self,first_name,last_name,*info):      #info 传入多个信息
        self.fn = first_name
        self.ln = last_name
        self.info = info
    def describe_user(self):
        print("first name is "+self.fn+",last name is "+self.ln)
        print("Like sports:")
        for item in self.info:            #遍历info
            print(item)
    def greet_user(self):
        print("Hello,"+self.fn+"-"+self.ln)
user = User('Lebron','James','basketball','swimming')
user.describe_user()
user.greet_user()

 

2、使用类和实例

  可以使用类来模拟世界中的很多情景,类编写好后,大部分时间都将花在使用根据类创建的实例上,需要执行的一个重要任务是修改实例的属性,可以直接修改实例的属性,也可以编写方法以特定的方式进行修改

class Car():
    def __init__(self,make,model,year):
        '''初始化描述汽车的属性'''
        self.make = make
        self.model = model
        self.year = year

    def get_descriptive_name(self):
        '''返回整洁的信息'''
        long_name = str(self.year)+' '+self.make+' '+self.model
        return long_name.title()
my_new_car = Car('audi','a4',2021)
print(my_new_car.get_descriptive_name())

 

  ①给属性指定默认值

  类中的每个属性都必须有初始值,哪怕这个值是0或空字符串。

  添加一个名为 odometer_reading 的属性,其初始值总是为0 ,再添加一个名为 read_odometer() 的方法,用于读取汽车的里程表。

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.model
        return long_name.title()
    def read_odometer(self):
        '''打印一条汽车里程的信息'''
        print("This car has "+str(self.odometer_reading)+" miles on it.")
my_new_car = Car('audi','a4',2021)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()

 

  可以以三种方法修改属性的值:直接通过实例进行修改、通过方法进行修改、通过方法进行递增(增加特定的值)

  ①直接修改属性的值

class Car():
    def __init__(self,make,model,year):
        '''初始化描述汽车的属性'''
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0    #添加的属性 odometer_reading 初始值为0

    def get_descriptive_name(self):
        '''返回整洁的信息'''
        long_name = str(self.year)+' '+self.make+' '+self.model
        return long_name.title()
    def read_odometer(self):
        '''打印一条汽车里程的信息'''
        print("This car has "+str(self.odometer_reading)+" miles on it.")

my_new_car = Car('audi','a4',2021)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
my_new_car.odometer_reading = 23    #直接修改属性 odometer_reading 的值为23
my_new_car.read_odometer()

 

  ②通过方法修改属性的值

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.model
        return long_name.title()
    def read_odometer(self):
        '''打印一条汽车里程的信息'''
        print("This car has "+str(self.odometer_reading)+" miles on it.")
    def update_data(self,data):      #定义一个用来修改属性值得方法
        self.odometer_reading = data    #将传入的参数的值存储到 odometer_reading 中

my_new_car = Car('audi','a4',2021)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
my_new_car.update_data(23)    #向方法update_data传递参数
my_new_car.read_odometer()

  可以添加逻辑禁止将里程表读数回调

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.model
        return long_name.title()
    def read_odometer(self):
        '''打印一条汽车里程的信息'''
        print("This car has "+str(self.odometer_reading)+" miles on it.")
    def update_data(self,data):
        if data >= self.odometer_reading:    #判断修改的里程是否大于定义的里程值
            self.odometer_reading = data
        else:
            print("You can't roll back an odometer!")

my_new_car = Car('audi','a4',2021)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
my_new_car.update_data(-1)    #将里程的值变为 -1
my_new_car.read_odometer()

 

   ③通过方法对属性的值进行递增

  有时候需要将属性值递增特定特定的量,而不是将其设置为全新的值。假设购买了一辆二手车,且从购买到登记期间增加了100英里的里程。

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.model
        return long_name.title()
    def read_odometer(self):
        '''打印一条汽车里程的信息'''
        print("This car has "+str(self.odometer_reading)+" miles on it.")
    def update_odometer(self,mileage):
        self.odometer_reading = mileage
    def increment_odometer(self,miles):
        self.odometer_reading += miles

my_used_car = Car('subaru','outback',2013)
print(my_used_car.get_descriptive_name())
my_used_car.update_odometer(23500)
my_used_car.read_odometer()

my_used_car.increment_odometer(23600)
my_used_car.read_odometer()

 

#User 类中,添加一个名为login_attempts 的属性。编写一个名为increment_login_attempts() 的方法, 它将属性login_attempts 的值加1。再编写一个名为reset_login_attempts() 的方法,它将属性login_attempts 的值重置为0。 根据User 类创建一个实例,再调用方法increment_login_attempts() 多次。打印属性login_attempts 的值,确认它被正确地递增;然后,调用方 法reset_login_attempts() ,并再次打印属性login_attempts 的值,确认它被重置为0。 
class User():
    def __init__(self,first_name,last_name,*info):
        self.fn = first_name
        self.ln = last_name
        self.info = info
        self.login_attempts = 20
    def describe_user(self):
        print("first name is "+self.fn+",last name is "+self.ln)
        print("Like sports:")
        for item in self.info:
            print(item)
    def greet_user(self):
        print("Hello,"+self.fn+"-"+self.ln)
        print("Now Login users are: "+str(user.login_attempts))
    def increment_login_attempts(self,login_number):
        self.login_attempts += login_number     #递增将属性login_attempts的值加1
    def reset_login_attempts(self):
        self.login_attempts = 0         #重置login_attempts的值为0
user = User('Lebron','James','basketball','swimming')
user.describe_user()
user.greet_user()
user.increment_login_attempts(10)   #验证login_attempts的值是递增的
user.greet_user()
user.increment_login_attempts(20)   #验证login_attempts的值是递增的
user.greet_user()

user.reset_login_attempts()         #重置login_attempts的值为0
user.greet_user()

 

3、继承

  编写类时,并非总是要从空白开始,如果编写的类是另一个现成类的特殊版本,可使用继承,一个类继承另一个类时,将自动获得另一个类的所有属性和方法

  原有的类称为父类,而新类称为子类,子类继承了其父类的所有属性和方法,同时还可以定义自己的属性和方法。

  ①子类的方法 __init__()

  创建子类的实例时,Python首先需要完成的任务是父类的所有属性赋值,为此,子类的 __init__()需要父类施以援手。

  例:模拟电动汽车,电动汽车是一种特殊的汽车,可以在前面的Car类的基础上创建新类ElectricCar,这样我们就只需为电动汽车特有的属性和行为编写代码。

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.model
        return long_name.title()
    def read_odometer(self):
        '''打印一条汽车里程的信息'''
        print("This car has "+str(self.odometer_reading)+" miles on it.")
    def update_data(self,mileage):
        if mileage >= self.odometer_reading:
            self.odometer_reading = mileage
        else:
            print("You can't roll back an odometer!")

class ElectricCar(Car):        #定义子类 ElectricCar,定义子类时,必须在括号内指定父类的名称
    """电动汽车的独特之处"""
    def __init__(self,make,model,year):    #方法 __init__()接受创建 Car 实例所需的信息
        """初始化父类的属性"""
        super().__init__(make,model,year)  #super()是一个特殊函数,帮助Python将父类和子类关联起来,让Python调用ElectricCar的父类方法__init__(),让ElectricCar实例包含父类的所有属性
                           #父类也称为超类,名称 super 因此而得名
my_tesla
= ElectricCar('tesla','model s',2016) print(my_tesla.get_descriptive_name())

 

  ②重写父类的方法

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

#Car 类有一个名为fill_gas_tank() 的方法,它对全电动汽车来说毫无意义,因此想重写它。
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.model
        return long_name.title()
    def read_odometer(self):
        '''打印一条汽车里程的信息'''
        print("This car has "+str(self.odometer_reading)+" miles on it.")
    def fill_gas_tank(self):          #父类中fill_gas_tank() 方法输出"汽车使用汽油"
        print("汽车使用汽油")

class ElectricCar(Car):
    """电动汽车的独特之处"""
    def __init__(self,make,model,year):
        """初始化父类的属性"""
        super().__init__(make,model,year)
    def fill_gas_tank(self):          #子类中重写 fill_gas_tank()方法,与父类方法同名,之后只调用子类的方法
        print("电动车用电")
my_tesla = ElectricCar('tesla','model s',2016)
print(my_tesla.get_descriptive_name())
my_tesla.fill_gas_tank()

  ③将实例用作属性

  使用代码模拟实物时,可能会发现自己给类添加的细节越累越多,属性和方法清单以及文件都越来越长,这种情况下需要将类的一部分作为一个独立的类提取出来,可以将大型类拆分成多个协同工作的小类。

class Car():
    def __init__(self,make,model,year):
        self.make = make
        self.model = model
        self.year = year
    def get_descriptive_name(self):
        '''返回整洁的信息'''
        long_time = str(self.year)+' '+self.make+' '+self.model
        return long_time
class Battery():              #新定义的Battery新类,没有继承任何类
    def __init__(self,battery_size=70):    #方法 __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()      #添加一个名为 self.battery的属性,让Python创建一个新的Battery实例(默认值70),并将该实例存储再属性self.battery中
                         #每当方法__init__()被调用时,都将执行该操作,因此现在每个ElectricCar实例都包含一个自动创建的Battery实例
my_tesla = ElectricCar('tesla','models',2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()  #需要使用电动汽车的属性 battery描述电瓶,这行代码让Python在实例my_tesla中查找属性battery,并对存储在该属性中的Battery实例调用方法describe_battery()

 

4、导入类

  随着不断给类添加功能,文件可能变得很长,为遵循Python的总体概念,应让文件尽可能简洁,Python允许将类存储再模块中,然后在主程序中导入所需的模块。

import module_name from class_name
例:从Car模块中导入my_Car
from Car import my_Car
my_new_car = my_Car('audi','a4',2016)
print(my_new_car.get_descriptive_name())

my_new_car.odometer_reading = 23
my_new_car.read_odometer()

 

  ①在一个模块中存储多个类

#Battery.py,定义函数
class Car():
    def __init__(self,make,model,year):
        self.make = make
        self.model = model
        self.year = year
    def get_descriptive_name(self):
        '''返回整洁的信息'''
        long_time = str(self.year)+' '+self.make+' '+self.model
        return long_time
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.")
    def get_range(self):
        if self.battery_size == 70:
            range = 240
        elif self.battery_size == 85:
            range = 270
        print("Hello,This car has a " + str(self.battery_size) + "-kwh battery"+",and "+str(range)+" km !")
class ElectricCar(Car):

    def __init__(self,make,model,year):
        """初始化父类的属性,再初始化电动汽车特有的属性"""
        super().__init__(make,model,year)
        self.battery = Battery()

  ②导入一个类进行调用

from Battery import ElectricCar
my_tesla = ElectricCar('tesla','models',2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()
my_tesla.battery.get_range()

 

   ③从一个模块中导入多个类

from module_name import class_name1,class_name2
例:
form Car import Car,ElectricCar

  ④导入整个模块

import module_name
例
import Car

  ⑤导入模块中的所有类

from module_name imprt *

5、在一个模块中导入另一个模块

  有时候需要将类分散到多个模块中,以免模块太大,或在同一个模块中存储不相关的类,将类存储在多个模块中时,可能会发现一个模块中的类依赖于另一个模块中的类,在这种情况下可在前一个模块中导入必要的类。

例:Car、ElectricCar类和Battery类分别存储在一个模块,ElectricCar类和Battery类依赖Car类,将后两者的文件复制到 Car类存在的文件
from car import Car
class Battery():
    --snip--

class ElectricCar(Car):
    --snip--
posted @ 2021-02-23 17:04  Lillard-Time  阅读(303)  评论(0编辑  收藏  举报