美文网首页Pythoner集中营程序员
python中的循环for 和 while

python中的循环for 和 while

作者: 老鼠慎言 | 来源:发表于2018-08-25 20:03 被阅读12次

近期在写代码是发现python中的for和c++的for 不同的地方

python中的for循环是一个通用的序列迭代器,可以遍历任何有序的序列对象内部的元素,(注意是遍历),也就是说循环的方式一开始就固定好了,本质上是遍历;看代码:

python:代码

count = 0
for i in range(8):
    if i % 2 == 0:
        i += 2
    print(i, end=' ')
    count += 1
print('\n总次数',count)

返回结果:

2 1 4 3 6 5 8 7 
总次数 8

我的本意是想让这个程序遇到偶数跳两个,很显然,它还是执行了八次

而c++代码就可以用for实现这个功能:

 for(int i = 1; i<=8;i++)
        {
            if(i%2==0){
               i += 2; 
            }
            cout<<i<<' ';
        }

结果为:

1 4 5 8 

python里要简单的实现上述功能,则需要用while了。
总结:\color{red}{python} 里的 \color{red}{for} 只是对一个有序序列的遍历

相关文章

  • 我的python学习笔记-第十天

    循环语句 Python中的循环语句有 for 和 while。 while 循环 Python中while语句的一...

  • Python3 循环

    Python中的循环语句有 for 和 while。 while循环 Python中while语句的一般形式: 同...

  • Python3 & 循环语句

    Python 提供了 for 循环和 while 循环(在 Python 中没有 do..while 循环)。 W...

  • 第五周python学习

    Python提供了for循环和while循环(在Python中没有do..while循环): 循环类型描述 whi...

  • 14、python循环语句

    本章节将为大家介绍Python循环语句的使用。Python中的循环语句有 for 和 while。 while循环...

  • Python3入门(五)循环语句

    Python中的循环语句有 for 和 while。Python循环语句的控制结构图如下所示 一、while循环 ...

  • Lesson 021 —— python 循环语句

    Lesson 021 —— python 循环语句 Python中的循环语句有 for 和 while。 循环可以...

  • 如何学习python|21、for循环

    除了while 循环外,Python 中还有一种更常用的循环——for 循环 和while 循环相比,for 循环...

  • Python3 循环语句

    while 循环 同样需要注意冒号和缩进。另外,在Python中没有do..while循环。Python中whil...

  • python循环执行

    python有两种循环,while循环和for循环。 python循环的流程图如下: while循环 python...

网友评论

    本文标题:python中的循环for 和 while

    本文链接:https://www.haomeiwen.com/subject/fgoiiftx.html