Supplementary Python Basics
This article will introduce supplementary content for Python basics.
1. Detailed Function Parameters
Compared to other programming languages, the passing and defining of function parameters in Python offers more convenient and practical features.
1.1 Passing Parameters When Calling Functions
When calling functions in Python, multiple parameter-passing methods are supported, such as:
Python |
---|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 | def f(a, b, c, d):
print(a, b, c, d)
# Directly pass parameters, must follow the order
f(1, 2, 3, 4)
# Pass parameters by specifying parameter names, no need to follow the order
f(c=3, b=2, a=1, d=4)
# Pass parameters as a list using *, must follow the order
params = [1, 2, 3, 4]
f(*params)
# Pass parameters as a dictionary using **, no need to follow the order
params = {
'd': 4,
'c': 3,
'a': 1,
'b': 2,
}
f(**params)
# Mixed usage above (pay attention to the order, positional arguments come first, named arguments come after)
params_list = [2]
params_dict = { 'd': 4 }
f(1, *params_list, c=3, **params_dict)
|
Output:
1.2 Defining Functions with Indefinite Parameters
When defining functions, multiple parameter definition methods are also supported:
Python |
---|
1
2
3
4
5
6
7
8
9
10
11
12
13
14 | def f(a, b=2, *args, **kwargs):
'''
a is a fixed parameter
b has a default value, can be omitted
*args automatically collects extra positional arguments
**kwargs automatically collects extra named arguments
'''
print(a, b, args, kwargs)
f(1)
f(1, 2)
f(1, 2, 3, 4)
f(1, 2, x=7, y=8)
f(1, 2, 3, 4, x=7, y=8)
|
Output:
Text Output |
---|
| 1 2 () {}
1 2 (3, 4) {}
1 2 () {'x': 7, 'y': 8}
1 2 (3, 4) {'x': 7, 'y': 8}
|
2. Lambda Functions
Python supports the Lambda function syntax, which facilitates creating simple functions. The syntax structure is as follows:

