ScanSkill

If statement

This if statement is used to control decision-making by checking True or False statements resulting in different executions of code, depending on if the result is True and if the result is False.

There are parts to the if statement: if, elif, and else.

Syntax

if boolean_expression-1:
   statement(s) # code to execute if boolean_expression_1 is True.
elif boolean_expression-2:
   statement(s) # code to execute if boolean_expression_1 is False, and boolean_expression-2 is True
else:
   statement(s) # code to execute if none of the above expressions are True

Here,

  • if: starts the if statement.
  • elif: Optional. Executes the below code if the if condition(boolean_expression-1) is False, and this condition(boolean_expression-2) is True.
  • else: Optional. Executes the below code if all the if and elif conditions(boolean_expression-1, …) are False.
  • boolean_expression(s): Required. A boolean expression that results in either True or False.
  • statement(s): Block of code to be executed.

Note: There can be multiple boolean expressions. And boolean expressions are connected using logical operators.

Nested if (else) statements are the inclusion of another one or multiple if statements within an if statement block.

Examples

  • if only statement
>>> string1 = "cloudyfox"
>>> if string1 == "cloudyfox": # True condition
...     print("This is an IT company.")
... 
This is an IT company.
>>> string1 = "cloudyfox"
>>> if string1 == "cloudy": # False condition
...     print("This is an IT company.")
... 
  • if else statements
>>> string1 = "cloudyfox"
>>> if string1 == "cloudyfox": # True condition
...     print("This is an IT company.")
... elif:
...     print("This is not an IT company.")
... 
This is an IT company.
>>> string1 = "cloudyfox"
>>> if string1 == "cloudy": # False condition
...     print("This is an IT company.")
... else:
...     print("This is not an IT company.")
... 
This is not an IT company.
  • if elif else statement
>>> string1 = "google"
>>> if string1 == "cloudyfox": 
...     print("This is an IT company.")
... elif string1 == "cloudy":
...     print("This is not an IT company.")
... else:
...     print("This company doesn't exist.")
... 
This company doesn't exist.
  • Nested if statement
>>> marks1 = int(input("Enter your marks: "))
>>> if marks1 >= 60:
...     if marks1 >= 80:
...         print("Congrats! You passed with distinction.")
...     else:
...         print("Great! You passed with good grades.")
... else:
...     print("Your score is less than 60.")
... 
Enter your marks: 90
Congrats! You passed with distinction.

# Output 2
Enter your marks: 65
Great! You passed with good grades.

# Output 3
Enter your marks: 53
Your score is less than 60.