The if
statement is a primary logic method in Python and we can find them everywhere in Python code. As a beginner, you often write long lines of code to check if something is true and then execute something based on the result of the condition.
This article will show you three different ways you can write more Pythonic, short and concise if/elif/else statements without long lines of code.
You will learn how to benefit from the boolean data types to write more concise code and create efficient switch statements for different choices.
As a geospatial data scientist, the examples I provide here have all the geo flavor, as usual. Let’s go.
3 Ways to Write Pythonic Conditional Statements
- Use if/else statements in one line.
- Use table functions for multiple if/elif statements.
- Take advantage of the boolean values.
1. Use If/Else Statements in One Line
It’s common to see if/else statements in Python code written like this:
lat = 32.56
long = -84.12
# Latitude
if lat > 0:
print("N")
else:
print("S")
# Longitude
if long > 0:
print("E")
else:
print("W")
#Output:
N
W
In the example above, the code specifies the latitude (north-south) and longitude (east-west) depending on the coordinate degrees.
This is fine but not necessary. To simplify the code and reduce the number of lines in the conditional statements, you can use an inline if conditional statement.
Consider the following concise code that performs the same with one line for each if/else conditional statement.
lat = 32.56
long = -84.12
print("N" if lat > 0 else "S")
print("E" if long > 0 else "W")
#Output:
N
W
It’s possible to reduce the statement into one line of code because it uses the inline if conditional statement.
Here’s the syntax:
true_expression if conditional else false_expression
So here, we get N
if Lat
is more than 0
degrees and S
otherwise.
There’s an even more beautiful way to shorten the code using the built-in boolean data type of Python, which I’ll show you below.
But first, let’s see an example with multiple if/elif statements.
2. Use Table Functions for Multiple If/Elif Statements
Because Python has no switch statements, you often end up writing a code like the following to choose between different (and multiple) if/elif choices.
The first part of the code creates four simplistic functions that print out the function. This snippet also sets the variable gdf
to empty string and n
to equal 3.
def plot_choropleth(gdf):
print("Plotting Choropleth")
def plot_heatmap(gdf):
print("Plotting Heatmap")
def plot_animation(gdf):
print("Plotting Animation")
def plot_bubblemap(gdf):
print("Plotting Bubblemap")
gdf = ""
n = 3
Next, let’s simulate choosing between these different choices using the if/elif statement.
if n == 1:
plot_choropleth(gdf)
elif n == 2:
plot_heatmap(gdf)
elif n == 3:
plot_animation(gdf)
elif n == 4:
plot_bubblemap(gdf)
#Output:
Plotting Animation
In this example, we have n = 3
, and therefore we call the plot_animation
function and print out “Plotting Animation.”
Code like that is verbose. Though it will work, it’s not neat. In Python, we say everything is an object, including functions. Therefore we can put the functions in a list just like any other object and access them with the index.
func_list = [plot_choropleth, plot_heatmap, plot_animation, plot_bubblemap][n-1]
Here we put the functions in a list by simply choosing the index of the n variable. Note that we subtract one since Python uses a zero-based index. Now we call the func_list
on the gdf
to simulate the switch statements without having explicit if/elif statements and long lines of code.
In the next example, I’ll show you a more concise way to write the if/else statement using Python’s built-in boolean data type.
3. Take Advantage of the Boolean Values
In the first example of the if/else statement, we’ve reduced the code into one line of code while still using an if/else statement like this:
"N" if lat > 0 else "S"
There’s no need to have the if/else statements. Instead, we can use boolean values. In Python, True
is equal to one
, and False
is equal to zero
. So we can write a code snippet like this, which might seem odd at first.
lat1, long1 = 57.792017, 12.054745
lat2, long2 = -14.896547, -3.132567
print('NS'[lat1 < 0])
print('NS'[lat2 < 0])
print('EW'[long1 < 0])
print('EW'[long2 < 0])
#Output:
N
S
E
W
But let’s go through the example in detail. The first snippet checks whether the latitude is less than 0 and sets it to either N
for north or S
for the south. The conditional returns are false in the first example of the latitude and true in the second example of the latitude.
Now, the next part is choosing the index’s string. So the first latitude is 57.792017
, and it is not less than 0, so it’s false, and therefore we choose the zero index of the string, which is N
. The second latitude is -14.896547
; therefore, the condition is true, and thus it returns the string at index one, S
.
lat1, long1 = 57.792017, 12.054745
lat2, long2 = -14.896547, -3.132567
print('NS'[lat1 < 0])
print('NS'[lat2 < 0])
#Output:
N
S
Now that you understand how to efficiently use boolean data types to simulate if/else statements, let’s write a more practical function that formats the coordinates into degrees of decimals.
def print_coords(lat, long):
ns = 'NS'[lat < 0] #True (1) defaults to "S" and False (0) defaults to "N"
we = 'EW'[long < 0] # True (1) defaults to "W" and False (0) defaults to "E"
print(f'{abs(lat):.2f}°{ns}, {abs(long):.2f}°{we}')
lat, long = 57.682605, 11.983421
print_coords(lat, long)
#Output:
57.68°N, 11.98°E
The Takeaway
Python has wonderful, subtle ways to write more compelling, concise, and Pythonic code. Refactoring code is an art, and we should constantly strive to improve our code’s readability and performance. Writing more Pythonic conditional statements is just one way to do it!
Frequently Asked Questions
What does it mean for code to be "Pythonic"?
Pythonic code means to write code in Python that emphasizes readability, simplicity and efficiency. It often follows best Python practices and uses built-in Python features for concise and elegant code solutions.
How do inline if/else statements work in Python?
Inline if/else statements in Python allow you to write Python conditionals using one line of code. This is a more concise alternative to multi-line if/else blocks.
An example of an inline if/else statement in Python is:
print("N" if lat > 0 else "S")
How does Boolean indexing work in Python conditional statements?
The boolean values True
equal 1
and False
equal 0
in Python, so you can use them as indices for a string in a conditional statement. For example:
print('NS'[lat < 0]) # Returns 'N' if lat >= 0, returns 'S' otherwise.