跳轉到

2.3 條件判斷敘述

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")

Test

3-1

Q1. 建立一個驗證密碼的小程式,程式 內建一組字串密碼,請使用者輸入一組字串密碼,
比對密碼是否輸入正確。
Expected Result:
請輸入密碼: Passw0rd
密碼正確
or
請輸入密碼: adfgg
密碼錯誤
password='0000'
myPass=input('請輸入密碼:')
if myPass==password:
    print('密碼正確')
else:
    print('密碼錯誤')