[0 Basic Introduction to Python Web Notes] 3. Python functions and commonly used built-in functions

function

Functions are a tool for encapsulating reusable blocks of code, organizing a series of operations into a logical unit.

function definition

In Python, functions are defined with the def keyword, followed by the function’s name, parameter list, and colon. The main code block of the function is indented and a value is returned using the return keyword when needed.

#定义函数
def hello(name):
    return "hello, " + name + "!"

In the above example, we define a function called hello, which has a parameter name. The body code of the function will connect the given name with the greeting and return the result.

function call

To call a function, simply pass the parameters to the function using the function name and a parameter list. The value returned by the function can be received in a variable or directly used in other operations.

#调用函数
result = hello("shiyuncode.com")
# 输出 "hello, shiyuncode.com!"
print(result)

In this example, we call the hello function, pass it the name "shiyuncode.com", assign the return value to the result variable, and finally print the result.

Function parameters

Functions can accept multiple parameters, which are specified through the parameter list when the function is defined. Function parameters can have default values, or different values ​​can be passed as needed.

Let's define an addition function as an example:


#定义一个加法函数
def add(itemA, itemB=2):
    return itemA + itemB
    
#默认参数itemB计算
result1 = add(1)  # 默认itmeB=2,所以1+2,结果为3
#自定义itemA和itemB进行计算
result2 = add(2, 3)  # 指定itemB为3,所以2+3,结果为5

#输出计算结果
print(result1)
print(result2)

In the above example, the add function has two parameters: itemA and itemB. The itemB parameter has a default value of 2, so you can omit it when calling the function. If you omit it, the default value will be used for calculations in the code block .

return value

Functions can use the return statement to return a value, and the return value can be of any data type. If the function does not use a return statement, it will return None.

# 定义一个有返回函数
def add(itemA, itemB=2):
    return itemA + itemB


# 定义一个无返回函数
def hello():
    print("hello shiyuncode.com!")


# 调用有返回函数
result1 = add(1)
# 调用无返回函数
result2 = hello()

# 输出函数结果
print("有返回:", result1)
print("无返回:", result2)

The result of executing the code:
Insert image description here

Commonly used built-in functions

input() function

The input() function is one of the Python built-in functions used to obtain input from the user. It allows the program to pause while running, wait for the user to enter data, and return the user-entered data as a string (that is, the string data received by the program).

Using the input() function, the keyboard input value can be obtained by the code. In layman's terms, the program can interact and the program can receive the information we provide.

Basic usage example:

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

Results of the:
Insert image description here

range() function

The range() function is one of Python's built-in functions, used to generate a sequence of integers. It is often used in loop structures, such as for loops, to specify the number of loops or index ranges.

The range() function can accept one (end), two (start, end) or three parameters (start, end, step) , depending on how it is used.

The default value of start is 0, and the default value of step is 1.

  • One parameter form:
# 生成从0到n-1的整数序列
for i in range(5):
    print(i)  # 输出:0 1 2 3 4
  • Two parameter form:
# 生成从start到stop-1的整数序列
for i in range(2, 6):
    print(i)  # 输出:2 3 4 5
  • Three parameter form:
# 生成从start到stop-1的整数序列,步长为step
for i in range(1, 10, 2):
    print(i)  # 输出:1 3 5 7 9

other

The following are some commonly used functions. We can explain them during the use process.

function describe Example
print() Print the value of a text or variable print("Hello")
len() Returns the length of the container len([1, 2, 3])
type() Returns the type of variable or object type(10)
int() Convert value to integer int("5")
float() Convert value to float float("3.14")
str() Convert value to string str(123)
list() Create list list(range(5))
tuple() Create tuple tuple([1, 2])
dict() Create dictionary dict(key=10)
set() Create a collection set([1, 2, 3])
max() Returns the maximum value in the sequence max(1, 2, 3)
min() Returns the minimum value in the sequence min([4, 5, 6])
sum() Calculate the sum of elements in a sequence sum([1, 2, 3])
sorted() Return the sorted sequence sorted([3, 1, 2])
abs() return absolute value abs(-5)
round() Rounding floating point numbers round(3.14159)
str.format() String formatting "Hello, {}".format("Alice")
join() Concatenate sequence elements into string " ".join(["Hello", "world"])
split() Split string into list of substrings "apple,banana".split(",")
strip() Remove whitespace characters from both ends of a string " text ".strip()
replace() Replace a substring in a string "hello".replace("h", "H")

PS: Why talk about input() separately? Because there is a little practice later! Will use it!

For more practical projects, please visit the official website below

Guess you like

Origin blog.csdn.net/m0_47220500/article/details/132380237