Logical operations
- In program development, execution results may be related to multiple conditions
- For example, if more than one condition is set up to execute, or if one condition can be executed, then a logical operator is required
- Logical operators can connect multiple conditions logically to become more complex conditions
- The logical operators in Python include: not three with and/or or/
1.
and
条件1 and 条件2
- and/And
- Two conditions are met at the same time, return
True
- As long as there is one unsatisfied, return
False
Condition 1 |
Condition 2 |
Results |
Was founded |
Was founded |
Was founded |
Was founded |
Not established |
Not established |
Not established |
Was founded |
Not established |
Not established |
Not established |
Not established |
2.
or
条件1 or 条件2
- OR/or
- Two conditions as long as there is a satisfaction, return
True
- Two conditions are not satisfied, return
False
Condition 1 |
Condition 2 |
Results |
Was founded |
Was founded |
Was founded |
Was founded |
Not established |
Was founded |
Not established |
Was founded |
Was founded |
Not established |
Not established |
Not established |
3.
not
not 条件
conditions |
Results |
Was founded |
Not established |
Not established |
Was founded |
Logical Operations Walkthrough
- Exercise 1: Define an Integer variable
age
and write code to determine whether the age is correct
- Requires a person's age between 0-120
- Exercise 2: Define two integer variables,
python_score
c_score
write code to judge scores
- Requires as long as there is a score > 60 points even if qualified
- Exercise 3: Define a Boolean variable
is_employee
, write code to determine whether the company's employees
- If not prompt not allowed in
Answer 1:
# 练习1: 定义一个整数变量 age,编写代码判断年龄是否正确age = 100# 要求人的年龄在 0-120 之间if age >= 0 and age <= 120: print("年龄正确")else: print("年龄不正确")
Answer 2:
# 练习2: 定义两个整数变量 python_score、c_score,编写代码判断成绩python_score = 50c_score = 50# 要求只要有一门成绩 > 60 分就算合格if python_score > 60 or c_score > 60: print("考试通过")else: print("再接再厉!")
Answer 3:
# 练习3: 定义一个布尔型变量 `is_employee`,编写代码判断是否是本公司员工is_employee = True# 如果不是提示不允许入内if not is_employee: print("非公勿内")
Learning python path: logical operators