Python 3 – IF Statement
One of the most essential components of programming is conditional statements. In most cases, programs require a way to make decisions based on certain conditions. This is where the IF statement comes in. In python 3, the IF statement is used to test a condition and execute a code block if the condition is met.
Syntax of the IF Statement
The IF statement follows the syntax below:
if condition:
code to be executed if the condition is true
The if keyword is followed by the condition to be evaluated, then a colon sign. The code block to be executed if the condition is met must be indented.
Example: Using the IF Statement
Let us see a basic example below:
number = 5
if number > 3:
print("The number is greater than 3")
This code block will print “The number is greater than 3” to the console because 5 is greater than 3. If the number was less than or equal to 3, the code block would not have been executed.
Multiple IF Statements
Sometimes, we need to test multiple conditions at once. We can use the IF statement alongside the elif and else statements.
The syntax for using multiple conditions is shown below:
if condition1:
code to be executed if condition1 is true
elif condition2:
code to be executed if condition2 is true
else:
code to be executed if both conditions above are false
Example
age = 20
if age < 10:
print("You are a Kid")
elif age < 18:
print("You are a Teenager")
else:
print("You are an adult")
In the code block above, the output will be “You are an adult” since the age is greater than or equal to 18.
Nested IF Statements
We can also use nested IF statements when we need to check for additional conditions within the code block of a previous IF statement. This concept of IF statement within another IF statement is called nesting.
Example
a = 5
b = 6
if a > 0:
print("a is greater than 0")
if b > 0:
print("b is greater than 0")
else:
print("a is not greater than 0")
In the code block above, the output will be “a is greater than 0” and “b is greater than 0” since both conditions are met.
Logical Operators with IF Statement
Logical operators can be used along with the if statement to test for multiple conditions. The common logical operators are AND, OR and NOT.
Example
a = 5
b = 6
c = 7
if a > 0 and b > 0 and c > 0:
print("All numbers are greater than 0")
In the code block above, the output will be “All numbers are greater than 0” since all conditions are met.
Conclusion
The IF statement is an essential component of programming that allows you to execute a code block depending on a specific condition. Multiple conditional statements can be achieved using the elif and else statements. Nested IF statements and logical operators can also be incorporated to test for multiple conditions. With this knowledge, you can write reliable programs that can make decisions based on specific conditions.