search
HomeBackend DevelopmentPython TutorialFive essential tips to improve the readability of Python code

Translator | Zhao Qingyu

Reviewer | Sun Shujuan

Do you often look back at the code you wrote 6 months ago and want to know what is going on in this code? Or Taking over a project from someone else and not knowing where to start? This situation is relatively common for developers. There are many methods in Python that help us understand the inner workings of code, so when you look at code from the beginning or write code, it should be easier to continue where you left off.

Here I will give you an example. We may get the code as shown below. This is not the worst, but there are some things we need to confirm, such as:

  • What do f and d represent in the load_las_file function?
  • Why do we need to do it in the clay function? Check the results?
  • What type do these functions require? Floats or DataFrames?

Five essential tips to improve the readability of Python code

In this article, I will cover 5 basic tips on how to improve the readability of your application/script through documentation, prompt input, and proper variable names. .

1. Comments

The first thing we can do to the code is to add comments to certain lines, but be careful to avoid commenting too much. Comments need to explain why the code works, or why something is done in a certain way, rather than how it is implemented. Comments in Python are usually completed using the pound sign (#), which can span one line or multiple lines.

# Comment using the hashtag
# Another comment using the hashtag

For multi-line comments, we can also use double quotes.

"""
This is an example of
a multi-line comment
"""

In the example below, some comments have been added to the code to explain how certain lines of code work and why:

Five essential tips to improve the readability of Python code

2. Display Type typing

The Python language is dynamically typed, which means that variable types are only checked at runtime. Additionally, variables can change type during code execution. Static typing, on the other hand, involves declaring the variable type explicitly and cannot change during code execution.

In 2014, PEP 484 introduced the concept of type hints, which was subsequently introduced into Python 3.5. This allows you to declare variable types explicitly. By adding type hints, you can significantly improve the readability of your code. In the following example, we can see:

  • Requires two parameters
  • The type of the parameter filename is a string
  • The type of the parameter start_depth is a float type , and the default value of this parameter is None
  • This function will return a pandas DataFrame object

Five essential tips to improve the readability of Python code

According to the type hint, we can know exactly the function What is required, and what it will return.

3. Documentation string

The documentation string is the string immediately following the function or class definition. Docstrings are a great way to explain in detail what a function does, what arguments it takes, what exceptions it will throw, its return value, and more. Additionally, if you use a tool like Sphinx to create online documentation for your code, the docstrings will be automatically extracted and converted into the appropriate documentation. The following example shows the docstring for a function named clay_volume. Here we can specify the meaning of each parameter. This makes it more detailed than basic type hints. You can also include more information about the methodology behind the function, such as academic references or equations.

Five essential tips to improve the readability of Python code

#Document strings are also very helpful when we call functions elsewhere in the code. For example, when writing code using Visual Studio, you can hover over a function call and see a popup showing what the function does and what it requires.

Five essential tips to improve the readability of Python code

If you use Visual Studio Code (VS Code) to edit your Python code, you can use extensions like autoDocstring to make the process of creating docstrings easier. You can enter three double quotes and the rest of the template will automatically fill in. You just need to fill in the details.

Five essential tips to improve the readability of Python code

Tip: If you have declared types in the parameters, they will be automatically selected.

4. Readable variable names

Sometimes, when you are writing code, you don’t care too much about the names of variables, especially when time is tight. However, if you go back and look at the code and you find a series of variables named x1 or var123, you may not understand at first glance what they represent. In the example below, there are two variables f and d. We can guess the meaning of such variables by looking at other parts of the code, but this can take time, especially if the code is long.

Five essential tips to improve the readability of Python code

If we give these variables appropriate names, we will be able to know that one of the variables is the data_file read by the lasio.read() call, and is most likely the original data. The data variable tells us that this is the actual data we are dealing with.

Five essential tips to improve the readability of Python code

5. Avoid magic numbers

Magic numbers are values ​​in code that have an unexplained meaning behind them and can be constants. Using these in code can cause ambiguity, especially if you are unfamiliar with using numbers in calculations. Furthermore, if we have the same magic number in multiple places, when it needs to be updated, we have to update every instance of it. However, if such numbers are assigned a suitably named variable, the substitution process becomes much easier. In the example below, we have a function that calculates a value called result and multiplies it by 0.6. What does this mean? Is it a conversion factor? A scalar?

Five essential tips to improve the readability of Python code

If we declare a variable and assign the value to it then we are more likely Know what it is. In this case, the ratio of clay to shale is used to convert the gamma-ray index to clay volume.

Five essential tips to improve the readability of Python code

6. Final Code

After applying the above tips, our final code now looks cleaner and easier to understand.

Five essential tips to improve the readability of Python code

7. Summary

Adding descriptions to your code through comments and docstrings can help you and others understand what the code is doing. It may feel like a chore at first, but with the use of the tools and regular practice, it will become second nature.

Original link: https://towardsdatascience.com/5-essential-tips-to-improve-the-readability-of-your-python-code-a1d5e62a4bf0

Translator’s introduction

Zhao Qingyi, 51CTO community editor, has been engaged in driver development for many years. His research interests include secure OS and network security fields, and he has published network-related patents.

The above is the detailed content of Five essential tips to improve the readability of Python code. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:51CTO.COM. If there is any infringement, please contact admin@php.cn delete
Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools