python学习笔记-基础语法每条if语句的核心都是一个值为True或False的表达式,我来为大家科普一下关于常用的基础语法?以下内容希望对你有帮助!
常用的基础语法
python学习笔记-基础语法
第五章 if语句 第六章 字典- 一、条件测试
- 二、if语句
- 三、使用if语句处理列表
- 四、使用字典
- 五、遍历字典
- 六、嵌套
每条if语句的核心都是一个值为True或False的表达式。
如果条件测试的值为True,Python就执行紧跟在if语句后面的代码;如果为False,Python就忽略这些代码。
方法 |
描述 |
== |
判断是否相等 |
!= |
判断是否不等 |
<= |
小于等于 |
>= |
大于等于 |
and |
检查两个条件是否都满足 |
or |
检查两个条件是否至少有一个满足 |
in |
检查特定值是否包含在列表中 |
not in |
检查特定值是否不包含在列表中 |
布尔表达式 |
记录条件 |
>>> 1 == 1
True
>>> 1 != 1
False
>>> 1 <= 1
True
>>> 1 >= 2
False
>>> 1 >= 0 and 2 >= 1
True
>>> cars = ['bmw','audi','toyota','byd']
>>> ('bmw' in cars) or ('subaru' in cars)
#使用括号更为简洁
True
>>> 'subaru' not in cars
True
- 在if语句中,缩进的作用与for循环中相同。如果测试通过了,将执行if语句后面所有所进的代码行,否则将忽略他们。
- else包罗万象,若要知道最重要测试的条件,应考虑使用一个elif代码块来代替else代码块。
- 若想执行一个代码块,就使用 if-elif-else 结构;如果要运行多个代码块,就使用一系列独立的 if 语句。
age = 19
if age < 2:
print('你是一个婴儿!')
elif age < 4:
print('你正蹒跚学步!')
elif age < 13:
print('你是儿童!')
elif age < 20:
print('你是青少年!')
elif age < 65:
print('你是成年人!')
else:
print('你是老年人!')
favorite_fruits = ['banlala','watermelon','strawberry']
if 'apple' in favorite_fruits :
print('You really like apples!')
if 'banlala' in favorite_fruits :
print('You really like banlalas!')
输出结果为:
你是青少年!
You really like banlalas!
1、检查特殊元素
request_toppings = ['mushrooms','green peppers','extra cheese']
for request_topping in request_toppings:
if request_topping == 'green peppers':
print('Sorry! The green peppers is out now!')
else:
print('Adding' request_topping '.')
print('\nFinished making your pizza!')
输出结果为:
Addingmushrooms.
Sorry! The green peppers is out now!
Addingextra cheese.
Finished making your pizza!
2、确定列表不是空的
- Python将在列表至少包含一个元素时返回True,在列表为空时返回False。
request_toppings = []
if request_toppings: #显然此处等价于if False:
for request_topping in request_toppings:
print('Adding' request_topping '.')
else:
print('Are you sure to buy a plain pizza?')
输出结果为:
Are you sure to buy a plain pizza?
3、使用多个列表
requested_toppings = ['mushrooms','french fries','extra cheese']
avalible_toppings = ['mushrooms','olives','green peppers','pepperoni','pineapple','extra cheese']
for requested_topping in requested_toppings:
if requested_topping in avalible_toppings:
print('Adding' requested_topping '.')
else:
print("Sorry, we dont't have " requested_topping '.')
输出结果为:
Addingmushrooms.
Sorry, we dont't have french fries.
Addingextra cheese.
- 字典是一系列键-值对。每个键都与一个值相关联,可以使用键来访问与之相关联的值。
- 键和值之间用冒号分隔,键-值对之间用逗号分隔。
1、访问字典中的值
>>> alien_0 ={'color':'green','points':5}
>>> new_points = alien_0['points']
>>> print("You just earned " str(new_points) "points!")
You just earned 5points!
>>> print("You just earned " str(new_points) " points!")
You just earned 5 points!
>>> alien_0["color"] #不区分单双引号
'green'
>>> alien_0[0] #不可使用索引
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
alien_0[0]
KeyError: 0
2、添加键-值对、创建空字典要添加键-值对,可依次指定字典名、用方括号括起的键和相关联的值。
>>> alien_0 = {} #直接创建一个空字典
>>> alien_0['x_position'] = 0
>>> alien_0['y_position'] = 25
>>> print(alien_0)
{'x_position': 0, 'y_position': 25}
3、修改字典中的值要修改字典中的值,可依次指定字典名、用方括号括起的键以及与该键相关联的新值。类比列表修改元素。
alien_0 = {'x_position' : 0,'y_position' : 25,'speed': 'medium'}
print('Original x_position: ' str(alien_0['x_position']))
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else: #一定很快
x_increment = 3
alien_0['x_position'] = alien_0['x_position'] x_increment
print('New x_position: ' str(alien_0['x_position']))
输出结果为:
Original x_position: 0
New x_position: 2
4、删除键-值对
- 使用del 来永久删除字典的键-值对
- 使用del 语句时,必须指定字典名和要删除的键。
alien_0 ={'color':'green','points':5}
print(alien_0)
del alien_0['color']
print(alien_0)
输出结果为:
{'color': 'green', 'points': 5}
{'points': 5}
5、由类似对象组成的字典
- 确定需要使用多行来定义字典时,在输入左花括号后按回车键,再在下一行缩进四个空格,指定第一个键-值对,并在其后加上一个逗号。
favorite_language = {
'jen':'Python',
'sarah':'C',
'edward':'ruby',
'phil':'python',
}
print("Sarah's favorite language is "
favorite_language['sarah'] '.')
#回车以保持美观
输出结果为:
Sarah's favorite language is C.
- 1、遍历所有的键-值对
- 方法:.items()
遍历字典时,键-值对的返回顺序与存储顺序未必保持一致。
示例1:
user_0 = {
'username':'efermi',
'first':'enrico',
'last':'fermi',
}
for key, value in user_0.items():
print('\nkey: ' key)
print('value: ' value)
输出结果为:
key: username
value: efermi
key: first
value: enrico
key: last
value: fermi
示例2:
favorite_languages = {
'jen':'python',
'sarah':'C',
'edward':'ruby',
'phil':'python',
}
for name, language in favorite_languages.items():
print(name.title() "'s favorite language is"
" " language ".")
输出结果为:
Jen's favorite language is python.
Sarah's favorite language is C.
Edward's favorite language is ruby.
Phil's favorite language is python.
2、遍历字典中的所有键方法:.keys()或者直接使用字典名称for name in favorite_languages.keys():等价于for name in favorite_languages:
favorite_languages = {
'jen':'python',
'sarah':'C',
'edward':'ruby',
'phil':'python',
}
friends = ['phil','sarah']
for name in favorite_languages.keys():
print(name.title())
if name in friends:
print("Hi " name.title()
", I see your favorite language is "
favorite_languages[name].title() "!\n")
if 'erin' not in favorite_languages:
print('Erin, please take our poll!')
输出结果为:
Jen
Sarah
Hi Sarah, I see your favorite language is C!
Edward
Phil
Hi Phil, I see your favorite language is Python!
Erin, please take our poll!
3、按顺序遍历字典中的所有键方法:sorted()函数按字母排序
favorite_languages = {
'jen':'python',
'sarah':'C',
'edward':'ruby',
'phil':'python',
}
for name in sorted(favorite_languages.keys()):
print(name.title() ", thank you for takeing the poll.")
输出结果为:
Edward, thank you for takeing the poll.
Jen, thank you for takeing the poll.
Phil, thank you for takeing the poll.
Sarah, thank you for takeing the poll.
4、遍历字典中的所有值方法:.values()
- 通过对包含重复元素的列表调用 set() 函数,可让Python找出列表中独一无二的元素,并使用这些元素来创建一个集合。
favorite_languages = {
'jen':'python',
'sarah':'C',
'edward':'ruby',
'phil':'python',
}
for value in set(favorite_languages.values()):
print(value.title())
输出结果为:
C
Ruby
Python #重复的值被省去了
5、按顺序遍历字典中的所有值同按顺序遍历字典中的所有键一样,使用sorted()函数即可
favorite_languages = {
'jen':'python',
'sarah':'C',
'edward':'ruby',
'phil':'python',
}
for value in sorted(set(favorite_languages.values())):
print(value.title())
输出结果为:
C
Python
Ruby
1、字典列表将一些列字典储存在列表中
#创建一个空的机器人列表
aliens = []
#生成30个机器人并存储于列表中
for alien in range(30):
new_alien = {'color':'green','points':5,'speed':'slow'}
aliens.append(new_alien)
for alien in aliens[0:3]:
if alien["color"] == 'green':
alien["color"] = 'yellow'
alien["points"] = 10
alien["speed"] = 'medium'
for alien in aliens[0:5]:
print(alien)
print("...")
print('Total number of aliens: ' str(len(aliens)))
输出结果为:
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...
Total number of aliens: 30
2、在字典中存储列表
favorite_laguages = {
'jen':['python','ruby'],
'sarah':['c'],
'edward':['ruby','go'],
'phil':['python','Haskell'],
}
for name, languages in favorite_laguages.items():
if len(languages) == 1:
print("\n" name.title() "'s favorite language is " languages[0].title())
else:
print("\n" name.title() "'s favorite language are: ")
for language in languages:
print(language.title())
输出结果为:
Jen's favorite language are:
Python
Ruby
Sarah's favorite language is C
Edward's favorite language are:
Ruby
Go
Phil's favorite language are:
Python
Haskell
3、在字典中储存字典
users = {
'aeinstein':{
'first_name':'albert',
'last_name':'einstein',
'location':'princeton',
},
'mcurie':{
'first_name':'marie',
'last_name':'cruie',
'location':'paris',
},
}
for name, info in users.items():
print("\nUsername: " name.title())
print("\tFull name: " (info['first_name']).title() " " (info['last_name']).title())
输出结果为:
Username: Aeinstein
Full name: Albert Einstein
Username: Mcurie
Full name: Marie Cruie
注:
- 表示每位用户的字典的结构都相同,虽然Python并没有这样的要求,但这使得嵌套的字典处理起来更加容易。
- 倘若每位用户的字典都包含不同的键,for循环内部的代码将更复杂。