Python if-else Statement
Python if-else Statement
Let’s learn about Python’s if-else statement in this tutorial. The if statement executes a simple or compound statement when the logical expression provided in the if statement is evaluated to be true. An else statement contains the block of code that gets executed if the conditional expression in the statement evaluates to 0 or false.
Syntax
The general syntax of if… else statement is as follows
if condition:
statement(s)
else:
statement(s)
The logical condition or expression associated with if is evaluated; if the condition is evaluated to be true, then the code statements following the if block are executed. If the test condition is evaluated to be false, then the code statements associated with the else block are executed. The else statement is optional; only one else statement can follow the if.
Example
Let’s understand the concept with the help of an example. An example of an if-else statement is to decide whether a given number is even or odd.
# Python program for if-else demo # Python Tutorials - www.TestingDocs.com number = input('Enter a number:=') # Prompt user number = int(number) # convert to integer if number % 2 == 0: print('Number is even') else: print('Number is odd')
We can see that when the test expression number %2==0 is evaluated to be true, the if block is executed. The output is displayed as “Number is even”
We can see that when the test expression number %2==0 is evaluated to be false, the else construct output is displayed as “Number is odd” for a false test condition.
—
Python Tutorials
Python Tutorial on this website can be found at:
https://www.testingdocs.com/python-tutorials/
More information on Python is available at the official website: