Introduction to day10 function
Summary:
- Elementary function
- Parameters of function
- Return value of function
1. Initial function
What exactly is a function?
Function can be regarded as a collection of a lot of function code.
def Function name(): Write code in function ... ... Function name # For example: # Define a function called info def info(): print("first line") print("Second line") print("The first n that 's ok...") info()
Function application scenario:
-
If there is duplicate code, use functions to increase the reusability of the code.
def send_email(): # 10 lines of code print("Welcome to the computer monitoring system") if CPU Occupancy rate > 90%: send_email() if Hard disk utilization > 99%: send_email() if Memory usage > 98%: send_email() ...
-
The code is too long. Use the function to increase the readability of the code:
def calculate_same_num_rule(): """Judge whether it is a leopard""" pass def calculate_same_color_rule(): """Judge whether it is the same flower""" pass def calculate_straight_rule(): """Judge whether shunzi""" pass def calculate_double_card_rule(poke_list): """Judge whether it is right""" pass def calculate_single_card_rule(): """Judge whether a single card""" pass # 1. Generate a deck of playing cards card_color_list = ["heart", "spade", "Square slice", "Plum blossom"] card_nums = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] # A all_card_list = [[color, num] for color in card_color_list for num in card_nums] # 2. Shuffle random.shuffle(all_card_list) # 3. Deal cards to players ... # 4. The judgment board is: leopard? Flush? Shunzi? Right? Single point? calculate_same_num_rule() calculate_same_color_rule() calculate_straight_rule() ... # Try to write a function on one screen
In the past, our programming was completed step by step from top to bottom according to logic, which is called: interview process programming; Now after learning functions, using functional programming is called functional programming.
2. Parameters of function
python send mail:
- Registered mailbox
- Basic configuration
- Authorization code
- SMTP server: smtp.126.com
- Code send mail
Case: email function
import smtplib from email.mime.text import MIMEText from email.utils import formataddr # 1. Mail content configuration # Message text msg = MIMEText("Have a beer at eight tonight?", 'html', 'utf-8') # Sender shown on message msg['from'] = formataddr(["dave", "dave2022@126.com"]) # Subject displayed on message msg['subject'] = "See you or leave" # 2. Send mail server = smtplib.SMTP_SSL("smtp.126.com") server.login("dave2022@126.com", "PGSGHLNNGIQFKRJT") server.sendmail("dave2022@126.com", "2729726517@qq.com", msg.as_string()) server.quit()
Send email to multiple users according to the above code:
import smtplib from email.mime.text import MIMEText from email.utils import formataddr def send_email(email): # 1. Mail content configuration # Message text msg = MIMEText("Have a beer at eight tonight?", 'html', 'utf-8') # Sender shown on message msg['from'] = formataddr(["dave", "dave2022@126.com"]) # Subject displayed on message msg['subject'] = "See you or leave" # 2. Send mail server = smtplib.SMTP_SSL("smtp.126.com") server.login("dave2022@126.com", "PGSGHLNNGIQFKRJT") server.sendmail("dave2022@126.com", email, msg.as_string()) server.quit() v1 = "535397697@qq.com" v2 = "2729726517@qq.com" send_email(v1) send_email(v2)
2.1 parameters
When customizing a function, if a variable is added in parentheses, we call it the formal parameter of the function:
# Define a function with three parameters (a1/a2/a3 is generally called formal parameter formal parameter) def func(a1,a2,a3): print(a1+a2+a3) # Execute the function and pass in parameters (it is generally called actual parameter actual parameter when executing the function to transfer values) func(11,22,33) # Execute the function and pass in parameters func(9,2,103)
-
Position transfer parameter
def add(n1,n2): print(n1+n2) add(1,22)
-
Keyword parameters
def add(n1,n2): print(n1+n2) add(n1=1,n2=2) # Execute the function and pass in parameters. The order of parameters can be changed def func(a1,a2,a3): print(a1+a2+a3) func(9, 2, 103) # Execution function func(a1=99, a2=88, a3=1) func(a1=99, a3=1, a2=88) # In mixed collocation, the position parameter must be in the front and the keyword parameter must be in the back func(a1=99, 1, a2=88) # Wrong writing func(99, a1=2, a3=88) # Wrong writing func(99, a2=2, a3=88) # correct
2.2 default parameters
def func(a1, a2, a3=10): print(a1 + a2 + a3) # Position transfer parameter func(8, 19) func(1, 2, 99) # When you pass in parameters, the default value of a3 above will be overwritten # Keyword parameter transfer (when position and key are mixed, keyword parameter transfer should be followed) func(12, 9, a3=90) func(12, a2=9, a3=90) func(a1=12, a2=9, a3=90)
file_object = open('xxx.text') # The first incoming path and the second incoming mode can be passed or not if there is a default value. The default is rt. if it is passed in, it will be overwritten.
2.3 dynamic parameters
-
*
def func(*args): print(args) # Tuple type (22,) (22,33,99,) () # Parameters can only be passed by position func(22) func(22,33) func(22,33,99) func() # If there is no parameter, it is an empty tuple
-
**
def func(**kwargs): print(kwargs) # Receive parameters by dictionary type: {"n1":"dave"} {"n1":"dave","age":"18","email":"xxxx"} if not, an empty dictionary {} func(n1="dave") func(n1="dave", age=18) func(n1="dave", age=18, email='xx@live.com')
-
*, * * generally used in combination
def func(*args,**kwargs): print(args,kwargs) # (22,33,99) {} automatically identify and put it into tuple, otherwise it will be empty # Parameters can only be passed by keyword func(22,33,99) func(n1="dave",age=18) func(22,33,99,n1="dave",age=18) func()
Tip: do you remember the format function when formatting strings? The processing mechanism is similar
v1 = "My name is{},this year{},Gender{}".format("dave",18,"male") v2 = "My name is{name},this year{age},Gender{gender}".format(name="dave",age=18,gender="male")
matters needing attention:
# 1. * * must be placed behind * def func1(*args, **kwargs): print(args, **kwargs) # 2. When parameters and dynamic parameters are mixed, dynamic parameters can only be placed last. def func2(a1, a2, a3, *args, **kwargs): print(a1, a2, a3, args, **kwargs) # 3. The default value parameter and dynamic parameter exist at the same time. The default parameter must be placed in front of * * kwargs def func3(a1, a2, a3, a4=10, *args, a5=20, **kwargs): print(a1, a2, a3, a4, a5, args, kwargs) func3(11, 22, 33, 44, 55, 66, 77, a5=10, a10=123)
3. Function return value
During the development process, we hope that the function can help us realize a function, but sometimes we need some results to feed back to us after the function realizes a function, such as:?
import requests from xml.etree import ElementTree as ET def xml_to_list(city): data_list = [] url = "http://ws.webxml.com.cn//WebServices/WeatherWebService.asmx/getWeatherbyCityName?theCityName={}".format(city) res = requests.get(url=url) root = ET.XML(res.text) for node in root: data_list.append(node.text) return data_list result = xml_to_list("Beijing") print(result)
# Cases returned directly def func(): return 666 res = func() print(res)
# The case that returns the result of function execution def magic(num): result = num + 1000 return result data = magic(9) print(data)
Key knowledge points
-
The return value can be of any type. If return is not written in the function, None will be returned by default
def func(): return [1,Ture,(11,22,33)] result = func() print(result)
def func(): value = 1 + 1 ret = func() print(ret) # None
When the return value is not written in the function, or return or return node, the return value obtained by executing the function is None
def func(): value = 1 + 1 return # Or return None ret = func() print(ret) # None
-
If the value after return has a comma, the returned value will be converted into a tuple and returned by default
def func(): return 1,2,3 value = func() print(value) # (1,2,3)
-
Once the function encounters return, it will immediately exit the function (terminate all code in the function)
def func(): print(1) return "It's over" print(2) ret = func() print(ret)
def func(): print(1) for i in range(10): print(i) return 999 print(2) result = func() print(result) # output 1 0 999
def func(): print(1) for i in range(10): print(i) for j in range(100) print(j) return print(2) result = func() print(result) # output 1 0 0 None
Summary:
-
Complete a result and hope to get the result
def send_email(): ... return True v1 = send_email()
def encrypt(old): ... return "ciphertext..." data = encrypt("Page") print(data)
-
Stop the function based on the return control
def func(name): with open("xxx.txt",mode='r',encoding="utf-8") as file_object: # Open file for line in file_object: # Circular judgment if name in line: return True data = func("Page") if data: print("existence") else: print("non-existent")
def foo(): while True: num = input("Please enter a number( Q): ") if num.upper() == "Q": return num = int(num) if num == 99: print("You guessed right") else: print("Wrong guess, please continue!") print("....") foo()
summary
-
How to define a function
-
The specification of function name is the same as that of variable name
-
standard
-
proposal
def change_num(): pass
-
-
Function annotation to explain the function
def encrypt(origin): """ For data encryption and xxx """ pass
-
When defining a function, the parameters generally include the following cases (formal parameters)
-
Scenario 1:
def func(a1,a2): pass
-
Scenario 2:
def func(a1,a2=123): pass
-
Scenario 3:
def func(*args,**kwargs): pass
-
-
The return value of the function, which is generally used to return to the caller when the function is executed
- The default return is None
- If return is encountered, the function is completed