Python learning function

The cast function
int() function can convert other data types to integers:

int('123')
123
int(12.34)
12

The str() function converts other types to str:

str(123)
'123'
str(1.23)
'1.23'

The format of the function
In Python, to define a function, use the def statement, write the function name, parentheses, parameters in parentheses, and colon: in turn, then write the function body in an indented block, and the return value of the function is returned with the return statement .

Let's take a custom my_abs function that finds the absolute value as an example:

def my_abs(x):
    if x >= 0:
        return x
    else:
        return -x

Please note that when the statement inside the function body is executed, once the return is executed, the function is executed and the result is returned. Therefore, very complex logic can be implemented inside the function through conditional judgment and looping.

If there is no return statement, the function will return the result after execution, but the result is None.
return None can be shortened to return.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325485702&siteId=291194637