Python Basics: Numbers, Strings, Functions, Data Structures, Classes, and Tools
This article provides a comprehensive Python tutorial covering numeric operations, string manipulation, function definitions, data structures, class creation, object introspection, and useful built‑in tools, complete with clear code examples for each concept.
This tutorial introduces essential Python concepts, starting with numeric operations such as absolute value, base conversions, complex numbers, and arithmetic utilities like abs , bin , oct , hex , divmod , round , and pow . It also demonstrates logical checks using all and any , and boolean conversion with bool .
<code>In [1]: abs(-6)
Out[1]: 6
In [2]: bin(10)
Out[2]: '0b1010'
In [3]: oct(9)
Out[3]: '0o11'
In [4]: hex(15)
Out[4]: '0xf'
In [5]: divmod(10, 3)
Out[5]: (3, 1)
In[6]: round(10.0222222, 3)
Out[6]: 10.022
In[7]: pow(3, 2, 4)
Out[7]: 1
</code>String handling examples include converting strings to bytes, casting objects to strings, executing code stored in strings, evaluating expressions, and formatting output with format :
<code>In [12]: s = "apple"
In [13]: bytes(s, encoding='utf-8')
Out[13]: b'apple'
In [14]: str(100)
Out[14]: '100'
In [15]: exec(compile("print('helloworld')", "<string>", "exec"))
helloworld
In [16]: eval("1 + 3 + 5")
Out[16]: 9
In [18]: "i am {0},age{1}".format("tom", 18)
Out[18]: 'i am tom,age18'
</code>Function utilities cover built‑in functions such as sorted , sum , and custom functions demonstrating variable arguments, keyword‑only arguments, and lambda expressions:
<code>def max_len(*lists):
return max(*lists, key=lambda v: len(v))
max_len([1,2,3], [4,5,6,7], [8]) # returns the longest list
</code>Data‑structure sections show how to create dictionaries, frozensets, sets, slices, tuples, and how to convert between them:
<code>dict(a=1, b=2)
frozenset([1,1,3,2,3])
set([1,4,2,3,1])
slice(1,10,2)
tuple([1,3,5])
</code>The class and object part explains defining classes, using __init__ , __repr__ , checking callability, adding attributes dynamically, using classmethod , property decorators, and introspection functions like callable , hasattr , getattr , isinstance , issubclass , and type :
<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}'
xiaoming = Student('001', 'xiaoming')
print(callable(xiaoming)) # False
print(hasattr(xiaoming, 'name')) # True
</code>Tools covered include enumeration, size inspection with sys.getsizeof , filtering with filter , hashing with hash , help documentation, file I/O with open , range generation, reversed iteration, zip aggregation, chained operations, and JSON serialization of objects:
<code>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]
with open('json.txt', 'w', encoding='utf-8') as f:
json.dump([xiaoming, xiaohong], f, default=lambda obj: obj.__dict__, ensure_ascii=False, indent=2)
</code>Overall, the article serves as a practical reference for Python beginners and intermediate users, illustrating core language features and common utilities with ready‑to‑run code snippets.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.