@Channelchan
2017-11-27T05:54:34.000000Z
字数 2278
阅读 137767

Python分支(条件)语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块。
Python程序语言指定任何非0和非空(null)值为true,0 或者 null为false。
if 语句的判断条件可以用>(大于)、<(小于)、==(等于)、>=(大于等于)、<=(小于等于)来表示其关系。
Python 编程中 if 语句用于控制程序的执行,基本形式为:
if 判断条件:执行语句……else:执行语句……
# if-else实例Stocks=['APPL','MSFT','GOOG']if 'APPL' in Stocks:print ('Stocks has APPL')else:print ('Stocks has not APPL')
Stocks has APPL
# 当判断条件为多个值时,使用以下形式:Stocks=['APPL','MSFT','GOOG']if 'YHOO' in Stocks:print ('Stocks have YHOO')elif 'IBKR' in Stocks:print('Stocks have IBKR')elif 'SBUX' in Stocks:print ('Stocks have SBUX')else:print ('Stocks don`t have YHOO,IBKR,SBUX')
Stocks don`t have YHOO,IBKR,SBUX

Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。其基本形式为:
while 判断条件:
执行语句……
# while实例count = 0while (count < 6):print ('The count is:', count)count+=1print ("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

Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。
# for迭代列表实例count=[0,1,2,3,4,5]for c in count: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}for k in d:print (k,':',d[k])
AAPL : 120
MSFT : 62.5
GOOG : 800

break语句用来终止循环语句,即循环条件没有False条件或者序列还没被完全递归完,也会停止执行循环语句。
# break 实例for word in 'QuantitativeTrader':if word == 'i':breakprint ('Current word :', word)
Current word : Q
Current word : u
Current word : a
Current word : n
Current word : t

continue 语句用来告诉Python跳过当前循环的剩余语句,然后继续进行下一轮循环。
# continue实例for word in 'Quantitation': # First Exampleif word == 'i':continueprint('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
Python pass是空语句,是为了保持程序结构的完整性。
# pass实例for word in 'Quantitation':if word == 'i':passprint ('执行了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 = []for x in range(1,5,1):list_count.append(x**2)print (list_count)
[1, 4, 9, 16]
# 一行代码完成新列表生成list_comprehension = [x**2 for x in range(1,5,1)]
list_comprehension
[1, 4, 9, 16]
key = ['a','b','c','d']
key_value = list(zip(key, list_comprehension))
# 一行代码完成新字典生成dict_comprehension = {k:v for k,v in key_value}
dict_comprehension
{'a': 1, 'b': 4, 'c': 9, 'd': 16}