Example |
---|
| def plus(x, y):
return x + y
# Equivalent to
lambda_plus = lambda x, y: x + y
print(plus(1, 2) == lambda_plus(1, 2))
|
Output:
3. Truth Value Testing
In Python, besides the bool types True
and False
, many other values can be directly used in if
, while
statements or other contexts that require truth value testing:
Python |
---|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 | for v in [ 0, 1, 2]:
result = bool(v)
print(f'Number {v} will be evaluated as: {result}')
for v in [ 'false', '' ]:
result = bool(v)
print(f'String "{v}" will be evaluated as: {result}')
for v in [ [1, 2, 3], [] ]:
result = bool(v)
print(f'List {v} will be evaluated as: {result}')
for v in [ (1, 2, 3), tuple() ]:
result = bool(v)
print(f'Tuple {v} will be evaluated as: {result}')
for v in [ { 'a': 1}, {} ]:
result = bool(v)
print(f'Dictionary {v} will be evaluated as: {result}')
for v in [ {1, 2, 3}, set() ]:
result = bool(v)
print(f'Set {v} will be evaluated as: {result}')
|
Output:
Text Output |
---|
1
2
3
4
5
6
7
8
9
10
11
12
13 | Number 0 will be evaluated as: False
Number 1 will be evaluated as: True
Number 2 will be evaluated as: True
String "false" will be evaluated as: True
String "" will be evaluated as: False
List [1, 2, 3] will be evaluated as: True
List [] will be evaluated as: False
Tuple (1, 2, 3) will be evaluated as: True
Tuple () will be evaluated as: False
Dictionary {'a': 1} will be evaluated as: True
Dictionary {} will be evaluated as: False
Set {1, 2, 3} will be evaluated as: True
Set set() will be evaluated as: False
|
4. Built-in Functions
Python includes many useful built-in functions that allow you to achieve desired results quickly without writing complex code.
4.1 General Category
Python |
---|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32 | print('Generator producing elements in the range [0, 3):')
for x in range(3):
print(f' {x}')
print('Generator producing elements in the range [3, 5):')
for x in range(3, 5):
print(f' {x}')
print('Generator producing elements in the range [3, 10) with a step of 2:')
for x in range(3, 10, 2):
print(f' {x}')
value = [ 'a', 'b', 'c' ]
print('Return type:', type(value))
print('Return attributes:', dir(value))
print('Return length:', len(value))
print('Return sequence with index:')
for i, x in enumerate(value):
print(f' value[{i}] = {x}')
value = [ 'a', 'b', 'c' ]
other = [ 'x', 'y', 'z' ]
result = list(zip(value, other))
print('Return paired lists from two lists:', result)
l = [ 1, 2, 3, 4, 5 ]
result = list(map(lambda x: x ** 2, l))
print('Return new list where each element is processed by the specified function:', result)
result = list(filter(lambda x: x % 2 == 0, l))
print('Return new list where each element is judged as True by the specified function:', result)
|
The functions range(..), zip(...), map(...), filter(...) return iterable objects, which can be used directly in loops or converted into lists using list(...)
Output:
Text Output |
---|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 | Generator producing elements in the range [0, 3):
0
1
2
Generator producing elements in the range [3, 5):
3
4
Generator producing elements in the range [3, 10) with a step of 2:
3
5
7
9
Return type: <class 'list'>
Return attributes: ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
Return length: 3
Return sequence with index:
value[0] = a
value[1] = b
value[2] = c
Return paired lists from two lists: [('a', 'x'), ('b', 'y'), ('c', 'z')]
Return new list where each element is processed by the specified function: [1, 4, 9, 16, 25]
Return new list where each element is judged as True by the specified function: [2, 4]
|
4.2 Mathematical Category
Python |
---|
| print('Return absolute value :', abs(-5))
print('Return rounded integer :', round(2.6))
print('Return exponent :', pow(2, 3))
print('Return quotient and remainder of division:', divmod(9, 2))
print('Return maximum value :', max([1, 5, 2, 9]))
print('Return minimum value :', min([9, 2, -4, 2]))
print('Return sum :', sum([2, -1, 9, 12]))
|
Output:
Text Output |
---|
| Return absolute value : 5
Return rounded integer : 3
Return exponent : 8
Return quotient and remainder of division: (4, 1)
Return maximum value : 9
Return minimum value : -4
Return sum : 22
|
4.3 Conversion Category
Python |
---|
| print('Convert to integer :', int("5"))
print('Convert to float :', float(2))
print('Convert to string :', str(2.3))
print('Convert to boolean :', bool(0))
print('Convert to binary :', bin(56))
print('Convert to octal :', oct(56))
print('Convert to hexadecimal :', hex(56))
print('Return ASCII code corresponding to character:', ord("A"))
print('Return character corresponding to ASCII code:', chr(65))
|
Output:
Text Output |
---|
| Convert to integer : 5
Convert to float : 2.0
Convert to string : 2.3
Convert to boolean : False
Convert to binary : 0b111000
Convert to octal : 0o70
Convert to hexadecimal : 0x38
Return ASCII code corresponding to character: 65
Return character corresponding to ASCII code: A
|
4.4 Initialization Category
Python |
---|
| print('Initialize list:', list((1, 2, 3)))
print('Initialize tuple:', tuple([2, 3, 4]))
print('Initialize dictionary:', dict(a=1, b="hello", c=True))
print('Initialize set:', set([5, 6, 7]))
|
Output:
Text Output |
---|
| Initialize list: [1, 2, 3]
Initialize tuple: (2, 3, 4)
Initialize dictionary: {'a': 1, 'b': 'hello', 'c': True}
Initialize set: {5, 6, 7}
|
4.5 Class and Object Operations
Python |
---|
| print('Check if an object is an instance of a class:', isinstance(100, int))
print('Check if an object is an instance of one of several classes:', isinstance(100, (int, float)))
class User(object):
pass
class Student(User):
pass
print('Check if a class is a subclass of another class:', issubclass(Student, User))
|
Output:
Text Output |
---|
| Check if an object is an instance of a class: True
Check if an object is an instance of one of several classes: True
Check if a class is a subclass of another class: True
|
Python |
---|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 | result = 'Hello, I am %s, I am %d years old' % ('John Doe', 25)
print('Old-style tuple formatting (not recommended):', result)
result = 'Hello, I am %(name)s, I am %(age)d years old' % { 'name': 'John Doe', 'age' : 25 }
print('Old-style dictionary formatting (not recommended):', result)
result = 'Hello, I am {}, I am {} years old'.format('John Doe', 25)
print('format function formatting, parameters arranged in order:', result)
result = 'Hello, I am {0}, I am {1} years old, {1} years ago was born'.format('John Doe', 25)
print('format function formatting, parameters inserted by index:', result)
params = {
'name': 'John Doe',
'age' : 25,
'job' : 'student',
}
result = 'Hello, I am {name}, I am {age} years old, {age} years ago was born'.format(**params)
print('format function formatting, parameters inserted by dictionary key (extra parameters do not affect):', result)
result = 'Hello, I am {name}, I am {age} years old, {age} years ago was born'.format(name='John Doe', age=25, job='student')
print('format function formatting, parameters inserted by parameter name=value (extra parameters do not affect):', result)
name = 'John Doe'
age = 25
result = f'Hello, I am "{name}", I am {age} years old, {age} years ago was born'
print('Latest f-string formatting (recommended):', result)
|
When using f-strings, pay attention to single and double quotes, refer to 'Python Basics / Basic Data Types / Strings str' for details.
Output:
Text Output |
---|
| Old-style tuple formatting (not recommended): Hello, I am John Doe, I am 25 years old
Old-style dictionary formatting (not recommended): Hello, I am John Doe, I am 25 years old
format function formatting, parameters arranged in order: Hello, I am John Doe, I am 25 years old
format function formatting, parameters inserted by index: Hello, I am John Doe, I am 25 years old, 25 years ago was born
format function formatting, parameters inserted by dictionary key (extra parameters do not affect): Hello, I am John Doe, I am 25 years old, 25 years ago was born
format function formatting, parameters inserted by parameter name=value (extra parameters do not affect): Hello, I am John Doe, I am 25 years old, 25 years ago was born
Latest f-string formatting (recommended): Hello, I am "John Doe", I am 25 years old, 25 years ago was born
|
6. String Methods
Strings are very commonly used objects in Python. Python strings have rich built-in methods.
Python |
---|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43 | s = 'Hello, world! Python world!'
sub = 'world'
print('Return the number of occurrences of the specified string :', s.count(sub))
print('Return the index of the first occurrence of the specified string (returns -1 if not found) :', s.find(sub))
print('Return the index of the first occurrence of the specified string from right (returns -1 if not found) :', s.rfind(sub))
print('Return the index of the first occurrence of the specified string (raises error if not found) :', s.index(sub))
print('Return the index of the first occurrence of the specified string from right (raises error if not found) :', s.rindex(sub))
print('Check if the string contains only letters and numbers :', 'abcd1234'.isalnum())
print('Check if the string contains only letters :', 'abcd'.isalpha())
print('Check if the string contains only digits :', '1234'.isdigit())
print('Check if every word starts with uppercase letter :', 'Tom Jerry'.istitle())
print('Check if the string consists entirely of spaces :', ' '.isspace())
print('Check if the string is all lowercase :', 'TOM JERRY'.isupper())
print('Check if the string is all uppercase :', 'tom jerry'.islower())
s = 'apple,microsoft,ibm,intel,amd'
print('Split the string by the specified separator :', s.split(','))
print('Split the string by the specified separator, limit the split count to 3 times :', s.split(',', 3))
print('Split the string by the specified separator from right :', s.rsplit(','))
print('Split the string by the specified separator from right, limit the split count to 3 times :', s.rsplit(',', 3))
print('Join the list with the string as separator :', ', '.join(['Tom', 'Jerry', 'John']))
print('Join the list with empty string as separator :', ''.join(['Tom', 'Jerry', 'John']))
print(f'Remove leading and trailing spaces :【{" abc ".strip()}】')
print(f'Remove trailing spaces :【{" abc ".rstrip()}】')
print(f'Remove leading spaces :【{" abc ".lstrip()}】')
print(f'Remove specified characters at both ends :【{"xyzabc789".strip("xyz789")}】')
print(f'Remove specified characters at both ends :【{"xyzabc789".rstrip("xyz789")}】')
print(f'Remove specified characters at both ends :【{"xyzabc789".lstrip("xyz789")}】')
print('Replace specified content in the string :', 'abc123abc'.replace('123', 'xyz'))
print('Capitalize the first letter of the string :', 'hello, world'.capitalize())
print('Convert the entire string to uppercase :', 'Hello, World'.upper())
print('Convert the entire string to lowercase :', 'Hello, World'.lower())
print('Swap case of the string :', 'Hello, World'.swapcase())
print('Capitalize the first letter of each word :', 'hello, world'.title())
print(f'Center the string within the specified width :【{"abc".center(10)}】')
print(f'Left justify the string within the specified width :【{"abc".ljust(10)}】')
print(f'Right justify the string within the specified width :【{"abc".rjust(10)}】')
print(f'Left justify the string within the specified width with padding :【{"abc".ljust(10, "_")}】')
print(f'Center the string within the specified width with padding :【{"abc".center(10, "_")}】')
print(f'Right justify the string within the specified width with padding :【{"abc".rjust(10, "_")}】')
|
Output:
Text Output |
---|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36 | Return the number of occurrences of the specified string : 2
Return the index of the first occurrence of the specified string (returns -1 if not found) : 7
Return the index of the first occurrence of the specified string from right (returns -1 if not found) : 21
Return the index of the first occurrence of the specified string (raises error if not found) : 7
Return the index of the first occurrence of the specified string from right (raises error if not found) : 21
Check if the string contains only letters and numbers : True
Check if the string contains only letters : True
Check if the string contains only digits : True
Check if every word starts with uppercase letter : True
Check if the string consists entirely of spaces : True
Check if the string is all lowercase : True
Check if the string is all uppercase : True
Split the string by the specified separator : ['apple', 'microsoft', 'ibm', 'intel', 'amd']
Split the string by the specified separator, limit the split count to 3 times : ['apple', 'microsoft', 'ibm', 'intel,amd']
Split the string by the specified separator from right : ['apple', 'microsoft', 'ibm', 'intel', 'amd']
Split the string by the specified separator from right, limit the split count to 3 times : ['apple,microsoft', 'ibm', 'intel', 'amd']
Join the list with the string as separator : Tom, Jerry, John
Join the list with empty string as separator : TomJerryJohn
Remove leading and trailing spaces :【abc】
Remove trailing spaces :【 abc】
Remove leading spaces :【abc 】
Remove specified characters at both ends :【abc】
Remove specified characters at both ends :【xyzabc】
Remove specified characters at both ends :【abc789】
Replace specified content in the string : abcxyzabc
Capitalize the first letter of the string : Hello, world
Convert the entire string to uppercase : HELLO, WORLD
Convert the entire string to lowercase : hello, world
Swap case of the string : hELLO, wORLD
Capitalize the first letter of each word : Hello, World
Center the string within the specified width :【 abc 】
Left justify the string within the specified width :【abc 】
Right justify the string within the specified width :【 abc】
Left justify the string within the specified width with padding :【abc_______】
Center the string within the specified width with padding :【___abc____】
Right justify the string within the specified width with padding :【_______abc】
|
7. List Methods
Lists are very commonly used objects in Python. Python lists have rich built-in methods.
Since tuples are similar to lists, some methods that do not alter the original object also apply to tuples
Python |
---|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 | l = [True, 1, "hello!", False]
print('Count the number of elements in the list :', len(l))
print('Check if all elements in the list are true :', all(l))
print('Check if any element in the list is true :', any(l))
l = [3, 2, 1]
print('Return the smallest element in the list:', min(l))
print('Return the largest element in the list:', max(l))
print('Return the sum of elements in the list:', sum(l))
print('Return a new sorted list:', sorted(l))
print('Return a new reversed list:', list(reversed(l)))
l = [3, 3, 2, 1]
print('Return the number of occurrences of the specified element in the list :', l.count(3))
print('Return the index of the first occurrence of the specified element in the list:', l.index(2))
l.sort()
print('Sort this list:', l)
l.reverse()
print('Reverse this list:', l)
l.extend([7, 8, 9])
print('Concatenate another list to this list:', l)
l.append(10)
print('Append an element to this list:', l)
x = l.pop()
print('Pop an element from this list:', l, x)
del l[0]
print('Delete the element at the specified index from this list:', l)
|
Output:
Text Output |
---|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 | Count the number of elements in the list : 4
Check if all elements in the list are true : False
Check if any element in the list is true : True
Return the smallest element in the list: 1
Return the largest element in the list: 3
Return the sum of elements in the list: 6
Return a new sorted list: [1, 2, 3]
Return a new reversed list: [1, 2, 3]
Return the number of occurrences of the specified element in the list : 2
Return the index of the first occurrence of the specified element in the list: 2
Sort this list: [1, 2, 3, 3]
Reverse this list: [3, 3, 2, 1]
Concatenate another list to this list: [3, 3, 2, 1, 7, 8, 9]
Append an element to this list: [3, 3, 2, 1, 7, 8, 9, 10]
Pop an element from this list: [3, 3, 2, 1, 7, 8, 9] 10
Delete the element at the specified index from this list: [3, 2, 1, 7, 8, 9]
|
sorted(...) and reversed(...) functions return new lists and do not modify the original list. However, list.sort() and list.reverse() sort the original list and do not produce new lists
reversed(...) and range(...) functions similarly return generators. If an actual list is required, use the list(...) function to convert them into actual lists