In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces how to create and call functions in Python, which has a certain reference value, and interested friends can refer to it. I hope you can learn a lot after reading this article.
Create function
The function is created with a def statement and the syntax is as follows:
Def function name (parameter list): # specific treatment, parameter optional "" function description document string "" function encapsulated code … "
The header line consists of the def keyword, the name of the function, and a collection of parameters, if any
The rest of the def clause includes an optional but highly recommended document string and the required function body
The naming of function names should conform to the naming rules of identifiers.
Can consist of letters, underscores, and numbers
Cannot start with a number
Cannot have the same name as the keyword
Def washing_machine (): # the washing machine can help us complete the print ("fetch") print ("wash") print ("dry") call function
Call the function with a pair of parentheses (). If there are no parentheses, it is just a reference to the function.
Any input parameters must be placed in parentheses
Legend:
Case study: adding washing powder
Def washing_machine (): # washing machine can help us finish print ("draw water") print ("add detergent!") Print ("laundry") print ("throw dry") # morning laundry washing_machine () # noon laundry washing_machine () # evening laundry washing_machine ()
Summary
Once the function is defined, it only means that the function encapsulates a piece of code
If the function is not called actively, the function will not be executed actively.
Thinking
Can I put the function call above the function definition?
I can't!
Because before calling a function with a function name, you must make sure that Python already knows the existence of the function.
Otherwise, the console will prompt NameError: name 'menu' is not defined (name error: menu is not defined)
Parameter parameters and actual parameters of a function
Formal parameters: when defining a function, the parameters in parentheses are used to receive parameters and are used as variables inside the function.
Argument: when calling a function, the parameters in parentheses are used to pass data to the inside of the function.
problem
When we want to wash something else, we have to manually change the code inside the method:
Def washing_machine (): # washing machine can help us finish print ("draw water") print ("add detergent!") Print ("washing sheets") # washing quilt covers print ("dry")
There is a variable value within the function:
Def washing_machine (): # washing machine can help us finish print ("draw water") print ("add detergent!") Print ("laundry") print ("dry") washing_machine () def washing_machine (): # washing machine can help us finish print ("fetch water") print ("add washing powder!") Print ("washing sheets") print ("dry") washing_machine ().
Think about what's wrong.
Functions can only deal with fixed data
How to solve?
It would be nice to pass the data that needs to be processed to the inside of the function when calling the function.
Transfer parameters
Fill in the parameters inside the parentheses after the function name
Use between multiple parameters, separate
When calling a function, the number of arguments needs to be the same as the number of parameters, and the arguments will be passed to the parameters in turn.
Def washing_machine (something): # washing machine can help us finish print ("drawing water") print ("add detergent!") Print ("wash" + something) print ("throw dry") # laundry washing_machine ("clothes") # bed sheets washing_machine ("sheets")
Legend
Def washing_machine (xidiji,something): # washing machine can help us complete print ("draw water") print ("plus" + xidiji) print ("wash clothes" + something) print ("shake dry") # wash clothes in the morning # the way to pass parameters according to the order of parameter position is called position transfer parameter # use washing machine Execute the logic inside the washing machine washing_machine ("detergent", "clothes") # something = clothes # wash the quilt cover at noon washing_machine ("washing powder", "quilt cover") # something = quilt cover # washing_machine ("Wuliangye", "bed sheet") # something = bed sheet at night
Action
Function that organizes blocks of code with independent functions into a small module that can be called when needed
Function parameters, increase the versatility of the function, for the same data processing logic, can adapt to more data
1. Within the function, the parameters are used as variables for the required data processing
two。 When the function is called, the data that you want to process inside the function is passed through the parameters according to the order of the parameters defined by the function.
Position parameter
Similar to the shell script, the program name and parameters are passed to the python program as positional parameters, which are received using the argv list of the sys module
Legend
Default parameter
The default parameter is the parameter that declares the default value, and because the parameter is assigned a default value, it is allowed not to pass a value to the parameter when the function is called.
The return value of the function
In program development, sometimes you want to tell the caller a result after the execution of a function, so that the caller can do subsequent processing for the specific result.
The return value is the final result given to the caller after the function finishes its work.
Use the return keyword in the function to return the result
On the calling side of the function, you can use variables to receive the returned results of the function.
Example: calculate the return value of the sum # function of any two numbers: return, used to deal with the subsequent logic # understanding: guess the result, do what you want to do later, print if you want, sum if you want # Note: # a. If there is no return in the function, the interpreter will automatically add a return None# b. Return to indicate the termination of the function, and the code after return will not execute # 1 to define a function, calculate the sum of two numbers and # 2 to determine whether the sum of the two numbers is an even number def get_sum (x, y # sum): # default parameter he = x + y # sum = 10 + 20 return he # return 30 print ("return represents the termination of the function The code after return will not execute ") # assign the result of the function return to the variable dc: dc = sum-> dc = 30dc = get_sum (10,20) # x = 10, y = 20print (" dc: ", dc) # 30dc1 = get_sum (10) # x = 10, y = 100print (" dc1: " Dc1) # 11lane if dc% 2 = = 0else:# print # print ("even") # else:# print ("odd") # default parameter # Note: a parameter with a default value cannot be followed by a parameter without a default value (def get_sum): he = a + b + c return he dc = get_sum (1, 2, 3) # a, 1, 2, c=3print ("dc:") Dc) # 6dc1 = get_sum (1Magne2) # axi1bao2 c=10print ("dc1:", dc1) # 13dc2 = get_sum (1) # axi1bao5 c=10print ("dc2:", dc2) # 16dc3 = get_sum () print ("dc3:", dc3) # 35
Modify the Fibonacci sequence
Def new_fib (Numb8): list01 = [0Magne1] # definition list, specify the initial value for dc in range (NMur2): list01.append (list01 [- 1] + list01 [- 2]) return list01 dc = new_fib () # No parameter defaults to 8dc1 = new_fib (10) print ("dc:", dc) print ("dc1:", dc1)
Generate a random password:
# exercise: generate a random password # create a randpass.py script The requirements are as follows: # write a program that can generate 8-bit random passwords # randomly fetch characters using the choice function of random # the password length is determined by the user import randomdef new_password (): n = int (input ("password length:") password = "" all = "0123456789zxcvbnmlkjhgfdsaqwertyuiopPOIUYTREWQASDFGHJKLMNBVCXZ" # 0-9 Amurz Amurz random.choice (all) for i in range (n): dc = random. Choice (all) password + = dc # print ("passwd:" Password) return password# calls the function To execute the function internal logic dc = new_password () print ("dc:", dc)
# exercise: generate a random password # create a randpass.py script The requirements are as follows: # write a program that can generate 8-bit random passwords # use the choice function of random to randomly fetch characters # Let the user determine the password length import random Stringdef new_password (): n = int (input ("password length:") password = "" all = string.ascii_letters + string.digits random.choice (all) for i in range (n): dc = random.choice (all) password + = dc # print ("passwd:", password) return password# calls the function To execute the function internal logic dc = new_password () print ("dc:", dc)
Basic definition of module basic concepts of module
A module is a form of logically organizing python code
When the contemporary code volume becomes quite large, it is best to divide the code into organized code segments, as long as they interact with each other.
These code fragments are related to each other, either as a class containing data members and methods, or as a set of related but independent operation functions.
Import module (import)
Import a module using import
The module attribute is called through the method call of the "module name. Property"
If you only need some attributes in the module, you can also import them separately.
Why do I need to import modules?
It can improve development efficiency and simplify code.
Correct use
# test.py, put the file_copy.py in the same directory # requirements: to copy / etc/passwd to / tmp/passwdsrc_path = "/ etc/passwd" dst_path = "/ tmp/passwd" # how to copy? # call methods in existing modules #-highly recommended Simple and rude without using the brain #-directly use the file_copy.py method # Import method 1: directly import the module import file_copy # pay attention to the path problem file_copy.copy (src_path, dst_path) # Import method 2: import only the copy method of the file_copy module from file_copy import copy # if you import multiple modules from file_copy import * copy (src_path) at the same time Dst_path) # Import method 4: import module alias asimport file_copy as fcfc.copy (src_path, dst_path)
Common methods of importing modules
One line guide into a module, you can import multiple lines, for example: import random
Import only some methods in the module, such as from random import choice, randint
Module loading (load)
A module is loaded only once, no matter how many times it is imported
When loading only once prevents multiple imports, the code is executed multiple times
If two files are imported into each other, it prevents unlimited loading of each other.
When the module is loaded, the top-level code executes automatically, so it is the best programming habit to put the function at the top level of the module.
Module characteristics and case module characteristics
When the module is imported, all the programs in the module will be executed completely first.
Case
# foo.pyprint (_ _ name__) # bar.pyimport foo # importing foo.py will execute the code in foo.py once, so print (_ _ name__) in foo will be executed.
Results:
# foo.py-> _ _ main__ when the module file is executed directly, the value of _ _ name__ is'_ _ main__'
# bar.py-> foo when a module is imported by another file, the value of _ _ name__ is the name of the module
So we will execute the standard format of the code in the Python module later:
Def test (): .if _ name__ = = "_ main__": test () Thank you for reading this article carefully. I hope the article "how to create and call functions in Python" shared by the editor will be helpful to you. At the same time, I hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.