3 1 1 If Statement Explained
Key Concepts
The 3 1 1 If Statement in Python is a fundamental control flow statement used to make decisions based on conditions. The key concepts include:
- Basic Structure of an If Statement
- Boolean Expressions
- Indentation and Block Structure
1. Basic Structure of an If Statement
An If Statement allows a program to execute a block of code only if a specified condition is true. The basic structure is:
if condition: # Code to execute if condition is true
Example:
x = 10 if x > 5: print("x is greater than 5")
In this example, the message "x is greater than 5" will be printed because the condition x > 5
is true.
2. Boolean Expressions
The condition in an If Statement is a Boolean expression that evaluates to either True
or False
. Common Boolean operators include >
, <
, ==
, !=
, &&
, and ||
.
Example:
y = 20 if y == 20: print("y is equal to 20")
Here, the condition y == 20
evaluates to True
, so the message "y is equal to 20" will be printed.
3. Indentation and Block Structure
In Python, indentation is used to define the block of code that belongs to the If Statement. The code block is indented by four spaces or a tab. Proper indentation is crucial for the correct execution of the code.
Example:
z = 30 if z < 40: print("z is less than 40") print("This is still part of the if block") print("This is outside the if block")
In this example, both print statements inside the if block will execute if the condition z < 40
is true. The last print statement is outside the if block and will execute regardless of the condition.
Putting It All Together
By understanding the basic structure, Boolean expressions, and indentation in If Statements, you can control the flow of your Python programs effectively. This allows you to create dynamic and responsive applications.
Example:
age = int(input("Enter your age: ")) if age >= 18: print("You are eligible to vote.") else: print("You are not eligible to vote.")
This example takes user input for age, checks if the age is 18 or older, and prints a corresponding message based on the condition.