In the Python programming language, conditional statements guide the flow of your code based on specific conditions. These statements, comprising if
, elif
, and else
, act as the traffic controllers of your program, directing it down different paths depending on the circumstances.
Picture a scenario where your program needs to respond differently to different inputs or conditions. This is where the magic of decision-making comes into play. Python’s conditional statements enable your code to make informed decisions, executing specific blocks of code based on whether a condition is met or not.
Basic Syntax
The syntax for conditional statements in Python follows a clear and structured pattern, employing the if
, elif
(else if), and else
keywords.
if condition:
# Code to execute if the condition is true
elif another_condition:
# Code to execute if the first condition is false and this condition is true
else:
# Code to execute if none of the above conditions are true
The syntax is designed for readability and simplicity, making it accessible to both newcomers and seasoned Python developers. Each block of code is indented, emphasizing the hierarchical structure of the conditions.
Examples
Let’s learn by taking a few examples:
Example 1: The Basic if
Statement
# Taking user input for age
user_input = input("Enter your age: ")
age = int(user_input)
if age >= 18:
print("You are eligible to vote.")
The above code uses the input()
function to get the user input. The code checks if the age is greater than or equal to 18 and provides the appropriate message.
Also Read: Taking User Input in Python
Example 2: Introducing else
# Taking user input for the number
user_input = input("Enter a number: ")
number = float(user_input)
if number >= 0:
print("The number is positive.")
else:
print("The number is negative.")
The above code uses the input()
function to get the user input. The code checks if the number is greater than or equal to 0 and provides the “The number is positive.” message. If the input is lesser than 0, it gives “The number is negative” message.
Example 3: Introducing elif for Multiple Conditions
# Taking user input for the exam score
user_input = input("Enter your exam score: ")
# Validating and processing the input
exam_score = int(user_input)
if exam_score >= 90:
print("Grade: A")
elif exam_score >= 80:
print("Grade: B")
elif exam_score >= 70:
print("Grade: C")
elif exam_score >= 60:
print("Grade: D")
else:
print("Grade: F (You did not pass)")
The above code uses the input()
function to get the user input. It then, uses a series of if
, elif
(else if
), and else
statements to determine the grade based on the entered exam score. Each elif
block represents a different grade range.
If the exam score falls within a specific range, the corresponding grade is printed.
If none of the conditions are met (i.e., the score is below 60), a message “Grade: F (You did not pass)” is printed.
Example 4: Nesting Conditions for Precision
x = int(input("Enter x: "))
y = int(input("Enter y: "))
if x > 0:
if y > 0:
print("Both x and y are positive.")
else:
print("Only x is positive.")
else:
print("Neither x nor y is positive.")
The above code uses the input()
function to get the user input. It then:
- Uses nested if statements to evaluate the positivity of both
x
andy
.
- If
x
is greater than 0, it enters the first if block.
- Inside the first if block, it checks if
y
is greater than 0. If true, it prints “Bothx
andy
are positive.” If false, it prints “Only x is positive.”
- If
x
is not greater than 0 (i.e., it’s either 0 or negative), it enters the else block and prints “Neither x nor y is positive.”
This example showcases the power of nested conditions, allowing for intricate decision-making based on the values of x
and y
.
Logical Operators:
Operators, namely and
, or
, and not
, play a pivotal role in crafting complex conditions that respond dynamically to various scenarios.
and
: Returns True if both conditions on its left and right are true.
or
: Returns True if at least one of the conditions on its left or right is true.
not
: Returns True if the condition following it is false, and vice versa.
Let’s understand with the help of an example:
# Taking user input for age and checking if it's within a certain range
age = int(input("Enter your age: "))
# Checking if age is between 18 and 30 using 'and'
if age >= 18 and age <= 30:
print("You are in the prime of your life!")
# Checking if age is either below 18 or above 65 using 'or'
elif age < 18 or age > 65:
print("You are either young or enjoying your golden years.")
# Checking if age is not exactly 25 using 'not'
elif not age == 25:
print("Age is not 25. Exciting times!")
# Default message if none of the above conditions are met
else:
print("You are in an interesting phase of life.")
The above code uses the input()
function to get the user input. It then:
- The and operator ensures that the age is both greater than or equal to 18 and less than or equal to 30. If yes, it prints : “You are in the prime of your life!”
- The ‘or’ operator checks if the age is either below 18 or above 65. If yes, it prints: “You are in the prime of your life!”
- The
not
operator verifies if the age is not exactly 25. If yes, it prints: “Age is not 25. Exciting times!”
Ternary Operator
The ternary operator in Python is a compact and elegant way to express simple conditions in a single line. It provides a concise alternative to the traditional if-else
statement, allowing developers to enhance readability and streamline code for straightforward decision-making.
Syntax
value_if_true if condition else value_if_false
- If the condition is true, it returns
value_if_true
.
- If the condition is false, it returns
value_if_false
.
Example
Let’s take an example to understand better:
# Taking user input for temperature and determining weather condition
temperature = float(input("Enter the temperature in Celsius: "))
# Using the ternary operator to decide the weather condition
weather_condition = "Warm" if temperature >= 25 else "Cool"
# Displaying the result
print(f"The weather is {weather_condition}.")
The above code uses the input()
function to get the user input for the temperature. It, then, utilizes the ternary operator to determine the weather condition. If the temperature is greater than or equal to 25, it assigns “Warm” to the variable weather_condition. If the temperature is less than 25, it assigns “Cool” to the variable weather_condition
. F-strings are then used, in a pythonic manner, to display the result.
The ternary operator shines in scenarios where conditions are simple and the goal is to enhance code readability. Its succinct syntax contributes to more streamlined and maintainable code, making it a valuable tool in the Python developer’s arsenal.
Read also :
Best Practices
In the world of Python programming, adhering to best practices is hugely important. These practices, help you code that is not only functional but also efficient, elegant and maintainable. Let’s delve into some cardinal rules that’ll help you along your journey of familiarizing yourself with conditional statements in python:
Keep it Simple: Prioritizing Simplicity
When it comes to crafting conditions, simplicity is a virtue. Aim for straightforward and easy-to-understand conditions that don’t require deciphering like a cryptic code. While it’s tempting to create complex boolean expressions, opting for simplicity enhances code readability and makes it more accessible to collaborators and your future self.
Use Meaningful Names: Clarity is Key
Choosing meaningful names for your variables enhances the clarity of your conditions. Instead of cryptic names like a
or temp
, opt for descriptive names that convey the purpose of the variable. This practice significantly contributes to code maintainability and aids anyone reading your code, including your future self.
Comment for Clarity
For complex conditions, don’t hesitate to add comments explaining the logic. Comments act as guideposts, offering insights into the thought process behind the conditions. This is especially valuable when dealing with intricate business logic or conditions that might not be immediately obvious.
Minimize Nested Loops
While nested loops are a powerful tool, they come with a potential cost to both performance and readability. Excessive nesting can make code harder to understand and maintain. They are also less efficient and take more time to run. In scenarios where nested loops are necessary, optimizing their efficiency becomes crucial.
Continue your journey by exploring additional resources that deepen your understanding of Python’s conditional statements. Dive into online tutorials, refer to official documentation, and engage with interactive coding platforms to hone your skills. For those seeking to push boundaries, consider delving into advanced topics like exception handling, intricate logical conditions, and design patterns to unlock the full potential of your Python programming expertise.
Happy coding!
Also Read: