def print_area(length):
area=length*length
return(area)
result=print_area(12)
print(f" The area of this square is {result}")
among f Indicates format output , Use curly braces to enclose the variable you want to replace , In order to realize this function .
def Represents the constructed function , Function is only called later , The system will execute the relevant code of the function , Otherwise, the system will directly skip the relevant code . Besides , Suppose you want to use the result of a function run , Use the return value , So that the result can be passed back to the place of the call .( The understanding here is similar to c++ Exactly the same, but in a slightly different form )
If return Inside the loop , Then the loop of this function will only execute once , From then to return when , The loop will automatically end . Stop this function call .
And c++ The difference is ,python Multiple values can be returned at the same time , for instance ( Don't leave out the colon )
def print_area(length):
area=length*length
return area,length
result=print_area(12)
print(f" The area of this square is {result}")
When multiple values are returned , Need to use “,” separation , So the compiler will Returns the relevant data in the form of tuples
If there is no return value in the function , Then a null value will be returned (NULL)
Add a few simple functions
print() Output some data range() Generate a list of numbers listappend() Append an element to the list len() Returns the length of the tuple of the character list or the number of elementspython The default value of the parameter in the function
def print_area(length=100):
area=length*length
return area,length
result=print_area()
print(f" The area of this square is {result}")
Be careful : If when calling a function , Is not a parameter length Provide parameters , So parameters length The default is 100.
The default parameter can have any number of , But it must be defined after the required parameter , If the required parameter exists .
Define the order of function parameters :
1、 Required parameters
2、 Default parameters
When there are required parameters and default parameters , The required parameter must be written before the default parameter , Otherwise, the program will report an error .