In real life, there are times when we must make decisions and then decide what to do next based on those decisions. Similar circumstances exist in programming, where we must make decisions and then execute the following block of code depending on those decisions. In programming languages, decision-making statements determine the course of program execution. In Python, if else, elif statement is used for decision making. In this session we will learn about if statement.
The syntax of the if-else statement is −
if expression:
statement 1(s)
if expression:
statement 2(s)
if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.
Example:
# If the number is positive, we print an appropriate message
num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")
num = -1
if num > 0:
print(num, "is a positive number.")
print("This is also always printed.")
Output:
3 is a positive number
This is always printed
This is also always printed.