Python学习第三天 --- 分支、循环、条件、枚举
1.表达式:
表达式(Expression)是运算符(operator)和操作数(operand)所构成的序列。
2.表达式的优先级:
3.python的注释:
#单行注释 ''' 多行注释 '''
4.流程控制语句:
if-else:
mood = False if mood : print('go to left') #print('back awray') else : print('go to right') //执行结果: 'go to right'
当然,if后可以跟从表达式:
a = 1 b = 2 c = 2 if a or b + 1 == c : print(a or b + 1 == c) else : print('go to right') //执行结果 1
进行判断时,会将非布尔值强制转换为bool:
a = 1 b = 2 c = 2 d = [] if d == 1 : print(a or b + 1 == c) elif d: print('go to right') else: print('go to left')
while循环
与其他语言不同的是,while可以配置else,因此else总能执行到。
CONDITION = 10 while CONDITION : CONDITION -= 1; print('I am While') else: print('EOR')
此时产生的结果是:
I am While
I am While
I am While
I am While
I am While
I am While
I am While
I am While
I am While
I am While
EOR
for循环:
# 主要是用来遍历/循环 序列或集合、字典 a = ['apple', 'orange', 'banana', 'grape']; for x in a: print(x);
结果是:
apple
orange
banana
grape
for循环嵌套:
# 主要是用来遍历/循环 序列或集合、字典 a = [['apple', 'orange', 'banana', 'grape'],('red','blue', 'pink' )]; for x in a: for y in x: print(y, end=' ') //end是为了控制每次打印结尾是什么,默认是\n,因此会自动换行
结果是:
apple orange banana grape red blue pink
for与else结合:
# 主要是用来遍历/循环 序列或集合、字典 a = [['apple', 'orange', 'banana', 'grape'],('red','blue', 'pink' )]; for x in a: for y in x: print(y, end=' ') else: print('第一个结尾') else: print('最外边的结尾')
最终的结果是:
apple orange banana grape 第一个结尾
red blue pink 第一个结尾
最外边的结尾
退出循环:
a = [1,2,3] for x in a: if x == 2: break print(x);
最终的结果是:
1 //break会立刻跳出循环
跳过此轮循环,进入下一轮:
a = [1,2,3] for x in a: if x == 2: continue print(x);
结果是:
1 3
但是,如果是break打破循环,则else就不会执行:
a = [1,2,3] for x in a: if x == 2: break print(x) else: print('ERO')
结果是:1
range
循环一定次数时, 用range
for x in range(0,10): print(x)
其中: 0表示起始值,10是偏移量,默认1的步值
for x in range(0,10,2): print(x, end= ' | ')
其结果是:
0 | 2 | 4 | 6 | 8 |
其他测试:
for x in range(10,2,2): print(x, end= ' | ')
这个打印不到任何数据
步值可以是负的:
for x in range(10,2,-2): print(x, end= ' | ')
其结果是:
10 | 8 | 6 | 4 |
取奇数:
方法一:
a = [1,2,3,4,5,6,7,8,9] for x in a: if x % 2 == 0: continue print(x)
方法二:
for i in range(0, len(a), 2): print(a[i], end = ' | ')
b = a[0:len(a):2] print(b)