python loops_python - loops

本文深入讲解了Python中循环与迭代的基础知识,包括while无限循环、for定义循环的应用场景及使用技巧,并通过具体示例演示了如何利用break和continue来控制循环流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

loops and iteration

While

while loops are called indefinite loops because they keep going until a logical condition becomes False.

# break out of a loop

while True:

line = input('>')

if line == 'done':

break

print(line)

print('done!')

# finishing an iteration with contine

while True:

line = input('>')

if line[0] == '#':

continue # go up back to the tope of loop

if line == 'done':

break # get out of the loop

print(line)

print('done!')

for

definite loops iterate through the members of a set.

for i in [5,4,3,2,1]: # i is iteration variable

print(i)

print('blast off!')

friends = ['ke','xinlei','xjc']

for friend in friends:

print('hi',friend)

print('ok')

# count

count = 0

sum = 0

print('before',count,sum)

for things in [9,41,12,3,74,15]:

count += 1

sum += things

print(things,count,sum)

print('after',count,sum)

# a none type

smallest = None

print('before',smallest)

for value in [9,41,12,3,74,15]:

if smallest is None:

smallest = value

elif value < smallest:

smallest = value

print(smallest,value)

print('after',smallest)

# 'is' is stronger than '==' e.g. 0 == 0.00

# use is for None/ Ture False, not recommended use for integer

condition

astr = 'hello'

try:

print('hello')

astr = int(astr) #注意此处错误

except: # 只在try错误的时候触发 每一条

astr = -1

print('First', istr)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值