蓝桥杯Python B组练习——python复习1
一、简介
距蓝桥杯比赛还有一个多月,今天复习python,参考书《Python编程从入门到实践》,[美]Eric Mathes著。
二、Python复习
一、变量和简单数据类型
1.变量的命名和使用
1)变量名只能包含字母、数字和下划线。变量名可以字母或下划线打头,但不能以数字打头。
2)变量名不能包含空格,但可使用下划线来分隔其中的单词。
3)不要将Python关键字和函数名用作变量名,即不要使用Python保留用于特殊用途的单词。
4)变量名应即简短又具有描述性。
5)慎用小写字母l和大写字母O,因为它们可能被人错看成数字1或0。
2.字符串
字符串就是一系列字符。在Python中,用引号括起来的都是字符串,其中引号可以是单引号,也可以是双引号。
1)使用方法修改字符串的大小写
title()以首字母大写的方式显示每个单词
upper()将字符串改为全部大写
lower()将字符串改为全部小写
name = "ada lovelace"
print(name.title())
print(name.upper())
print(name.lower())
运行结果
D:\5\Scripts\python.exe C:\Users\Administrator\PycharmProjects\5\蓝桥杯\python\变量.py
Ada Lovelace
ADA LOVELACE
ada lovelace
2)合并(拼接)字符串
Python使用加号(+)来合并字符串。
first_name="ada"
last_name="lovelace"
full_name=first_name+" "+last_name
print(full_name)
运行结果
ada lovelace
3)使用制表符或换行符来打印空白
制表符 \t
换行符 \n
4)删除空白
删除末尾空白 rstrip()
删除开头空白 lstrip()
同时删除开头和末尾空白 strip()
3.数字
1)整数
可对整数执行加(+)减(-)乘(*)除(/)
Python使用两个**表示乘方运算
2)浮点数
Python将带小数点的数字都称为浮点数
3)使用函数str()避免类型错误
函数str(),将非字符串值表示为字符串
二、列表
1.什么是列表
列表是由一系列按特定顺序排列的元素组成。其中元素之间可以没有任何关系,用方括号([])来表示列表。
1)访问列表元素
bicycles=['trek','cannondale','redline','specialized']
print(bicycles[0])
运行结果
trek
注意:索引从0而不是1开始
索引设置为-1可让python返回最后一个列表元素,-2返回列表倒数第二个,依次类推
2.修改、添加和删除元素
1)修改列表元素
要修改列表元素,可指定列表名和要修改的元素的索引,再指定该元素的新值。
bicycles=['trek','cannondale','redline','specialized']
bicycles[0]='ducati'
print(bicycles)
运行结果
['ducati', 'cannondale', 'redline', 'specialized']
2)在列表中添加元素
将元素附加到列表末尾 append()
在列表中插入元素 insert()
bicycles=['trek','cannondale','redline','specialized']
bicycles[0]='ducati'
bicycles.insert(0,'trek')
print(bicycles)
运行结果
['trek', 'ducati', 'cannondale', 'redline', 'specialized']
3)从列表中删除元素
1.del语句删除元素
del bicycles[0]
需要知道删除元素在列表中的位置,删除后,无法再访问
2.方法pop()删除元素
poped_bicycles=bicycles.pop()
方法pop可删除列表末尾的元素,并让你能够接着使用它
实际上方法pop可以传递参数删除任何位置处的元素bicycles.pop(0)
3.根据值删除元素
你不知道从列表中删除的值所处的位置。如果你只知道要删除的元素的值,可使用方法remove()
bicycles.remove('ducati')
使用remove()从列表中删除元素时,也可接着使用它的值。并且remove()只删除第一个指定的值,如果要删除的值可能在列表中出现多次,用循环来判断。
3.组织列表
1)使用方法sort()对列表进行永久性排序
cars=['bmw','audi','toyota','subaru']
cars.sort()
print(cars)
运行结果
['audi', 'bmw', 'subaru', 'toyota']
还可以按与字母顺序相反的顺序排列列表字母,只需要向sort()方法传递参数reverse=True
2)使用函数sorted()对列表进行临时排序
sorted(cars)
还可以按与字母顺序相反的顺序排列列表字母,只需要向sort()方法传递参数reverse=True
3)倒着打印列表
要反转列表元素的排列顺序,可使用方法reverse()
cars.reverse()
方法reverse()永久性地修改列表元素的排列顺序,再次调用reverse()即可恢复
4)确定列表长度
使用函数len()可快速获悉列表的长度
len(cars)
三、操作列表
1.遍历整个列表
magicians = ['alice', 'david','carolina']
for magician in magicians:
print(magician)
运行结果:
D:\5\Scripts\python.exe C:\Users\Administrator\PycharmProjects\5\蓝桥杯\python\字符串逆序.py
alice
david
carolina
2.创建数值列表
1)使用函数range()
函数range()能轻松生成一系列的数字
for value in range(1,5):
print(value)
运行结果:
1
2
3
4
注意:生成的数字是左闭右开
2)使用range()创建数字列表
要创建数字列表,可使用函数list()将range()的结果直接转换为列表。
numbers = list(range(1,6))
print(numbers)
运行结果:
[1, 2, 3, 4, 5]
使用函数range()时,还可以指定步长。例如,下面代码打印1~10内的偶数:
even_numbers=list(range(2,11,2))
print(even_numbers)
运行结果:
[2, 4, 6, 8, 10]
3)对数字列表执行简单的统计计算
digits=list(range(0,10))
print(min(digits))
print(max(digits))
print(sum(digits))
运行结果:
0
9
45
4)列表解析
列表解析将for循环和创建新元素的代码合并成一行,并自动附加新元素。
squares=[value**2 for value in range(1,11)]
print(squares)
运行结果:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
3.使用列表的一部分
1)切片
squares=[value**2 for value in range(1,11)]
print(squares)
print(squares[0:3])
print(squares[1:4])
#如果没有指定第一个索引,Python列表将自动从列表开头开始
print(squares[:4])
#要让切片终止于列表末尾,使用如下
print(squares[2:])
#如果要提取后三个,使用如下
print(squares[-3:])
#指定步长
print(squares[1:6:2])
print(squares[-1::-1])
运行结果:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[1, 4, 9]
[4, 9, 16]
[1, 4, 9, 16]
[9, 16, 25, 36, 49, 64, 81, 100]
[64, 81, 100]
[4, 16, 36]
[100, 81, 64, 49, 36, 25, 16, 9, 4, 1]
注意:索引从0开始,左闭右开
2)遍历切片
players = ['charles','martina','michael','florence','eli']
print("Here are the first three players on my team:")
for player in players[:3]:
print(player.title())
运行结果:
Here are the first three players on my team:
Charles
Martina
Michael
3)复制列表
要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引([:])
my_foods = ['pizza','falafel','carrot cake']
friend_foods=my_foods[:]
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
运行结果:
My favorite foods are:
['pizza', 'falafel', 'carrot cake']My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake']
4.元组
列表非常适合用于存储在程序运行期间可能变化的数据集。列表是可以修改的,这对处理网站用户列表或游戏中的角色列表至关重要。然而,有时候你需要创建一系列不可修改的元素,元组可以满足这种需求。Python将不能修改的值称为不可变的,而不可变的列表被称为元组。
1)定义元组
元组看起来犹如列表,但使用圆括号而不是方括号来标识。定义元组后,就可以使用索引来访问其元素,就像访问列表元素一样。
dimensions = (200,50)
print(dimensions[0])
print(dimensions[1])
运行结果:
200
50
修改元组的值将会报错
dimensions = (200,50)
dimensions[0]=250
print(dimensions[0])
print(dimensions[1])
运行结果:
Traceback (most recent call last):
File "C:\Users\Administrator\PycharmProjects\5\蓝桥杯\python\字符串逆序.py", line 89, in <module>
dimensions[0]=250
TypeError: 'tuple' object does not support item assignment
2)遍历元组中的所有值
像列表一样,也可以使用for循环来遍历元组中的所有值
dimensions = (200,50)
for dimension in dimensions:
print(dimension)
运行结果:
200
50
3)修改元组变量
虽然不能修改元组的元素,但可以给存储元组的变量赋值。因此,如果要修改前述矩形的尺寸,可重新定义整个元组。
dimensions = (200,50)
print("Original dimensions:")
for dimension in dimensions:
print(dimension)
dimensions=(400,100)
print("\nModified dimensions:")
for dimension in dimensions:
print(dimension)
运行结果:
Original dimensions:
200
50Modified dimensions:
400
100
四、if语句
1.一个简单示例
cars = ['dudi','bmw','subaru','toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
运行结果:
Dudi
BMW
Subaru
Toyota
2.条件测试
每条if语句的核心都是一个值为True或False的表达式,这种表达式被称为条件测试。Python根据条件测试的值为True还是False来决定是否执行if语句中的代码。如果条件测试的值为True,Python就执行紧跟在if语句后面的代码;如果为False,Python就忽略这些代码。
1)检查是否相等
car = 'bmw' car=='bmw'
一个等号是陈述;可解读为“将变量car的值设置为‘bmw’”。两个等号是发问;可解读为“变量car的值是‘bmw’吗?”
2)检查是否相等时不考虑大小写
在Python中检查是否相等时区分大小写。如果两个大小写不同的值会被视为不相等。如果大小写很重要,这种行为有其优点。但如果大小写不关紧要,而只想检查变量的值,可将变量的值转换为小写,再进行比较:
car='Audi'
car.lower()='dudi'
3)检查是否不相等
要判断两个值是否相等,可结合使用惊叹号和等号(!=),其中惊叹号表示不,在很多编程语言中都如此。
requested_topping = 'mushrooms'
if requested_topping !='anchovies':
print("Hold the anchovies!")
运行结果:
Hold the anchovies!
4)比较数字
小于<、小于等于<=、大于>、大于等于>=
5)检查多个条件
1.使用and检查多个条件
要检查是否两个条件都为True,可使用关键字and将两个条件测试合而为一。
例如要检查两个人都小于21
age_0=22
age_1=18
age_0>=21 and age_1 >=21
False
age_1=22
age_0>=21 and age_1>=21
True
2.使用or检查多个条件
关键字or也能够让你检查多个条件,但只要至少有一个条件满足,就能通过整个测试。
age_0=22
age_1=18
age_0>=21 or age_1 >=21
True
age_1=18
age_0>=21 or age_1>=21
False
6)检查特定值是否包含在列表中
要判断特定的值是否包含在列表中,可使用关键字in。
requested_toppings = ['mushrooms','onions','pineapple']
'mushrooms' in requested_toppings
True
'pepperoni' in requested_toppings
False
7)检查特定值是否不包含在列表中
要判断特定值未包含在列表中,可使用关键字 not in。
banned_users=['andrew','carolina','david']
user='marie'
if user not in banned_users:
print(user.title()+",you can not post a response if you wish.")
运行结果:
Marie,you can not post a response if you wish.
8)布尔表达式
它不过是条件测试的别名,用于记录条件,如判断游戏是否正在运行。
3.if语句
1)简单的if语句
最简单的if语句只有一个测试和一个操作:
if conditional_test:
do something
2)if-else语句
经常需要在条件测试通过了时执行一个操作,并在没有通过时执行另一个操作;在这种情况下,可使用Python提供的if-else语句。
age=17
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
else:
print("Sorry,you are too young to vote.")
print("Please register to vote as soon as you turn 18!")
运行结果:
Sorry,you are too young to vote.
Please register to vote as soon as you turn 18!
3)if-elif-else结构
经常需要检查超过两个的情形,为此可使用Python提供的if-else-else结构。
age=12
if age<4:
price=0
elif age<18:
price=5
else:
price=10
print("Your admission cost is $"+str(price)+'.')
运行结果:
Your admission cost is $5.
4)使用多个elif代码块
age=12
if age<4:
price=0
elif age<18:
price=5
elif age<65:
price=10
else:
price=5
print("Your admission cost is $"+str(price)+'.')
运行结果:
Your admission cost is $5.
5)省略else代码块
age=80
if age<4:
price=0
elif age<18:
price=5
elif age<65:
price=10
elif age>=65:
price=5
print("Your admission cost is $"+str(price)+'.')
运行结果:
Your admission cost is $5.
6)测试多个条件
if-elif-else结构功能强大,但仅适合于只有一个条件满足的情况:遇到通过了的测试后,Python就跳过余下的测试。这种行为很好,效率很高,让你能够测试一个特定的条件。
有时候必须检查你关心的所有条件,应使用一系列不包含elif和else代码块的简单的if语句。
requested_toppings = ['mushrooms','extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
if 'pepperoni' in requested_toppings:
print("Adding pepperoni.")
if 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
print("\n Finished making your pizza!")
运行结果:
Adding mushrooms.
Adding extra cheese.Finished making your pizza!
4.使用if语句处理列表
1)检查特殊元素
requested_toppings = ['mushrooms','green peppers','extra cheese']
for requested_topping in requested_toppings:
if requested_topping == 'green peppers':
print("Sorry,we are out of green peppers right now.")
else:
print("Adding "+requested_topping +'.')
print("\nFinished making your pizza!")
运行结果:
Adding mushrooms.
Sorry,we are out of green peppers right now.
Adding extra cheese.
Finished making your pizza!
2)确定列表不是空的
requested_toppings=[]
if requested_toppings:
for requested_topping in requested_toppings:
print("Adding"+requested_topping+".")
print("\nFinished making your pizza!")
else:
print("Are you sure you want a plain pizza?")
运行结果:
Are you sure you want a plain pizza?
3)使用多个列表
available_toppings =['mushrooms','olives','green peppers','pepperoni','pineapple','extra cheese']
requested_toppings =['mushrooms','french fries','extra cheese']
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print("Adding"+requested_topping+".")
else:
print("Sorry,we don't have"+requested_topping+".")
print("\nFinished making your pizza!")
运行结果:
Addingmushrooms.
Sorry,we don't havefrench fries.
Addingextra cheese.
Finished making your pizza!