while 循环

Python 中级

Hugo Bowne-Anderson

Data Scientist at DataCamp

if-elif-else

control.py

  • 仅通过该结构一次!
z = 6
if z % 2 == 0 :  # True
    print("z is divisible by 2")  # 执行
elif z % 3 == 0 :
    print("z is divisible by 3")
else :
    print("z is neither divisible by 2 nor by 3")

...   # 继续
  • While 循环 = 重复的 if 语句
Python 中级

While

while condition :
    expression
  • 数值计算模型
  • "重复执行,直到满足条件"
  • 示例
    • 误差初始为 50
    • 每次运行将误差除以 4
    • 继续直到误差不再 > 1
Python 中级

While

while condition :
    expression

while_loop.py

error = 50.0


while error > 1:
error = error / 4
print(error)
  • 误差初始为 50
  • 每次运行将误差除以 4
  • 继续直到误差不再 > 1
Python 中级

While

while condition :
    expression

while_loop.py

error = 50.0
#     50
while error > 1:    # True
      error = error / 4
      print(error)
12.5
Python 中级

While

while condition :
    expression

while_loop.py

error = 50.0
#     12.5
while error > 1:    # True
      error = error / 4
      print(error)
12.5
3.125
Python 中级

While

while condition :
    expression

while_loop.py

error = 50.0
#     3.125
while error > 1:    # True
      error = error / 4
      print(error)
12.5
3.125
0.78125
Python 中级

While

while condition :
    expression

while_loop.py

error = 50.0
#     0.78125
while error > 1:    # False
    error = error / 4
    print(error)
12.5
3.125
0.78125
Python 中级

While

while condition :
    expression

while_loop.py

error = 50.0
while error > 1 :    # always True
    # error = error / 4
    print(error)
50
50
50
50
50
50
50
...
  • DataCamp:会话已断开
  • 本地系统:Control + C
Python 中级

Vamos praticar!

Python 中级

Preparing Video For Download...