- Conditional Statements
- Comparison Operators
- Logical Operators
- Identity Operators
- Membership Operators
- Ternary Operator
- Match-Case Statement
- Operator Precedence
- Summary
- Tasks
Conditional statements allow you to execute different blocks of code based on certain conditions.
The if
statement executes a block of code if a specified condition is true.
x = 10
if x > 5:
print("x is greater than 5")
Output:
x is greater than 5
The if-else
statement executes one block of code if the condition is true, and another block if the condition is false.
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
Output:
x is not greater than 5
The if-elif-else
statement allows you to check multiple conditions.
x = 7
if x > 10:
print("x is greater than 10")
elif x > 5:
print("x is greater than 5 but less than or equal to 10")
else:
print("x is 5 or less")
Output:
x is greater than 5 but less than or equal to 10
You can nest if
statements inside other if
statements.
x = 15
if x > 10:
print("x is greater than 10")
if x > 20:
print("x is also greater than 20")
else:
print("x is not greater than 20")
Output:
x is greater than 10
x is not greater than 20
Comparison operators are used to compare two values.
x = 10
y = 20
print(x == y) # Equal to
print(x != y) # Not equal to
print(x > y) # Greater than
print(x < y) # Less than
print(x >= y) # Greater than or equal to
print(x <= y) # Less than or equal to
Output:
False
True
False
True
False
True
age = 18
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
Output:
You are an adult.
Logical operators are used to combine conditional statements.
The and
operator returns True
if both conditions are true.
x = 10
y = 20
print(x > 5 and y > 15) # True
print(x > 15 and y > 15) # False
Output:
True
False
The or
operator returns True
if at least one condition is true.
x = 10
y = 20
print(x > 5 or y > 25) # True
print(x > 15 or y > 25) # False
Output:
True
False
The not
operator returns True
if the condition is false.
x = 10
print(not (x > 15)) # True
print(not (x > 5)) # False
Output:
True
False
age = 25
income = 50000
if age > 18 and income > 30000:
print("You are eligible for the loan.")
else:
print("You are not eligible for the loan.")
Output:
You are eligible for the loan.
Identity operators are used to compare the memory locations of two objects.
The is
operator returns True
if both variables point to the same object.
x = ["apple", "banana"]
y = ["apple", "banana"]
z = x
print(x is z) # True because z is the same object as x
print(x is y) # False because x is not the same object as y
print(x == y) # True because x is equal to y
Output:
True
False
True
The is not
operator returns True
if both variables do not point to the same object.
x = ["apple", "banana"]
y = ["apple", "banana"]
z = x
print(x is not z) # False because z is the same object as x
print(x is not y) # True because x is not the same object as y
Output:
False
True
Membership operators are used to test if a sequence is presented in an object.
The in
operator returns True
if a specified value is present in the object.
x = ["apple", "banana"]
print("banana" in x) # True because "banana" is in the list
print("cherry" in x) # False because "cherry" is not in the list
Output:
True
False
The not in
operator returns True
if a specified value is not present in the object.
x = ["apple", "banana"]
print("banana" not in x) # False because "banana" is in the list
print("cherry" not in x) # True because "cherry" is not in the list
Output:
False
True
The ternary operator allows you to assign a value to a variable based on a condition.
x = 10
y = 20
result = "x is greater" if x > y else "y is greater"
print(result)
Output:
y is greater
number = 5
result = "Even" if number % 2 == 0 else "Odd"
print(result)
Output:
Odd
The match-case
statement is used for pattern matching and is similar to the switch
statement in other languages.
def http_status(status):
match status:
case 200:
return "OK"
case 404:
return "Not Found"
case 500:
return "Internal Server Error"
case _:
return "Unknown Status"
print(http_status(200))
print(http_status(404))
print(http_status(500))
print(http_status(123))
Output:
OK
Not Found
Internal Server Error
Unknown Status
def day_of_week(day):
match day:
case 1:
return "Monday"
case 2:
return "Tuesday"
case 3:
return "Wednesday"
case 4:
return "Thursday"
case 5:
return "Friday"
case 6:
return "Saturday"
case 7:
return "Sunday"
case _:
return "Invalid day"
print(day_of_week(1))
print(day_of_week(5))
print(day_of_week(7))
print(day_of_week(0))
Output:
Monday
Friday
Sunday
Invalid day
Operator precedence determines the order in which operations are performed in an expression. Operators with higher precedence are evaluated before operators with lower precedence.
Here is a table of operators in Python, listed from highest to lowest precedence:
**
(Exponentiation)+x
,-x
,~x
(Unary plus, Unary minus, Bitwise NOT)*
,/
,//
,%
(Multiplication, Division, Floor Division, Modulus)+
,-
(Addition, Subtraction)<<
,>>
(Bitwise shift operators)&
(Bitwise AND)^
(Bitwise XOR)|
(Bitwise OR)==
,!=
,>
,>=
,<
,<=
,is
,is not
,in
,not in
(Comparisons, Identity, Membership)not
(Logical NOT)and
(Logical AND)or
(Logical OR)if
-else
(Ternary operator)=
(Assignment) and other assignment operators (+=
,-=
,*=
,/=
,//=
,%=
,**=
,&=
,|=
,^=
,>>=
,<<=
)
result = 2 ** 3 * 4
print(result)
Output:
32
Explanation: Exponentiation (**
) has higher precedence than multiplication (*
), so 2 ** 3
is evaluated first, resulting in 8
, and then 8 * 4
is evaluated, resulting in 32
.
result = 2 + 3 * 4
print(result)
Output:
14
Explanation: Multiplication (*
) has higher precedence than addition (+
), so 3 * 4
is evaluated first, resulting in 12
, and then 2 + 12
is evaluated, resulting in 14
.
result = (2 + 3) * 4
print(result)
Output:
20
Explanation: Parentheses have the highest precedence, so the expression inside the parentheses (2 + 3)
is evaluated first, resulting in 5
, and then 5 * 4
is evaluated, resulting in 20
.
result = not (True and False) or True
print(result)
Output:
True
Explanation: The and
operator has higher precedence than not
, so True and False
is evaluated first, resulting in False
. Then not False
is evaluated, resulting in True
. Finally, True or True
is evaluated, resulting in True
.
x = 10
y = 20
result = x < y and y > 15
print(result)
Output:
True
Explanation: Comparison operators (<
, >
) have higher precedence than logical operators (and
), so x < y
and y > 15
are evaluated first, resulting in True
and True
respectively. Then True and True
is evaluated, resulting in True
.
In this chapter, we covered conditional statements, comparison operators, logical operators, identity operators, membership operators, the ternary operator, the match-case statement, and operator precedence.
- Write a program that checks if a number is positive, negative, or zero.
- Write a program that checks if a number is even or odd.
- Write a program that takes a grade as input and prints the corresponding letter grade (A, B, C, D, F).
- Write a program that uses the match-case statement to print the name of the day of the week based on a number (1 for Monday, 2 for Tuesday, etc.).
- Write a program that demonstrates operator precedence by using different operators in a single expression.