#範例4-1-6 無限循環的程式 while True: x = input("請輸入一個數字: ") print(x)
#範例4-1-7 第一次使用break while True: x = input("請輸入一個數字, 輸入 0 可終止程式: ") if x == "0": break else: print(x) print("程式終止")
4-1-3. Case Study個案研究 : 判斷質數
以下的程式可以while迴圈,依序檢查是否能整除,若有可以整除的情況就代表不是質數。
# 範例4-1-8 判斷質數 num = eval(input('Enter an integer: ')) flag = 1 k = 2 while k < num/2: if num % k == 0: flag = 0 break else: k += 1
if flag == 1: print('%d is a prime number.' % (num)) else: print('%d is not a prime number.' % (num))
# 範例4-1-9 判斷質數-第二種寫法 N = int(input("Enter an integer: ")) if N < 2 or N % 2 == 0: #排除2以下及所有偶數 s = "This is not a prime number" elif N == 2: #2是質數 s = "This is a prime number" else: s = "This is a prime number" i = 3 while i <= int(N**0.5): if N % i == 0: s = "This is not a prime number" break i += 2 print(s)
# 範例4-1-10 範例4-1-9的程式有誤, 應改成以下 N = int(input("Enter an integer: ")) if N == 2: #2是質數 s = "This is a prime number" elif N < 2 or N % 2 == 0: #排除2以下及所有偶數 s = "This is not a prime number" else: s = "This is a prime number" i = 3 while i <= int(N**0.5): if N % i == 0: s = "This is not a prime number" break i += 2 print(s)