Python编程系列3-条件与循环

  • 条件语句
  • 循环语句

2.0 条件语句

2.0.1 if 语句

if语句的语法如下:

In [ ]:
if expression:  
    expr_true_suite

if语句的expr_true_suite代码块只有当条件表达式(expression)结果为真时才执行,否则将继续执行紧跟在该代码块后面的语句。

多重条件表达式

单个if语句中的expression条件表达式可以通过布尔操作符and,or和not实现多重条件判断。

In [1]:
if 2>1 and not 2>3:                    # 如果2>1并且 2>3为为假
    print('Correct judgement!')           # 那么打印(‘Correct judgement’)
Correct judgement!

2.0.2 else 语句

同其他语言一样,python提供与if搭配使用的else,如果if语句的条件表达式结果布尔值为假,那么程序将执行else语句后的代码。

In [ ]:
if expression:                        # 如果 expression 为真
    expr_true_suite                   # 那么执行 expr_true_suite
else:                                 # 否则
    expr_false_suite                  # 执行 expr_false_suite 

注意:python使用缩进而不是大括号来标记代码块边界,因此要特别注意else的悬挂问题。比如:

In [ ]:
if a>1: 
    if a>2:
        print('a>2')
else:
    print('1<a<2')

 则else语句会被判给外层的if而不是内层的。如果想将其与内层搭配,必须再缩进使其与内层的if对齐。

2.0.3 elif语句

elif语句即为else if用来检查多个表达式是否为真,并在为真时执行特定代码块中的代码。同else一样,elif是可选的。然而不同的是一个if只能有一个对应的
else,却可以有任意数量的elif。语法如下:

In [ ]:
if expression1:                     # 如果 expression1 为真
    expr1_true_suite                # 那么执行 expr1_true_suite
elif expression2:                   # 否则,如果 expression2 为真
    expr2_true_suite                # 那么执行 expr2_true_suite
          .
          .
elif expressionN:
    exprN_true_suite
else:                                # 否则
    expr_false_suite                # 执行 expr_false_suite

 例如:

In [2]:
num = 5     
if num == 3:            # 判断num的值
    print('3')        
elif num == 2:
    print ('2')
elif num == 1:
    print ('1')
elif num < 0:           # 值小于零时输出
    print ('error')
else:
    print ('roadman')     # 条件均不成立时输出
roadman

2.1 循环语句

接下来介绍循环语句。

  • Python提供了for循环和while循环(在Python中没有do…while循环),for循环一般比while计数器循环运行得更快
  • break语句,在语句块执行过程中终止循环,并且跳出整个循环
  • continue语句,在语句块执行过程中终止当前循环,跳出该次循环,执行下一次循环
  • pass语句,是空语句,是为了保持程序结构的完整性。不做任何事情,一般用做占位语句
  • 循环else块,只有当循环正常离开时才会执行(也就是没有碰到break语句)

2.1.1 while循环

while中的代码块会一直循环执行,直到循环条件不再为真

      while expression:
          suite_to_repeat

while循环的suite_to_repeat子句会一直循环执行,直到expression值为布尔假

例如:

In [3]:
count=0
while(count<9):
    print('the count is',count)
    count+=1
the count is 0
the count is 1
the count is 2
the count is 3
the count is 4
the count is 5
the count is 6
the count is 7
the count is 8

 代码块中包含了print和自增语句,它们被重复执行,直到count不再小于9。

注意:当使用while循环时,有可能conditon永远不为假,那么程序就会变成一个无限循环

2.1.2 for循环

for循环时Python中最强大的循环结构,可以遍历任何有序的序列对象内的元素。可用于字符串、列表、元组、其他内置可迭代对象等。语法如下:

In [ ]:
for iter_var in interables
    suite_to_repeat

 每次循环,iter_var迭代变量被设置为可迭代对象interales的当前元素,提供给suite_to_repeat语句块使用。

In [4]:
for eachletter in 'python':          # 第一个实例
    print('当前字母:',eachletter)
当前字母: p
当前字母: y
当前字母: t
当前字母: h
当前字母: o
当前字母: n
In [5]:
fruits=['banana','apple','mango']
for fruit in fruits:          # 第二个实例
    print ('当前水果 :', fruit)  
当前水果 : banana
当前水果 : apple
当前水果 : mango

 同时,我们还可以通过序列的索引来迭代:

In [6]:
namelist=['Cathy','Lily','Joe','Lucy']
for i in range(len(namelist)):       # 第三个实例
    print('Liu',namelist[i])
Liu Cathy
Liu Lily
Liu Joe
Liu Lucy

2.1.3 break 语句

Python中的break语句可以结束当前循环然后跳转到下调语句。常常用在某个外部条件被触发时(一般通过if语句来检测),需要立即从循环中退出时。

In [7]:
for letter in 'Python':     # 当遇到字母“h”时跳出循环
    if letter == 'h':
        break
    print ('Current Letter :', letter)
Current Letter : P
Current Letter : y
Current Letter : t

2.1.4 continue语句

continue语句会终结当前循环,并忽略剩余的语句,然后回到循环的顶端。

In [8]:
for letter in 'Python':     # 第一个实例
    if letter == 'h':
        continue
    print ('当前字母 :', letter)
当前字母 : P
当前字母 : y
当前字母 : t
当前字母 : o
当前字母 : n

2.1.5 pass语句

pass语句的意思是“不做任何事”,如果你在需要有语句的地方不写任何语句,那么解释器会提示出错,而pass语句就是用来解决这些问题的

In [9]:
def a_func():
  File "<ipython-input-9-7e3b0349c6bb>", line 1
    def a_func():
                 ^
SyntaxError: unexpected EOF while parsing
In [10]:
def a_func():
    pass

 从上面两个例子可以看出,定义一个函数时,如果不写语句就会报错,这时就可以用pass替代。

下面我们使用本章所学的语句来写一个验证用户密码的程序。

In [3]:
passwdList=['123','345','890']
valid=False
count=3
while count>0:
    password=input('enter password')
    for eachPasswd in passwdList:
        if password==eachPasswd:
            valid=True
            break
    if not valid:
        print('invalid input')
        count-=1
        continue
    else: 
        break 
enter password123

 

Python编程系列目录:
1. Python编程系列1-变量、字符串与列表
2. Python编程系列2-字典、元组与集合
当前阅读>3. Python编程系列3-条件与循环
4. Python编程系列4-函数
5. Python编程系列5-Numpy库
6. Python编程系列6-Scipy库
7. Python编程系列7-Pandas库
8. Python编程系列8-Matplotlib库