1. 程式人生 > 其它 >python---條件控制結構(if語句)

python---條件控制結構(if語句)

1. 簡單的選擇--if語句

a. if...else...語句

number = int(input('Please input number:'))
if number % 2 ==0:
    print(f'{number} is oven')
else:
    print(f'{number} is odd')

b. 只有if語句

"""
如果加班:直接回家
如果不加班:看完電影再回家
"""
ot = False
if not ot:
    print('watch movie')
print('go home')

"""
執行結果:
watch movie
go home
""" ot = True if not ot: print('watch movie') print('go home') """ 執行結果: go home """

2. 多情況的選擇

age = int(input('please enter your age:'))
if 6 <= age < 18:
    print('teenager')
elif age >= 18:
    print('adult')
else:
    print('kid')

3. if 巢狀語句

a = input('Please input number a:
') b = input('Please input number b:') c = input('Please input number c:') if a>b: if a>c: max=a else: max=c else: if b>c: max=b else: max=c print(f'The max number is {max}')

4. 三目運算子

Python 可通過 if 語句來實現三目運算子的功能,因此可以近似地把這種 if 語句當成三目運算子。作為三目運算子的 if 語句的語法格式如下:

True_statements if expression else False_statements
a = int(input('Please input number a:'))
y = a if a >= 0 else -a
print(f'The absolute value of {a} is {y}')