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

  1. Use if/else statements in one line.
  2. Use table functions for multiple if/elif statements.
  3. 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 
S
E

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.

print("N" if lat < 0 else "S")
print("E" if long < 0 else "W")
Output 
S
E

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 less 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.

More From Abdishakur HassanThe 7 Best Thematic Map Types for Geospatial Data

 

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 three.

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 haven = 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.

Python Tutorial: Conditionals and Booleans — If, Else and Elif Statements

More Expert Tips on Cleaning Up Your Code5 Ways to Write More Pythonic Code

 

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 the 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])
N
S

But let's go through the example in detail. The first snippet checks whether the latitude is less than zero 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 zero, 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.

print('NS'[lat1 < 0])
print('NS'[lat2 < 0])
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 "N" and False(0) defaults to "S"
    we = 'EW'[long < 0] # True (1) defaults to "E" and False(0) defaults to "W
    print(f'{abs(lat):.2f}°{ns}, {abs(long):.2f}°{we}')
 
lat, long = 57.682605, 11.983421
 
print_coords(lat, long)
57.68°N, 11.98°E

More Resources for Your Python ToolkitIncrease the Readability of Your Python Script With 1 Simple Tool

 

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!

Expert Contributors

Built In’s expert contributor network publishes thoughtful, solutions-oriented stories written by innovative tech professionals. It is the tech industry’s definitive destination for sharing compelling, first-person accounts of problem-solving on the road to innovation.

Learn More

Great Companies Need Great People. That's Where We Come In.

Recruit With Us