CONDITIONAL STATEMENTS IN PYTHON
Python conditionals are fundamental programming structures to make decisions and control the flow of your code based on certain conditions. The three main conditional statements in Python are the “if”, “elif” (short for “else if”), and “else” statements. These statements are powerful to create dynamic and flexible programs.
1. Introduction to Conditionals
Conditionals evaluate Boolean expressions to determine whether they are true or false. The conditional statements then direct the flow of the program accordingly.
People encounter conditional decisions in their daily lives, such as deciding whether to take an umbrella if it’s raining. Similarly, conditional statements in programming are intended to take different actions based on different input conditions. In Python there are several comparison operators, logical operators, and control structures to facilitate these decisions.
2. The “if” Statement
The “if” statement is the most basic conditional statement in Python. It executes a block of code only if a condition is true. The structure of an “if” statement includes the “if” keyword, a conditional expression, and an indented code block.
Basic “if” Statement Structure
The syntax of a basic “if” statement in Python is as follows:
# code block to execute if condition is true
The condition is a Boolean expression that evaluates to either True or False. If the condition is true, the code following the “if” statement is executed. If the condition is false, the line is skipped, and the program continues to the next statement.
Using Comparison Operators in “if” Statements
To evaluate conditions in “if” statements, you can use comparison operators such as:
“==”: Equal to,
“!=”: Not equal to,
“<“: Less than,
“>”: Greater than,
“<=”: Less than or equal to,
“>=”: Greater than or equal to.
For example, consider the following “if” statement that checks if a number is positive:
num = 5 if num > 0: print("The number is positive.")
If the value of “num” is greater than 0, the condition inside the “if” statement is right and the message “The number is positive.” will be printed.
Combining Conditions with “and” and “or” Operators
To combine multiple conditions, you can use the logical operators “and” and “or”. The “and” operator requires all conditions to be true for the overall condition to be true, while the “or” operator only requires one of the conditions to be true.
The following “if” statement checks if a number is both positive and even:
num = 6 if num > 0 and num % 2 == 0: print("The number is positive and even.")
The condition num > 0 and num % 2 == 0 checks if the number is greater than 0 and if it is divisible by 2 without any remainder. If both conditions are true, the message “The number is positive and even.” will be printed.
3. The “elif” Statement
The “elif” statement may chain multiple conditions together in a series of checks. It is used when you have multiple conditions to evaluate, and you want to run a different line of code for each condition.
Chained Conditionals with “elif”
The syntax of the “elif” statement is as follows:
# code block to execute if condition1 is true
# code block to execute if condition1 is false and condition2 is true
# code block to execute if condition1 and condition2 are false and condition3 is true …
# code block to execute if all conditions are false
The “elif” statement is evaluated only if the preceding condition(s) in the chain are false. If the “elif” condition is true, the code block implements the “elif” statement and the rest of the chain is skipped. If none of the conditions in the chain are true, the code following the “else” statement is executed.
Nested “if” Statements
In addition to chaining conditions with “elif”, you can also nest “if” statements within other “if” statements. It is used for more complex decision-making within your code.
The following nested “if” statement checks if a number is positive, negative, or zero:
num = -5 if num > 0: print("The number is positive.") elif num < 0: print("The number is negative.") else: print("The number is zero.")
If the value of “num” is greater than 0, the line of code inside the first “if” statement will be executed. If the value is less than 0, the “elif” statement will run the code inside it. If neither condition is true, then the script will display the message inside the “else” statement.
4. The “else” Statement
The “else” statement is used in conjunction with the “if” statement to specify what to do when the condition in the “if” statement is false. Therefore, you can define a default case when none of the preceding conditions are true.
The syntax of the “else” statement is as follows:
# code to execute if condition is true
# code to execute if condition is false
The lines following the “else” statement are executed only if the condition in the “if” statement is false. It provides an alternative set of instructions when the condition is not met.
5. Indentation and the Importance of Syntax
In Python, proper indentation is crucial for the correct execution of conditional statements. Unlike other programming languages that use brackets or parentheses to denote code blocks, Python uses indentation to define the scope of the code belonging to a particular conditional statement.
The Role of Indentation in “if” Statements
In Python, the lines of code following an “if”, “elif”, or “else” statement must be indented with four spaces, although other conventions, like tabs or two spaces, are also possible. However, it is important to maintain consistency in indentation throughout your scripts.
For example, consider the following “if” statement with proper indentation:
# code block to execute if condition is true
print(“This code is inside the ‘if’ code block.”)
# code outside the ‘if’ code block
print(“This code is outside the ‘if’ code block.”)
The code inside the “if” is indented with four spaces wheras the line outside the “if” part is not indented and will be executed regardless of the condition.
6. Use Cases for Conditional Statements
Filtering Data based on Conditions
Conditional statements are often used to filter data based on multiple conditions. For instance, you may want to display only items within a certain price range or filter out data that does not meet certain criteria.
prices = [10, 20, 30, 40, 50, 60, 70] for price in prices: if price > 30: print(price)
In the script above, the “if” statement filters out prices that are not greater than 30, and only displays the prices that meet the condition.
Validating User Input
Conditional statements are useful for validating user input and ensuring that it meets certain requirements. For example, when a program has to check if a user’s password meets the required complexity criteria or if an input value falls within an acceptable range.
password = input("Enter your password: ") if len(password) >= 8 and any(char.isdigit() for char in password): print("Password is valid.") else: print("Password is invalid.")
Here, the “if” statement checks if the password is at least 8 characters long and contains at least one digit. If both conditions are true, it prints a message indicating that the password is valid; otherwise, it prints a message indicating that the password is invalid.
Running Different Code Blocks based on Conditions
Different code chunks based on many conditions can be practical for implementing different functionalities or handling different scenarios within your program.
user_role = "admin" if user_role == "admin": print("Welcome, admin.") elif user_role == "user": print("Welcome, user.") else: print("Unknown user role.")
The “if” and “elif” lines check the value of “user_role” and the condition applies if it is right. The “else” statement handles the case when none of the conditions are true.
7. Importance of Conditional Statements in Python
Some of the reasons why conditionals are popular and important in Python are:
Flexibility and Adaptability
Programs can adapt easily to different situations and handle several scenarios. Developers can create programs that respond intelligently to various inputs and conditions.
Complex logic and decision-making processes may be embedded in the code by utilizing comparisons, logical operators, and conditional structures. You can write software that behave differently based on the values and states of variables.
Simplified Code Structure
Programs can be broken down into logical parts that are executed selectively based on pre-defined conditions. This helps to avoid repetitive code and improve the overall structure and readability of the programs. It is then easier to handle different cases and scenarios without cluttering your code with unnecessary if-else blocks.
8. Best Practices for Using Conditionals
To ensure clear and readable code, here are some best practices for using conditionals in your Python programs:
Clear and Readable Code
Use descriptive variable names and comments to make your code more understandable. Clearly define the purpose of the conditions being evaluated. This will make it easier for others (and yourself) to understand the logic of your code.
Avoiding Deeply Nested “if” Statements
While nested “if” statements can be important in certain situations, it is generally recommended to avoid deep nesting. Deeply nested code can become difficult to read and understand, leading to potential bugs and maintenance issues. Consider refactoring your code into smaller, more manageable functions or using additional “elif” statements to simplify complex conditions.