[A zero-based introduction to Python] Commonly used built-in functions revisited

Introduction to Python

Python is an interpreted, high-level and general-purpose programming language. Python was created by Guido van Rossum and first released in 1991. The design of Python emphasizes the readability of code, which allows us to use more code than C++ or Java. Express concepts with less code. Python makes it simpler and faster. Let's take a look at the commonly used built-in functions of Python with me.

Python built-in functions

Why learn built-in functions

Python built-in function (Built-In Function) is a function directly provided by the Python interpreter. Compared with otherPython functions, no Import any module to use. Being familiar with Python's built-in functions can not only help us quickly complete common programming tasks, but also make our code more concise and easy to read.

Set operations

In the previous part, we introduced data type conversion functions and built-in functions related to mathematical operations. Now let's explore the built-in functions in Python for processing sets.

Python set operations

len(): calculate length

len()The function returns the object (character, list, tuple, etc.) length or number of items.

Format:

length = len(s)

example:

my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print("数组:", my_list, "长度:", length)

Output result:

数组: [1, 2, 3, 4, 5] 长度: 5

sorted(): sort

sorted()The function returns a sorted list.

example:

original_list= [1, 3, 5, 2, 4]
sorted_list = sorted(original_list)
print("原始数组:", original_list)
print("排序后的数组:", sorted_list)

Output result:

原始数组: [1, 3, 5, 2, 4]
排序后的数组: [1, 2, 3, 4, 5]

all(): Check all elements

all()The function is used to determine whether all elements in the given iterable parameter are True, if so, return True, otherwise return False.

example:

my_list = [1, 3, 4, 5]
result = all(my_list)
print(result)

Output result:

True

any(): Check any element

any()The function is used to determine whether the given iterable parameters are all False, then return False, if one is True, then return True.

example:

my_list = [0, 1, False]
result = any(my_list)
print(result)

Output result:

True

Common usage:

# 列表推导式
numbers = [1, 3, 5, 7, 9]
result = any(n % 2 == 0 for n in numbers)  # False, 没有偶数
print(result)

result = any(n % 2 != 0 for n in numbers)  # True, 有奇数
print(result)

# 检查字符串中的字符
string = "Hello, World!"
result = any(c.isupper() for c in string)  # True, 'H' 和 'W' 是大写字母
print(result)

result = any(c.isdigit() for c in string)  # False, 没有数字
print(result)

Output result:

False
True
True
False

filter(): filter elements

filter(): The function is used to filter the sequence, filter out elements that do not meet the conditions, and return an iterable object. If you want to convert it to a list, you can use list() to convert.

numbers = [-3, -2, -1, 1, 2, 3]
less_than_zero = filter(lambda x: x < 0, numbers)
print(list(less_than_zero))

map(): application function

map()The function maps the specified sequence according to the provided function.

example:

# 列表平方
numbers = [1, 2, 3, 4, 5]
squared = map(lambda x: x**2, numbers)
print(list(squared))

# 列表对应位置相加
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = map(lambda x,y: x+y, list1, list2)
print(list(result))

Output result:

[1, 4, 9, 16, 25]
[5, 7, 9]

zip(): combine elements

zip()Functions are used to take iterable objects as parameters,

example:

numbers = [1, 2, 3]
letters = ['a', 'b', 'c']
zipped = zip(numbers, letters)
print(list(zipped)) 

Output result:

[(1, 'a'), (2, 'b'), (3, 'c')]

Commonly used methods:

# 创建字典
keys = ['name', 'age', 'gender']
values = ['我是小白呀', 18, 'Female']
dictionary = dict(zip(keys, values))
print(dictionary)

# 遍历俩列表
meals = ['早饭', '中饭', '晚饭']
foods = ['皮蛋瘦肉粥', '雪菜肉丝面', '黄焖鸡米饭']
for meal, food in zip(meals, foods):
    print(f'{meal} 吃了 {food}')

Output result:

{'name': '我是小白呀', 'age': 18, 'gender': 'Female'}
早饭吃了: 皮蛋瘦肉粥
中饭吃了: 雪菜肉丝面
晚饭吃了: 黄焖鸡米饭

File operations and input and output

Now, Xiaobai, I will take you to explore the built-in functions in Python for processing files and input and output.

open(): open the file

open(): Function is used to open a file and return the file object.

example:

# 打开文件用于读取
f = open('example.txt', 'r') 

# 读取文件内容
content = f.read()

# 关闭文件
f.close()  

read(): read file

read()Method for reading a specified number of bytes from a file, or not reading all bytes if not given.

Format:

file.read(size)

parameter:

  • size: number of bytes

example:

# 打开文件用于读取
f = open('example.txt', 'r')

# 读取前 10 个字符
content = f.read(10)

# 关闭文件
f.close()

write(): write to file

write()Method used to write the specified string to the file.

example:

# 打开文件
f = open('example.txt', 'w')

# 写入字符串
f.write('Hello, World!')

# 关闭文件
f.close()

input(): Get user input

input()Functions can help us get the input stream (Input Stream).

example:

name = input('请输入名字: ')
print('你好, ' + name + '!')

Output result:

请输入名字: 我是小白呀
你好, 我是小白呀!

print(): print output

print()The function is used to output information to the console, that is, the output stream (Output Stream).

example:

# 输出
print('Hello World')

# 多个输出 (中间空格)
print('Hello World', '123')

# 换行输出
print('Hello World', '123', sep="\n")

Output result:

Hello World
Hello World 123
Hello World
123

format(): format string

format()Function used to format strings.

example:

name = "World"
message = "Hello, {}!".format(name)
print(message)

Output result:

Hello, World!

Error and exception handling

Let’s explore the built-in functions (Build-In Function) for handling errors and exceptions in Python

try expert: exception capture

try andexcept can help us absorb exception handling.

example:

try:
    result = 10 / 0
except ZeroDivisionError:
    print("不能除以 0 哦!")

Output result:

不能除以 0 哦!

finally: cleanup operation

finallyStatements are used for blocks of code that are executed regardless of whether an exception occurs, usually for resource cleanup operations.

example:

try:
    f = open('example.txt', 'r')
    content = f.read()
except FileNotFoundError:
    print("File not found!")
finally:
    f.close()

raise: trigger an exception

raisestatement is used to trigger an exception.

example:

x = -1
if x < 0:
    raise ValueError("x 不能为负")

Output result:

Traceback (most recent call last):
  File "C:\Users\Windows\Desktop\Python 基础\文件操作和输入输出.py", line 13, in <module>
    raise ValueError("x 不能为负")
ValueError: x 不能为负

assert: assert

assertStatements are used to set checkpoints in the program and trigger exceptions when the condition is False.

example:

x = -2
assert x > 0, "x must be positive"

Output result:

Traceback (most recent call last):
  File "C:\Users\Windows\Desktop\Python 基础\文件操作和输入输出.py", line 17, in <module>
    assert x > 0, "x must be positive"
AssertionError: x must be positive

with: context management

withStatements are used to simplify resource management (such as file reading and writing), and they ensure that resources are closed correctly after use.

example:

with open('example.txt', 'r') as f:
    content = f.read()

When we use the with statement to open a file, Python will ensure that the file is properly closed after the with code block is executed, even if it occurs in the code The same is true for exceptions. We don't need to use f.close() to release resources.

Guess you like

Origin blog.csdn.net/weixin_46274168/article/details/134101956