Unlock Python’s 68 Built‑in Functions: A Complete Guide for Beginners
This article presents a comprehensive overview of Python’s 68 built‑in functions, categorizing them into numeric, data‑structure, scope, iterator, string execution, I/O, memory, file, module, and utility groups, and provides clear code examples for each to help beginners master Python fundamentals.
Python provides 68 built‑in functions (up to version 3.6.2) that can be used directly, such as print, input, and many others.
abs() dict() help() min() setattr()
all() dir() hex() next() slice()
any() divmod() id() object() sorted()
ascii() enumerate() input() oct() staticmethod()
bin() eval() int() open() str()
bool() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()
delattr() hash() memoryview() set()Related to Numbers
1. Data Types
bool: Boolean type (True, False)
int: Integer type
float: Floating‑point type
complex: Complex number type
2. Base Conversion
bin()converts a value to binary oct() converts a value to octal hex() converts a value to hexadecimal
print(bin(10)) # binary: 0b1010
print(hex(10)) # hexadecimal: 0xa
print(oct(10)) # octal: 0o123. Mathematical Operations
abs()returns absolute value divmod() returns quotient and remainder round() rounds a number pow(a, b[, c]) computes aⁿ, optionally modulo c sum() returns the sum of an iterable min() returns the smallest value max() returns the largest value
print(abs(-2)) # 2
print(divmod(20, 3)) # (6, 2)
print(round(4.50)) # 4
print(round(4.51)) # 5
print(pow(10, 2, 3)) # 1 (10² mod 3)
print(sum([1,2,3,4,5,6,7,8,9,10])) # 55
print(min(5,3,9,12,7,2)) # 2
print(max(7,3,15,9,4,13)) # 15Related to Data Structures
1. Sequences
(1) Lists and tuples list() converts an iterable to a list tuple() converts an iterable to a tuple
print(list((1,2,3,4,5,6))) # [1, 2, 3, 4, 5, 6]
print(tuple([1,2,3,4,5,6])) # (1, 2, 3, 4, 5, 6)(2) Related built‑ins reversed() returns an iterator that yields items in reverse order slice() creates a slice object for list slicing
lst = "你好啊"
it = reversed(lst) # returns an iterator, original unchanged
print(list(it)) # ['啊', '好', '你']
lst = [1,2,3,4,5,6,7]
print(lst[1:3:1]) # [2, 3]
s = slice(1, 3, 1)
print(lst[s]) # [2, 3](3) Strings str() converts a value to a string
print(str(123) + '456') # 123456
print(format('hello world!', '^20')) # centered
print(format('hello world!', '<20')) # left‑aligned
print(format('hello world!', '>20')) # right‑aligned
print(format(3, 'b')) # binary: 11
print(format(97, 'c')) # unicode character: a
print(format(11, 'x')) # hex (lowercase): b
print(format(11, 'X')) # hex (uppercase): B
print(format(11, 'e')) # scientific notation: 1.100000e+01 bytes()converts a string to a bytes object bytearray() creates a mutable byte array ord() returns the Unicode code point of a character chr() returns the character for a Unicode code point ascii() returns a printable representation of an object repr() returns the string representation that can be evaluated
bs = bytes("今天吃饭了吗", encoding="utf-8")
print(bs) # b'...'
ret = bytearray("alex", encoding='utf-8')
print(ret[0]) # 97
print(ret) # bytearray(b'alex')
ret[0] = 65
print(str(ret)) # bytearray(b'Alex')
print(ord('a')) # 97
print(chr(65)) # A
print(ascii('@')) # '@'2. Collections
dict()creates a dictionary set() creates a set frozenset() creates an immutable set
3. Collection Utilities
len()returns the number of items sorted() returns a new sorted list; optional key and reverse arguments enumerate() yields (index, element) pairs all() returns True if every element is truthy any() returns True if at least one element is truthy zip() aggregates elements from multiple iterables into tuples filter() filters an iterable using a predicate function map() applies a function to each element of an iterable
lst = [5,7,6,12,1,13,9,18,5]
lst.sort()
print(lst) # [1,5,5,6,7,9,12,13,18]
print(sorted(lst, reverse=True)) # [18,13,12,9,7,6,5,5,1]
lst = ['one','two','three','four','five','six']
print(sorted(lst, key=len)) # ['one','two','six','four','five','three']
for index, el in enumerate(['one','two','three','four','five'], 1):
print(index)
print(el)
print(all([1,'hello',True,9])) # True
print(any([0,0,0,False,1,'good'])) # True
lst1 = [1,2,3,4,5,6]
lst2 = ['A','B','C','D','E','F']
lst3 = ['US','CN','FR','IT','KR','JP']
for el in zip(lst1, lst2, lst3):
print(el)
def is_odd(i):
return i % 2 == 1
lst = [1,2,3,4,5,6,7,8,9]
print(list(filter(is_odd, lst))) # [1,3,5,7,9]
def identity(i):
return i
print(list(map(identity, [1,2,3,4,5,6,7]))) # [1,2,3,4,5,6,7]Related to Scope
locals()returns a dictionary of the current local symbol table globals() returns a dictionary of the current global symbol table
def func():
a = 10
print(locals()) # {'a': 10}
print(globals()) # {...}
print("今天内容很多")
func()Related to Iterators and Generators
range()generates a sequence of numbers iter() obtains an iterator from an iterable next() advances an iterator
for i in range(15, -1, -5):
print(i) # 15 10 5 0
lst = [1,2,3,4,5]
it = iter(lst)
print(it.__next__()) # 1
print(next(it)) # 2
print(next(it)) # 3
print(next(it)) # 4Executing Code from Strings
eval()evaluates a string as an expression and returns the result exec() executes a string as a block of statements compile() compiles source code to a code object that can be executed with exec or evaluated with
eval s1 = input("请输入 a+b:") # e.g., 8+9
print(eval(s1)) # 17
s2 = "for i in range(5): print(i)"
exec(s2) # prints 0‑4
code = "for i in range(3): print(i)"
obj = compile(code, "", mode="exec")
exec(obj) # 0 1 2
expr = "5+6+7"
obj2 = compile(expr, "", mode="eval")
print(eval(obj2)) # 18Input and Output
print()outputs data to the console input() reads a line from standard input
print("hello", "world", sep="*", end="@") # hello*world@Memory Related
hash()returns the hash value of an object (int, str, bool, tuple). Hash tables give dictionaries fast look‑ups but require extra memory.
s = "alex"
print(hash(s)) # e.g., -168324845050430382
print(id(s)) # memory address of the objectFile Operations
open()opens a file and returns a file object
f = open('file', mode='r', encoding='utf-8')
content = f.read()
f.close()Modules
__import__()imports a module dynamically
import os
name = input("请输入你要导入的模块:")
__import__(name) # dynamically imports the specified moduleHelp
help()displays the documentation of an object
print(help(str)) # shows help for the str typeCalling
callable()checks whether an object appears callable
a = 10
print(callable(a)) # False
def f():
print("hello")
print(callable(f)) # TrueInspect Built‑in Attributes
dir()lists the attributes of an object
print(dir(tuple)) # shows methods of the tuple typeSigned-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Linux
Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.
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.
