Why Should You Learn Python?

Why Should You Learn Python?

Dennis Groß's photo
Dennis Groß
·Mar 6, 2022·

7 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

Python is known as a beginner-friendly programming language. Find out what makes Python one of the most popular programming languages.

PYPL PoluraitY ranks Python as the most popular programming language in 2022. Python is both a portable and versatile programming language. This is the reason why companies employ Python in many different parts of their technology stack.

Python's Syntax is Simple

The Python community is restrictive with new language features or syntactic sugar. The main object of the Python programming language is to be simple and to make it easy for beginners to learn the language.

Python is opinionated and offers often only one way to achieve something. There is a for example one way to write a for loop. The Typescript programming language on the other hand offers multiple different ways to write a for loop.

In Typescript

my_array = ["foo", "bar"]

# forEach 
my_array.forEach((elem) -> console.log(elem));

# for..of
for(elem of my_array) {
    console.log(elem);
}

# for..in
for(index in my_array) {
    console.log(ny_array[index]
}

In Python

my_array = ["foo", "bar"]

for elem in my_array:
    print(elem)

You might think that this is a disadvantage. More language features are better after all, aren't they?

No. They make it more difficult to learn a new language. Programmers need to understand the complete syntax of a language to understand all code written in it.

Python has few Data Structures

The most basic data structures in Python are lists and dictionaries.

Lists yield an enumeration of data objects and dictionaries contain key-/value mappings of data. And that's almost all data structures that you are going to need with Python.

my_list = ["hello", "world"]
my_dictionary = { "apples": 5, "bananas": 7 }

Other programming languages like Java come with an abundance of data structures that you need to know.

For example:

  • HashMaps
  • TreeMaps
  • HashTables
  • LinkedLists
  • HashSets
  • ...

Not only do you have to know what data structures exist in Java, but you also need to know their use case and how to use them.

Python has simple Low-Level Operations

Have you ever tried manipulating a string in C++?

Here is a code snippet that splits the string "foo.bear" on the "." sign and prints the words out.

std:string s = "foo.bear";
std:string delimiter = ".";

std::vector<std::string> output;
tokenize(s, delimiter, output);
for (auto &s: out) {
    std::cout << s << std::endl;
}
> foo
> bear

That doesn't look simple, does it?

Let's do the same thing in Python.

print("foo.bear".split("."))
> ["foo", "bear"]

What you notice is that Python offers a simple low-level API for primitives like string and integer. What is even better is that Python does not deliver a large number of different primitive data types.

In contrast, C++ differentiates between signed and unsigned numbers in 16 bits (short), 32 bits (integer), 64 bits (long) while Python has only the int data type.

Are all Other Languages Bad?

I have told you that Python is much simpler in a lot of regards in comparison with languages like Typescript, Java, or even C++. And that is true but it does not mean that those languages are bad or less valuable than Python.

All programming languages have trade-offs.

  • C++ code is close to the machine model but complicated because of pointer arithmetic and many different data types.
  • Java is a strong object-oriented programming language but doesn't deliver well in the functional programming department.
  • Typescript gets primarily used for frontend development and focuses on asynchronous code and callbacks which make the life of coding beginners sometimes difficult.

You must understand the trade-offs of the programming languages and use the right tool to get the job done.

Testing in Python is Effective

pytest is the standard testing library in Python. It provides many goodies like fixtures, test discovery, plug-ins, and much more.

But there is one feature that I love the most about pytest.

Parametrized tests, also known as Table Driven tests, are test cases that you can re-run for a set of test scenarios. The idea behind this is that you write code for a test once and use the same code for several test parameters.

Writing Table Driven Tests saves you a ton of time. Almost all test code that I write as a professional software developer is table-driven.

Here is an example.

@pytest.mark.parametrize(
    "base, exponent, result", 
    [(2, 2, 4), (3, 2, 9), (5, 2, 25)]
)
def test_power(base, exponent, result):
  assert power_of(base, exponent) is result

The test code above makes sure that our power_of functions deliver correct results. The annotation @pytest.mark.parametrize injects test parameters into the test_power function. The test_power function runs three times for the three test parameters (2, 2, 4), (3, 2, 9), (5, 2, 25). We wrote on test function but check if the value of 2^2=4, 3^2=9, and 5^2=25.

We would need to write three different test functions if we don't use the "parametrize" annotation. Table Driven Tests make it easy for developers to add more test cases in the future without changing the code much.

Python is not the only language that offers table-driven testing. Here is the same test is written in Java.

class MyPowerTest {

    @Override
    public Stream<? extends Arguments> provideArguments(ExtensionContext context) {
        return Stream.of(
            Arguments.of(2, 2, 4),
            Arguments.of(3, 2, 9),
            Arguments.of(5, 2, 25)
        );
    }

    @ParameterizedTest
    @ArgumentsSource()
    void testMyPower(int base, int exponent, int result) {
        assertEquals(result, powerOf(base, exponent));
    }
}

Table-driven tests in Java are more verbose. We need two methods for the test. One provides the test cases and the other one the test code. It might not look like much more code but it scales much worse than Python test code.

Meta Programming in Python is Powerful

It is easy to access object attributes and functions dynamically in Python. We call this in program speak meta-programming.

The python code snippet below accesses the attributes "name", "last_name" and "birth_date" of the Person object dynamically with the geattr accessor.

def check_is_not_none(instance, attr_name):
    if hasattr(instance, attr_name) is None:
        raise IllegalArgumentError("%s.%s does not exist".format(instance, attr_name))

    assert getattr(instance, attr_name) is not None


person = Person("John", "Doe")

check_is_not_none(person, "name")
check_is_not_none(person, "last_name")
check_is_not_none(person, "birth_date")

We use the getattr accessor in the code to make the check_is_not_none validator generic. And that's the idea behind meta programming. We access object attributes and functions dynamically to make our logic more generic and have to write less code as a consequence.

But that is possible in other languages too. We can use the java.lang.reflect library from Java to achieve similar results. But Java is a strong-typed language. Metaprogramming in Java results in a lot of verbose try-/catch code which makes it unpractical for refactoring.

The Python Community is Big

Python has a large open-source community. Many content creators provide educational Python content which makes learning Python easier. The community provides many libraries and frameworks that you can use in your projects too.

Rich support of open source software is vital for programming languages. You don't want to work with an unpopular programming language and end up creating everything from scratch.

There is also a huge demand for Python developers. The site glassdoor reports more than 72.000 Python jobs in 2022.

Companies use Python in many different areas.

  • CI/CD Automation Scripts
  • Machine Learning
  • Data Processing
  • Backend Development
  • Command-Line Interfaces

That's great if you start programming. You might not know now which sub-field of programming you want to specialize in later.

Python is Portable

You can install and run Python applications on any machine that has a Python interpreter installed. You don't have to code in Python that is specific for a certain operating system or CPU architecture like in C++. That makes the deployment of Python on production systems easier.

You can use libraries like PyInstaller to create a single executable from your Python source code. That's a great option if you don't have enough permissions on the production system to install project dependencies or a Python interpreter.

Conclusion

Python is a beginner-friendly programming language with a large open-source community. Educational Python content is abundant and open source libraries & frameworks that make your life as a Python programmer easier.

Well-written Python code is easy to understand and the meta-programming features offer great refactoring capabilities. The same holds for test code. You can write table-driven tests in the Python testing library pytest using simple annotations.

Python is versatile. It covers many interesting areas like web development, data processing, or machine learning. The versatility of Python makes it a favorable choice for any organization which creates a huge job market for developers.

Applications written in Python are portable and you can deploy them to any operating system that features a Python interpreter.

Did you find this article valuable?

Support Dennis Groß by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this