Python If Else Statement

The Python If Else Statement is an extension to the If (which we discussed in the earlier post). If condition only executes the code block when the given condition is true and when the condition is false, it will not execute the code.

In the real world, it would be nice to execute something when the expression fails. To do so, the Python If condition is used, and here, the Else block will run some code when the condition fails.

Python If Else Syntax

The syntax of the Python If Else Statement is

if (Test condition):
     # The condition is TRUE then these lines will be printed
     True codes
     # When the condition evaluates to FALSE then these lines will print
     False codes

When the test condition present in the above Python If else structure is evaluated to true, True statements are executed. When it returns false, a False code is executed.

If Else Statement Example

In this Python If Else statement program, we will place 4 different lines. When the condition is met true, it will display 2 distinct lines. When the conditional expression evaluates to false, we will show the other 2 statements using this else block code.

# Example
marks = int(input(" Please Enter Your Subject Marks:  "))
if marks >= 50:
    print(" Congratulations ") #s1
    print(" You cleared the subject ") #s2
    print(" You Failed") #s3
    print(" Better Luck Next Time") #s4

Please save this file and run the script file by pressing F5.

We enter 60 as marks for the demo purpose, which is greater than 50. That’s why the Python if else program printed (s1 and s2 statements) inside the If block.

Please Enter Your Subject Marks: 60
You cleared the subject

We entered 30 as marks. It means the Condition is FALSE, so s3 and s4 inside the else block will print.

Python If Else Statement 5

First, we ask the user to enter marks. int() restricts the user not to enter non-integer values.

When you look at the Python if else statement example, the Value stored in the marks variable is greater than or equal to 50, then the following print lines will execute. If it is less than 50, the below code inside Else will execute.

About Suresh

Suresh is the founder of TutorialGateway and a freelance software developer. He specialized in Designing and Developing Windows and Web applications. The experience he gained in Programming and BI integration, and reporting tools translates into this blog. You can find him on Facebook or Twitter.