Python if-else
Python if-else
The else statement is associated with if statement. An else statement executes if the conditional expression in if the statement becomes false or a Zero value.
If the conditional expression is false, then control transfers to the else block. An else statement is optional, and there could be only one else statement.
Syntax
The syntax of the if…else statement is following.
if expression:
Statement
else:
statement
The colon (:) is important because it splits the condition from the statements to be executed after the evaluation of the condition. This is especially important for statements where there is only a single statement and the bracket ( ) is not used.
Flow Diagram
In the above flowchart, first it checks the condition if the condition is true, then conditional code (if statement) will be executed. If the condition is false, then else block (else statement) will be executed.
The if…else statement examples are the following:
- Write a program to check number is even or odd
num = int(input(
"Enter the number"
))
if
num%2==0 : print(num,
"is a even number"
)
else
: print(num,
"is a odd number "
)
Output:
Enter the number 25 25 is odd number
- Write a program to check the voter’s age for valid for voting or not
age = int(input(
"Enter the age"
))
if
age<18: print(
"You are not eligible for Voting"
)
else
: print(
"You are eligible for Voting"
)
Output:
Enter the age 17 You are not eligible for Voting
- Write a program to display student marks
score_theory = int(input("Enter theory marks:")) practical = int(input("Enter practical marks:")) total = score_theory+practical if practical+score_theory>100: print("Please check the input. Score exceeds total possible score.") else: print("Score validated. Your total is: ",total)
Output:
Enter theory marks: 60 Enter practical marks: 45 Score validate. Your total is: 95