Python-分支、循环、条件与枚举

一、条件
1、if、else
if 条件:
    print('go to left')
else:
   print('go to right')
2、if、elif
if 判断条件1:
    执行语句1……
elif 判断条件2:
    执行语句2……
elif 判断条件3:
    执行语句3……
else:
    执行语句4……
备注:

python中无switch语法

二、循环
1、while循环
  • while
while condition:
        #代码块
        pass
  • while...else
while condition:
        #代码块
        pass
else:
        #代码块
        pass
备注:

while使用场景:递归

2、for循环
  • 直接读取元素
a = [['apple','orange','banana'],(1,2,3)]
for x in a:
        for y in x: 
                print(y)
  • 通过序列索引迭代
a = ['apple','orange','banana']
for index in range(len(a)):
      print(a[index])
a = [1,2,3,4,5,6]
b = [0:len(a):2]
print(b)
备注:

使用场景:主要是用来遍历/循环 序列或者集合、字典

3、嵌套循环
  • for...else
a = ['apple','orange','banana']
for index in range(len(a)):
      print(a[index])
else:
      print('EOF')
备注:
  • for...else:只有当for语句正常执行遍历完毕,else后的语句方可执行,若使用break中断最外层循环的话,else后的语句是不会执行的
  • range(0,10,2):0:起始(包含),10:结尾(不包含),2:步幅
总结:
  • python 是依靠缩进来做代码包裹的,不可以被混淆、压缩。
    因为混淆压缩时会吧代码中的空格去掉,以减少代码的体积。
  • python规范要求每个模块文件应该添加一段文字描述该该文件的作用
  • python规范如果定义变量不是在函数和类中,python会认为该变量为常量
  • python规范要求缩进需为4个空格

你可能感兴趣的:(Python-分支、循环、条件与枚举)