python 知识点整理(二)
本文只是对python部分知识点进行学习和整理
本篇主要是针对python的flow control的总结
本文目录
conditional flow
comparison operators
check the variables and don’t change values
< <= == >= >
logical operators
combine several logical expressions into a single expression
ture/false
not or and
identity operators
compare the storage units of two objects
indentation 缩进
python中比较重要的部分 某个整块内容往往缩进是一致的
increase/maintain/decrease
decision
one way decision
just one decision
tem=5
if tem==5:
print('is 5')
print('over!')
is 5
over!
nested decision
tem=42
if tem>1:
print('more than 1')
if tem<100:
print('less than 100')
print('finish')
more than 1
less than 100
finish
two way decision
tem=1
if tem>2:
print('bigger')
else:
print('smaller')
smaller
muti-way decision
tem=5
if tem<2:
print('small')
elif tem<10:
print('medium')
else:
print('large')
try/expect structure
- If the code in try block works, the except block is skipped
- If the code in try block fails, the except block will be executed
astr='hello bob'#it is a string data
try:
istr=int(astr)
except:
istr=-1
print('first',istr)
astr='123'
try:
istr=int(astr)
except:
istr=-1
print('second',istr)
first -1
second 123
repeated flow
infinite loop
- Sometimes it can be hard to determine whether a loop will terminate
n=5
while n>0:
print('lather')
print('rinse')
n=n-1
print('off')
won’t stop
break/continue
while (True):
line= input('Enter a word')
if line =='done':
break
print(line)
print('finish')
while True:
line= input('input a word')
if line[0]=='#':continue
if line =='done':
break
print(line)
print('done')
only input done will finish
indefinite(while) OR definite(for)loop
- while loop is called the"indefinite loop" since they keep going until a logical condition becomes false
- for loop is callede definite loop
for loop
for i in [seq]
For loops (definite loops) have explicit iteration variables that change each time through a loop.
for i in [1,2,3,4,5]:
print(i)
usage of for loop
searching:find x in list[]
counting: use sum and i in list[]
filtering:use a temp and search i in list[]