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.
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,
False
, and this condition(boolean_expression-2) is True
.False
.True
or False
.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.
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.
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.