顺序、分支、循环
注意:python中没有switch语句

1、分支

注意:# ‘’ 0 None 默认为False

  1. age = 17
  2. if age > 4:
  3. print("age > 4 ")
  4. print("....")
  5. if age >= 18:
  6. print("age >= 18")
  7. print("....")
  8. else:
  9. print("age < 18")
  10. if 0 < age < 17:
  11. print("0 < age < 17")
  12. elif 17 <= age < 30:
  13. print("age >=17 and age<30")
  14. print("....")
  15. elif age < 0 or age >= 30:
  16. print("age < 0 or age >= 30")

2、循环

2.1、while

  1. row = 1
  2. while row <= 9:
  3. col = 1
  4. while col <= row:
  5. print("%d * %d = %d" % (col, row, col * row), end="\t")
  6. col += 1
  7. row += 1
  8. print("")
  9. -------------------
  10. 1 * 1 = 1
  11. 1 * 2 = 2 2 * 2 = 4
  12. 1 * 3 = 3 2 * 3 = 6 3 * 3 = 9
  13. 1 * 4 = 4 2 * 4 = 8 3 * 4 = 12 4 * 4 = 16
  14. 1 * 5 = 5 2 * 5 = 10 3 * 5 = 15 4 * 5 = 20 5 * 5 = 25
  15. 1 * 6 = 6 2 * 6 = 12 3 * 6 = 18 4 * 6 = 24 5 * 6 = 30 6 * 6 = 36
  16. 1 * 7 = 7 2 * 7 = 14 3 * 7 = 21 4 * 7 = 28 5 * 7 = 35 6 * 7 = 42 7 * 7 = 49
  17. 1 * 8 = 8 2 * 8 = 16 3 * 8 = 24 4 * 8 = 32 5 * 8 = 40 6 * 8 = 48 7 * 8 = 56 8 * 8 = 64
  18. 1 * 9 = 9 2 * 9 = 18 3 * 9 = 27 4 * 9 = 36 5 * 9 = 45 6 * 9 = 54 7 * 9 = 63 8 * 9 = 72 9 * 9 = 81
  1. i = 0
  2. while i < 10:
  3. if i % 2 == 0:
  4. i += 1
  5. continue
  6. if i == 7:
  7. break
  8. print(i)
  9. i += 1

2.2、for

  1. for i in range(0, 10):
  2. print(i)
  3. for i in [1, 2, 3, 6]:
  4. print(i)
  5. for i in 'hello':
  6. print(i)