跳轉到

4.條件判斷敘述

Control Flow

if條件判斷

輸入冒號(:)代表條件結束

num = 3
if num > 0:
  print(num, "is a positive number.")
num = -1
if num > 0:
  print(num, "is a positive number.")

## Output: 3 is a positive number.

if ... else

num = -1
if num >= 0:
  print(num, "Positive or Zero")
else:
  print(num, "is a Negative number")

## Output: -1 is a Negative number.

if ... elif ... else

num = 0
if num > 0:
  print("Positive number")
elif num == 0:
  print("Zero")
else:
  print("Negative number")
## Output: Zero

Logical - or, and

亦可使用|(or)和&(and)做表示

num = 5

if num == 0 or num == 1:
  print("Zero or One")
elif num >= 2 and num <= 10:
  print("From 2 to 10")
else:
  print('More')

## Output: From 2 to 10

is, not

num = 4

# num == 4
if num is 4:
  print("num is 4")

# !(num == 5)
if not num == 5:
  print("num is not 5")

# num != 6
if num is not 6:
  print("num is not 6")

# !(num == 7)
if not num is 7:
  print("num is not 7")

For Loop迴圈

結尾需要有:

# Program to find the sum of all numbers stored in a list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# iterate over the list
sum = 0
for val in numbers:
  sum = sum + val

print("The sum is", sum) # The sum is 55

For loop with range()

# range(stop)
# range(start, stop[, step])
numbers = [1, 2, 3, 4, 5, 6]
# iterate over the list using index
for i in range(len(numbers)):
  print("number", numbers[i])

# iterate over the list using 2 steps
for i in range(0, len(numbers), 2):
  print("2 steps", numbers[i])

# Output
number 1
number 2
number 3
number 4
number 5
number 6
# Output
2 steps 1
2 steps 3
2 steps 5

For loop with enumerate( )

取得迴圈目前的索引值

pets = ('Dogs', 'Cats', 'Turtles', 'Rabbits')
for index, pet in enumerate(pets):
  print(index, pet)

# Output:
0 Dogs
1 Cats
2 Turtles
3 Rabbits

While Loop

n = 10
# initialize sum and counter
sum = 0
i = 1
while i <= n:
  sum = sum + i
  i = i+1 # update counter
# print the sum
print("The sum is", sum) # The sum is 55

Nested Loop

for i in range(0, 2):
  for j in range(0, 2):
    print("i=", i, "j=", j, ", i*j=", i*j)
# Output:
i= 0 j= 0 , i*j= 0
i= 0 j= 1 , i*j= 0
i= 1 j= 0 , i*j= 0
i= 1 j= 1 , i*j= 1

break, continue and pass

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# break
for val in numbers:
  if val >= 4:
  break
print(val) 

# Output
1
2

# pass 3
for val in numbers:
  pass

# continue
for val in numbers:
  if val >= 3 and val <=8:
  continue
print(val) 
# Output
1
2
9
10

List comprehension

用迴圈快速產生串列

# make new lists by using iterable
squares = []
for x in range(10):
  squares.append(x**2)
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# equivalently
squares = [x**2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

迴圈內加入判斷式產生串列

# with if
squares = [x**2 for x in range(10) if x % 2 == 0]
print(squares) ## [0, 4, 16, 36, 64]

# equivalently
squares = []
for x in range(10):
  if x % 2 == 0:
    squares.append(x**2)
print(squares) ## [0, 4, 16, 36, 64]

Test

3-1

Q1. 建立一個驗證密碼的小程式,程式 內建一組字串密碼,請使用者輸入一組字串密碼,
比對密碼是否輸入正確。
Expected Result:
請輸入密碼: Passw0rd
密碼正確
or
請輸入密碼: adfgg
密碼錯誤
password='0000'
myPass=input('請輸入密碼:')
if myPass==password:
    print('密碼正確')
else:
    print('密碼錯誤')
Q2. 給予一個列表,計算出列表中元素為 2的倍數的和。
Sample List : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Expected Result : 30
list=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
tot=0
for index,num in enumerate(list):
    if(index%2==1):
        tot+=num
print(tot)
Q3. 輸入人物的身高、體重,計算出該人物的 BMI
公式:BMI = 體重(公斤) / 身高*身高 (公尺)
P.S. 於2002年4月公布臺灣成人肥胖標準:
BMI<18.5 為過輕,
18.5≦BMI<24 為正常體重,
24≦BMI<27 為過重,
BMI≧27 即為肥胖
weight=float(input('請輸入體重(kg)'))
high=float(input('請輸入身高(m)'))
bmi=weight/(high*high)
print(type(bmi))
if bmi<18.5:
  print('過輕')
elif bmi<24.0 and bmi>=18.5:
  print('正常')
elif bmi<27 and bmi>=24:
  print('過重')
else:
  print('肥胖')
Q4. 印出 1 到 50,但如果是 3 的倍數就印 Fizz,如果是 5 的倍數就印 Buzz,如
果同時是 3 和 5 的倍數就印 FizzBuzz。
for num in range(1,51):
  if num%3==0 and num%5==0:
    print('FizzBuzz ',num)  
  elif num%5==0:
    print('buzz ',num)
  elif num%3==0:
    print('Fizz ',num)
  else:
    print(num)