The operators alone cannot help you achieve anything. For example, if you want to assign grades to the students in a class, you can add the marks of the students in each subject to find the total obtained marks and use the division operator to find the percentage. But how would you assign grades based on the percentages dynamically? This is where the conditional statements come into play.
Generally, a program is executed from top to bottom and left to right. But, in certain conditions, we need to change this flow in order to achieve the desired result. The Control Flow statements help you execute blocks of codes according to certain conditions. The interpreter or compiler decides to execute a code block according to the result of the given condition. In this article, we will explore these statements and write a final program to assign the grades to the students based on their percentages. Stay tuned!
Conditional Statements
Conditional Statements are used to implement the decision-making in Python. When there is a need to decide which block to execute, the compiler or interpreter evaluates a condition and decides according to the result of that condition.
To understand this, there are 2 ways to go to your friend’s house. If you choose Way 1, you can reach his house earlier. Whereas, if you select Way 2, it will take you more time to reach their house. Of course, you cannot go both ways, so which way will you choose? If you consider convenience, you will choose Way 1. This is the type of situation we need conditional statements in programming.
There are three types of conditional statements in Python:
- if statement
- if-else statement
- if-elif-else statement
‘if’ Statement
The ‘if’ statement is used in basic conditions. It executes the block of code if the condition is True and does nothing if it’s False.
Syntax:
if condition:
#statement(s) to execute
Example:
weather = 30
if weather <= 30: # Here, the condition is True, so it prints the following statement.
print("Weather is moderate.")
Output:
Weather is moderate.
‘if-else’ Statement
The ‘if-else’ statement is used to execute a block of code if the condition is True and another block of code if it’s False. It is better than using plain ‘if’ since the user still gets a response if the condition is false.
Syntax:
if condition:
# Statement(s) if the condition is True.
else:
# Statement(s) if the condition is False.
Example:
weather = 40
if weather <= 30: # Here, the condition is False,
print("Weather is moderate.") # so this statement is ignored.
else:
print("Weather is hot.") # And this statement is executed.
Output:
Weather is hot.
‘if-elif-else’ Statement
The ‘if-elif-else’ statement is used to evaluate multiple conditions. It goes through the conditions one by one unless a True one is found. It then executes the code following the True condition. The rest of the blocks are ignored. If none of the conditions is found to be True, the else block is executed.
Syntax:
if condition:
Statement(s)
elif condition:
Statement(s)
elif condition:
Statement(s)
else:
Statement(s)
Example:
# Finding if a number is positive or negative
number = -10
if number > 0: # False
print(number, " is positive.") # This statement is ignored.
elif number < 0: # True
print(number, " is negative.") # This statement is executed.
else:
print(number, " is zero.")
Output:
-10 is negative.
Nested Conditionals
Python allows you to use if within if, else within else, and elif within another elif statement. This concept is called Nesting. You can use any statement within another statement according to your requirements.
Syntax:
if condition: # if this condition is true,
if condition: # this condition is checked. If this is True,
Statement(s) # this statement is executed.
else:
Statement(s)
else: #if the first condition is False,
Statement(s) # This statement is executed.
Example:
user_status = "Logged in"
user_role = "Admin"
if user_status == "Logged in": # True
if user_role == "Admin": # True
print("You are logged in as an administrator.") # Executed!
else:
print("You are logged in as a user.")
else:
print("You are not logged in.")
Output:
You are logged in as an administrator.
Please note that a nested condition is only evaluated if the outer condition is True. If the outer condition is False, the inner condition is ignored by the compiler or interpreter.
Indentation
Many programming languages rely upon curly braces to define code blocks. Whereas Python uses indentation to identify the beginning and ending of the code blocks. It is highly crucial to maintain a proper indentation while using decision constructs and defining multiple code blocks. Else, you will get indentation errors or unexpected output.
Assigning Grades to Students – Practice Project
To practice what we have learned above, we will write a program to find the grades of the students based on their percentages.
marks_english = 40
marks_science = 50
marks_maths = 70
marks_total = 300
grade = "" # Will be assigned later
total_obtained_marks = marks_english + marks_science + marks_maths # Calculate total marks obtained by the student
percentage = total_obtained_marks/marks_total * 100 # Calculate the percentage
if percentage >= 80: # if this is true, the grade will be A1.
grade = "A1"
elif percentage >= 70: # if this is true, the grade will be A.
grade = "A"
elif percentage >= 60: # if this is true, the grade will be B.
grade = "B"
elif percentage >= 50: # if this is true, the grade will be C.
grade = "C"
else: # if all the above conditions are false, the grade will be Fail.
grade = "Fail"
print("Your Grade is: ", grade)
Output:
Your Grade is: C
To make the above example more interesting, calculate the total marks of at least 7 subjects. For further practice, you can write programs to find whether a number is even or odd and a letter is a vowel or consonant. You can find many programming exercises online to enhance your coding skills. Ensure to get a good hands-on experience with these fundamental concepts as they are used widely in advanced computer programming. In the next article, we will learn the loop constructs that allow you to execute a block of code multiple times.