Python 流程控制
分支语句
if、elif、else
Python分支(条件)语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块。
Python程序语言指定任何非0和非空(null)值为true,0 或者 null为false。
if 语句的判断条件可以用>(大于)、=(大于等于)、<=(小于等于)来表示其关系。
Python 编程中 if 语句用于控制程序的执行,基本形式为:
if判断条件:
执行语句……
else:
执行语句……
# if-else实例
Stocks=['APPL','MSFT','GOOG']
if'APPL'inStocks:
print('Stocks has APPL')
else:
print('Stocks has not APPL')Stocks has APPL
# 当判断条件为多个值时,使用以下形式:
Stocks=['APPL','MSFT','GOOG']
if'YHOO'inStocks:
print('Stocks have YHOO')
elif'IBKR'inStocks:
print('Stocks have IBKR')
elif'SBUX'inStocks:
print('Stocks have SBUX')
else:
print('Stocks don`t have YHOO,IBKR,SBUX')Stocks don`t have YHOO,IBKR,SBUX
循环语句
while
Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。其基本形式为:
while 判断条件:执行语句……
# while实例
count=0
while(count<6):
print('The count is:',count)
count+=1
print("Over")The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
Over
for
Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。
# for迭代列表实例
count=[0,1,2,3,4,5]
forcincount:
print('The count is:',c)
print('Over')The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
Over
# for迭代字典实例
d={'AAPL':120,'MSFT':62.5,'GOOG':800}
forkind:
print(k,':',d[k])AAPL : 120
MSFT : 62.5
GOOG : 800
循环控制语句(break、 continue、 pass)
break
break语句用来终止循环语句,即循环条件没有False条件或者序列还没被完全递归完,也会停止执行循环语句。
# break 实例
forwordin'QuantitativeTrader':
ifword=='i':
break
print('Current word :',word)Current word : Q
Current word : u
Current word : a
Current word : n
Current word : t
continue
continue 语句用来告诉Python跳过当前循环的剩余语句,然后继续进行下一轮循环。
# continue实例
forwordin'Quantitation':# First Example
ifword=='i':
continue
print('Current word :',word)Current word : Q
Current word : u
Current word : a
Current word : n
Current word : t
Current word : t
Current word : a
Current word : t
Current word : o
Current word : n
pass
Python pass是空语句,是为了保持程序结构的完整性。
# pass实例
forwordin'Quantitation':
ifword=='i':
pass
print('执行了pass')
print('Current word :',word)Current word : Q
Current word : u
Current word : a
Current word : n
Current word : t
执行了pass
Current word : i
Current word : t
Current word : a
Current word : t
执行了pass
Current word : i
Current word : o
Current word : n
列表解析
列表解析根据已有列表,高效创建新列表的方式。
list_count=[]
forxinrange(1,5,1):
list_count.append(x**2)
print(list_count)[1, 4, 9, 16]
# 一行代码完成新列表生成
list_comprehension=[x**2forxinrange(1,5,1)]
list_comprehension[1, 4, 9, 16]
key=['a','b','c','d']
key_value=list(zip(key,list_comprehension))
# 一行代码完成新字典生成
dict_comprehension={k:vfork,vinkey_value}
dict_comprehension{'a': 1, 'b': 4, 'c': 9, 'd': 16}