Python中的条件判断

条件判断:在Python中使用 if 语句来实现

格式一:

score = int(input('please enter your age:'))
if score > 60:
    print('Your score  is :'  , age)
    print('Pass!')

如果if语句判断是 True,则执行缩进的两行print语句。否则,什么也不做

格式二:

score = int(input('please enter your age:'))
if score > 60:
    print('Your score  is :'  , age)
    print('Pass!')
else:
    print('You didn't pass!')

如果if判断条件为False,则执行else下面缩进的语句

格式三:

age = int(input('请输入你的年龄:'))
if age >= 60:
    print('老年人了')
elif age >=40:
    print('中年人了')
elif age >=20:
    print('年轻人')
else:
    print('还是个孩子!')

if语句特点:从上往下判断,如果在某一个条件上判断为True,则执行该判断下的语句,忽略其余的 elif 和else。

if的条件还可以简写:

if x:
    pass

只要 x 是非零数值、非空字符串、非空list。就判断True,否则为False

关于input()

input返回的数据类型是 str。如果要和数字进行比较,需要使用 int()函数转换成整数。

关于int()函数,如果参数不是一个合法的数字的时候会报错。

原文地址:https://www.cnblogs.com/hongyu0518/p/9635404.html