summary
I Define function
-
What is a function
-
concept
A function is the encapsulation of the code that implements a specific function - > a function corresponds to a function (the function stored in the function)
-
Classification (by who created the function)
- System functions - there are functions that have been created in Python language (Python's own functions), such as print, input, type, id, max, min, sorted, sum, etc
- Custom function - a function created by the programmer himself
-
-
Define function
-
grammar
def Function name(parameter list ): Function description document Function body
-
explain
def - keyword; Fixed writing Function name - Named by the programmer himself; Requirement: identifier, not keyword Scope: see name and meaning(When you see the function name, you probably know what the function is), Do not use the system function name, class name, module name All letters are lowercase, and multiple words are separated by underscores (): - Fixed writing parameter list - with'Variable name 1, Variable name 2, Variable name 3,...'Each variable here is a formal parameter; Formal parameters can be none or multiple. Formal parameters can transfer data outside the function to the inside of the function; How many formal parameters are needed when defining a function? It depends on whether additional data is needed to implement the function. How many parameters are needed Function description document - The essence is harmony def Keep an indented multiline comment; It is used to describe the function, parameters and return value of a function Function body - and def Keeping one or more statements indented is essentially the code to realize the function.
-
practice
# Exercise 1: write a function to sum two numbers def sum2(num1, num2): """ (Function description area)Find the sum of any two numbers :param num1: (Parameter description) Number 1 :param num2: Number 1 :return: (Return value description) None """ print(num1 + num2) sum2(10, 20) # Exercise 2: write a function to find the result of 5 times 6 def product(num1, num2): print(num1 * num2) product(5, 6) product(99, 120) # Exercise 3: write a function to count the number of numeric characters in a specified string def count_number(str1): """Number of statistics characters""" count = 0 for x in str1: if x.isdigit(): count += 1 print(count) count_number('ajhf1238 Shanhaijing 02') count_number('2791 of the number') # Exercise 4: define a function to get the ten digits of any integer (both positive and negative) def get_tens_digit(num): """Get ten digits""" if num < 0: num *= -1 print(num // 10 % 10) get_tens_digit(123) get_tens_digit(-132) # Exercise 5: define a function to get all the numeric elements in the specified list def get_numbers(list1): """Get numeric element""" new_list = [] for x in list1: if type(x) in (int, float): new_list.append(x) print(new_list) get_numbers([19, 'yes d', 23.8, True, None]) # Exercise 6: define a function to get the common part of two strings def get_common_char(str1, str2): """Gets the common part of two strings""" result = set(str1) & set(str2) print(''.join(result)) get_common_char('abcn', '123ba92') # Exercise 7: define a function exchange Dictionary of keys and values def change_key_value(dict1): new_dict = {} for key in dict1: new_dict[dict1[key]] = key print(new_dict) change_key_value({'a': 10, 'b': 20, 'c': 30})
-
II Call function
-
Call function
-
Important conclusion: the function will not be executed when defining the function, but only when calling
-
Syntax:
Function name (argument list)
-
explain
Function name - Call the function of which function you need, and write the function name of which function you want to call Note: the function name here must be the function name of the defined function () - Fixed writing Argument list - with 'Data 1, Data 2, Data 3,...' The form of existence; An argument is the data that is really passed to the inside of a function through a formal parameter The number of arguments is determined by the formal parameters. By default, the number of arguments is required when the function is called
-
Function call procedure
When the code executes the function call statement: Step 1: return to the position defined by the function Step 2: pass on parameters(The process of assigning values to formal parameters with arguments),When passing parameters, you must ensure that each formal parameter has a value Step 3: execute the function body Step 4: determine the return value Step 5: return to the location of the function call, and then execute it later ```python def func1(): # print('abc'[10]) print('=====================') print('====hello python=====') print('=====================') func1() def sum2(num1, num2): """(Function description area)Find the sum of any two numbers""" # Transmission parameter: num1 = 10; num2 = 20 print(num1 + num2) # print(10 + 20) -> print(30) sum2(10, 20) sum2(100, 200) ```
-
III Parameters of function
-
Positional parameters and keyword parameters - the arguments of the function are divided into these two types according to the different transmission methods of the arguments
-
Location parameters
When calling a function, separate multiple data directly with commas, and the actual parameters and formal parameters correspond to each other in position
-
Keyword parameters
When calling the function, add 'formal parameter name =' in front of the data, and the actual parameter and formal parameter are corresponding by the formal parameter name
-
Mixed use of two parameters
It is required to ensure that the location parameter is in front of the keyword parameter
def func1(x, y, z): print(f'x:{x}, y:{y}, z:{z}') func1(10, 20, 30) func1(20, 10, 30) func1(x=100, y=200, z=300) func1(z=3, x=1, y=2) func1(10, y=20, z=30) func1(10, z=30, y=20) func1(10, 20, z=30) # func1(10, b=20, 30) # report errors! SyntaxError: positional argument follows keyword argument
-
-
Parameter defaults
-
When defining a function, you can assign default values to formal parameters. When calling a function, there are already default parameters. You can directly use the default values without passing parameters.
-
If you assign default values to some parameters, you must ensure that the parameters without default values precede the parameters with default values
def func2(x=1, y=2, z=3): print(f'x:{x}, y:{y}, z:{z}') func2(10, 20, 30) func2() func2(100) func2(100, 200) func2(y=200) def func3(x, y, z=3, t=4): pass def connect(host, user, pw, port=3306): pass
-
-
Parameter type description - specify the parameter type when defining the function
-
Add type description for parameters without default value
Parameter name: data type
-
For parameters with default values, the type of default value is the type of parameter
-
-
Indefinite length parameter
-
Indefinite length parameter with *
-
Add * before the formal parameter, and the parameter becomes a tuple, which is used to receive all the corresponding arguments (the arguments are the elements in the tuple)
-
Remember: if the function parameter is after the parameter with *, the latter parameters must use keyword parameters when calling
# Define a function to sum multiple numbers def sum1(*nums): print(nums) sum1(10, 20) sum1(2, 34, 5) sum1(10, 29, 38, 9, 19) sum1(1) sum1() def student_info(name, *score): print(name, score) student_info('Xiao Ming') student_info('floret', 397, 420) student_info('Zhang San', 397, 328, 300)
-
IV Return value of function
-
Meaning: the return value is the data passed from the inside of the function to the outside of the function
-
How to determine the return value (how to pass the data inside the function to the outside of the function as the return value):
- In the function body, put the data to be returned after return;
- The return value of the function is the value after return. If there is no return, the return value is None
-
How to get the return value (how to get the data passed from inside the function outside the function):
- Obtain the result of the function call expression outside the function;
- The value of the function call expression is the return value of the function
-
When the return value is needed: if the function of the implementation function generates new data, the new data will be returned as the return value
def sum2(n1, n2): # n1 = 10; n2 = 20 result = n1 + n2 # result = 30 print(f'inside:{result}') return result # return 30 a = sum2(10, 20) # The value of the function call expression is the return value of the function print(f'a:{a}') def func1(): return 100 # b = 100 b = func1() print(f'b:{b}') print(100 * 2, func1() * 2) print(100 < 200, func1() < 200) list1 = [100, 200, func1()] print(list1) def func2(): return 'abc' print(func2()) print('abc'[-1], func2()[-1]) # 'abc'[-1] def sum3(x, y): return x + y result = sum3(100, 230) print(result)
task
-
Write a function to exchange the key and value of the specified dictionary.
# For example: dict1 = {a ': 1,' B ': 2,' C ': 3} -- > dict1 = {1:' a ', 2:' B ', 3:' C '} def exchange_key_value(dict1:dict): """Exchange dictionary keys and values""" result = {value:key for key,value in dict1.items()} return result
-
Write a function to extract all the letters in the specified string, and then splice them together to produce a new string
# For example, '12a&bc12d - +' -- > 'ABCD' is passed in def get_letters(str1:str): """Extracts all letters in the specified string""" str2 = '' for i in str1: if 'a' <= i <= 'z' or 'A' <= i <= 'Z': str2 += i return str2
-
Write your own capitalize function, which can turn the first letter of the specified string into uppercase letters
# For example: 'ABC' - > 'ABC' - '12asd' -- > '12asd' def change_initial(str1:str): """Converts the first letter of the specified string to uppercase""" str2 = '' first = str1[0] if 'a' <= first <= 'z': first = chr(ord(first) - 32) str2 = first + str1[1:] return str2 else: return str1
-
Write your own endswitch function to judge whether a string has ended with the specified string
# For example: String 1:'abc231ab' string 2:'ab' function result: True # String 1:'abc231ab' string 2:'ab1' function result: False def new_endswith(str1:str, str2:str): """Determines whether a string has ended with the specified string""" a = len(str2) result = (str1[-a:] == str2) return result
-
Write your own isdigit function to judge whether a string is a pure digital string
# For example: '1234921' result: True # '23 function' result: False # 'a2390' result: False def new_isdigit(str1:str): for i in str1: if not'0' <= i <= '9': return False break else: return True
-
Write your own upper function to change all lowercase letters in a string into uppercase letters
# For example: 'abh23 good RP1' result: 'abh23 good RP1' def new_upper(str1:str): str2 = '' for i in str1: if 'a' <= i <= 'z': i = chr(ord(i) - 32) str2 += i return str2
-
Write your own rjust function to create a string whose length is the specified length. The original string is right aligned in the new string, and the rest is filled with the specified characters
# For example: original character: 'abc' width: 7 characters: '^' result: '^ ^ ^ ^ abc' # Original character: 'how are you' width: 5 characters: '0' result: '00 how are you' def new_rjust(str1:str, width:int, char1:str): a = len(str1) str2 = char1 * (width - a) + str1 return str2
-
Write your own index function to count all the subscripts of the specified elements in the specified list. If there is no specified element in the list, return - 1
# For example: List: [1, 2, 45, 'abc', 1, 'hello', 1, 0] element: 1 Result: 0,4,6 list: ['Zhao Yun', 'Guo Jia', 'Zhuge Liang', 'Cao Cao', 'Zhao Yun', 'Sun Quan'] element: 'Zhao Yun' result: 0,4 list: ['Zhao Yun', 'Guo Jia', 'Zhuge Liang', 'Cao Cao', 'Zhao Yun', 'Sun Quan'] element: 'Guan Yu' result: #-1 def new_index(list1:list, element): list2 = [] if element in list1: for index,item in enumerate(list1): if item == element: list2.append(index) return list2 else: return -1
-
Write your own len function to count the number of elements in the specified sequence
for example: sequence:[1, 3, 5, 6] result: 4 sequence:(1, 34, 'a', 45, 'bbb') result: 5 # Sequence: 'hello w' result: 7 def new_len(sequence): count = 0 for i in sequence: count += 1 return count
-
Write your own max function to get the maximum value of the elements in the specified sequence. If the sequence is a dictionary, take the maximum value of the dictionary value
for example: sequence:[-7, -12, -1, -9] result: -1 sequence:'abcdpzasdz' result: 'z' # Sequence: {'Xiaoming': 90, 'Zhang San': 76, 'Luffy': 30, 'Xiaohua': 98} result: 98 def max_value(sequence): if type(sequence) == list: sequence.sort(reverse=True) return sequence[0] elif type(sequence) == str: max_value = sequence[0] for i in range(1,len(sequence)): if max_value < sequence[i]: max_value = sequence[i] return max_value else: max_value = sequence['Xiao Ming'] for i in sequence: if max_value < sequence[i]: max_value = sequence[i] return max_value
-
Write a function to realize its own in operation and judge whether the specified element exists in the specified sequence
for example: sequence: (12, 90, 'abc') element: '90' result: False # Sequence: [12, 90, 'abc'] element: 90 result: True def new_in(sequence, item): for i in sequence: if i == item: return True else: return False
-
Write your own replace function to convert the old string specified in the specified string into the new string specified
# for example: Original string: 'how are you? and you?' Old string: 'you' New string:'me' result: #'how are me? and me?' def new_replace(str1:str, str2, str3): if str2 in str1: new_str = str3.join(str1.rsplit(str2)) return new_str
-