Python Coding Day 6 | if Condition & Operators
If Condition & Operators
Watch the lesson tutorial 🔻
The if condition is a fundamental concept in programming that allows your code to make decisions and execute different blocks of code based on whether a certain condition is True or False.
The Basic Structure
The structure you provided is a standard if/else block:
if condition:
# This code runs if the 'condition' is True.
do this
else:
# This code runs if the 'condition' is False.
do this
Practical Example Code
This example checks if a student's score is high enough to pass an exam.
score = 75
passing_grade = 60
if score >= passing_grade:
print("✅ Congratulations! You passed the exam.")
else:
print("❌ Unfortunately, you did not pass. Try again.")
# Output for score = 75: ✅ Congratulations! You passed the exam.
# Output for score = 50: ❌ Unfortunately, you did not pass. Try again.
💻 Relational and Equality Operators
In Python, conditions are formed using operators that compare values. The most common ones are relational (comparison) and equality operators. They always return either True or False.
| Operator | Description | Example | Result |
> | Greater Than: Checks if the left value is larger than the right. | 10 > 5 | True |
< | Less Than: Checks if the left value is smaller than the right. | 10 < 5 | False |
>= | Greater Than or Equal To: Checks if the left value is larger than or equal to the right. | 10 >= 10 | True |
<= | Less Than or Equal To: Checks if the left value is smaller than or equal to the right. | 10 <= 9 | False |
== | Equal To: Checks if two values are exactly the same. (Note the double equals sign!) | 5 == 5 | True |
!= | Not Equal To: Checks if two values are different. | 5 != 6 | True |
Practical Example Code
user_age = 18
legal_drinking_age = 21
# Example uses of operators in 'if' conditions
if user_age < legal_drinking_age:
print("Underage. Cannot purchase alcohol.")
if user_age == 18:
print("You are exactly 18 years old.")
if user_age != legal_drinking_age:
print("Your age is not the legal drinking age.")
# Output:
# Underage. Cannot purchase alcohol.
# You are exactly 18 years old.
# Your age is not the legal drinking age.
🔢 Explaining the Odd/Even Calculator Code
The Python code you provided is a complete and robust application that determines if an integer is even or odd. It uses input(), the if/else condition, the modulo operator (%), and error handling (try/except).
The Code Breakdown
# Prompt the user to enter a number
num_str = input("Enter an integer: ")
try:
# Convert the input string to an integer
num = int(num_str)
# Check if the number is even or odd using the modulo operator
if (num % 2) == 0:
print(f"{num} is an even number.")
else:
print(f"{num} is an odd number.")
except ValueError:
print("Invalid input. Please enter a valid integer.")
Key Concepts Explained
1. The Modulo Operator (%)
The core of this calculator is the modulo operator (%). The modulo operator returns the remainder of a division.
An even number is any integer that can be divided by 2 with a remainder of 0.
Example: $6 \div 2 = 3$ remainder 0. So, $6 \% 2$ equals 0.
An odd number is any integer that can be divided by 2 with a remainder of 1.
Example: $7 \div 2 = 3$ remainder 1. So, $7 \% 2$ equals 1.
The condition (num % 2) == 0 is the check: If the remainder of dividing the number by 2 is equal to 0, the number is even. Otherwise (in the else block), it must be odd.
2. Input and Type Conversion (input() and int())
num_str = input("Enter an integer: "): This pauses the program and waits for the user to type something. The result is always stored as a string (text) in thenum_strvariable.num = int(num_str): Since mathematical operations (like%) only work on numbers, theint()function is used to convert the text input into an integer (a whole number).
3. Error Handling (try and except)
This part makes the code robust. What if the user types "hello" instead of a number?
try:: The code inside this block is attempted first. If the conversionint(num_str)fails (because "hello" cannot be converted to an integer), Python raises aValueError.except ValueError:: If aValueErroroccurs in thetryblock, the program jumps immediately to this section, preventing the program from crashing and printing a friendly error message instead:"Invalid input. Please enter a valid integer."
- by Chirana Nimnaka

Comments
Post a Comment