if语句,字典,循环
目录
前言
本文将对书中第五章至第七章的内容进行梳理,内容包括条件判断,字典,循环
一、条件判断
1.1条件判断简介
1.1.1条件判断示例
car="audi"
date=20
if car == "audi": #相等
print("true")
if car != "ben": #不相等
print("false")
if car == "audi" and date == 20: #与条件使用and连接
print("true")
if car == "ben" or date == 20: #或条件使用or连接
print("true")
与c语言同理,需要进行组合时可以采用圆括号()。
1.1.2检查特定值是否在列表中
bicycles=['hello','meituan','qingju']
if 'hello' in bicycles:
print("true")
if 'colorful' not in bicycles:
print("true")
1.1.3布尔表达式
布尔值只有两个值True和Flase,声明方式:
game_active = True
1.2 if-else以及if-elif-else结构
age = 23
if age <= 18:
print("false")
elif age <= 20:
print("false")
else:
print("true")
二、字典
2.1字典简介
2.1.1示例
字典类似c语言中的结构体但有区别,字典是由键值对组成的,一个键关联一个值,可以使用键来访问值
alien_0 = {'color':'greeen', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
输出为:
green
5
与键相关联的值可以使数、字符串、列表、字典。字典使用花括号{}创建,键值对之间使用冒号:
2.1.2字典基础操作
添加键值对:字典是动态结构,可使用如下方式直接添加新的键值对
alien_0 = {'color':'greeen', 'points': 5}
alien_0['x_position']=0
alien_0['y_position']=250
print(alien_0)
修改键值对:
alien_0['x_position']=150
删除键值对:
del alien_0['points']
2.1.3 get()方法避免键值对不存在的错误
当所需要使用的键不存在时调用该键值对会发生错误,此时可以使用get()方法来避免错误。
get的第一个参数用于指定键,第二个参数为指定的键不存在时要返回的值,用法示例:
point_value = alien_0.get('points','not exist')
print(point_value)
2.2遍历字典
2.2.1遍历所有键值对
使用方法items()可以返回字典中的键值对
user = {
'username' : 'mois',
'password' : '987654',
}
for key,value in user.items():
print(f"Key:{key}")
print(f"Value:{value}")
2.2.2遍历所有键
使用方法keys()可以返回字典中的键
user_language = {
'panhao' : 'c++',
'lishimin' : 'python',
'mc' : 'java',
}
for key in user_language.keys(): #与for key in user_language:效果相同
print(key)
注:直接遍历字典时也是默认遍历所有键,所以可以不使用key()方法直接遍历字典。
需要排序时:使用sorted()函数
for key in sorted(user_language):
print(key)
2.2.3遍历所有值
使用方法values()来遍历字典中的所有值
for value in user_language.values():
print(value)
2.2.4 set()函数去重
当字典中存在重复项需要去除时,可以使用set()函数:
for language in set(user_language.values()):
print(language)
2.3嵌套
列表与字典可以自嵌套及相互嵌套。
字典列表:
alien_0={'color': 'green', 'points': 5}
alien_1={'color': 'red', 'points': 10}
alien_2={'color': 'yellow', 'points': 15}
aliens=[alien_0, alien_1, alien_2] #存储在列表中的字典
print(aliens[0]['color']) #列表中的字典的使用方法
列表字典:
pizza = {
'crust': 'thick',
'toppings': ['mushroom', 'extra cheese'], #存储在字典中的列表
}
print(pizza)
print(pizza['toppings'][1]) #存储在字典中的列表的使用方法
字典中存储字典:
users = {
'user_1' : {
'user_name' : 'ph',
'password' : '123456',
},
'user_2' : {
'user_name' : 'tl',
'password' : '456789',
}
}
print(users)
print(users['user_1']['password']) #在字典自嵌套中使用元素的方法
3.用户输入与while循环
3.1.1 获取字符串输入
input()函数可以使程序暂停运行并获得用户输入,可接受一个待打印字符串作为参数:
message=input('Please enter your choice:')
print(message)
输出:
Please enter your choice:A
A
3.1.2 +=运算符
+=运算符可以将两个字符串连接
message="such a frozen dream"
message+="\nsuch a golden dream"
print(message)
输出:
such a frozen dream
such a golden dream
3.1.3 %求模运算符
%是求模运算符,可得到两个数相除的余数。
3.1.4 获取数值输入
input()函数可以获得字符串输入,int()函数可以将字符串转化为数值类型,例如:
height=input("how tall are you?\n")
height=int(height)
if height > 150 :
print("okey")
3.2 while循环
3.2.1示例
message=""
while message !- 'quit' :
message = input("enter your choice('quit' to end)\n")
print(message)
3.2.2 break与continue
与c语言中的break和continue用法相同
message=""
while True :
message = input("enter your choice('quit' to end)\n")
if message != 'quit' and message != 'continue' :
print(message)
elif message == 'continue':
continue
else :
break
3.2.3 使用while循环处理列表和字典
可以使用for循环遍历列表,但不要使用for循环去修改列表,会导致python难以追踪列表元素,可以使用while循环对列表进行修改。
在两个列表之间移动元素
old_bicycles = ['trek','cannondale','redlin','specialized','hello']
new_bicycles=[]
while old_bicycles :
temp=old_bicycles.pop()
print(temp)
new_bicycles.append(temp)
print(new_bicycles)
3.2.4 删除为特定值的所有列表元素
pets =['dog', 'snake', 'cat', 'mouse', 'cat', 'dog']
while 'cat' in pets:
pets.remove('cat')
print(pets)
3.2.3 使用用户输入填充字典
responses={}
flag=True
while flag:
name=input('what\'s your name?')
response=input('How do you think of it?')
responses[name]=response
repeat=input("continue?")
if repeat == 'no':
flag = False
print(responses)
总结
以上即为对python中的条件判断、字典、while循环的介绍