Fundamentals 22 min read

Python Basics: Numbers, Strings, Functions, Data Structures, Classes and Utilities

This tutorial provides a comprehensive introduction to core Python concepts, covering numeric operations, string handling, built‑in functions, common data structures, class and object mechanics, as well as useful utilities such as iteration tools, file I/O and JSON serialization.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Python Basics: Numbers, Strings, Functions, Data Structures, Classes and Utilities

This article presents a step‑by‑step guide to essential Python features, organized into several sections.

1. Numbers – Demonstrates absolute value, binary/hex/octal conversion, character code lookup, truth testing, boolean conversion, division with remainder, rounding, complex numbers and exponentiation.

<code>abs(-6)          # 6
bin(10)          # '0b1010'
oct(9)          # '0o11'
hex(15)         # '0xf'
chr(65)         # 'A'
ord('A')        # 65
all([1,0,3,6])  # False
any([0,0,1])    # True
bool([0,0,0])   # True
bool([])        # False
divmod(10,3)    # (3, 1)
round(10.0222222,3)  # 10.022
complex(1,2)    # (1+2j)
pow(3,2,4)      # 1
</code>

2. Strings – Shows conversion to bytes, generic string conversion, compiling and executing code strings, evaluating expressions, and formatting with format and format specifications.

<code>s = "apple"
bytes(s, encoding='utf-8')   # b'apple'
str(100)                     # '100'
code_obj = compile("print('helloworld')", "<string>", "exec")
exec(code_obj)               # prints helloworld
eval("1 + 3 + 5")          # 9
print("i am {0},age{1}".format("tom",18))  # i am tom,age18
</code>

3. Functions – Covers built‑in functions such as sorted , sum , nonlocal , global , lambda expressions, and custom functions with positional, keyword, default, *args and **kwargs parameters.

<code>a = [1,4,2,3,1]
sorted(a, reverse=True)   # [4,3,2,1,1]
sum(a)                    # 11
sum(a,10)                 # 21

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}")
    return wrapper

def f(*lists, **d):
    return max(*lists, key=lambda v: len(v))
</code>

4. Data Structures – Illustrates creation and conversion of dictionaries, frozensets, sets, tuples, and slice objects.

<code>dict(a=1, b=2)                     # {'a': 1, 'b': 2}
frozenset([1,1,3,2,3])            # frozenset({1,2,3})
set([1,4,2,3,1])                  # {1,2,3,4}
tuple([1,3,5])                    # (1, 3, 5)
my_slice = slice(1,10,2)
a[my_slice]                      # slice operation
</code>

5. Classes and Objects – Defines a Student class with __init__ , __repr__ , demonstrates callable , custom __call__ , class methods, dynamic attribute access ( getattr , setattr , delattr ), introspection ( dir , hasattr , isinstance , issubclass ), and explains metaclasses.

<code>class Student:
    def __init__(self, id, name):
        self.id = id
        self.name = name
    def __repr__(self):
        return f"id = {self.id}, name = {self.name}"
    def __call__(self):
        print("I can be called", f"my name is {self.name}")

xiaoming = Student('001', 'xiaoming')
callable(Student)          # True
callable(xiaoming)        # False
xiaoming()                 # I can be called, my name is xiaoming
hasattr(xiaoming, 'name') # True
getattr(xiaoming, 'name') # 'xiaoming'
</code>

6. Tools – Shows enumeration, memory size with sys.getsizeof , filtering, hashing, help, iteration protocols ( iter , reversed , zip ), and JSON serialization of objects.

<code>for i, v in enumerate(['a','b','c'], 1):
    print(i, v)

import sys
sys.getsizeof({"a":1,"b":2.0})   # 240 bytes
filtered = filter(lambda x: x>10, [1,11,2,45,7,6,13])
list(filtered)                     # [11,45,13]
hash(xiaoming)                     # e.g., 6139638
help(Student)
rev = reversed([1,4,2,3,1])
list(rev)                          # [1,3,2,4,1]
import json
with open('json.txt','w',encoding='utf-8') as f:
    json.dump([xiaoming, xiaohong], f, default=lambda o: o.__dict__, ensure_ascii=False, indent=2, sort_keys=True)
</code>

The article concludes with a QR‑code invitation to a free Python public course and additional reading links.

Data StructuresTutorialClassesFunctionsbasicsutilities
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.