Python – If…Else Condition

IF ELSE is a Decision Condition where a particular condition is true then that block of code is executed else break or different block of code is executed. Condition can be made using Operators such as Assignment, Comparison, Logical, Membership, Identity Operators

StudyGyaan - Python Tutorial - If..Else Condition

Syntax

If ( Condition ) :
   Statement (s)

If Statement

If statement can be written using if keyword. For example –

a = 33
b = 200
if b > a:
  print("b is greater than a")

# Output: b is greater than a

Indentation

Python relies on indentation, using whitespace, to define scope in the code. Other programming languages often use curly-brackets for this purpose.

a = 33
b = 200
if b > a:
print("b is greater than a")

# Output: Indentation Error Please put Indentation

Elif Statement

The elif keyword is pythons way of saying “if the previous conditions were not true, then try this condition”.

x = 100

if (x==10):
print("X is equal to 10")
elif (x==100):
print("X is equal to 100")

Else Statement

The else keyword catches anything which isn’t caught by the preceding conditions.

x = 100

if (x==10):
print("X is equal to 10")
elif (x==100):
print("X is equal to 100")
else:
print("X is not equal 10")

Nested If Else Statement

Nested If Else means Condition inside Condition. For Example:

y = "Hello"

if (x==100):
   if(y=="Hello"):
      print("X = 100 & y = Hello")
   else:
      print("Not true")
Filed under: Python

No comment yet, add your voice below!


Leave a Reply