Python flow control

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[]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值