Python

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.

if-else 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.

Python if-else 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')

 

Python if-else Statement

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: