while loop

  1. 流程圖

    \begin{tikzpicture}[node distance=1.5cm,auto]\setlength \baselineskip{1ex}
......

  2. 語法
    while expression:
    	statement(s)
    
  3. 範例:while 迴圈直接輸入 q 才退出。
    [dywang@deyu zzz]$ cat loop1.py 
    #!/usr/bin/env python3
    # coding: utf-8
    
    var = 'start'
    while var != 'q':
    	var = input("Enter a string: ")
    	print("You entered:", var)
    print("Good bye!")
    
  4. 執行程式,直到輸入 q 程式才退出。
    [dywang@deyu zzz]$ ./loop1.py 
    Enter a string: 123
    You entered:  123
    Enter a string: qwe
    You entered:  qwe
    Enter a string: q
    You entered:  q
    Good bye!
    
  5. 練習使用 while 從 1 累加到輸入的數字,印出結果。