if语句
条件用== != 比较两个数字或字符串是否相等
>>> a,b = 1,1
>>> a == b
True
>>> a,b = 1,2
>>> a != b
True
用 > >= < <= 可以比较两个数字大小
>>> a,b=1,2
>>> a<b
True
使用and or测试多个条件
>>> a,b=1,2
>>> a==1 and b==2
True
>>> a,b=1,2
>>> a==2 or b==2
True
使用in/not in测试从属
>>> a=[1,2,3]
>>> 1 in a
True
>>> 4 not in a
True
空列表作为if条件时为False
a = []
if a:
print("Not empty")
else:
print("Empty")
#输出结果:Empty
基本形式:
if condition:
# ...
if-else
if condition:
# ...
else:
# ...
if-elif-else
if condition:# ...
elif condition:
# ...
else:
# ...
多个elif
if condition:
# ...
elif condition:
# ...
elif condition:
# ...
else:
# ...
省略else
if condition:
# ...
elif condition:
# ...
字典
字典是一系列键值对,每个键对应一个值在Python中字典用大括号括起来的若干个键值对组成,键值之间用冒号分割,键值对之间用逗号分隔
debug_info = {'level': 'error', 'msg': 'file not found'}
使用字典
通过下标访问字典中的值:
debug_info = {'level': 'error', 'msg': 'file not found'}
print(debug_info['msg'])
#输出结果:file not found
通过下标添加键值对:
debug_info = {'level': 'error', 'msg': 'file not found'}
debug_info['os'] = 'windows'
使用下标修改字典中的值:
debug_info = {'level': 'error', 'msg': 'file not found'}
debug_info['level'] = 'info'
用del删除键值对:
debug_info = {'level': 'error', 'msg': 'file not found'}
del debug_info['level']
print(debug_info)
遍历字典
遍历所有键值对
字典的items()方法返回键值对列表,用for in遍历它:
debug_info = {'level': 'error', 'msg': 'file not found'}
for key, value in debug_info.items():
print("key:" + key + " value: " + value)
#输出结果:
key:msg value: file not found
key:level value: error
遍历字典中所有的键
字典的keys()方法返回所有的键
debug_info = {'level': 'error', 'msg': 'file not found'}
for key in debug_info.keys():
print("key:" + key)
#输出结果:
key:msg
key:level
遍历字典中的所有值
字典的values()方法返回所有的值。
debug_info = {'level': 'error', 'msg': 'file not found'}
for value in debug_info.values():
print("value:" + value)
#输出结果:
value:file not found
value:error
嵌套
字典列表debug_info = {'level': 'error', 'msg': 'file not found'}
debug_info = {'level': 'info', 'msg': 'invalid input'}
debug_infos = [
{'level': 'error', 'msg': 'file not found'},
{'level': 'info', 'msg': 'invalid input'}
]
for debug_info in debug_infos:
print(debug_info)
#输出结果:
{'msg': 'file not found', 'level': 'error'}
{'msg': 'invalid input', 'level': 'info'}
字典中存储列表
debug_info = {'level': 'error', 'msgs': ['file not found', 'invalid input']}
print(debug_info)
#输出结果:
{'msgs': ['file not found', 'invalid input'], 'level': 'error'}
字典中存储字典
debug_info = {
'level': 'error',
'msgs': 'file not found',
'version':{'main': 5, 'sub': 17}}
print(debug_info)
#输出结果:
{'version': {'main': 5, 'sub': 17}, 'msgs': 'file not found', 'level': 'error'}
用户输入和while循环
用input来获取输入,input接收一个字符串参数,用来打印提示返回值为一个字符串:
message = input("Enter a message:")
print(message)
#输出结果:
Enter a message:Hello world
Hello world
while循环
num = 1
while num < 5:
print(num)
num += 1
#输出结果:
1
2
3
4
break退出最内层循环
continue退出本次迭代,继续执行下一次迭代