☰ Contents · Computing

Logical expression practice and the if…else operator

Lessons 36–37 · 2 lessons · M. R. Fayziyeva, D. M. Sayfurov, N. S. Xaytullayeva. Informatics and Information Technologies, Grade 9. “Nashriyot uyi Tasvir”, Tashkent, 2020
36

Practical lesson: logical expressions

Textbook: pp. 75–76
GoalIn the practical lesson, finds the value of logical expressions taking the order of operations into account, and checks numeric and string comparisons in a program.
New words
value of an expression: the result after all operations are carried out; for conditions it is True or False · ifoda qiymatiorder of operations: arithmetic first, then comparison, then not, and, or · amallar tartibistring comparison: == is True only if the strings match exactly, including case and spaces · satrlarni taqqoslashtesting: running the expression in the interactive environment to confirm the hand result · tekshirish
Explanation

When finding the value of a compound logical expression the order of operations matters: first the arithmetic operations, then comparison, then not, and, and finally or. So in True or False and False the and works first (False and False = False) and then the or: True or False = True. Brackets change the order: (True or False) and False is False. Splitting the expression into parts and writing the value of each part in the notebook reduces mistakes. When comparing strings == gives True only on an exact match: letter case and a trailing space count too. Check the answer you found by hand in the interactive environment of IDLE; if they differ, recalculate the expression step by step.

Worked examples
A numeric expression: x = 9 ⏎ print(x % 2 == 1 and x * x > 50) It prints True because 9 is odd and 81 > 50.
Order and strings: print(True or False and False, (True or False) and False, not False or False) The result is True False True. Strings: name = "Toshkent" ⏎ print(name == "Toshkent", name == "toshkent", name == "Toshkent ") Only the first matches exactly: True False False.
Class activity

“Expression chain”: the group writes each other a logical expression with and without brackets (3–4 operations); the partner calculates it by hand in parts and then in IDLE.

Practice
1
Find the value of (2 < 5) and not (3 > 4).
2
If a = 8 and b = a ** 2, what is the value of a < b / 10?
3
Write a program that prints True or False for whether the typed number n is two-digit.
4
Why is "Book" == "book" False?