Python编程:02-布尔表达式,条件判断与分支语句

2023-03-27  本文已影响0人  小小一颗卤蛋

布尔表达式

布尔表达式: true(真)和false(假)两个取值

 print(100==100)  #判断等式左侧和右侧是否相等

字符串比较时,根据ASCII码进行判断 a=97 A=65

 print('a'=='A')
 print('a'>='A')  #True #字符串的比较,只比较第一位
 print('aA'=='Aa')  #False
 print(True+True+True+True+True)
 list1=[10,20,[80,90,100]]
 print(10 in list1)  #True
 print(80 in list1)  #False
 print(2>1 and 1>2)  #一假为假,全真为真
 print(2>1 or 1>2)  #一真为真,全假为假
 print(2>1 and 1>2 or 3>2 and not False)
 print(2>1 and 1>2 and not 1 or 3>2)  #not 1相当于not True,not 0相当于not False
 print('a'!='A')
print(isinstance(100.1,float))

分支语句

缩进
python对于缩进是有比较严格的要求的,不需要缩进的地方不能缩进,需要缩进的地方必须缩进 python对于缩进几个空格没有强制性要求,可以1个,也可以多个,一般默认为4个空格

 if 10>9:  #如果if后面的布尔表达式为真,则执行下面的语句
     print('Hello')

写一个程序,用户输入一个分数,如果大于等于90分,则打印"优秀",如果大于等于80分,则打印"不错",如果大于等于60分,则打印"及格",否则打印不及格

 score=input('请输入一个数字:  ')  #input()读取用户的输入,返回值是str型
 if score.isdigit():  #判断对象是否是由纯数字组成
     score=int(score)  #int()将对象转为整数型
     if score>=90:
         print('优秀')
     elif score>=80:
         print('不错')
     elif score>=60:
         print('及格')
     else:  #如果以上条件都不满足,则执行else中的语句
         print('不及格')

复合条件语句

如果一个人的年龄大于60岁,并且为男性,我们称他为老先生

 age=69
 gender='male'
 if age>60 and gender=='male':
     print('老先生')

或者

 if age>60:
     if gender=='male':
         print('老先生')
上一篇 下一篇

猜你喜欢

热点阅读