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")  # Executed
elif z % 3 == 0 :
    print("z is divisible by 3")
else :
    print("z is neither divisible by 2 nor by 3")

...   # Moving on
  • 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 中級

一起來練習吧!

Python 中級

Preparing Video For Download...