Logical Expressions: and, or, not
Comparison operations produce True or False. With and, or and not we combine several conditions and write programs that make complex decisions.
All topics (5 of 11)
Chapter 1. Python Basics
Chapter 2. Lists and Strings
Chapter 3. Functions and Modules
Chapter 4. Working with Files
In Python, comparison operations (==, !=, <, >, <=, >=) produce a logical value: True or False. For example, 5 > 3 is True and 5 == 3 is False. Such values belong to the bool type and are used as conditions in if and while statements.
Three logical operations let us combine several conditions. and gives True only if both conditions are true, or gives True if at least one is true, and not reverses a value. For example, x > 0 and x < 10 checks that x lies between 0 and 10.
Operations are carried out in a fixed order: comparison first, then not, then and, and finally or. To change the order or make the code clearer, use parentheses: (a > 0 or b > 0) and c > 0. Python also allows chained comparison: 0 < x < 10 means the same as 0 < x and x < 10.
Example: let us check a user’s age. age = int(input("Yoshingiz: ")), then if age >= 7 and age <= 17: we print print("Siz maktab o‘quvchisi bo‘lishingiz mumkin"), otherwise the else branch runs. The most common mistake in logical expressions is mixing up = (assignment) and == (comparison).
Key takeaways
- The result of a comparison is a
boolvalue:TrueorFalse. andmeans both are true,ormeans at least one is true,notmeans the opposite.- Order of operations: comparison,
not,and,or; parentheses change the order. =assigns a value, while==compares.
Practice tasks
- Enter a number and use
andto check that it lies between 1 and 100; print the result as “yes” or “no”. - Enter a year and decide whether it is a leap year: divisible by 4 and not by 100, or divisible by 400.
- Write a weather program: if the temperature is above 25 or it is not raining, print “Let’s go for a walk”; write the logical expression with parentheses.
Review questions
Test yourself: think first, then reveal the answer.
1What value does `x > 5 and x < 7` give when x = 7?Show answerHide answer
`False`, because the second condition (7 < 7) is false and `and` needs both conditions to be true.2What is the difference between `or` and `and`?Show answerHide answer
`and` is true only when both conditions are true, while `or` is true when at least one of them is.
0 of 11 topics completed
Sign in to mark