Fundamentals 29 min read

Master Python Basics: Numbers, Strings, Functions, Data Structures, Classes & Tools

This comprehensive guide walks you through essential Python concepts—from absolute values and numeral system conversions to string manipulation, function utilities, data structures, class mechanics, and handy built‑in tools—complete with clear code examples and explanations for each topic.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Python Basics: Numbers, Strings, Functions, Data Structures, Classes & Tools

1. Numbers

1. Absolute value

Calculate the absolute value (or magnitude) of a number.

abs(-6)  # 6

2. Base conversion

Convert decimal numbers to binary, octal, and hexadecimal.

bin(10)   # '0b1010'
oct(9)   # '0o11'
hex(15)  # '0xf'

3. Integer ↔ ASCII

Convert between integer codes and ASCII characters.

chr(65)   # 'A'
ord('A')  # 65

4. All‑true check

Return True if every element in an iterable is truthy, otherwise False.

all([1, 0, 3, 6])   # False
all([1, 2, 3])      # True

5. Any‑true check

Return True if at least one element is truthy.

any([0, 0, 0, []])   # False
any([0, 0, 1])       # True

6. Boolean evaluation

Use bool() to evaluate truthiness of objects.

bool([0,0,0])   # True
bool([])        # False
bool([1,0,1])   # True

7. Complex numbers

Create a complex number.

complex(1, 2)   # (1+2j)

8. Quotient and remainder

Use divmod() to get both quotient and remainder.

divmod(10, 3)   # (3, 1)

9. Float conversion

Convert integers or numeric strings to float; raises ValueError on failure.

float(3)        # 3.0
float('a')      # ValueError

10. Integer conversion with base

Convert strings to integers with a specified base.

int('12', 16)   # 18

11. Power with modulus

Compute exponentiation with optional modulus.

pow(3, 2, 4)   # 1

12. Rounding

Round numbers to a given number of decimal places.

round(10.0222222, 3)   # 10.022
round(10.05, 1)       # 10.1

13. Chain comparison

Demonstrate Python's chained comparison operators.

i = 3
print(1 < i < 3)   # False
print(1 < i <= 3)  # True

2. Strings

14. String → bytes

Encode a string to bytes using UTF‑8.

bytes('apple', encoding='utf-8')   # b'apple'

15. Any object → string

Convert objects to their string representation.

str(100)      # '100'
str([])       # '[]'
str(tuple())  # '()'

16. Execute code from a string

Compile and execute a string as Python code.

s = "print('helloworld')"
r = compile(s, "<string>", "exec")
exec(r)   # prints helloworld

17. Evaluate an expression

Evaluate a string expression and return its result.

eval("1 + 3 + 5")   # 9

18. String formatting

Use format() to format strings.

"i am {0},age{1}".format("tom", 18)   # i am tom,age18

19. Formatting table examples

Showcase various format specifications (precision, padding, grouping, percentages, scientific notation, alignment).

3. Functions

19. Sorting

Sort lists directly or by a key.

a = [1,4,2,3,1]
sorted(a, reverse=True)   # [4,3,2,1,1]
students = [{'name':'xiaoming','age':18,'gender':'male'}, {'name':'xiaohong','age':20,'gender':'female'}]
sorted(students, key=lambda x: x['age'])   # sorted by age

20. Sum

Calculate the sum of an iterable, optionally with a start value.

a = [1,4,2,3,1]
sum(a)          # 11
sum(a, 10)      # 21

21. nonlocal keyword

Use nonlocal to modify a variable in an enclosing (non‑global) scope.

def wrapper():
    i = 0
    def inner():
        nonlocal i
        i += 1
        print(i)
    return inner

22. global keyword

Declare a variable as global to modify it inside a function.

i = 0

def h():
    global i
    i += 1
h()
print(i)   # 1

23. Swap two elements

Swap values using tuple unpacking.

def swap(a, b):
    return b, a
print(swap(1, 0))   # (0, 1)

24. Function objects list

Store functions in a list and call by index.

def f():
    print("i'm f")
def g():
    print("i'm g")
[ f, g ][1]()   # prints i'm g

25. Reverse sequence generation

Generate a descending list using range() with a negative step.

list(range(10, -1, -1))   # [10, 9, ..., 0]

26. Five types of function parameters

Demonstrate positional, keyword, default, *args, and **kwargs.

def f(a, *b, c=10, **d):
    print(f'a:{a}, b:{b}, c:{c}, d:{d}')

f(1, 2, 5, width=10, height=20)   # a:1, b:(2,5), c:10, d:{'width':10,'height':20}

27. Slice object

Use a slice object for reusable slicing.

perfect_slice = slice(1, 10, 2)
cake1 = list(range(5, 0, -1))
print(cake1[perfect_slice])   # [4, 2]

