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}')
posted @ 2022-01-18 18:31  ElsaWang  阅读(245)  评论(0)    收藏  举报