条件语句
Python 常用循环语句:
y = |x|
if x<0:
y = -x
else:
y = x
Python 中不支持switch 语句,当存在多个判断时在python里面可以用else if来实现 表达式为 elif。
if condition0:
statement_0
elif condition1:
statement_1
elif condition2:
statement_2
else:
statement_3
顺序执行 当满足其中一个condition的时候就返回结果 结束if elif else 语句。
循环语句
本质就是遍历集合中的元素
list = ['a','b','c',1,3]
for av in list:
print(av)
输出结果:
a
b
c
1
3
字典本身只有键是可迭代的,要遍历字典的值或者是键值对,需要通过内置函数实现 items()或者values()其中values()返回字典的值得集合,items()返回键值对的集合
dic = {'name':'cangjinkong','age':18,'favorite':'mlove'}
dic.values()
dic.items()
输出结果:
dict_values(['cangjinkong', 18, 'mlove'])
dict_items([('name', 'cangjinkong'), ('age', 18), ('favorite', 'mlove')])
一般循环语句和continue、break搭配使用。continue表示结束当前次循环,break表示退出当前整个循环。搭配continue,break往往会使代码更清晰更简洁。
while和for 在某些时候是可以相互替换的,一般是已知的集合用for 循环更简洁,重复着某些操作,但又不是一个已知的结合的时候用while更好一点。
条件与循环的复用:
expression1 if condition else expression2 for item in iterable
等同于:
for item in iterable:
if condition:
expression1
else:
expression2
例:
Jap = [value if value>5 else 'cangLS' for value in range(10) ]
print (Jap)
结果为:
['cangLS', 'cangLS', 'cangLS', 'cangLS', 'cangLS', 'cangLS', 6, 7, 8, 9]
没有else时,语句是不同的,if是在后面:
expression1 for item in iterable if condition
等同于:
for item in iterable:
if condition:
expression1
例:
Jap = [value for value in range(10) if value>5]
print (Jap)
结果:
[6, 7, 8, 9]