Supplementary Python Basics
This article will introduce supplementary content of Python basics.
1. Detailed Function Parameters
Compared to other programming languages, the passing and definition of function parameters in Python have 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)
# The above can be mixed (note 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 Variable 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 parameters
**kwargs automatically collects extra named parameters
'''
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 lambda function syntax, which is used to conveniently create 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 True
and False
of the bool type, many other values can be directly evaluated in if
, while
statements or other truth value tests:
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} evaluates to: {result}')
for v in [ 'false', '' ]:
result = bool(v)
print(f'String "{v}" evaluates to: {result}')
for v in [ [1, 2, 3], [] ]:
result = bool(v)
print(f'List {v} evaluates to: {result}')
for v in [ (1, 2, 3), tuple() ]:
result = bool(v)
print(f'Tuple {v} evaluates to: {result}')
for v in [ { 'a': 1}, {} ]:
result = bool(v)
print(f'Dictionary {v} evaluates to: {result}')
for v in [ {1, 2, 3}, set() ]:
result = bool(v)
print(f'Set {v} evaluates to: {result}')
|
Output:
Text Output |
---|
1
2
3
4
5
6
7
8
9
10
11
12
13 | Number 0 evaluates to: False
Number 1 evaluates to: True
Number 2 evaluates to: True
String "false" evaluates to: True
String "" evaluates to: False
List [1, 2, 3] evaluates to: True
List [] evaluates to: False
Tuple (1, 2, 3) evaluates to: True
Tuple () evaluates to: False
Dictionary {'a': 1} evaluates to: True
Dictionary {} evaluates to: False
Set {1, 2, 3} evaluates to: True
Set set() evaluates to: False
|
4. Built-in Functions
Python includes many useful built-in functions that allow you to quickly achieve desired results 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 for elements in the range [0, 3):')
for x in range(3):
print(f' {x}')
print('Generator for elements in the range [3, 5):')
for x in range(3, 5):
print(f' {x}')
print('Generator for elements in the range [3, 10) with step 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 indices:')
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 a given function:', result)
result = list(filter(lambda x: x % 2 == 0, l))
print('Return new list where each element is judged as True by a given function:', result)
|
The return values of range(...)
, zip(...)
, map(...)
and filter(...)
are iterable objects that can be directly used in loops or converted to 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 for elements in the range [0, 3):
0
1
2
Generator for elements in the range [3, 5):
3
4
Generator for elements in the range [3, 10) with step 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 indices:
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 a given function: [1, 4, 9, 16, 25]
Return new list where each element is judged as True by a given 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:', divmod(9, 2))
print('Return maximum :', max([1, 5, 2, 9]))
print('Return minimum :', 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: (4, 1)
Return maximum : 9
Return minimum : -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 of character :', ord("A"))
print('Return character of 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 of character : 65
Return character of 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 Classes and Object Operations
Python |
---|
| print('Check if object is an instance of a class:', isinstance(100, int))
print('Check if object is an instance of one of a group of 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 object is an instance of a class: True
Check if object is an instance of one of a group of 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' % ('Zhang San', 25)
print('Old-style tuple formatting (not recommended):', result)
result = 'Hello, I am %(name)s, I am %(age)d years old' % { 'name': 'Zhang San', 'age' : 25 }
print('Old-style dictionary formatting (not recommended):', result)
result = 'Hello, I am {}, I am {} years old'.format('Zhang San', 25)
print('`format` function formatting, parameters arranged in order:', result)
result = 'Hello, I am {0}, I am {1} years old, {1} years ago I was born'.format('Zhang San', 25)
print('`format` function formatting, parameters inserted by index:', result)
params = {
'name': 'Zhang San',
'age' : 25,
'job' : 'student',
}
result = 'Hello, I am {name}, I am {age} years old, {age} years ago I 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 I was born'.format(name='Zhang San', age=25, job='student')
print('`format` function formatting, parameters inserted by name=value (extra parameters do not affect):', result)
name = 'Zhang San'
age = 25
result = f'Hello, I am "{name}", I am {age} years old, {age} years ago I 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 / String str」
Output:
Text Output |
---|
| Old-style tuple formatting (not recommended): Hello, I am Zhang San, I am 25 years old
Old-style dictionary formatting (not recommended): Hello, I am Zhang San, I am 25 years old
`format` function formatting, parameters arranged in order: Hello, I am Zhang San, I am 25 years old
`format` function formatting, parameters inserted by index: Hello, I am Zhang San, I am 25 years old, 25 years ago I was born
`format` function formatting, parameters inserted by dictionary key (extra parameters do not affect): Hello, I am Zhang San, I am 25 years old, 25 years ago I was born
`format` function formatting, parameters inserted by name=value (extra parameters do not affect): Hello, I am Zhang San, I am 25 years old, 25 years ago I was born
Latest f-string formatting (recommended): Hello, I am "Zhang San", I am 25 years old, 25 years ago I was born
|
6. String Methods
Strings in Python are very commonly used objects. Python strings include rich and useful 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 a specified string :', s.count(sub))
print('Return the index of the first occurrence of a specified string (returns -1 if not found) :', s.find(sub))
print('Return the index of the first occurrence of a specified string from right (returns -1 if not found) :', s.rfind(sub))
print('Return the index of the first occurrence of a specified string (raises error if not found) :', s.index(sub))
print('Return the index of the first occurrence of a specified string from right (raises error if not found) :', s.rindex(sub))
print('Check if string contains only letters and digits :', 'abcd1234'.isalnum())
print('Check if string contains only letters :', 'abcd'.isalpha())
print('Check if string contains only digits :', '1234'.isdigit())
print('Check if every word starts with uppercase letter:', 'Tom Jerry'.istitle())
print('Check if string is all spaces :', ' '.isspace())
print('Check if string is all lowercase :', 'TOM JERRY'.isupper())
print('Check if string is all uppercase :', 'tom jerry'.islower())
s = 'apple,microsoft,ibm,intel,amd'
print('Split string by specified delimiter :', s.split(','))
print('Split string by specified delimiter, limiting splits to 3 times :', s.split(',', 3))
print('Split string by specified delimiter from right :', s.rsplit(','))
print('Split string by specified delimiter from right, limiting splits to 3 times:', s.rsplit(',', 3))
print('Join list items into a string separated by commas :', ', '.join(['Tom', 'Jerry', 'John']))
print('Join list items into a string separated by empty string:', ''.join(['Tom', 'Jerry', 'John']))
print(f'Remove leading and trailing whitespaces :【{" abc ".strip()}】')
print(f'Remove trailing whitespaces :【{" abc ".rstrip()}】')
print(f'Remove leading whitespaces :【{" abc ".lstrip()}】')
print(f'Remove specified characters from both ends :【{"xyzabc789".strip("xyz789")}】')
print(f'Remove specified characters from the right end :【{"xyzabc789".rstrip("xyz789")}】')
print(f'Remove specified characters from the left end :【{"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 entire string to uppercase :', 'Hello, World'.upper())
print('Convert entire string to lowercase :', 'Hello, World'.lower())
print('Swap case of each letter in the string :', 'Hello, World'.swapcase())
print('Capitalize the first letter of each word in the string:', 'hello, world'.title())
print(f'Center-align the string to specified width :【{"abc".center(10)}】')
print(f'Left-align the string to specified width :【{"abc".ljust(10)}】')
print(f'Right-align the string to specified width :【{"abc".rjust(10)}】')
print(f'Left-align the string to specified width and fill with specified content:【{"abc".ljust(10, "_")}】')
print(f'Center-align the string to specified width and fill with specified content:【{"abc".center(10, "_")}】')
print(f'Right-align the string to specified width and fill with specified content:【{"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 a specified string : 2
Return the index of the first occurrence of a specified string (returns -1 if not found) : 7
Return the index of the first occurrence of a specified string from right (returns -1 if not found) : 21
Return the index of the first occurrence of a specified string (raises error if not found) : 7
Return the index of the first occurrence of a specified string from right (raises error if not found) : 21
Check if string contains only letters and digits : True
Check if string contains only letters : True
Check if string contains only digits : True
Check if every word starts with uppercase letter: True
Check if string is all spaces : True
Check if string is all lowercase : True
Check if string is all uppercase : True
Split string by specified delimiter : ['apple', 'microsoft', 'ibm', 'intel', 'amd']
Split string by specified delimiter, limiting splits to 3 times : ['apple', 'microsoft', 'ibm', 'intel,amd']
Split string by specified delimiter from right : ['apple', 'microsoft', 'ibm', 'intel', 'amd']
Split string by specified delimiter from right, limiting splits to 3 times: ['apple,microsoft', 'ibm', 'intel', 'amd']
Join list items into a string separated by commas : Tom, Jerry, John
Join list items into a string separated by empty string: TomJerryJohn
Remove leading and trailing whitespaces :【abc】
Remove trailing whitespaces :【 abc】
Remove leading whitespaces :【abc 】
Remove specified characters from both ends :【abc】
Remove specified characters from the right end :【xyzabc】
Remove specified characters from the left end :【abc789】
Replace specified content in the string : abcxyzabc
Capitalize the first letter of the string : Hello, world
Convert entire string to uppercase : HELLO, WORLD
Convert entire string to lowercase : hello, world
Swap case of each letter in the string : hELLO, wORLD
Capitalize the first letter of each word in the string: Hello, World
Center-align the string to specified width :【 abc 】
Left-align the string to specified width :【abc 】
Right-align the string to specified width :【 abc】
Left-align the string to specified width and fill with specified content:【abc_______】
Center-align the string to specified width and fill with specified content:【___abc____】
Right-align the string to specified width and fill with specified content:【_______abc】
|
7. List Methods
Lists in Python are very commonly used objects. Python lists include rich and useful built-in methods.
Since tuples are similar to lists, some methods that do not alter the original object are also applicable 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('Check 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 value in the list:', min(l))
print('Return the largest value in the list:', max(l))
print('Return the sum of the 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 a specified element in the list :', l.count(3))
print('Return the index of the first occurrence of a 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 a 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 | Check 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 value in the list: 1
Return the largest value in the list: 3
Return the sum of the 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 a specified element in the list : 2
Return the index of the first occurrence of a 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 a specified index from this list: [3, 2, 1, 7, 8, 9]
|
sorted(...)
and reversed(...)
return new lists and do not change the original list. However, list.sort()
and list.reverse()
sort the original list and do not produce new lists.
reversed(...)
and range(...)
functions actually return generators. If you really need a list, you can use the list(...)
function to convert it into an actual list.