简体   繁体   中英

Python Style - Adding 0 After Decimal

I had a question regarding Python code style. I couldn't find an answer on PEP 8 and decided to ask here.

I've noticed in many cases when expressing floating-point numbers people omit the trailing 0. For example:

# List containing floating point numbers.
a = [0., 1., 2., 3.]

However, I've always found it convenient and clearer to add the extra 0 like so:

a = [0.0, 1.0, 2.0, 3.0]

Is there a standard for this, or should I just go with whatever is the least ambiguous?

Some languages, notably Python have rules for what should be well written code . For Python, PEP-8 is the reference, which allows various programmers to easily read code written by others provided PEP-8 is respected.

Here you are in a case that is not covered by PEP-8. So you just have to apply the good old rule: choose one convention among a project or team and stick to it.

If you work alone and prefere adding a 0, just do it. If you work in a team, speak of that with your fellows, and choose one convention for all of you. If you edit existing code where a convention is used, stick to the existing convention.

What I use is opinion only and has not to be in a SO answer.

In PEP 20 it says that "readability counts".

In this example it is easier to read the second version than the first. For example if these were longer lists it would be harder to determine if the first list is a list of floats or floats and integers.

With the first example if a decimal point was missing this may not be obvious.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM