Fundamentals 17 min read

Python Built-in Functions and Common Usage Guide

This article provides a comprehensive overview of Python's built-in functions, data types, numeric conversions, mathematical operations, data structures, string handling, scope utilities, iterator tools, dynamic code execution, and file and module operations, complete with practical code examples for each concept.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Python Built-in Functions and Common Usage Guide

Python offers 68 built-in functions (as of version 3.6.2) such as print , input , abs , len , and many others that can be used directly without import.

Numeric related functions

Data types: bool , int , float , complex

Base conversion: bin() (binary), oct() (octal), hex() (hexadecimal)

<code><span>print(bin(10))   # 二进制:0b1010</span></code><code><span>print(hex(10))   # 十六进制:0xa</span></code><code><span>print(oct(10))   # 八进制:0o12</span></code>

Mathematical operations

abs() – absolute value

divmod() – quotient and remainder

round() – rounding

pow(a, b, mod=None) – exponentiation (optional modulus)

sum() , min() , max() – aggregation

<code><span>print(abs(-2))               # 2</span></code><code><span>print(divmod(20, 3))        # (6, 2)</span></code><code><span>print(round(4.51))           # 5</span></code><code><span>print(pow(10, 2, 3))        # 1</span></code><code><span>print(sum([1,2,3,4,5,6,7,8,9,10]))  # 55</span></code><code><span>print(min(5,3,9,12,7,2))   # 2</span></code><code><span>print(max(7,3,15,9,4,13))   # 15</span></code>

Sequences and collections

list() converts an iterable to a list; tuple() converts to a tuple.

reversed() returns an iterator that yields items in reverse order.

slice() creates a slice object for list slicing.

<code><span>lst = ["你好啊"]</span></code><code><span>it = reversed(lst)</span></code><code><span>print(list(it))   # ['啊', '好', '你']</span></code><code><span>lst = [1,2,3,4,5,6,7]</span></code><code><span>print(lst[1:3:1])   # [2, 3]</span></code><code><span>s = slice(1,3,1)</span></code><code><span>print(lst[s])       # [2, 3]</span></code>

String handling

str() converts a value to a string.

format() formats strings with alignment, base conversion, and scientific notation.

<code><span>print(str(123) + '456')               # 123456</span></code><code><span>print(format('hello world!', '^20')) #   hello world!   </span></code><code><span>print(format('hello world!', '<20')) # hello world!        </span></code><code><span>print(format('hello world!', '>20')) #        hello world!</span></code><code><span>print(format(11, 'b'))               # 1011</span></code><code><span>print(format(11, 'c'))               # k</span></code><code><span>print(format(123456789, 'e'))         # 1.234568e+08</span></code>

Bytes and encoding

bytes() creates a bytes object from a string.

bytearray() creates a mutable byte array.

ord() returns the Unicode code point of a character; chr() returns the character for a code point.

<code><span>bs = bytes("今天吃饭了吗", encoding="utf-8")</span></code><code><span>print(bs)   # b'\xe4\xbb\x8a\xe5\xa4\xa9\xe5\x90\x83\xe9\xa5\xad\xe4\xba\x86\xe5\x90\x97'</span></code><code><span>ret = bytearray("alex", encoding="utf-8")</span></code><code><span>print(ret[0])   # 97</span></code><code><span>print(ret)      # bytearray(b'alex')</span></code><code><span>ret[0] = 65</span></code><code><span>print(str(ret)) # bytearray(b'Alex')</span></code><code><span>print(ord('a'))   # 97</span></code><code><span>print(chr(65))    # A</span></code>

Collections utilities

len() – number of items.

sorted() – returns a new sorted list; supports key and reverse arguments.

enumerate() – yields (index, element) pairs.

all() / any() – logical aggregation over iterables.

zip() – aggregates elements from multiple iterables.

filter() – filters items using a predicate function.

map() – applies a function to each item.

<code><span>lst = [5,7,6,12,1,13,9,18,5]</span></code><code><span>print(sorted(lst))                # [1, 5, 5, 6, 7, 9, 12, 13, 18]</span></code><code><span>print(sorted(lst, reverse=True)) # [18, 13, 12, 9, 7, 6, 5, 5, 1]</span></code><code><span>def f(s): return len(s)</span></code><code><span>print(sorted(['one','two','three','four','five','six'], key=f))</span></code><code><span>print(all([1,'hello',True,9]))   # True</span></code><code><span>print(any([0,0,0,False,1,'good'])) # True</span></code><code><span>lst1 = [1,2,3,4,5,6]</span></code><code><span>lst2 = ['醉乡民谣','驴得水','放牛班的春天','美丽人生','辩护人','被嫌弃的松子的一生']</span></code><code><span>lst3 = ['美国','中国','法国','意大利','韩国','日本']</span></code><code><span>for el in zip(lst1, lst2, lst3): print(el)</span></code>

Scope utilities

locals() – dictionary of current local symbol table.

globals() – dictionary of global symbol table.

<code><span>def func():</span></code><code><span>    a = 10</span></code><code><span>    print(locals())   # {'a': 10}</span></code><code><span>    print(globals())  # {...}</span></code><span>func()</span></code>

Iterator and generator helpers

range() – generates arithmetic progressions.

iter() – returns an iterator from an iterable.

next() – fetches the next item from an iterator.

<code><span>for i in range(15, -1, -5): print(i)</span></code><code><span># 15 10 5 0</span></code><code><span>lst = [1,2,3,4,5]</span></code><code><span>it = iter(lst)</span></code><code><span>print(next(it))   # 1</span></code>

Dynamic code execution

eval() – evaluates an expression string and returns the result.

exec() – executes a block of code.

compile() – compiles source code to a code object.

<code><span>s1 = input("请输入a+b:")   # e.g., 8+9</span></code><code><span>print(eval(s1))               # 17</span></code><code><span>s2 = "for i in range(5): print(i)"</span></code><code><span>exec(s2)                     # prints 0-4</span></code><code><span>code1 = "for i in range(3): print(i)"</span></code><code><span>com = compile(code1, "", mode="exec")</span></code><code><span>exec(com)                     # 0 1 2</span></code>

Input/Output

print() – prints to stdout with optional sep and end parameters.

input() – reads a line from stdin.

<code><span>print("hello", "world", sep="*", end="@")   # hello*world@</span></code>

Memory utilities

hash() – returns the hash value of an object.

id() – returns the memory address of an object.

<code><span>s = 'alex'</span></code><code><span>print(hash(s))   # e.g., -168324845050430382</span></code><code><span>print(id(s))     # e.g., 2278345368944</span></code>

File operations

open() – opens a file and returns a file object.

<code><span>f = open('file', mode='r', encoding='utf-8')</span></code><code><span>content = f.read()</span></code><code><span>f.close()</span></code>

Module handling

__import__() – imports a module dynamically.

help() – displays the help page for an object.

callable() – checks if an object appears callable.

dir() – lists the attributes of an object.

<code><span>name = input("请输入你要导入的模块:")</span></code><code><span>__import__(name)</span></code><code><span>print(help(str))</span></code><code><span>a = 10</span></code><code><span>print(callable(a))   # False</span></code><code><span>def f(): print("hello")</span></code><code><span>print(callable(f))   # True</span></code><code><span>print(dir(tuple))</span></code>

This guide consolidates essential Python built‑in functions and utilities, providing clear explanations and ready‑to‑run code snippets for learners and developers seeking a solid foundation in Python programming.

Data Typescode examplesTutorialProgramming Basicsbuilt-in-functions
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.