五、if语句
==
两边值相等返回True,不等False
!=
两边值不等返回True,相等False
and
每个条件都满足才可返回true
or
至少一个条件满足就可返回true
in
检查特定值是否包含在列表中
not in
检查特定值是否包含在列表中
>>> list = ['a','b','c']
>>> 'a' in list
True
>>> 2 in list
False
- if结构
- if-else 结构
- if-elif-else 结构(可省略else,可增加elif)
如果只想执行一个代码块,就使用if-elif-else结构;如果要执行多个代码块,就使用一系列独立的if语句。
If+列表名 列表不空时返回true,否则返回false。
age = 17
# if结构
if age < 18:
print(f'yes {age}.')
# if-else 结构
if age > 18:
print(f'yes {age}.')
else:
print(f'no {age}.')
# if-elif-else 结构(可省略else,可增加elif)
if age < 10:
print('free')
elif age < 20:
print('10$')
else:
print('15$')
yes 17.
no 17.
10$
六、字典
在python中,字典是一系列键值对。每一个键都与一个值相关联,可使用键来访问相关联的值。与键相关联的值可以是数、字符串、列表乃至字典。
键值对是两个相关联的的值,键与值之间用冒号分隔,而键值对之间用逗号分开。
aline_0 = {'color':'green','points':5}
1.访问字典中的值
1.1字典名+[ 键 ]
aline_0 = {'color':'green','points':5}
print(aline_0['color'])
green
1.2使用get()
来访问值
使用放在方括号的键访问字典中的值可能会引发问题:如果指定的键不存在就会出错。
aline_0 = {'color':'green','points':5}
print(aline_0['speed'])
这将导致python显示tarceback,指出存在键值错误(KeyError):
Traceback (most recent call last):
File "D:\work_python\……", line 2, in <module>
print(aline_0['speed'])
KeyError: 'speed'
就字典而言,可使用方法get()
在指定键不存在时返回一个默认值,从而避免错误。
方法get()
的第一个参数用于指定键,是必不可少的;第二个参数为指定的键不存在时要返回的值,是可选的。(如果没有指定第二个参数且指定的键不存在,python将返回值None)
aline_0 = {'color':'green','points':5}
print(aline_0.get('speed','no speed key'))
no speed key
2.添加键值对
依次指定字典名、用方括号括起的键和相关联的值。
aline_0 = {'color':'green','points':5}
aline_0['x_position'] = 0
aline_0['y_position'] = 10
print(aline_0)
{‘color’: ‘green’, ‘points’: 5, ‘x_position’: 0, ‘y_position’: 10}
3.修改字典中的值
指定字典名、用方括号括起的键,以及该键相关联的新值。
aline_0 = {'color':'green','points':5}
aline_0['color'] = 'yellow'
print(aline_0)
{‘color’: ‘yellow’, ‘points’: 5}
4.删除键值对
使用del语句,指定字典名和要删除的键(永远消失)
aline_0 = {'color':'green','points':5}
del aline_0['color']
print(aline_0)
{‘points’: 5}
5.遍历字典
5.1遍历所有键值对
for
循环遍历字典,声明两个变量,用于存储键值对中的键和值。
方法items()
,它返回一个键值对列表
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'java',
}
for name,language in favorite_languages.items():
print(f'{name.title()} : {language}')
Jen : python
Sarah : c
Edward : ruby
Phil : java
5.2遍历字典中的所有键
使用方法keys()
进行遍历
方法keys()
并非只能用于遍历:实际上,它返回一个列表,其中包含字典中的所有键。因此,可以判断一个键是否在字典中
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'java',
}
for name in favorite_languages.keys(): # 遍历
print(name.title())
if 'jone' not in favorite_languages.keys(): # 判断
print('NO')
Jen
Sarah
Edward
Phil
NO
遍历字典时,会默认遍历所有键,因此
for name in favorite_languages.keys():
可替换为
for name in favorite_languages:
5.3遍历字典中的所有值
使用方法values()
返回一个值列表,不包含任何键
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'java',
'jone':'python'
}
for language in favorite_languages.values():
print(language.title())
Python
C
Ruby
Java
Python
这种做法提取字典中的所有值,没有考虑是否重复。如果为了剔除重复项,可使用集合(set),集合中的每一个元素都必须是独一无二的。
通过对包含重复元素的列表调用set()
,可让python找出列表中独一无二的元素,并使用这些元素来创建一个集合。
# 这里使用的是上一个例子的字典
for language in set(favorite_languages.values()):
print(language.title())
print(set(favorite_languages.values())) # 输出整个集合
Ruby
Java
C
Python
{‘ruby’, ‘java’, ‘c’, ‘python’}
5.4按特定顺序遍历字典
一种方法是在for循环中对返回后的键进行排序。为此,可使用函数sorted()
来获得特定顺序排列的键列表的副本。
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'java',
'jone':'python'
}
for name in sorted(favorite_languages.keys()):
print(name.title(),':',favorite_languages[name])# 输出键以及对应值
Edward : ruby
Jen : python
Jone : python
Phil : java
Sarah : c
6.嵌套
6.1字典列表
aline_0 = {'color':'green','points':5}
aline_1 = {'color':'yellow','points':10}
aline_2 = {'color':'red','points':15}
alines = [aline_0,aline_1,aline_2]
for aline in alines:
print(aline)
{‘color’: ‘green’, ‘points’: 5}
{‘color’: ‘yellow’, ‘points’: 10}
{‘color’: ‘red’, ‘points’: 15}
6.2在字典中存储列表
favorite_languages = {
'jen':['python','c++'],
'sarah':['c'],
'edward':['ruby','go'],
'phil':['java','c'],
'jone':['python','haskell'],
}
for name,languages in favorite_languages.items():
print(f'{name.title()}:')
for language in languages:
print('\t',language)
Jen:
python
c++
Sarah:
c
Edward:
ruby
go
Phil:
java
c
Jone:
python
haskell
6.3在字典中存储字典
users = {
'aeinstein':{
'frist':'albert',
'last':'einstein',
'location':'princetion',
},
'mcurie':{
'frist':'marie',
'last':'curie',
'location':'paris',
},
}
for username,user_info in users.items():#两个变量分别用于存放用户名和用户信息
print(f'\nUsername:{username}')
fullname = f"{user_info['frist']} {user_info['last']}"
location = user_info['location']
print(f'\tFullname:{fullname}')
print(f'\tLocation:{location}')
Username:aeinstein
Fullname:albert einstein
Location:princetion
Username:mcurie
Fullname:marie curie
Location:paris
七、用户输入和while
循环
1.函数input()
使用(用户输入)
函数input()
让程序暂停运行,等待用户输入一些文本。
函数input()
接受一个参数——要向用户显示的提示或说明,让用户知道如何操作。
message = input("Tell me something:")
print(message)
Tell me something:666
666
有时候,提示可能超过一行,以下是过长字符串和多行字符串创建方式
使用使用运算符+=
使用反斜杠
使用三引号’‘’ ‘’’
# 第一种使用运算符+=
prompt = "If you tell us who you are, we can personalize the message you see."
prompt += "\nWhat is your first name?"
# 第二种使用反斜杠\
prompt = "If you tell us who you are, we can personalize the message you see.\
\nWhat is your first name?"
# 第三种使用三引号''' '''
prompt = '''If you tell us who you are, we can personalize the message you see.
What is your first name?'''
message = input(prompt)
print(f'Hello, {message}!')
If you tell us who you are, we can personalize the message you see.
What is your first name?Eirc
Hello, Eirc!
使用函数input()
时,python将用户输入解读为字符串。要将数的字符串转化为数值表示,可使用函数int()
。
age = input("How old are you?")
print(age == '20')
age = int(age) # 转化
print(age == 20)
How old are you?20
True
True
2.while
循环
2.1使用while
循环
注意冒号
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
1
2
3
4
5
2.2使用标志
在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量称为标志( flag ),充当程序的交通信号灯。让程序在标志为 True 时继续运行,并在任何事件导致标志的值为 False 时让程序停止运行。
prompt = "Tell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program."
flag = True
while flag:
message = input(prompt)
if message == 'quit':
flag = False
else:
print(message)
Tell me something, and I will repeat it back to you:
Enter ‘quit’ to end the program.Hello
Hello
Tell me something, and I will repeat it back to you:
Enter ‘quit’ to end the program.yes
yes
Tell me something, and I will repeat it back to you:
Enter ‘quit’ to end the program.quit
2.3使用break
退出循环
要立即退出while
循环,不在运行循环中余下的代码,也不管条件测试的结果如何,可使用break
语句。
prompt = "Please enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.)"
while True:
city = input(prompt)
if city == 'quit':
break
else:
print(f"I'd love to go to {city}!")
Please enter the name of a city you have visited:
(Enter ‘quit’ when you are finished.)Beijing
I’d love to go to Beijing!
Please enter the name of a city you have visited:
(Enter ‘quit’ when you are finished.)quit
在任何python循环中都可以使用 break 语句。
2.4在循环中使用contine
要返回循环开头,并根据条件测试结果决定是否继续执行循环,可使用 continue 语句。
# 从一数到十只打印奇数
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
else:
print(current_number)
1
3
5
7
9
3.使用 while 循环处理列表和字典
for 循环是一种遍历列表的有效方式,但不应在 for 循环中修改列表,否则会导致python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用 while 循环。
3.1在列表之间移动元素
# 首先,创建一个待验证用户列表,和一个用于存储已验证用户空列表
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
while unconfirmed_users: # 列表不为空是循环
user = unconfirmed_users.pop() # 从列表末尾删除一个元素
print(f"Verifying user: {user.title()}")
confirmed_users.append(user) # 插入 unconfirmed_users 中拿出的元素
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user)
Verifying user: Candace
Verifying user: Brian
Verifying user: Alice
The following users have been confirmed:
candace
brian
alice
3.2删除列表中的所有特定值
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets: # 'cat' 在列表中循环进行
pets.remove('cat')
print(pets)
[‘dog’, ‘cat’, ‘dog’, ‘goldfish’, ‘cat’, ‘rabbit’, ‘cat’]
[‘dog’, ‘dog’, ‘goldfish’, ‘rabbit’]
3.3使用用户输入来填充字典
responses = {} # 创建空字典
flag = True # 设置标志
while flag:
name = input("\nWhat is your name?") # 输入名字和回答
response = input("Which mountain would you like to climb someday?")
responses[name] = response # 将回答存入字典
# 看看是否还有人参与调查
repeat = input("Would you like to let another person respond?(yes/no)")
if repeat == 'no':
flag = False
# 调查结束,显示结果
print("\n--- Poll Results ---")
for name, response in responses.items():
print(f"{name} would like to climb {response}. ")
What is your name?Eric
Which mountain would you like to climb someday?Denali
Would you like to let another person respond?(yes/no)yes
What is your name?Lynn
Which mountain would you like to climb someday?Devil’s Thumb
Would you like to let another person respond?(yes/no)no
--- Poll Results ---
Eric would like to climb Denali.
Lynn would like to climb Devil’s Thumb.