jack0he的个人博客分享 http://blog.sciencenet.cn/u/jack0he

博文

Python -Note-5-for-statements

已有 2097 次阅读 2017-4-11 03:55 |个人分类:Python 笔记|系统分类:科研笔记

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








https://wap.sciencenet.cn/blog-850613-1048045.html

上一篇:Python-Note-4-Continue-statements
下一篇:Python-Note-6-Global and local variables
收藏 IP: 80.101.95.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...
扫一扫,分享此博文

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-4-30 02:26

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部