vòng lặp while

Python nâng cao

Hugo Bowne-Anderson

Data Scientist at DataCamp

if-elif-else

control.py

  • Chỉ đi qua cấu trúc một lần!
z = 6
if z % 2 == 0 :  # True
    print("z is divisible by 2")  # Được thực thi
elif z % 3 == 0 :
    print("z is divisible by 3")
else :
    print("z is neither divisible by 2 nor by 3")

...   # Tiếp tục
  • While = if lặp lại
Python nâng cao

While

while condition :
    expression
  • Tính mô hình số
  • "lặp lại hành động cho đến khi thỏa điều kiện"
  • Ví dụ
    • Lỗi bắt đầu tại 50
    • Chia lỗi cho 4 mỗi lần lặp
    • Tiếp tục cho đến khi lỗi không còn > 1
Python nâng cao

While

while condition :
    expression

while_loop.py

error = 50.0


while error > 1:
error = error / 4
print(error)
  • Lỗi bắt đầu tại 50
  • Chia lỗi cho 4 mỗi lần lặp
  • Tiếp tục cho đến khi lỗi không còn > 1
Python nâng cao

While

while condition :
    expression

while_loop.py

error = 50.0
#     50
while error > 1:    # True
      error = error / 4
      print(error)
12.5
Python nâng cao

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 nâng cao

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 nâng cao

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 nâng cao

While

while condition :
    expression

while_loop.py

error = 50.0
while error > 1 :    # luôn True
    # error = error / 4
    print(error)
50
50
50
50
50
50
50
...
  • DataCamp: phiên bị ngắt kết nối
  • Hệ thống cục bộ: Control + C
Python nâng cao

Ayo berlatih!

Python nâng cao

Preparing Video For Download...