布尔表达式
布尔表达式: true(真)和false(假)两个取值
- =表示赋值,==表示判断恒等
print(100==100) #判断等式左侧和右侧是否相等
字符串比较时,根据ASCII码进行判断 a=97 A=65
print('a'=='A')
print('a'>='A') #True #字符串的比较,只比较第一位
print('aA'=='Aa') #False
- True和False可以参与算术运算,True相当于1,False相当于0
print(True+True+True+True+True)
- in,not in
list1=[10,20,[80,90,100]]
print(10 in list1) #True
print(80 in list1) #False
- and,or
print(2>1 and 1>2) #一假为假,全真为真
print(2>1 or 1>2) #一真为真,全假为假
- not,and,or组合条件 优先级not>and>or
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')
- isinstance() 判断某个对象是否属于某个类,返回值为布尔型
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('老先生')
网友评论