【发布时间】:2021-02-11 02:20:38
【问题描述】:
我有 2 个布尔变量:
a = True
b = True
每一个都有一些表现在它们的字符串表示中的属性:
a_str = "a is real"
b_str = "b is surreal"
结果应该:
- 检查
a and b是否为真,是否为真,输出“a 是真实的,b 是超现实的” - 检查是否只有
a为True,然后输出:“a is real” - 检查是否只有
b为True,然后输出:“b is surreal”
我尝试了以下方法并且它有效,但引出不同的 if-elifs 相当冗长,即
a = True
b = True
a_str = "a is real"
b_str = "b is surreal"
if a and b:
print(f"{a_str} AND {b_str}")
elif a:
print(a_str)
elif b:
print(b_str)
特别是。如果有一个新变量c,例如
a = True
b = True
c = True
a_str = "a is real"
b_str = "b is surreal"
c_str = "c is cereal"
if a and b and c:
print(f"{a_str} AND {b_str} AND {c_str")
elif a and b:
print(f"{a_str} AND {b_str}")
elif a and c:
print(f"{a_str} AND {b_str}")
elif b and c:
print(f"{b_str} AND {c_str}")
elif a:
print(a_str)
elif b:
print(b_str)
elif c:
print(c_str)
有没有更简洁的方法来枚举布尔检查的不同情况?
【问题讨论】:
标签: python string if-statement boolean combinations