Python学习笔记(二)

操作列表

1.for循环:遍历整个列表,对每个元素执行相同的操作。

magicians.py

magicians=['alice','davida','caroliona']
for magician in magicians:
    print(magician)
for magician in magicians:  Python从magicians取出一个名字,存储在magician中,对于每个名字执行print(magician)直至最后一个元素;

for循环中,包含多少代码行都行,每个缩进的代码行都是缩进的一部分,且对列表的每一个值都执行一次,for后的:号表示下一行是循环的的一行,Python根据缩进来判断代码与前一个代码的关系;

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

magicians=['alice','davida','caroliona']
for magician in magicians:
    print(magician.title() + " , that was a grat trick!")
    print("I can not wait to see you next trick," + magician + "!")
运行结果为

Alice , that was a grat trick!
I can not wait to see you next trick,alice!
Davida , that was a grat trick!
I can not wait to see you next trick,davida!
Caroliona , that was a grat trick!
I can not wait to see you next trick,caroliona!
2.创建数值列表

a.函数range()生成一系列数字

差一行为:Python从指定的第一个值开始,到第二个值前停止;

numbers.py

for value in range(1,6):
    print(value)

运行结果

1
2
3
4
5

b.函数range()和list()创建数值列表

函数range()还可指定步长;

even_numbers=list(range(2,11,2))
print(even_numbers)
运行结果

[2, 4, 6, 8, 10]
c.squares.py

squares=[]
for value in range(1,11):
    squares.append(value**2)
print(squares)
运行结果

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

还可使用列表解析的方式,更为简洁;

squares=[value**2 for value in range(1,11)]
print(squares)
3.使用列表的一部分

a.切片:列表的部分元素;与range一样,到达指定的第二个元素前停止

没有制定起始索引,列表从头开始提取;省略终止索引,列表终于末尾;

players.py

players=['guoqing','xianghao','jiangnan','huangsong']
print(players[1:3])
print(players[:2])
print(players[:]

运行结果

['xianghao', 'jiangnan']
['guoqing', 'xianghao']
['guoqing', 'xianghao', 'jiangnan', 'huangsong']
b.遍历切片:在for循环中使用切片

players=['guoqing','xianghao','jiangnan','huangsong']
for player in players[1:3]:
    print(player)
print("They are the first two players on my team!")
运行结果

xianghao
jiangnan
They are the first two players on my team!
c.复制列表:创建一个包含整个列表的切片,即同时省略起始索引和终止索引;

若只是简单地赋给,则不能得到两个列表,因为这种语法实质上是让Python将新变量关联到包含列表的变量中,两者均指同一值

foods.py

foods=['pizza','falafel','carot cake']
friend_foods=foods[:]
foods.append('carnoli')
friend_foods.append('ice_cream')
print("My favorite foods are:")
print(foods)
print("My friend favorite foods are:")
print(friend_foods) 
运行结果

My favorite foods are:
['pizza', 'falafel', 'carot cake', 'carnoli']
My friend favorite foods are:
['pizza', 'falafel', 'carot cake', 'ice_cream']
若只是简单的 foods=friend_foods 结果则不一样,可以尝试

4.元组

  列表非常适合运行期间可能变化的数据集,列表是可修改的,元组可满足创建一系列不可修改的元素。

a.元组:python将不能修改的值称为不可变的,不可变的列表称为元组;

元组使用圆括号而非方括号,可以使用for循环来遍历元组中的值;

试图修改元组值的操作是禁止的。

dimensions.py

dimensions=(200,50)
for dimension in dimensions:
    print(dimension)
运行结果

200
5
b.修改元组变量:虽不能修改元组的元素,但可以给元组的变量赋值,即重新定义整个元组。

dimensions=(200,50)
for dimension in dimensions:
    print(dimension)
dimensions=(400,100)
for dimension in dimensions:
    print(dimension)
运行结果

200
50
400
100
5.设置代码格式

a.缩进:PEP8建议每级缩进四个空格

b.空行:将程序的不同部分分开,可使用空行;空行不会影响代码运行,但会影响可读性


IF语句

让你能够检查程序当前的状态,并采取相应的措施

1. 条件测试:每条if语句的核心都是一个值True或false的表达式,这种表达式称为条件测试;

   如果条件测试值为True,python执行if后紧跟的语句,为False就忽略。

 a. python检查时会区分大小写,若大小写并不重要,可转换为小写。

>>> car = 'Audi'

>>> car.lower() == 'audi'

>>> car
'Audi'

 b. 使用!=检查不相等

toppings.py

requested_topping = 'mushrooms'
if  requested_topping != 'anchovies' :
    print('Hold the anchovies')

运行结果

Hold the anchovies

 c. 小于、小于等于、大于、大于等于比较数字

>>> age = 19
>>> age < 21
True
>>> age <= 21
True
>>> age > 21
False
>>> age >= 21
False

d. 检查多个条件

  关键字and两个条件都为True,结果为True,关键字or至少有一个满足,结果为True。

>>> age_0 = 22
>>> age_1 = 18
>>> age_0 >= 21 and age_1 >= 21
False
>>> age_1 = 21
>>> ( age_1 >= 21) and (age_0 >= 21)
True

为改善可读性,可将每个测试都分别分在一对括号内,但并非必须这样做

e. 检查特定值是否在列表中

requested_toppings = ['mushrooms','onions','pineapples']
>>> 'mushrooms' in requested_toppings
True

banned_users.py

banned_users = ['andrew','carolina','david']
user = 'marie'
if user not in banned_users:
    print(user.title() + ",  you can post a response if you wish.")

运行结果:

Marie,  you can post a response if you wish

f. 布尔表达式

   布尔表达式通常用于记录条件,要么为True,要么为False.

game_active = True

2. if语句

 a. 简单的if语句:只有一个测试和一个操作,如果测试结果为True,python执行if语句后面的代码

    if语句中,缩进作用与for循环相同,测试通过,执行if后所有缩进的代码行。

voting.py

age =19
if age > 18 :
    print("you are old enough to vote")
    print("Have you regeisted to vate yet")

运行结果:

you are old enough to vote
Have you regeisted to vate yet

 b. if-else语句:条件测试通过了执行一个操作,没有通过执行另一个操作.

age = 17
if age >= 18 :
    print("You are enough to vote!")
    print("Have you registed to vote yet?")
else :
    print("You are too young to vote!")
    print("Please registed to vote as soon as you turn 18!")

运行结果:

You are too young to vote!
Please registed to vote as soon as you turn 18!
c. if-elif-else结构:检查超过两个,它依次检查每个测试,测试通过后


猜你喜欢

转载自blog.csdn.net/qq_35379989/article/details/79201152