对象的布尔值
Python一切皆对象,所有对象都有一个布尔值
获取对象的布尔值:使用内置函数bool()
以下对昂的布尔值为False
- False
- 数值0
- None
- 空字符串
- 空列表
- 空元组
- 空字典
- 空集合
print(bool(False)) #False
print(bool(0)) #False
print(bool(0.0)) #False
print(bool(None)) #False
print(bool("")) #False
print(bool('')) #False
print(bool([])) #False 空列表
print(bool(list())) #False 空列表
print(bool(())) #False 空元组
print(bool(tuple())) #False 空元组
print(bool({})) #False 空字典
print(bool(dict())) #False 空字典
print(bool(set())) #False 空集合
False
False
False
False
False
False
False
False
False
False
False
False
False
其他对象都是True
分支结构
单分支
money = 1000
s = int(input("请输入取款金额:"))
if money >= s:
money -= s
print("取款成功,余额为:", money)
双分支结构:
money = 1000
s = int(input("请输入取款金额:"))
if money >= s:
money -= s
print("取款成功,余额为:", money)
else:
print("余额不足!")
多分支:
score=int(input("请输入成绩:"))
if score >= 90 and score <= 100:
print("A")
elif score >= 80 and score < 90:
print("B")
elif score >= 70 and score < 80:
print("C")
elif score >= 60 and score < 70:
print("D")
elif score >= 0 and score < 60:
print("E")
else:
print("输入成绩有误,不再有效范围内")
请输入成绩:100
A
另外一种想法
score=int(input("请输入成绩:"))
if 90 <= score <= 100:
print("A")
elif 80 <= score < 90:
print("B")
elif 70 <= score < 80:
print("C")
elif 60 <= score < 70:
print("D")
elif 0 <= score < 60:
print("E")
else:
print("输入成绩有误,不再有效范围内")
if的嵌套使用
answer=input("是会员吗?y/n")
money=float(input('请输入您的购物金额:'))
if answer == 'y':
if money >= 200:
print('打8折,付款金额为:', money * 0.8)
elif money >= 100:
print('打9折,付款金额为:', money * 0.9)
else:
print('不打折,付款金额为:', money)
else:
if money >= 200:
print('打9.5折,付款金额为:', money * 0.95)
else:
print('不打折,付款金额为:', money)
条件表达式
num_a=int(input('请输入第一个整数'))
num_b=int(input('请输入第二个整数'))
print((num_a, '大于等于', num_b) if num_a > num_b else (num_a, '小于', num_b))
num_a = int(input('请输入第一个整数:'))
num_b = int(input('请输入第二个整数:'))
print(str(num_a) + '大于等于' + str(num_b) if num_a > num_b else str(num_a) + '小于' + str(num_b))
pass语句
语句什么都不做,知识一个占位符,用在语法上需要语句的地方
什么时候使用:
先搭建语法结构,还没有想好代码怎么写的时候
num_a = int(input('请输入第一个整数:'))
num_b = int(input('请输入第二个整数:'))
if num_a >= num_b:
pass
else:
pass