Selection control statements or conditional branching statements usually jumps from one part of the code to another depending on whether a particular condition is satisfied or not.
Actually, these statements allow us to execute statements selectively based on certain decisions.
Python supports the following conditional branching statements:
- If statement
- Nested if statement
- If-else statement
- If-elif-else statement
It is the simplest form of decision control statement that is frequently used in decision making. An if statement is a selection control statement based on the value of a given Boolean expression.
The general form of a simple if statement is:
If(test_expression): statement-block statement-x
Here ‘statement-block’ may be a single statement or a group of statements. If the test_expression is true, then the statement block is executed; otherwise, statement-block is skipped, and execution jumps to the statement-x.
When the condition is true, both statement-block and the statement-x are executed in sequence.
age=int(input("enter the age:-")) if(age>=18): print("You are eligible to vote")
enter the age:-23
You are eligible to vote
char=input("Enter the character") if(char.isalpha()): print("You have entered a character") if(char.isdigit()): print("You have entered a digit")
Enter the character56
You have entered a digit
science=98 computer=67 language=94 average_marks=(science+computer+language)/3 if(average_marks>=90 and average_marks<=100): print("Grade E") if(average_marks>=80 and average_marks<90): print("Grade A") if(average_marks>=70 and average_marks<80): print("Grade B") if(average_marks>=60 and average_marks<70): print("Grade C") if(average_marks>=40 and average_marks<60): print("Grade D") if(average_marks>=0 and average_marks<40): print("Fail")