if语句
1、if…else表单一条件判断,else后不用加上条件
guess = int(input('please input a number: '))
# 如果输入9即显示正确,输入其他数字则显示错误
if guess == 9:
print('right')
else:
print('wrong')
2、用if…elif…elif…else表多条件判断
my_score = int(input('please input your score: '))
# 根据输入的分数(百分制)判断属于哪个等级
if my_score >= 90 and my_score<= 100:
print('优秀')
elif my_score >=70 and my_score <= 89:
print('良好')
elif my_score >=60 and my_score <= 69:
print('及格')
else:
print('不及格')
3、在if语句的应用中,需注意层级的缩进
逻辑运算符
1、and、or、not是常用的逻辑运算符,使用其在语句中进行判断,返回的结果为True或False
2、and两边全为真时,结果为真;只要有一边为假,结果为假
3、or两边全为假时,结果为假;只要有一边为真,结果为真
4、当一个语句中存在较多逻辑运算符时,Python会安装默认的优先级进行判断,如需要重新定义优先级,用括号即可完成(就如同加减乘除中用括号改变式子中运算的先后顺序一样)
5、优先级的排序为: not > and > or
再扩展一下,不局限于上面三个的话,顺序是这样的:
(<, <=, >, >=, !=, ==)> (in, not in) > not > and > or > if