The Python If Else Statement is an extension to the If (which we discussed in the earlier post). The If condition will only executes the code block when the given condition is true and if the condition is false, it will not execute statements.
In real world, it would be nice to execute something when the condition fails. To do so, Python If else statement is used. Here, Else block will execute the 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 statements will be executed True statements else # When the condition evaluates to FALSE then these statements will execute False statements
If the test condition present in the above Python If else structure is evaluated to true, True statements executed. When it return false, False code executed.
Python If Else Statement Example
In this Python If Else program we are going to place 4 different lines. If the condition is met true, it will display 2 different statements, if the conditional expression evaluated to false we will show the other 2 statements using this else block code.
marks = int(input(" Please Enter Your Subject Marks: ")) if marks >= 50: print(" Congratulations ") #s1 print(" You cleared the subject ") #s2 else: print(" You Failed") #s3 print(" Better Luck Next Time") #s4
Please save this Python file and run the script by pressing F5. We enter 60 as marks, which is greater than 50. That’s why it printed (s1 and s2) inside the If block.
Please Enter Your Subject Marks: 60
You cleared the subject
To demonstrate the else clause, we entered 30 as marks. It means Condition is FALSE so, s3 and s4 inside the else block will print.
First, we asks the user to enter marks. int() restrict the user not to enter non integer values.
If you look at the python if else, If Value stored in the marks variable is greater than or equal to 50, then following print lines will execute. When it is less than 50, below code, inside the Else will execute.