前言
常用的逻辑运算共分为三种:与(and)、或(or)、非(not)。与运算就是同真才真,有假则假;或运算就是有真则真,同假才假;非运算就是真变假,假变真。我们接下来举个例子加以分析。
实践
我们从键盘获取输入作为今天的温度,然后判断若今天温度满足[0, 30],则输出今天是个好天气,适合出去玩耍:
temp = int(input("What is the temperature outside?: "))
if temp>=0 and temp<=30:
print("the temperature is good today!")
print("go outside!")
>>> What is the temperature outside?: 15
>>> the temperature is good today!
>>> go outside!
若今天温度低于0°或高于30°我们就呆在家里:
temp = int(input("What is the temperature outside?: "))
if temp<0 or temp>30:
print("the temperature is bad today!")
print("stay inside!")
>>> What is the temperature outside?: -2
>>> the temperature is bad today!
>>> stay inside!
我们将上述两段代码进行合并:
temp = int(input("What is the temperature outside?: "))
if temp>=0 and temp<=30:
print("the temperature is good today!")
print("go outside!")
elif temp<0 or temp>30:
print("the temperature is bad today!")
print("stay inside!")
取反运算的使用方法如下:
if not(True):
print("False")
else:
print("True")
>>> True
以上便是逻辑运算的全部内容,感谢大家的收藏、点赞、评论。我们下一节将介绍while循环(While Loops),敬请期待~