If Statement in Python
An if statement in Python is used to execute a block of code only if a specified condition is true. It allows you to control the flow of your program by checking conditions and performing different actions based on the results.
Syntax of the if Statement
Here’s the basic syntax of an if statement in Python:
- The keyword if is followed by a condition (or expression).
- If the condition evaluates to True, the block of code underneath the if statement runs.
- If the condition evaluates to False, the block is skipped, and the program continues to the next - statement after the if block.
Indentation in Python
Python relies on indentation (typically 4 spaces) to define the blocks of code associated with control structures. This is different from many other programming languages that use curly braces {}
. So, proper indentation is crucial in Python.
Checking a Simple Condition
Let’s start with a simple example that checks if a number is positive.
Checking a Boolean Variable
The condition in an if statement can also be a boolean value. Let’s explore how it works.
More Complex Conditions
You can use comparison operators (<, >, ==, etc.)
or logical operators (and, or, not)
in the if condition.
Common Pitfalls with if Statements
Forgetting Indentation In Python, the code block after the if statement must be indented. Forgetting to indent will raise an error.
Using Assignment
(=)
Instead of Comparison(==)
Another common mistake is using a single equals sign
(=)
instead of a double equals sign(==)
. Remember,=
is for assignment, while==
is for comparison.
Nested If Statements
You can place an if statement inside another if statement to check multiple conditions in sequence.
Explanation:
The first if checks if the person is 18 or older. The second if inside the first one checks if the person is younger than 21. If both conditions are satisfied, the message will be printed.
Exercise: if Statements
Write a program that checks if a number entered by the user is even or odd.
Hint:
Use the modulus operator % to find the remainder of a division.
If the remainder of the number divided by 2 is 0, it’s even.Create a program that takes the temperature as input and prints “It’s freezing!” if the temperature is below 0.
Hint:
check if the temperature is less than 0.