In this article, we’ll be taking a look at two common coding styles that programmers use to handle scenarios where a piece of code might fail: “Look Before You Leap” (LBYL) and “Easier To Ask for Forgiveness Than Permission” (EAFP).

If you aren’t familiar with the LBYL vs. EAFP debate, that’s fine. We’ll cover both of them shortly.

Understanding the nuances of these paradigms will help you write cleaner and more efficient code. We’ll be looking at this topic from a Python perspective, but some of the concepts apply to other languages as well.

Let’s get started!

Look Before You Leap

LBYL is the traditional programming style in which we check if a piece of code is going to work before actually running it.

In other words, if a piece of code needs some prerequisites, we place conditional statements such that the code only runs if all the prerequisites are met.

In the example below, we check if the keys (nameage, and gender) exist and then print them:

person = {'name': 'John Doe', 'age':30, 'gender': 'male'}

#LBYL
if 'name' in person and 'age' in person and 'gender' in person:
    print("{name} is a {age} year old {gender}.".format(**person))
else:
    print("Some keys are missing")
    

#data-science #python #programming #coding

In Python, Don’t Look Before You Leap
3.15 GEEK