In Python, the if statement test expression is evaluated, and if the result is True, the statement(s) followed by the expression is evaluated; else, if the expression is False, the statement is skipped by the compiler.
But what if we want a separate set of statements to be executed when the expression returns a zero value? In such a case, we use an if-else statement rather than using a simple if statement. Actually, the if-else statement is an extension of the simple if statement.
The general form is:
if(test expression): True-block statement(s) else: False-block statement(s) statement-x
If the test expression is true, then the True-block statement(s) immediately follows if the statement is executed; otherwise, the False-block statement(s) are executed. In either case, either true-block or false-block is executed, not both. In both cases, the control is transferred subsequently to the statement-x.
Python if-else Examples
number=int(input("Enter the value of number:-")) if(number%2==0): print("The number is Even") else: print("The number is Odd")
Enter the value of number:-89
The number is Odd
char=input("Enter the character:-") if(char.isalpha()): if(char.isupper()): print("The entered value is an Alphabet and is in Uppercase") else: print("The entered value is an Alphabet and is in Lowercase") else: print("The entered value is a digit")
Enter the character:-A
The entered value is an Alphabet and is in Uppercase