HOW TO USE IF ELSE IN THE PYTHON?

Using the if keyword in the Python

Syntax-

if <Logical_Condition>:

<if_block>

When <Logical_Condition> returns True value then the code given in <if_block> will execute as shown in below example-

a = 50
b = 100
if b > a:
  print("b is greater than a")

Output

b is greater than a

Using the Elif keyword in the Python

The Elif keyword is used to provide another Logical Condition in case the previously provided condition is not true, as shown below-

a = 50
b = 100
if b < a:
  print("b is less than a")
elif a < b:
  print("a is less than b")

output

a is less than b

Using the Else keyword in the Python

The else keyword executes the else block in case all the preceding conditions return False

a = 50
b = 50
if b < a:
  print("b is less than a")
elif a < b:
  print("a is less than b")
else:
  print("a is equal to b")

output

a is equal to b

We can also use else without the elif as shown in the below example

a = 100
b = 50
if b > a:
  print("b is greater than a")
else:
  print("b is not greater than a")

output

b is not greater than a

Using Short Hand If or one-line if statement

a=100
b=50
if a > b: print("a is greater than b")

output

a is greater than b

Using Short Hand If else or one-line if else statement

a = 50
b = 100
print("A") if a > b else print("B")

output

B

Nested If

We can put if statements inside if statements, this is called nested if statements as shown in below example

x = 100
if x > 10:
  print("Above ten,")
  if x > 20:
    print("and also above 20!")
  else:
    print("but not above 20.")

output

Above ten,
and also above 20!

The pass Statement

The if statements cannot be empty, but if we have an if statement with no content, we can put in the pass statement to avoid getting an error.

a = 50
b = 100
if b > a:
  pass
Print("We are out of if block without any error")

output

We are out of if block without any error

Posted

in

Tags:

Comments

Leave a Reply