If Statement Python

If Statement Python is the decision-making control statements in Python which decides the direction of flow of program execution. As we have seen the different types of operators in the last tutorial, in the next few tutorials, we can learn how to use those operators along with conditions. In this tutorial, we will cover the ‘If Else’ loops.

IF ELSE:

IF:

The “If” statement starts with the “if” keyword followed by the condition.

a=3
b=2
if a>b:
  print("a is greater than b")

First and foremost, we need to understand in python we use indentation (whitespace at the beginning of a line) to define the scope of the code. Whereas in other programming languages, curly brackets are used to define the scope. The block of code that follows the ‘if’ statement at the same indent level will be executed if the condition is true.

In the above example, the statement “a is greater than b” will get printed only if variable a is greater than b. Nothing will get printed in case, the variable b is greater than a.

ELSE:

Suppose you want to execute the negative condition of ‘if’ condition, then ‘else’ statement is used. The ‘else’ statement is just an ‘else’ keyword.

a=3 
b=4
if a>b: 
   print("variable a is greater than variable b")
else:
   print("variable b is greater than variable a")

ELIF:

In the above example, we are testing only two conditions. Either a is greater than b or b is greater than a. If there is more than one condition to test, then ‘elif’ statement is used.

a=4
b=4 
if a>b: 
  print("variable a is greater than variable b") 
elif a==b:
  print("variable a and variable b are equal")
else: 
  print("variable b is greater than variable a")

Single line If Statement Python:

If there is only one statement to execute, then we can write the statement and if condition in the same line.

a=5
b=4 
if a>b: print("a is greater than b")

Single line If Statement Python:

If there is only one statement to execute, one for if, and one for else, we can put it all on the same line:

a=4
b=5 
print("a is greater than b") if a>b else print("b is greater than a")

Logical Operators: AND and OR

The and and or keywords are logical operators. We can combine two or more if statements using the and and or operators.

a=8
b=9
c=6
if a>b and a>c:
  print("a is greatest")
elif b>c:
  print("b is greatest")
else: 
  print("c is greatest")
a=8
b=9
c=6
if a>b or a>c:
  print("a is greater than either b or c")

Nested If Statement Python:

If there is an ‘if’ statement inside ‘if’ statement then it is called ‘nested if’ statement.

a=15
if a>10:
  if a>20:
    print("a is greater than 20")
  else:
    print("a is greater than 10")
Translate »