If Statement in Python Programming Language
The working and structure of if statement is almost the same in other programming languages. In Python programming language the if statement is a logical expression which is used to evaluate values and returns the results base on the specified results. You can see the demo below:
if test expression: statement(s)
Now we will break down the above if statement.
The above if statement only executes if the test expression is True otherwise it won’t run.
Below is the flow chart of python if statement.
Python if Statement Flowchart
Example of Python if Statement
# If the number is non-zero, Our message will be shown on the screen number = 10 if number > 0: print(number, "is a positive number.") print("When a number is positive this is always printed.") number = -1 if number > 0: print(number, "is a positive number.") print("This is also positive because it is a non-zero number.")
When the above program executes the following result will display.
(10, 'is a positive number.') When a number is positive this is always printed. This is also positive because it is a non-zero number.
In the above example of if statement in Python programming language we see that:
In our above example, the variable number is equal to 10 which is greater than 0 so our test condition become True and code inside of if is executed.
But in the second case where -1 is not greater than 0 so our test condition is not meet the specified condition so it becomes False and the code inside of this if statement will be skipped.