1.if-else
x=5
if x>4 or x!=9:
print("{}".format(x))
else:
print("x is not greater than 4")
#结果
5
2.if-elif-else
x=5
if x>6:
print("x is greater than six")
elif x>4 and x==5:
print("{}".format(x))
else:
print("x is not greater than 4")
#结果
5
3.for循环
y=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct',\
'Nov','Dec']
z=['Annie','Betty','Claire','Daphne','Ellie','Franchesca','Greta',
'Holly','Isabel','Jenny']
another_dict={'x':'printer','y':5,'z':['star','circle',9]}
print("#Print 月份")
for month in y:
print("{!s}".format(month))
print("#Print Name")
for i in range(len(z)):
print("{0!s}:{1:s}".format(i,z[i]))
print("#Print Name noly For 'Jxxx'")
for j in range(len(z)):
if y[j].startswith('J'):
print("{!s}".format(y[j]))
print("#Print dict for key value")
for key,value in another_dict.items():
print("{0:s},{1}".format(key,value))
#结果
#Print 月份
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug
Sep
Oct
Nov
Dec
#Print Name
0:Annie
1:Betty
2:Claire
3:Daphne
4:Ellie
5:Franchesca
6:Greta
7:Holly
8:Isabel
9:Jenny
#Print Name noly For 'Jxxx'
Jan
Jun
Jul
#Print dict for key value
x,printer
y,5
z,['star', 'circle', 9]
4.简化for循环,列表,集合与字典生成式;
#列表生成式
my_data=[[1,2,3],[4,5,6],[7,8,9]]
rows_to_keep=[row for row in my_data if row[2]>5]
print("list compression:{}".format(rows_to_keep))
#结果
list compression:[[4, 5, 6], [7, 8, 9]]
#集合生成式。
my_data=[(1,2,3),(4,5,6),(7,8,9)]
set_of_tuples1={x for x in my_data} #定义集合并设置集合的元素
print("set comprehension:{}".format(set_of_tuples1))
set_of_tuples2=set(my_data) #列表变集合
print("set function:{}".format(set_of_tuples2))
#结果
set comprehension:{(7, 8, 9), (1, 2, 3), (4, 5, 6)}
set function:{(7, 8, 9), (1, 2, 3), (4, 5, 6)}
#字典生成式;
my_dictionary={'customer1':7,'customer2':9,'customer3':11}
my_results={key:value for key,value in my_dictionary.items() if value>10}
print("dictionary comprehension:{}".format(my_results))
#结果
dictionary comprehension:{'customer3': 11}
5.while循环
x=0
while x<11:
print("{!s}".format(x))
x+=1
#结果
0
1
2
3
4
5
6
7
8
9
10
#知道循环次数可以使用while,不知道循环次数使用for循环。
6.函数
def getMean(numericValues):
return sum(numericValues)/len(numericValues) if len(numericValues>0) \
else float('nan')
my_list=[2,3,4,5,6,6,8,8]
print("mean:{!s}".format(getMean(my_list)))
#结果
mean:5.25
7.异常捕获:try-except
def getMean(numericValues):
return sum(numericValues)/len(numericValues)
my_list2=[]
try:
print("{}".format(getMean(my_list2)))
except ZeroDivisionError as detail:
print("Error:{}".format(float('nan')))
print("Error:{}".format(detail))
#结果
Error:nan
Error:division by zero
8.异常捕获及处理异常
def getMean(numericValues):
return sum(numericValues)/len(numericValues)
my_list2=[]
try:
result=getMean(my_list2)
except ZeroDivisionError as detail:
print("Error:{}".format(float('nan')))
print("Error:{}".format(detail))
else:
print("The mean is:{}".format(result))
finally:
print("The finally block is executed every time")
#结果
Error:nan
Error:division by zero
The finally block is executed every time
9.总结
知道循环次数可以使用while,不知道循环次数使用for循环。