Python if-else statements are used extensively in decision-making code. In real-world applications, there are numerous cases where you must run a certain group of code depending on certain conditions. These statements will help you write logical and efficient code as well as assist you in managing user inputs, validating data, and controlling programs. Here in this article, you will see various ways to implement if-else statements in Python with real-time examples with step-by-step illustrations.
Table of Contents:
- Python Conditional Statements
- Shorthand If and If…Else in Python
- Logical Operators with If…Else Statements in Python
- Using If…Else Statements Inside Functions in Python
- Working with If…Else Statements in Loops
- Best Practices for Using If Statements in Python
- Comparison of Conditional Statements in Python
- Real-World Examples of the If…Else Statement in Python
- Conclusion
Python Conditional Statements
In Python, conditional statements control the flow of a program by making decisions based on the given conditions. These statements help in determining the execution of the programs by evaluating the conditions, such as True or False. This helps in making the Python program more interactive, as it responds to different situations automatically and returns the output. Adding conditional statements to your Python code is necessary to control the program flow and improve the process of decision-making, which makes the code organized and efficient.
There are 4 types of conditional statements in Python:
- if statement
- if-else statement
- if-elif-else statement
- Nested if statement
1. If Statement in Python
The if statement checks a condition and executes the code only if the condition is True and does not return any output if the condition is False. It is very useful for controlling the flow of the program and helps ensure that the specific code runs only when it is needed.
Syntax:
if condition: # Code to execute if the condition is True # This block runs only when the condition is met
Example:
Output:
Explanation: Here, the program checks if the age is greater than or equal to 16, prints a message if the condition is true, and does not return any output if the condition is False.
2. If…Else Statement in Python
The if-else statement runs one block of code if the condition is True and another if the condition does not match and is False. This ensures that the Python programs return some statements.
The following flowchart will show you how the If…Else statement in Python works:
Syntax:
if condition: # Statement executes if the condition is True else: # Statement executes if the condition is False
Example:
Output:
Explanation: Here, it is checked whether the marks are equal to or more than 60, and prints the message only if the condition is satisfied.
3. If…Elif…Else Statement in Python
The if-elif-else statement checks multiple conditions one after the other and executes the condition that is satisfied first and is true. It is useful if there is a possibility of multiple results.
Syntax:
if condition1: # Code executes if condition1 is True elif condition2: # Code executes if condition1 is False and condition2 is True else: # Code executes if neither condition1 nor condition2 is True
Example:
Output:
Explanation: Here, different messages are assigned based on the value of the score.
4. Nested if Statement in Python
A nested if statement is an if statement inside another if. It is used when multiple conditions should be met and returns the statement only if all the conditions are satisfied.
Syntax:
if condition1: if condition2: # Statement if both conditions are True
Example:
Output:
Explanation: Here, it is checked if the age of the user is more than 16, then confirms course registration before displaying the message.
Shorthand If and If…Else in Python
Shorthand if and if-else is nothing but a way to write the if and the else block without any indentation in a single line. This is very useful when we have only one statement to be executed in the if block and the else block.
Shorthand If Syntax:
# Syntax for a shorthand if statement if condition: statement
Example:
Output:
Explanation: Here, if the completion_percentage is more than 80 percent, then the message is printed.
Shorthand If…Else Syntax:
# Syntax for a shorthand if-else statement statement_if_true if condition else statement_if_false
Example:
Output:
Explanation: Here, if marks are 60 or more, it prints “Congratulations! You passed the Intellipaat exam!”. Otherwise, it prints “Keep learning and try again!”.
Logical Operators with If…Else Statements in Python
Logical operators help to combine multiple conditions in if-else statements, which makes the decision-making more flexible. They allow checking multiple conditions at once instead of writing separate if statements.
1. Using ‘and’ Logical Operator with If-Else in Python
The and keyword is used when multiple conditions need to be checked. It makes sure that, to execute the statement, both conditions must be true. If any condition is False, it returns another statement.
Example:
Output:
Explanation: Here, the and operator ensures that both conditions (num > 10 and num < 20) must be True.
2. Using or Logical Operator with If…Else in Python
The or keyword is used when at least one of the conditions mentioned is True. If any condition is True, the block under it is executed. If both conditions are False, the other statement, which is given inside the else block, is executed.
Example:
Output:
Explanation: Here, the ‘or’ operator checks if at least one condition is True. Since num is less than 10, the statement is executed, even though num is not greater than 50.
3. Using not Logical Operator with If…Else in Python
The not keyword is used to reverse a condition. If the condition is True, then this keyword makes it False. This is useful when checking for the opposite of a condition.
Example:
Output:
Explanation: Here, the not operator gives the condition num > 0. Since num is not greater than 0, the statement under the if is executed successfully.
Using If…Else Statements Inside Functions in Python
Using if-else statements inside Python functions makes the code more structured, reusable, and efficient. Functions allow you to encapsulate logic and execute conditional checks based on user input or given values.
Example:
Output:
Explanation: Here, the function check_voting_eligibility(age) checks if the age of the voter is greater than or equal to 18 and prints the eligibility status.
Working with If…Else Statements in Loops
If-Else statements inside loops allow decision-making during each iteration, which helps to execute different blocks of code based on conditions.
Using If…Else in a For Loop
A for loop runs a block of code a fixed number of times, and if-else inside it checks conditions for each iteration.
Example:
Output:
Explanation: The loop runs from 1 to 5. The if condition checks whether the number is even or odd and prints the result accordingly.
Using If…Else in a While Loop
A while loop runs repeatedly as long as a condition is True, and if-else inside it helps make decisions during each iteration.
Example:
Output:
Explanation: The loop starts at 5 and decreases until it reaches 0, printing a different message for zero.
Best Practices for Using If Statements in Python
- Use Proper Indentation: Always keep code within if, elif, and else properly indented, which helps to prevent mistakes and increase the readability.
- Keep Conditions Simple: Complex conditions should not be used, and always try to break the condition into smaller parts to make it simple to understand the condition.
- Use elif instead of Multiple if: When there are multiple conditions to be checked, elif has to be used so that the checking can be stopped once the condition is matched.
- Include else: The else statement has to be added to return some message when the condition is not True.
- Use Boolean Variables: A proper variable name has to be given for the True or false condition. You can use marks when you are adding marks instead of the variables x and y, which helps in improving the readability.
Comparison of Conditional Statements in Python
Features | if Statement | If…Else Statement | If…Elif…Else Statement | Nested if Statement |
Speed | Fast, as it checks only one condition. | Fast, as it checks one condition, then stops, | Moderate, checks conditions one after other until a match is found. | Slow, checks conditions inside conditions, which increases the time for execution. |
Readability | Very easy to understand, as it’s a single condition. | Clear and simple, as it handles two outcomes directly. | Clear but can be long, mainly when there are multiple conditions. | Difficult to read, as there are multiple statements used with a lot of indentations. |
Efficiency | Runs only when needed, but lacks a fallback option. | Efficient because there are no unnecessary checks. | More efficient compared to multiple if statements | Less efficient as each condition must be checked separately. |
Flexibility | No, only for one condition. | Flexible, but only for two conditions. | Very flexible, handles multiple conditions. | Less flexible, as one condition depends on another. |
Code Length | Short and simple with only one condition. | Short and structured, as it handles two conditions. | Moderate length and structured | Lengthy compared to others, as there are multiple nested conditions, |
Best for | Simple and single conditions, like checking if the numbers are positive. | For two choices, like checking pass or fail. | Selecting one from many, like choosing colours. | When one condition depends on the other. |
Real-World Examples of the If…Else Statement in Python
The Python If…Else statement is used in many real-world cases. Now let’s see some of the most common use cases of it.
- Checking Exam Results
Output:
Explanation: If the marks are greater than or equal to 60, it prints a pass message. Otherwise, it prints a fail message.
- Checking Login Credentials
Output:
Explanation: If both the username and password match, the login is successful. Otherwise, it fails.
- ATM Cash Withdrawal
Output:
Explanation: If the withdrawal amount is less than or equal to the balance, the transaction proceeds; Otherwise, it fails.
Conclusion
The Python if-else statement is essential in controlling program flow and decision making. It is important to use the conditional operators like if statements, if-elif-else blocks, and shorthand expressions, which can be used to write simple 1 line statements along with the condition to write a clean, efficient, and organized Python Code. Learn these conditional statements thoroughly, and you will be able to write logic in different situations and improve the logic of your program.
To take your skills to the next level, enroll in our Python training course and gain hands-on experience. Also, prepare for job interviews with our Python interview questions, prepared by industry experts.
The if-else statement enables decision-making in Python by running a piece of code if a condition is True and another code if the condition is False.
No, the else has to be used after an if statement since it serves as a default statement if the condition is not satisfied.
If there is no else, Python simply skips the if block when the condition is False and executes the rest of the code.
No, an if-else statement can only have a single else block, but many conditions can be addressed with elif.
It is a concise method to express if-else in one line, which makes the code more readable and compact.