循环

  1. # 循环语句包含了while循环和for循环
  2. i = 10
  3. while i != 0:
  4. print(f'i = {i}')
  5. i -= 1
  6. # i = 0 cannot be printed

累加

  1. # 高斯公式
  2. i = 0
  3. sum = 0
  4. while i <= 100:
  5. sum = sum + i
  6. i += 1
  7. print(sum)
  8. sum = (1 + 100) * 100 / 2
  9. print(sum)
  10. sum = i = 0
  11. while i <= 100:
  12. if i % 2 == 0:
  13. sum += i
  14. i += 1
  15. print(sum)
  16. # python has no i++

break

break直接跳出当前循环

continue

continue直接跳过下面的语句,重新进行循环

九九乘法表

  1. # 九九乘法表
  2. i, j = 0, 0
  3. while i < 9:
  4. i += 1
  5. while j < i:
  6. j += 1
  7. print(f'{i} * {j} = {i*j}\t', end="")
  8. j = 0
  9. print(end="\n")