Functions - Basic Concepts

#Function:
function, method, function
1. Improve the reusability of the code
2. Make the code more concise and simplify the code

Formal parameters (formal parameters), required parameters, default value parameters
Actual parameters (actual parameters)
default value parameters, non-required parameters (such as content = None)


Local variables:
The variables defined in the function are all local variables, which can only be used in the function, and cannot be used after the function is out.
#return
1. Return the result of the function processing
2. End the function, when the function encounters return , the function will end immediately
3. If only one return is written, it will return None
4. If there is no return in the function, it will return None by default

Global variables:
public variables, variables that can be used
1. Unsafe, because everyone can modify (modify with global)
2. Always occupy memory

constant


def sayHello(): #Define function name
print('hello') #Function body

#The function will not be executed if it is not called

sayHello() #call function

 

#Parameters of the function
def calc(a,b): #Formal parameters, Formal parameters
#Positional parameters, also required parameters
res = a * b
print('%s * %s = %s'%(a,b,res ))

calc(7,8) #actual parameters, actual parameters


Example: write a function to operate a file, and judge whether to write or read a file according to whether there is content
def op_file(file_name,conent = None): #conent default value parameter, it is a non-required parameter
f = open(file_name,'a+' , encoding)
f.seek(0)
if conent: #Not empty, it means writing the file
f.write(conent)
else: #Empty, it means reading the file
print(f.read())
f.close()
op_file( 'a.txt','gonglein')
op_file('a.txt')

 

#Get the value returned in the function (return) #Local
variable
def op_file(file_name,conent = None):
f = open(file_name,'a+')
f.seek(0)
if conent:
f.write(conent)
else:
all_user = f.read()
return all_user #After calling the function, return the result; if there is no return value after return, it only ends the function, and returns None
f.close()

op_file('a.txt')
print(op_file('a.txt')) #Print the return result

Guess you like

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