条件与循环:if、while、for
计算机之所以能做很多自动化的任务,因为它可以自己做条件判断。本篇将简述 Python 条件与循环。
一、条件 if
格式
if 判断条件:
执行语句……
else:
执行语句……
当 if 有多个条件时可使用括号来区分判断的先后顺序,括号中的判断优先执行,此外 and 和 or 的优先级低于>(大于)、<(小于)等判断符号,即大于和小于在没有括号的情况下会比与或要优先判断。
由于 python 并不支持 switch 语句,所以多个条件判断,只能用 elif 来实现,如果判断需要多个条件需同时判断时,可以使用 or (或),表示两个条件有一个成立时判断条件成功;使用 and (与)时,表示只有两个条件同时成立的情况下,判断条件才成功。
if 判断条件1:
执行语句1……
elif 判断条件2:
执行语句2……
elif 判断条件3:
执行语句3……
else:
执行语句4……
In [1]: num = 5
if num == 3: # 判断num的值
print('3')
elif num == 2:
print('2')
elif num == 1:
print('1')
elif num < 0: # 值小于0时输出
print('error')
else:
print('roadman') # 条件均不成立时输出
Out[1]: roadman
1.1 and、or
对 or 而言,Python 会由左到右求算操作对象,然后返回第一个为真的操作对象。
Python 会在其找到的第一个真值操作数的地方停止,通常叫短路计算。
In [2]: 2 < 3, 3 < 2
Out[2]: (True, False)
In [3]: 2 or 3, 3 or 2
Out[3]: (2, 3)
如果左边的操作数为假(空对象),Python 只会计算右边的操作数并将其返回
In [4]: [] or 3
Out[4]: 3
In [5]: [] or {}
Out[5]: {}
and 会停在第一个为假的对象上
In [6]: 2 and 3, 3 and 2
Out[6]: (3, 2)
In [7]: [] and {} # 空list本身等同于False
Out[7]: []
In [8]: # 由于一个空 list 本身等同于False,所以可以直接:
mylist = []
if mylist:
# Do something with my list
pass
else:
# The list is empty
pass
1.2 神奇的布尔值
从一个固定大小的集合中选择非空的对象,只要将其串在一个 or 表达式即可
In [9]: X = 'A' or 'B' or 'C' or None # 会把X设为A、B以及C中第一个非空(为真)的对象,或者所有对象都为空就设为None
In [10]:X = 'A' or default # 如果A为真(或非空)的话将X设置为A,否则,将X设置为default
In [ ]: if f1() or f2():... # 如果f1返回真值(非空),Python将不再执行f2,若要保证两个函数都执行,需要在or之前调用用他们,如
tmp1, tmp2 = f1(), f2()
if tmp1 or tmp2:...
二、循环
稍后会介绍更加奇特的迭代工具,如生成器、filter 和 reduce。现在先从最基础的学起。
Python 提供了 for 循环和 while 循环(在 Python 中没有 do…while 循环),for 循环一般比 while 计数器循环运行得更快
break 语句,在语句块执行过程中终止循环,并且跳出整个循环
continue 语句,在语句块执行过程中终止当前循环,跳出该次循环,执行下一次循环。
pass 语句,是空语句,是为了保持程序结构的完整性。不做任何事情,一般用做占位语句。
循环 else 块,只有当循环正常离开时才会执行(也就是没有碰到 break 语句)
2.1 while
In [11]:count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
Out[11]: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
2.2 for
是一个通用的序列迭代器,可以遍历任何有序的序列对象内的元素。可用于字符串、列表、元组、其他内置可迭代对象等
In [ ]: for interating_var in sequence:
statements(s)
In [12]:for letter in 'Python': # 第一个实例
print('当前字母:', leter)
fruits = ['banana', 'apple', 'mamgo']
for fruit in fruits: # 第二个实例
print('当前字母:', fruit)
Out[12]:当前字母 : P
当前字母 : y
当前字母 : t
当前字母 : h
当前字母 : o
当前字母 : n
当前字母 : banana
当前字母 : apple
当前字母 : mango
In [13]:T = [(1,2), (3,4), (5,6)]
for (a,b) in T:
print(a,b)
Out[13]:1 2
3 4
5 6
In [14]:D = {'a':1, 'b':2, 'c':3}
for key in D:
print(key, '=>', D[key])
Out[14]:a => 1
c => 3
b => 2
In [15]:D.items()
Out[15]:dict_items([('a', 1), ('c', 3), ('b', 2)])
In [16]:for (key, value) in D.items():
print(key, '=>', value)
Out[16]:a => 1
c => 3
b => 2
嵌套的结构可以自动解包
In [17]:for ((a,b), c) in [((1,2), 3), ((4,5), 6)]: print(a,b,c)
Out[17]:1 2 3
4 5 6
2.3 break
In [18]:for letter in 'Python': # First Example
if letter == 'h':
break
print('Current Letter:', letter)
Out[18]:Current Letter : P
Current Letter : y
Current Letter : t
2.4 continue
In [19]:for letter in 'Python': # 第一个实例
if letter == 'h':
continue
print('当前字母:', letter)
Out[19]:当前字母 : P
当前字母 : y
当前字母 : t
当前字母 : o
当前字母 : n
#2.4 pass
In [20]:for letter in 'Python':
if letter == 'h':
pass
print('这是 pass 块')
print('当前字母:', letter)
Out[20]:当前字母 : P
当前字母 : y
当前字母 : t
这是 pass 块
当前字母 : h
当前字母 : o
当前字母 : n