Python beginners must master 25 built-in functions, recommended collection

input()

Function: let the user input a string of characters from the console, press enter to end the input and return the string

Note: many beginners think it can return numbers, but it's wrong!

>>> line = input("Enter a number:")
Enter a number: 1
>>> line
'1'  # < -- see clearly, this is not a number, just a string


# If you add directly
>>> line + 1   
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str


# The correct method is to convert line into number first
>>> int(line) + 1
2

print()

Function: after converting parameters into strings, output them to the console

>>> print("hello", "world")
hello world

# Many people don't know that other characters can be inserted between parameters
>>> print("hello", "world", sep="~")
hello~world

# You can even let each parameter occupy one line
>>> print("hello", "world", sep="\n")
hello
world

set()

Function: construct a collection. A common method is to pass the list into set() and then turn it into a list to eliminate the duplication of the list.

>>> set([1, 2, 3, 3])
{1, 2, 3}

# This enables weight removal
>>> list(set([1, 2, 3, 3]))
[1, 2, 3]

str()

Function: converts an object into a string. It is often used to splice strings and numbers.

For example, an error will be reported:

>>> 'My Score is: ' + 100
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

So use str to convert:

>>> 'My Score is: ' + str(100)
'My Score is: 100'

chr(i)

Function: returns the character corresponding to the integer i, which is often used to generate the alphabet.

>>> chr(20013)
'in'
>>> chr(97)
'a'

# Cooperate with ord() to generate the alphabet
>>> [chr(ord('a') + i) for i in range(26)]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

ord()

Function: returns the decimal value corresponding to the character in the coding table

>>> ord('in')
20013
>>> ord('a')
97

# Cooperate with chr() to generate the alphabet
>>> [chr(ord('a') + i) for i in range(26)]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

bool()

Function: judge the Boolean value of an object and return True or False

bool(1) => True
bool(0) => False
bool([]) => False

Note: this function is rarely used in actual projects. It is only used as a test tool to let beginners understand the Boolean state of each object.

int()

Function: convert any binary string into an integer.

int('2') => 2
int('1010', 2) => 10  # Binary 1010 to integer 10

Description: pass in the second parameter to specify the hexadecimal type of parameter 1.

bin()

Function: convert integer to binary string

bin(2) => '0b10'
bin(10) => '0b1010'

Note: why is there a 0b in front of the string? Because this is the standard way of writing, starting with 0b means that the next number is binary.

oct()

Function: convert hexadecimal to octal string

oct(7) => '0o7'
oct(8) => '0o10'

hex()

Function: convert decimal to hexadecimal string

>>> hex(11)
'0xb'

>>> hex(16)
'0x10'

abs()

Function: take absolute value

>>> abs(-1)
1

divmod()

Function: return the quotient and remainder in the division operation at the same time, which is equivalent to one operation and get the results of a//b and a% b at the same time.

>>> divmod(1, 2)
(0, 1)

>>> divmod(4, 3)
(1, 1)

round()

Function: rounds a floating-point number

>>> round(1.3333)
1

>>> round(1.3333, 2)  # 2 means to keep 2 decimal places
1.33

pow(x, y[, z])

Function: if only x and Y parameters are filled in, the Y power of X is returned. If the z parameter is filled in, take the module again, which is equivalent to pow (x, y)% z.

>>> pow(10, 2)
100
# amount to
>>> 10**2 
100

>>> pow(10, 2, 3)
1
# amount to
>>> 10**2 % 3 
1

sum(iterable)

Function: sum all elements of array iterable.

>>> sum([1, 2, 3])
6

min(x, y, z, ...)

Function: returns the minimum number of all parameters

>>> min(1, 2, 3)
1

# You can also pass in an array
>>> min([1, 2, 3])
1

max(x, y, z, ...)

Function: similar to min(), return the maximum number of all parameters

list()

Function: create a list when the incoming parameter is empty; When the incoming parameter is not empty, the parameter is converted to a list

>>> list()
[]

# When not empty
>>> list('hello world')
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

# Try importing the dictionary
>>> list({'a': 1, 'b': 2})
['a', 'b']

tuple()

Function: almost as like as two peas, list, but list returns an array, and tuple returns tuples.

dict()

Function: construct dictionary

# Method 1:
>>> dict(a=1, b=2)
{'a': 1, 'b': 2}

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

# Method 3:
>>> dict([('a', 1), ('b', 2)])
{'a': 1, 'b': 2}

len()

Function: returns the length of the object or the number of elements

>>> len([1, 2])
2
>>> len({'a': 1, 'b': 2})
2
>>> len('hello')
5

reversed()

Function: invert the list.

Note: the returned is not a list, but an iterator.

>>> reversed([1, 2, 3])
<list_reverseiterator object at 0x1016190a0>

# Need to convert to list
>>> list(reversed([1, 2, 3]))
[3, 2, 1]

# The same is true for strings
>>> reversed('abc')
<reversed object at 0x1015ffd90>
>>> list(reversed('abc'))
['c', 'b', 'a']

enumerate()

Function: used to traverse objects. In normal traversal, such as for el in array, you can only get elements, not subscripts. You can use enumerate().

>>> for i, el in enumerate('abc'):
...     print(i, el)
...
0 a
1 b
2 c

How does this subscript work? For example, it can be used to modify the elements in the array in reverse:

>>> alphabet = ['a', 'b', 'c']
>>> for i, el in enumerate(alphabet):
...     alphabet[i] = el.upper()
...
>>> alphabet
['A', 'B', 'C']

filter(func, iterable)

Function: filter and return qualified elements

Note: an iterator is returned.

>>> alphabet = ['a', 'b', 'c', 'E', 'F', 'G']

>>> filter(lambda e: e.isupper(), alphabet)
<filter object at 0x1016190a0>

>>> list(filter(lambda e: e.isupper(), alphabet))
['E', 'F', 'G']

Tags: Python

Posted on Fri, 17 Sep 2021 04:14:03 -0400 by Elarion