Home >Backend Development >Python Tutorial >Excellent Tips for Writing Clean Python Code

Excellent Tips for Writing Clean Python Code

王林
王林forward
2023-04-10 10:21:031578browse

Let’s talk about some of the best tips for writing clean Python code!

Excellent Tips for Writing Clean Python Code

Variable/Function Name

A very common question I often do is the naming of variables/functions, basically, If your variables/functions look like this:

var1 = 12
var2 = 'tom'
var3 = 1234

It's easy to run into problems referencing these values, instead try doing it like this:

quantityofitems = 12
name = 'tom'
totalcost = 1234

This makes it easy to remember /Referencing these variables/functions becomes easier.

Separate code chunks

Another great way to clean up your Python code is to separate code chunks, it helps to make the code look better even though the project functionality is the same Looks better:

quantityofitems = 12
name = 'tom'
totalcost = 1234
print("总计 " + name + " 订单" + totalcost)

Even just printing them separately will make the code look clearer:

quantityofitems = 12
name = 'tom'
totalcost = 1234

print("总计 " + name + " 订单" + totalcost)

Comments Comments Comments

Keeps the code tidy Another important method is to comment the code, most of the time my projects contain more comments than code (that's probably why I'm a bad programmer). Comments help keep your code tidy by explaining what those blocks of code do, but they can also double as separating different parts of your project.

quantityofitems = 12 
name = 'tom' 
totalcost = 1234

print("总计" + name + "订单" + totalcost)

When we add comments, it can help explain what we are doing with our project:

#获取物品的数量
quantityofitems = 12

#客户名称
name = 'tom'

#总订单成本
totalcost = 1234

#打印总订单 
print("总计" + name + "订单是" + totalcost + "" + quantityofitems )

Using code formatters

Another great way to clean up your Python code is to use the Python Code Formatter, and while it's not perfect, it's still a great way to clean up your Python code! Check out the links below to learn more about these formatters:

https://www.toutiao.com/article/7211077147073495604/?log_from=7eb2b7c9a420e_1679108199569

Finally

These are some great tips for writing clean Python code, do you know any others? ​

The above is the detailed content of Excellent Tips for Writing Clean 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