Python语言基础 互动版

在线工具推荐: Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器

for语句


在 python 中,for … else 表示这样的意思,for 中的语句和普通的没有区别,else 中的语句会在循环正常执行完的情况下执行。如下格式:

for iterating_var in sequence:
      statements(s)
else:
      statements(s1)
num=10
for i in range(2,num): #to iterate on the factors of the number
   if num%i == 0:      #to determine the first factor
       j=num/i          #to calculate the second factor
       print '%d equals %d * %d' % (num,i,j)
else:                  # else part of the loop
   print num, 'is a prime number'

以上代码中range返回一个序列的数。