So far, weve learned about variables, data structures and some basic functions that you can use on them to manipulate, retrieve and process data. In this post, we’ll put our learnings to greater use by going beyond simple arithmetic and discovering how to use conditional statements on variables. If you’re new to programming, let me give you a heads up that this is where the real fun begins. The code that we’ll be writing from here on out will be more sophisticated, but it will also be more rewarding and more applicable to real world business situations.
Conditional statements are a fundamental aspect of programming that allow developers to execute specific blocks of code based on certain conditions. In Python, conditional statements are crucial for controlling the flow of a program, enabling it to make decisions and respond to different inputs or situations. Whether you’re checking user input, processing data, or making decisions in a game, conditional statements provide the necessary logic to handle these tasks effectively.
Understanding and mastering conditional statements is essential for anyone learning Python, as they form the backbone of decision-making in code which becomes crucial later on when we delve deeper into analytics and machine learning. By the end of this post, you should  have a solid grasp of the different types of conditional statements in Python, how to write them correctly, and how to apply them in real-world scenarios. Let’s dive into the basics of Python conditional statements and explore their syntax and usage.
Types of Conditional Statements
In Python, there are three main types of conditional statements: if, else, and elif. Each of these statements serves a unique purpose in controlling the flow of a program based on specific conditions.
The If Statement
The if statement is used to evaluate a condition and execute a block of code if the condition is true. It’s the most basic form of a conditional statement, allowing a program to make decisions based on whether a given condition is met.
In real-world applications, the if statement can be used to validate user inputs. For example, when a user signs up for a service, you might want to ensure their password meets certain criteria (e.g., minimum length, contains both letters and numbers) before allowing them to proceed.
The Else Statement
The else statement provides an alternative block of code that executes if the if condition is false. This allows the program to handle situations where the initial condition is not met, ensuring that an appropriate response is given. For example, the else statement is often used in situations where there are two mutually exclusive outcomes, such as determining whether a user has access to a certain feature based on their subscription status.
The else statement is often used in situations where there are two mutually exclusive outcomes. For instance, determining whether a user has access to a certain feature based on their subscription status: if they have a premium subscription, they get access; otherwise, they are shown an upgrade prompt.
The Elif Statement
The elif statement, short for “else if,” allows you to check multiple conditions in sequence. It is used to evaluate additional conditions if the previous if (or elif) statement’s condition is false. This is particularly useful when there are multiple potential conditions to handle.
An elif use case can be categorizing users into different age groups or determining the grade of a student based on their score. For instance, if the score is above 90, the grade is ‘A’; if it’s between 80 and 90, the grade is ‘B’; and so on.
Next, we’ll delve into the syntax of conditional statements in Python, exploring how to write them correctly and avoid common pitfalls.
Conditional Statement Syntax in Python
Understanding the syntax of conditional statements is crucial for writing correct and efficient code. At its basic level, Python’s conditional statements are pretty straightforward to write with just a couple of quirks that aren’t common in other programming languages. Let’s discuss the individual components of conditional statement  code first, then let’s break down an example later on:
The If Statement
The if statement is used to test a condition. It begins with the “if” keyword followed by a condition that evaluates to either True or False. If the condition is True, the indented block of code that follows the if statement is executed. If the condition is False, the program skips this block of code as you’ll see in the sample later on.
The Condition
The condition in an if statement is an expression that evaluates to either True or False. Conditions often involve comparison operators such as ==, !=, <, <=, >, and >=. The condition determines whether the code block inside the if statement will be executed or not.
A condition can also involve logical operators like and, or, and not to combine multiple conditions. The result of the condition must be a boolean value (either True or False).
The Colon
The colon (:) at the end of the condition is a mandatory syntax element in Python. It indicates that the following indented block of code is controlled by the if statement. The colon signals the start of the code block that will execute if the condition is true.
The Double Equals Sign (==)
The other comparison symbols mentioned earlier are pretty self-explanatory. Greater than or equal to and less than or equal to are concepts we studied in gradeschool. The double equals sign (==), however, may not be as familiar. Essentially, this is an equality operator used to compare two values. It checks whether the values on its left and right sides are equal – which is what the normal equals sign is for in basic mathematics.
The thing is, the single equals sign is already used as an assignment operator in Python (remember variable value assignment), so something else had to be a stand-in for the mathematical equals sign and the double equals sign was given that job by the language’s developers.
Indentation
Python uses indentation to define the scope of code blocks. Each block of code that belongs to a conditional statement must be indented by the same number of spaces or tabs. Consistent indentation is crucial because it defines which statements are part of the condition. Incorrect indentation will lead to errors, as Python relies on indentation to understand the structure of the code.
If you have a coding background in other languages, this will probably annoy you when you start learning Python. It’s just a quirk that has always been there and has never changed. It may sound harsh, but the sooner you accept it, the sooner you can learn to adjust to it. 😊
The Else Statement
The else statement provides an alternative block of code that executes if the if condition is false. This allows the program to handle scenarios where the initial condition is not met. The else block does not have a condition; it simply executes when the previous if (or elif) conditions are not true.
Sample Code and Breakdown
Now, let’s put it all together with a simple example:
age = 20
if age < 13: print("You are a child.") elif 13 <= age < 18: print("You are a teenager.") else: print("You are an adult.")
Let’s take the components one by one and see what each line of code does:
- if age < 13: This condition checks if the value of age is less than 13. If it is, the program prints “You are a child.”
- elif 13 <= age < 18: If the first condition is false, this elif statement checks if age is between 13 and 17 (inclusive). If it is, the program prints “You are a teenager.”
- else: If none of the above conditions are met, the else block is executed, and the program prints “You are an adult.”
In this example, age is 20, so the first condition (age < 13) is false, the second condition (13 <= age < 18) is also false, and thus the else block is executed, printing “You are an adult.”
Common Mistakes and Best Practices
Writing conditional statements is where things get more challenging for beginners in Python. However, there are a few things you can do to minimize errors in logic and syntax. Here are a few common mistakes to watch out for and some best practices that you have to keep in mind:
Common Mistakes in Python Conditional Statements
- Incorrect Indentation
- Mistake: This is by far the most common area of struggle even for experienced coders who are getting started with Python. Using inconsistent indentation (mixing tabs and spaces or using different numbers of spaces).
- Solution: Use a consistent number of spaces (commonly 4) for indentation. Another “hack†is configuring your text editor to insert spaces when you press the Tab key.
- Using Single Equals Sign (=) Instead of Double Equals Sign (==)
- Mistake: Using = instead of == in conditions. The = operator is used for assignment, not comparison.
- Solution: Always use == to compare values in conditional statements. It takes a while to get the hang of this, so practice as much as you can to rewire your brain’s habits into using double equals when necessary.
if x = 10: # Incorrect # Code block
if x == 10:Â # Correct # Code block
- Missing Colon (:)
- Mistake: Forgetting to add a colon at the end of the if, elif, or else statement.
- Solution: Ensure each conditional statement ends with a colon. Review your code thoroughly before running it.
if x == 10 # Incorrect # Code block
if x == 10: # Correct # Code block
- Logical Errors in Conditions:
- Mistake: Writing conditions that don’t logically make sense, leading to unexpected behavior.
- Solution: Double-check your conditions to make sure they correctly represent the logic you intend.
Fortunately, Jupyter Notebook is very good at returning suggestions along with error messages. For the most part, the line of code will be identified so you can quickly examine where the issue is coming from. You can also have generative AI platforms such as ChatGPT and Copilot examine your code for additional insights on errors and potential solutions.
Best Practices
1. Keep Conditions Simple and Readable
- Write clear and concise conditions.
- Break down complex conditions into simpler parts if needed.
if (x > 0 and x < 10) or (y > 0 and y < 10): # Complex
if (0 < x < 10) or (0 < y < 10): # Simpler and more readable
2. Use Meaningful Variable Names
- Use variable names that clearly indicate what they represent, making your code easier to understand.
if age >= 18: # Clear variable name print("You are eligible to vote.")
3. Test All Conditions:
- Ensure that your conditions cover all possible scenarios to avoid unexpected behavior.
- Write test cases to validate the logic of your conditions. Keep in mind that just because the code does not return an error doesn’t mean the program is working properly. In some cases, programs can run but return erroneous output due to mistakes in logic or flawed conditions.
4. Use Parentheses for Clarity
- Use parentheses to group conditions and make the logic clearer.
if (x > 0 and x < 10) or (y > 0 and y < 10): # Clear grouping # Code block
Comment on Your Code
- Add comments to explain the purpose of complex conditions or important logic, helping others (and yourself) understand the code later. This may sound tedious, but it helps you figure out what certain code blocks do at a glance when reviewing and debugging. Comments are especially crucial when working on a coding project within a team. Comments act as signposts for your colleagues’ guidance.
# Check if the user is a teenager or an adult if 13 <= age < 18: print("You are a teenager.") elif age >= 18: print("You are an adult.")
6. Don’t Shy Away from AI.Today’s generative AI platforms are amazing at code syntax and minimization. If you’re stuck with an error that you can’t seem to zap, you can ask an AI platform to check the code for you and help figure out what’s causing the issue.
In some cases, a missing comma, colon or indentation can cause an otherwise well-written program not to run. In some cases, manually coding complex algorithms can result in equally long and unwieldy code. In both cases, ChatGPT and Copilot have what it takes to give you insights on how to make your code better.
Of course, this doesn’t mean you shouldn’t hone your coding skills and simply rely on AI to do the rest. Keep in mind that as good as ChatGPT and Copilot’s current versions are, they’re far from perfect. You still need to know exactly how Python code works to avoid logical flaws.
And that’s about it for simple conditional statements in Python. Try running the examples given here on your own Jupyter Notebook or Google Colab setups and try coding your own scenarios. Practice makes perfect, so give it a few dozen reps until our next lesson.