Fundamentals 10 min read

Python Variable Usage, Naming Conventions, and Common Operations

This article teaches Python developers how to write cleaner, more elegant code by mastering variable unpacking, underscore placeholders, type annotations, PEP 8 naming rules, numeric literals, floating‑point precision handling with Decimal, boolean arithmetic tricks, and a wide range of string manipulation techniques, all illustrated with practical code examples.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Python Variable Usage, Naming Conventions, and Common Operations

When reading others' source code you may feel it looks sophisticated, but your own code can feel cheap; improving code quality requires mastering advanced usage beyond basic knowledge.

Variable unpacking allows assigning multiple values from an iterable in a single statement:

<code>usernames = ['honey', 'jack']
author, reader = usernames</code>

Nested structures can be unpacked with parentheses:

<code>usernames = [["honey", 90], ["jack", 100]]
(author, author_score), (reader, reader_score) = usernames</code>

Dynamic unpacking uses the asterisk to capture remaining items as a list:

<code>usernames = ['honey', 90, 100, 'jack']
author, *score, reader = usernames
print(score)  # [90, 100]</code>

The single underscore _ serves as a throw‑away placeholder in assignments:

<code>usernames = ['honey', 90, 100, 'jack']
author, *_, _ = usernames</code>

Type annotations (Python 3.5+) let you declare variable types, though they are only hints and need external tools like mypy for checking:

<code>from typing import List

def remove_invalid(items: List[int]):
    """Remove invalid elements"""
    ...</code>

PEP 8 naming conventions recommend:

snake_case for regular variables (e.g., max_value )

UPPER_CASE_WITH_UNDERSCORES for constants (e.g., MAX_VALUE )

leading underscore for internal‑use variables (e.g., _local_var )

trailing underscore when a name clashes with a keyword (e.g., class_ )

Other PEP 8 rules cover class names (CamelCase) and function names (snake_case).

Small tricks :

Boolean values behave as integers (True = 1, False = 0), enabling concise counting:

<code>numbers = [1, 2, 3, 4, 5, 6, 7]
count = sum(i % 2 == 0 for i in numbers)  # counts even numbers</code>

Numeric literals can include underscores for readability:

<code>i = 1_000_000</code>

Floating‑point arithmetic may produce unexpected results; use decimal.Decimal for exact decimal math:

<code>from decimal import Decimal
print(Decimal('0.1') + Decimal('0.2'))  # 0.3</code>

Passing a float directly to Decimal defeats the purpose because the float is already imprecise:

<code>print(Decimal(0.1))  # shows the binary representation error</code>

String operations include iteration, slicing, reversing, and built‑in methods:

<code>s = "hello, python!"
for c in s:
    print(c)

# reverse using slicing
print(s[::-1])

# reverse using reversed()
print(''.join(reversed(s)))</code>

Formatting options:

C‑style 'hello %s' % name (discouraged)

str.format() – supports positional arguments

f‑strings (Python 3.6+)

<code>name = 'python'
print(f'Hello, {name}')
print('{0}: name={0} score={1}'.format('jack', 100))
</code>

String concatenation can be done with join or the += operator:

<code>output = ['hello', 'python']
print(' '.join(s for s in output))
</code>

Splitting and partitioning differ: split() returns a list, partition() returns a 3‑tuple (before, sep, after):

<code>output = "name:jack"
print(output.split(':'))          # ['name', 'jack']
print(output.partition(':'))    # ('name', ':', 'jack')
</code>

Replacing characters:

<code>s = 'hello, python.'
print(s.replace(',', '!'))  # hello! python.

# translate for multiple replacements
table = s.maketrans(',.', '!。')
print(s.translate(table))  # hello! python。</code>

Strings vs. bytes :

Unicode str can be encoded to bytes via .encode()

bytes can be decoded back to str via .decode()

<code>s = 'hello, python.'
byte_s = s.encode('UTF-8')
print(byte_s)  # b'hello, python.'

byte_object = b'hello'
print(type(byte_object))  # <class 'bytes'>
print(byte_object.decode())  # hello
</code>

When writing to files, specify an encoding (e.g., encoding='UTF-8' ) so Python automatically converts strings to bytes:

<code>with open('output.txt', 'w', encoding='UTF-8') as fp:
    fp.write("hello python")
</code>

If no encoding is given, Python falls back to the system’s preferred encoding (often UTF‑8 on macOS):

<code>import locale
print(locale.getpreferredencoding())  # UTF-8
</code>

Practicing these techniques will gradually lead to more elegant Python code and help you become a Python master.

Pythoncode-styleVariablesstring-manipulationDecimalType Annotationspep8
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.