Python——条件判断

    xiaoxiao2023-03-24  4

    计算机之所以能做很多自动化的任务,因为他可以自己做条件判断。

    比如,输入用户年龄,根据年龄打印不同的内容,在Python程序中,用 if 语句实现:

    age = 20 if age>=18: print('you age is',age) print('adult')

    根据Python的缩进规则,如果 if 语句判断是True ,就把缩进两行的print语句执行了,否则,什么也不做。

    也可以给 if 添加一个 else语句,意思是,如果if判断是False,不要执行if的内容,去把else执行了

    age=3 if age >=18 : print('you age is',age) print('adult') else : print('you age is',age) print('teenage') 注意不要少写了冒号 :

    elif 是 else if 的缩写,完全可以有多个 elif 所以 if 语句的完整形势就是

    if <条件判断1>: <执行1> elif <条件判断2>: <执行2> elif <条件判断3>: <执行3> else: <执行4> if 语句执行有个特点,他就是从上往下判断,如果某个判断上是True,把该判断对应的语句执行之后,就忽略掉剩下的elif和else,所以,请测试并解释为什么下面的程序打印的是teenage:

    age = 20 if age >= 6: print('teenager') elif age >= 18: print('adult') else: print('kid') if 判断条件还可以简写,比如写:

    if x: <span style="white-space:pre"> </span>print('True') 只要 x 是非零数值、非空字符串、非空list等,就判断为True,否则为False。

    转载请注明原文地址: https://ju.6miu.com/read-1202402.html
    最新回复(0)