If-else statements in Python

if statements are useful for comparing and if the provided if condition is true then the code inside the if block will be executed or else, the block of code will be skipped for execution. there is no curly{ } , braces for sub-block of code, so in python we use indentation, indentation is know as providing 4 spaces or more after functions or statements

simple if statement

syntax:

if condition:
<indented statement 1>
<indented statement 2>
<non-indented statement>

observe the syntax provided above,if the condition returns true than the two indented statements will be provided. Otherwise if used doesn't provide indention to the lines of code,which comes under the above if condition,those block doesn't has any condition and they will be executed whether the above condition is true or false

example:

number = int(input("Enter a number: "))
if number%2==0:
print(f"Number{number} is even")
Enter a number: 4
Number4 is even

if-else statement

if-else statements allows us to handle two types of results True or false of the given condition.

if condition:
# if block
statement 1
statement 2
statement n
else:
# else block
statement 3
statement 4
statement n

you can see the syntax above,if the condition is True then the if block statements will be executed,if the same above condition is False then the else block statements will excited by skipping if block statements. Indention is mandatory here ,if you failed to give indentation before line's of sub blocks like if or else block,then compiler will throw an error

example:

number = int(input("Enter a number: "))
if number%2==0:
print(f"Number{number} is even")
else:
print(f"Number{number} is odd")

OUTPUT:

Enter a number: 5
Number5 is odd
Enter a number: 4
Number4 is even

else block initiation should be exactly below the if block initiation,if this rule fails compiler throws an error

Nested if-else

nested if-else is called as if-else statement inside another if-else block

if-elif-else statement

instead of writing multiple if-else statements we can use if-elif statements .

if condition_1:
# if block
statement
statement
more statement
elif condition_2:
# 1st elif block
statement
statement
more statement
elif condition_3:
# 2nd elif block
statement
statement
more statement
else :
statement
statement
more statement

now, the compiler checks conditions from condition 1,if any of the conditions are true , then respective elif block will be executed but , when all conditions are false then else block will be executed .if there are multiple conditions are True ,then the first occurrence of True, that block will be executed and loop breaks.

example:

score = int(input("Enter your marks: "))
if score >= 90:
print("Your grade is A")
elif score >= 80:
print("Your grade is B")
elif score >= 70:
print("Your grade is C")
elif score >= 60:
print("Your grade is D. ")
else:
print("You failed in the exam")
Enter your marks: 50
You failed in the exam
Last updated on by vishal devxo