Fundamentals 11 min read

Python Small Examples: From Basics to Advanced Techniques

This article presents a collection of concise Python examples covering fundamental concepts such as truth testing, object representation, dictionary creation, iteration utilities, property decorators, nonlocal usage, custom decorators, file conversion, and data grouping, encouraging readers to practice each snippet for deeper understanding.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Python Small Examples: From Basics to Advanced Techniques

The article introduces a series of compact Python examples, likening learning to martial arts practice, and encourages readers to explore a GitHub repository containing eight chapters of small, varied code snippets ranging from basic syntax to advanced techniques.

All elements are true : Demonstrates the all function, which returns True only if every element in an iterable is truthy, otherwise False .

At least one element is true : Shows the any function, returning True if any element in an iterable is truthy, otherwise False .

ASCII representation of objects : Uses the __repr__ method to obtain a string representation of an object.

<code>class Student():
    def __init__(self, id, name):
        self.id = id
        self.name = name
    def __repr__(self):
        return 'id = ' + self.id + ', name = ' + self.name

xiaoming = Student(id='1', name='xiaoming')
print(xiaoming)          # id = 1, name = xiaoming
print(ascii(xiaoming))   # 'id = 1, name = xiaoming'
</code>

Creating dictionaries : Provides four methods to build dictionaries using dict() , zip , a list of tuples, and eval on a string.

<code># Method 1: dict()
In [1]: dict()
Out[1]: {}

# Method 2: zip
In [2]: dict(zip(['a', 'b'], [1, 2]))
Out[2]: {'a': 1, 'b': 2}

# Method 3: list of tuples
In [3]: dict([('a', 1), ('b', 2)])
Out[3]: {'a': 1, 'b': 2}

# Method 4: eval on a string
s = "{'a':1, 'b':2}"
eval(s)  # {'a': 1, 'b': 2}
</code>

Enumerate objects : Shows how enumerate yields index‑value pairs.

<code>s = ["a", "b", "c"]
for i, v in enumerate(s, 1):
    print(i, v)
# 1 a
# 2 b
# 3 c
</code>

Filter function : Uses filter with a lambda to keep elements greater than 10.

<code>fil = filter(lambda x: x > 10, [1, 11, 2, 45, 7, 6, 13])
list(fil)  # [11, 45, 13]
</code>

Dynamic attribute access : Retrieves an attribute value with getattr .

<code>class Student():
    def __init__(self, id, name):
        self.id = id
        self.name = name

xiaoming = Student(id='001', name='xiaoming')
getattr(xiaoming, 'name')  # 'xiaoming'
</code>

Creating properties : Demonstrates both the classic property constructor and the decorator syntax.

<code>class C:
    def __init__(self):
        self._x = None
    def getx(self):
        return self._x
    def setx(self, value):
        self._x = value
    def delx(self):
        del self._x
    x = property(getx, setx, delx, "I'm the 'x' property.")

# Using decorator syntax
class C:
    def __init__(self):
        self._x = None
    @property
    def x(self):
        return self._x
    @x.setter
    def x(self, value):
        self._x = value
    @x.deleter
    def x(self):
        del self._x
</code>

Aggregating iterators : Shows how zip can combine elements from multiple iterables.

<code>x = [3, 2, 1]
y = [4, 5, 6]
list(zip(y, x))  # [(4, 3), (5, 2), (6, 1)]
</code>

nonlocal in nested functions : Explains the nonlocal keyword for modifying variables in an enclosing scope.

<code>def excepter(f):
    i = 0
    t1 = time.time()
    def wrapper():
        try:
            f()
        except Exception as e:
            nonlocal i
            i += 1
            print(f"{e.args[0]}: {i}")
            t2 = time.time()
            if i == n:
                print(f"spending time:{round(t2-t1,2)}")
    return wrapper
</code>

Calculator without if/else : Implements a simple calculator using a dictionary of operator functions.

<code>from operator import *

def calculator(a, b, k):
    return {'+': add, '-': sub, '*': mul, '/': truediv, '**': pow}[k](a, b)

calculator(1, 2, '+')   # 3
calculator(3, 4, '**')  # 81
</code>

Groupby by a single field : Groups a list of dictionaries by the weather key using itertools.groupby and itemgetter .

<code>a = [{'date':'2019-12-15','weather':'cloud'},
     {'date':'2019-12-13','weather':'sunny'},
     {'date':'2019-12-14','weather':'cloud'}]

# Using lambda
a.sort(key=lambda x: x['weather'])
for k, items in groupby(a, key=lambda x: x['weather']):
    print(k)
    for i in items:
        print(i)

# Using itemgetter
from operator import itemgetter
from itertools import groupby

a.sort(key=itemgetter('weather'))
for k, items in groupby(a, key=itemgetter('weather')):
    print(k)
    for i in items:
        print(i)
</code>

Exception counting decorator : Provides a decorator that counts how many times a specific exception occurs and reports the elapsed time when a threshold is reached.

<code>def excepter(f):
    i = 0
    t1 = time.time()
    def wrapper():
        try:
            f()
        except Exception as e:
            nonlocal i
            i += 1
            print(f"{e.args[0]}: {i}")
            t2 = time.time()
            if i == n:
                print(f"spending time:{round(t2-t1,2)}")
    return wrapper
</code>

Batch conversion of .xls to .xlsx : Shows a script that renames all files with the .xls extension to .xlsx in a given directory.

<code>import os

def xls_to_xlsx(work_dir):
    old_ext, new_ext = '.xls', '.xlsx'
    for filename in os.listdir(work_dir):
        _, file_ext = os.path.splitext(filename)
        if old_ext == file_ext:
            newfile = os.path.splitext(filename)[0] + new_ext
            os.rename(os.path.join(work_dir, filename), os.path.join(work_dir, newfile))
    print("完成重命名")
    print(os.listdir(work_dir))

xls_to_xlsx('./data')
</code>

The collection of snippets aims to boost readers' Python proficiency, urging them to run and modify the code to solidify their understanding.

PythonProgrammingtutorialfunctionsDecoratorsFile Conversiondata-grouping
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.