Python-based day04-function
Code repository address: https://gitee.com/andox_yj/python
1. Introduction, definition and invocation of functions
-
Introduction: When a piece of code needs to be reused, it can be encapsulated into a small function module, which can be called repeatedly when used.
This is the function. Functions improve the modularity of the application and the reuse of code. -
Note: Code within a function will be executed again each time it is called again
""" # Define function: Function name defines specifications, typically in lowercase letters, with _underscores connecting multiple words def Function name(): Code # Call function: Function name() # Define a function to output personal information def info(): print("Full name: Andox") print("Age: 18") print("Gender: Male") # Call function, execute code within function, repeatable call info() info()
2. Functions with parameters
-
Description: When calling a function, a function with parameters needs to be given some variables, values or objects. When passing these as parameters to a function definition function, it needs several parameters. Write the variable names of several receiving parameters in parentheses and use the variable directly in the code of the function. The received parameters are called "formal parameters".
def info(name, age, gender): print(name) print(age) print(gender) # Call function method 1: Pass in the same amount of data as the function definition receives. This is called an argument. info("Andox", "18", "male") # Call function method 2: Specify directly which data the parameter receives, which is the same as the result of the call above. info(name="Andox", age="18", gender="male") """ Be careful: 1.Parameters in parentheses when defined and used to receive parameters are called "formal parameters" 2.Parameters in parentheses when called, used to pass to a function, are called arguments 3.The number of formal parameters must be equal, and if the specified parameters are not assigned, they need to be filled in in order of location. 4.Multicast errors, fewer errors, if not used within the function will not be errors, if the parameters are not used, will be errors. 5.Position can change when assigning a transfer parameter. """
-
Parameter types of functions: position parameter, variable parameter, keyword parameter
# 1. Position parameter: passed in from left to right in order, called position parameter def info(name, age): print(name) # Andox print(age) # 18 info("Andox", 18) # 2. Variable parameters: Prepend the variable name with a * sign, which stores all unnamed variable parameters. The variable is tuple within the function, usually named Wei *args def info(*args): print(args) # ('Andox', 18) info("Andox", 18) # 3. Keyword parameters: Prefix the variable name with two * signs. The variable receives the key=value parameter, which is a dictionary within the function. It is usually named **kwargs def info(**kwargs): print(kwargs) # {'name': 'anem', 'age': 18} info(name="anem", age=18) # General parameter pair position order is: position parameter-->variable parameter-->keyword parameter def info(name, *args, **kwargs): print(name) # Andox print(args) # (18,) print(kwargs) # {'gender':'man'} info("Andox", 18, gender="male")
3. Functions with Return Values
-
Function return value: A function return value is a result that the function needs to give feedback after calling the function. So you need to use a parameter with the return value
-
Note: The variable that receives the return value of the function can be the same as the variable defined within the function.
There can only be one return within each function except if-else. A return can be followed by nothing, which acts as the stop of the function.# 1. Define a function with a return value, add the return keyword at the end of the function to return the result of the function execution def count(): num = 1 + 2 return num # 2. When calling a function, you need to use a variable to receive the return value of the function. The specification is: variable = function () num = count() print(num)
4. Nested Calls to Functions
Introduction: Called another function inside the function
def function1(): print("Function 1 Execution") def function2(): print("Function 2 begins execution") function1() print("End of function 2 execution") function2() """ When calling function 2, function 1 was encountered while executing in function 2. # When function 1 is executed, the remaining code of function 2 is executed back. Execution order: Function 2 begins execution Function 1 Execution End of function 2 execution """
5. Local and global variables
- Local variables are defined within a function and can be used from the beginning to the end of the function.
- Outside a function is a global variable, which can be used from the start of definition to the end of the program.
- Variables within a function can be modified to be global variables, ranging from the start of definition to the end of the program.
""" Definition method: Before defining variables within a function, use global Declare the variable as a global variable global Variable Name Variable Name = value """ num = 10 # Define global variables def info(): age = 10 # Define local variables global name # Declare global variables name = "Andox" info() print(name) # Andox
- Be careful:
- If a variable with the same name outside is defined before the function is called, the global declaration running to the function is that the outside function will be modified
- If a variable with the same name is not defined outside, it must be called before it can be used outside
6. Unpacking
# 1. Unpack function return values def info(): high = 175 weight = 120 age = 18 return high, weight, age high, weight, age = info() # Unpacking print(high, weight, age) # 175 120 18 # 2. Unpacking lists a, b = [1, 2] print(a, b) # 1 2 # 3. Unpacking Yuan Zu a, b = (3, 4) print(a, b) # 3 4 # 4. Unpacking the dictionary: Note that the key is what you take out a, b = {"a": 1, "b": 2} print(a, b) # a b
7. Citation
Citation Introduction:
Use id() to see where the data is stored in memory. The variable name actually stores the address of the data in memory.
We can access a variable stored in memory through this address. When we pass a variable, we actually pass it
References (addresses where variables are stored in memory) are passed out.
a = 100 b = [1, 2] c = (1, 2) d = {"name": "Andox"} print(id(a)) # 4321048320 print(id(b)) # 140495662574720 print(id(c)) # 140495643250240 print(id(d)) # 140495643211776
Variable and immutable types refer to the fact that if you can modify them directly, they are variable, otherwise they are immutable
Variable types are: list, dictionary, collection
Invariant types are numbers, strings, tuples,
When a variable is of an immutable type, modifying it is actually storing the modified new data address in the variable name again.
When a variable is of variable type, it is modified in the original location of memory
# Invariant Type a = 10 print(id(a)) # 4403084224 a += 1 print(id(a)) # 4403084256 #Modified Address Change # Variable data types b = [1] print(id(b)) # 140476780873152 b.append(2) print(id(b)) # 140476780873152 # Address unchanged after modification
8. Function Case-Student Management System
import time import os # Set up a list to store all the student information (each student is a dictionary) info_list = [] def print_menu(): print("---------------------------") print(" Student Management System V1.0") print(" 1:Add Students") print(" 2:Delete Students") print(" 3:Modify Students") print(" 4:Query Students") print(" 5:Show all students") print(" 6:Exit System") print("---------------------------") def add_new_info(): """Add Student Information""" global info_list new_name = input("Please enter your name:") new_tel = input("Please enter your mobile number:") new_qq = input("Please enter QQ:") for temp_info in info_list: if temp_info['name'] == new_name: print("This username is already in use,Please re-enter") return # If a function has only return, it is equivalent to ending the function without a return value # Define a dictionary to store the user's student information (this is a dictionary) info = {} # Add data to dictionary info["name"] = new_name info["tel"] = new_tel info["qq"] = new_qq # Add this dictionary to the list info_list.append(info) def del_info(): """Delete Student Information""" global info_list del_num = int(input("Please enter the serial number to delete:")) if 0 <= del_num < len(info_list): del_flag = input("Are you sure you want to delete it??yes or no") if del_flag == "yes": del info_list[del_num] else: print("Error Entering Sequence Number,Please re-enter") def modify_info(): """Modify Student Information""" global info_list modify_num = int(input("Please enter the serial number to be modified:")) if 0 <= modify_num < len(info_list): print("The information you want to modify is:") print("name:%s, tel:%s, QQ:%s" % (info_list[modify_num]['name'], info_list[modify_num]['tel'], info_list[modify_num]['qq'])) info_list[modify_num]['name'] = input("Please enter a new name:") info_list[modify_num]['tel'] = input("Please enter a new mobile number:") info_list[modify_num]['qq'] = input("Please enter a new one QQ:") else: print("Error Entering Sequence Number,Please re-enter") def search_info(): """Query Student Information""" search_name = input("Please enter the name of the student you want to query:") for temp_info in info_list: if temp_info['name'] == search_name: print("The information queried is as follows:") print("name:%s, tel:%s, QQ:%s" % (temp_info['name'], temp_info['tel'], temp_info['qq'])) break else: print("There is no information you are looking for....") def print_all_info(): """Traverse student information""" print("Sequence Number\t Full name\t\t Cell-phone number\t\tQQ") i = 0 for temp in info_list: # temp is a dictionary print("%d\t%s\t\t%s\t\t%s" % (i, temp['name'], temp['tel'], temp['qq'])) i += 1 def main(): """Used to control the entire process""" while True: # 1.Printing function print_menu() # 2.Get the user's choice num = input("Please enter the action to be taken(number)") # 3.Do the appropriate things according to the user's choice if num == "1": # Add Students add_new_info() elif num == "2": # Delete Students del_info() elif num == "3": # Modify Students modify_info() elif num == "4": # Query Students search_info() elif num == "5": # Traverse all information print_all_info() elif num == "6": # Exit System exit_flag = input("Dear,Are you sure you want to quit??~~~~(>_<)~~~~(yes or no) ") if exit_flag == "yes": break else: print("Input Error,Please re-enter......") # Start of program main()