python语言for循环的用法

for循环

  • for循环:像while循环一样,for可以完成循环的功能。
                           在Python中 for循环可以遍历任何序列的项目,如一个列表或者一个字符串等。

  • for循环的格式:
                   for 临时变量 in 列表或者字符串等可迭代对象:
                       循环满足条件时执行的代码

  • name = 'python'
    for in name:
        print(x)
    '''
    输出结果:
    p
    y
    t
    h
    o
    n
    '''
    • name = 'hello'
      for in name:
          print(x)
          if == 'l':
              print("Hello world!")
               
      '''
      输出结果
      h
      e
      l
      Hello world!
      l
      Hello world!
      o
      '''

    for和while的区别:

    • 1,Python中for循环和while循环本质上是没有区别的,但是在实际应用上,针对性不太一样。

    • 2,while循环适用于未知循环次数的循环,for循环适用于已知循环次数的循环。

    • 3,而while循环很少进行遍历使用(语句过多,没有for方便),while主要用于判断符合条件下循环。