||
for: iterate a clause over the items of any sequence. The sequence can be a set of numbers or strings.
Example-1
words=['cat', 'mice', 'rabbit']
for w in words:
print('Hello, '+w)
---
outPut:
Hello, cat
Hello, mice
Hello, rabbit
Example-2
for i in range(5):
print(i)
---
outPut:
0
1
2
3
4
NB1: range(a,b,c)--a-start point, b-end point, c-increment. The given end point is never part of the generated sequence
Example
range(2,10,2)--->2,4,6,8
range(-20,-100,-10)-->-20,-30,-40,-50,-60,-70,-80,-90
NB2: break and continue can also be used in for statements.
Example
for i in range(-20,-100,-10):
if i==-50:
break
print(i)
---
outPut
-20
-30
-40
Example: if i is larger than -50, go back to the for loop, otherwise, print the number of i
for i in range(-20,-100,-10):
if i>-50:
continue
print(i)
---
outPut
-50
-60
-70
-80
-90
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2024-4-30 02:26
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社