28. Lambda animation demo

Explain lambda functions with an example that finds the longest list.

def max_len(*lists):
    return max(*lists, key=lambda v: len(v))

r = max_len([1,2,3], [4,5,6,7], [8])
print(f'Longest list is {r}')   # [4,5,6,7]

4. Data Structures

29. Create a dictionary

Various ways to build dictionaries.

dict()
{'a':'a', 'b':'b'}
dict(zip(['a','b'], [1,2]))
dict([('a',1), ('b',2)])

30. Frozen set

Create an immutable set.

frozenset([1,1,3,2,3])   # frozenset({1,2,3})

31. Convert to set

Remove duplicates by converting a list to a set.

set([1,4,2,3,1])   # {1,2,3,4}

32. Slice object creation

Instantiate a slice and use it on a list.

my_slice = slice(0,5,2)
a = [1,4,2,3,1]
print(a[my_slice])   # [1,2,1]

33. Convert to tuple

Make an immutable tuple from a list.

i_am_tuple = tuple([1,3,5])   # (1, 3, 5)

5. Classes and Objects

34. Callable check

Use callable() to test if an object can be called.

callable(str)   # True
callable(int)   # True

35. __repr__ output

Define __repr__ to control the string representation of an instance.

class Student:
    def __init__(self, id, name):
        self.id = id
        self.name = name
    def __repr__(self):
        return f'id = {self.id}, name = {self.name}'

36. Class method

Use @classmethod to define a method that receives the class itself.

class Student:
    @classmethod
    def f(cls):
        print(cls)

37. Delete attribute

Remove an attribute with delattr() and check existence with hasattr().

delattr(xiaoming, 'id')
hasattr(xiaoming, 'id')   # False

38. List all attributes

Use dir() to list an object's attributes and methods.

dir(xiaoming)

39. Get attribute value

Retrieve an attribute dynamically with getattr().

getattr(xiaoming, 'name')   # 'xiaoming'

40. Attribute existence

Check if an object has a given attribute using hasattr().

hasattr(xiaoming, 'name')   # True
hasattr(xiaoming, 'address')   # False

41. Object identity

Get the memory address of an object with id().

id(xiaoming)

42. Instance test

Determine if an object is an instance of a class with isinstance().

isinstance(xiaoming, Student)   # True

43. Subclass test

Check inheritance relationships with issubclass().

class Undergraduate(Student):
    pass
issubclass(Undergraduate, Student)   # True

44. Root object

All classes inherit from object.

type(object())   # object

45. Property creation

Define managed attributes using property() or the @property decorator.

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

46. Type inspection

Use type() to get an object's type.

type(xiaoming)   # __main__.Student

47. Metaclass concept

Explain that classes themselves are objects created by the metaclass type.

Student = type('Student', (), {})

6. Tools

48. Enumerate

Iterate with index using enumerate().

s = ['a', 'b', 'c']
for i, v in enumerate(s, 1):
    print(i, v)
# 1 a
2 b
3 c

49. Size of an object

Get memory consumption with sys.getsizeof().

import sys
a = {'a':1, 'b':2.0}
sys.getsizeof(a)   # e.g., 240

50. Filter

Filter elements using a predicate function.

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

51. Hash value

Obtain an object's hash with hash(). Mutable built‑ins are unhashable.

hash(xiaoming)   # e.g., 6139638
hash([1,2,3])   # raises TypeError

52. Help

Show documentation for an object using help().

help(xiaoming)

53. User input

Read a line from standard input with input().

name = input()   # user types "aa"

54. Create iterator

Convert an iterable to an iterator with iter().

lst = [1,3,5]
for i in iter(lst):
    print(i)

55. Open file

Open a file with various modes (r, w, x, a, b, t, +).

fo = open('D:/a.txt', mode='r', encoding='utf-8')
content = fo.read()

56. Range

Generate immutable sequences with range().

range(11)          # 0..10
range(0, 11, 1)   # same as above

57. Reversed iterator

Iterate backwards using reversed().

for i in reversed([1,4,2,3,1]):
    print(i)

58. Zip aggregation

Combine multiple iterables element‑wise with zip().

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

59. Conditional operation

Choose a function based on a condition.

from operator import add, sub

def add_or_sub(a, b, oper):
    return (add if oper == '+' else sub)(a, b)

add_or_sub(1, 2, '-')   # -1

60. Object serialization

Serialize custom objects to JSON using json.dump() with a custom encoder.

import json
class Student:
    def __init__(self, **args):
        self.ids = args['ids']
        self.name = args['name']
        self.address = args['address']

xiaoming = Student(ids=1, name='xiaoming', address='北京')
xiaohong = Student(ids=2, name='xiaohong', address='南京')
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, sort_keys=True)
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Data Structuresclassesfunctionstoolsbasics
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

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.