Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the methods declared and called by the Python parameter

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "what is the method of Python parameter declaration and call". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the method of Python parameter declaration and invocation".

What is a function?

Functions are isolated blocks of code that perform specific tasks.

Functions are useful in programming because they eliminate unnecessary and excessive code copying and pasting throughout the program.

If you often need an action in different places, which is a good indicator, you can write a function for it. Functions are reusable.

Functions also help organize your code.

If you need to make changes, you only need to update that specific feature. This eliminates the need to copy and paste to search for different parts of the same code scattered in different locations in the program.

This is in line with the DRY (don't repeat yourself) principle in software development.

The code within the function runs only when the function is called.

The function can accept parameters and default values and may or may not return the value to the caller after the code runs.

How to define functions in Python

The general syntax for creating a function in Python is as follows:

Def function_name (parameters): function body

Let's break down what's going on here:

Def is a keyword that tells Python that a new function is being defined.

Next is the valid function name of your choice. Valid names begin with a letter or an underscore, but can contain numbers. The words are lowercase and separated by an underscore. It is important to know that the function name cannot be a Python reserved keyword.

Then we have a set of left and right parentheses, (). Within them, there can be zero, one, or more optional comma-separated parameters and their optional default values. These are passed to the function.

Next is a colon, which ends the definition line of the function.

Then there is a new line, followed by the indentation level (you can do this using the keyboard or using 1 Tab with 4 spaces). Indentation is important because it lets Python know which code will belong to the function.

And then we have the body of the function. Here is the code to be executed-the content of the action to be performed when the function is called.

Finally, there is an optional return statement in the function body that returns a value to the caller when the function exits.

Remember, if you forget parentheses () or colons: when you try to define a new function, Python will report an error: SyntaxError.

How to define and call basic functions in Python

The following is an example of a basic function that does not have a return statement and accepts no arguments.

It just prints when hello world is called.

Def hello_world_func (): print ("hello world")

Once a function is defined, the code does not run on its own.

To execute code within a function, you must make a function call or a function call.

You can then call the function as many times as needed.

To call a function, you need to do this:

Function_name (arguments)

This is a breakdown of the code:

Type the name of the function.

The function name must be followed by parentheses. If there are any required parameters, they must be passed in parentheses. If the function does not accept any arguments, you still need parentheses.

To call a function that does not accept any arguments in the above example:

Hello_world_func () # Output#hello world how to define and call functions with parameters

So far, you've seen some simple functions that don't actually do much except print something to the console.

What if you want to pass some extra data to the function?

We use terms such as parameters here.

What exactly is their definition?

Parameters are named placeholders that pass information to the function.

They act as variables defined locally in the function definition line.

Def hello_to_you (name): print ("Hello" + name)

In the above example, there is one parameter, name.

We can use f-string formatting instead-- it works in the same way as the previous example:

Def hello_to_you (name): print (f "Hello {name}")

There can be a list of parameters in parentheses, all of which are separated by commas.

Def name_and_age (name,age): print (f "I am {name} and I am {age} years old!")

Here, the arguments in the function are name and age.

When a function is called, parameters are passed in.

Parameters, like parameters, are the information passed to the function.

In particular, they are the actual values corresponding to the parameters in the function definition.

Call the function in the previous example and pass in the parameters as follows:

Def hello_to_you (name): print (f "Hello {name}") hello_to_you ("Timmy") # Output# Hello Timmy

This function can be called multiple times, passing in a different value each time.

Def hello_to_you (name): print (f "Hello {name}") hello_to_you ("Timmy") hello_to_you ("Kristy") hello_to_you ("Jackie") hello_to_you ("Liv") # Output:# "Hello Timmy" # "Hello Kristy" # "Hello Jackie" # "Hello Liv"

The parameters proposed so far are called position parameters.

All position parameters are very much needed.

The number of location parameters is important.

When calling a function, you need to pass in the correct number of parameters, otherwise an error will be reported.

For positional parameters, the number of parameters passed to the function call must be exactly the same as the number of parameters in the function definition.

You cannot leave anything out or add anything.

Suppose you have a function that takes two arguments:

Def hello_to_you (first_name,last_name): print (f "Hello, {first_name} {last_name}")

If you pass in only one parameter to call the function, like this, an error will occur:

Def hello_to_you (first_name,last_name): print (f "Hello, {first_name} {last_name}") hello_to_you ("Timmy")

Output:

Traceback (most recent call last): File "", line 1, in TypeError: hello_to_you () missing 1 required positional argument: 'last_name'

If the function is called with three parameters passed in, the error will occur again:

Def hello_to_you (first_name,last_name): print (f "Hello, {first_name} {last_name}") hello_to_you ("Timmy", "Jones", 34) Traceback (most recent call last): File ", line 1, in TypeError: hello_to_you () takes 2 positional arguments but 3 were given

If we don't pass in any parameters, there will be an error.

Def hello_to_you (first_name,last_name): print (f "Hello, {first_name} {last_name}") hello_to_you () Traceback (most recent call last): File ", line 1, in TypeError: hello_to_you () missing 2 required positional arguments: 'first_name' and' last_name'

Instead, we need two parameters because two parameters are listed in the function definition.

Def hello_to_you (first_name,last_name): print (f "Hello, {first_name} {last_name}") hello_to_you ("Timmy", "Jones") # Output:# Hello,Timmy Jones position parameter order is important

In addition to including the correct number of parameters, it is important to note that the order in which the parameters are passed is important.

The order in which parameters must be passed must be exactly the same as those declared in the function definition.

It works similar to variable assignment.

The first parameter is the value of the first parameter in the function definition. The second argument is the value of the second parameter in the function ddefinition-- and so on.

Def hello_to_you (first_name,last_name): print (f "Hello, {first_name} {last_name}") hello_to_you ("Timmy", "Jones") # Output#Hello,Timmy Jones # you can visualise it like:#first_name = "Timmy" # last_name = "Jones"

If the order is incorrect, the output may not make much sense or what you want.

Def fave_language (name,language): print (f "Hello, I am {name} and my favorite programming language is {language}") fave_language ("Python", "Dionysia") # output:#Hello, I am Python and my favorite programming language is Dionysia#it is like you did#name= "Python" # language = "Dionysia" how to use keyword arguments in Python functions

So far, you have seen one type of parameter, the positional parameter.

Using positional parameters, only the values passed in the function call are used to call the function. There, each value corresponds directly to the number, order, and location of each parameter in the function definition.

However, functions in Python can accept another type of parameter, the keyword parameter.

In this case, instead of passing only the value in the function call, you specify the name of the parameter, and then specify the value to be assigned to it in the format key = value.

Each key matches each parameter in the function definition.

Explicit invocation parameter names and the values they take can help you understand what you are passing in more clearly and avoid any possible confusion.

Def fave_language (name,language): print (f "Hello, I am {name} and my favorite programming language is {language}") fave_language (name= "Dionysia", language= "Python") # output:#Hello, I am Dionysia and my favorite programming language is Python

As shown above, keyword parameters can be arranged in a specific order. But they are more flexible than positional parameters, because the order of the parameters does not matter now.

So you can do this without making mistakes:

Def fave_language (name,language): print (f "Hello, I am {name} and my favorite programming language is {language}") fave_language (language= "Python", name= "Dionysia") # output:#Hello, I am Dionysia and my favorite programming language is Python

However, you must still provide the correct number of parameters.

You can use both positional and keyword parameters in a function call, as shown in the following example, where there is a positional parameter and a keyword parameter:

Def fave_language (name,language): print (f "Hello, I am {name} and my favorite programming language is {language}") fave_language ("dionysia", language= "Python") # output:#Hello, I am dionysia and my favorite programming language is Python

In this case, the order is very important.

Positional parameters always appear first, and all keyword parameters should follow positional parameters. Otherwise, an error will be reported:

Def fave_language (name,language): how print (f "Hello, I am {name} and my favorite programming language is {language}") fave_language (language= "Python", "dionysia") defines parameters with default values in Python

Function parameters can also have default values. They are called default or optional parameters.

For function parameters with default values, you must assign a default value to the parameters in the function definition.

You do this using the key=value form, where value will be the default value for this parameter.

Def fave_language (language= "python"): print (f "My favorite programming language is {language}!") Fave_language () # output#My favorite programming language is python!

As you can see, the default parameters are not required in the function call, and the value language will always default to Python if no other value is provided in the call.

However, if you provide another value in a function call, you can easily override the default value:

Def fave_language (language= "python"): print (f "My favorite programming language is {language}!") Fave_language ("Java") # prints "My favorite programming language is Java!" To the console

Multiple default values can be passed to the function.

When you call a function, you can provide none, one, some, or all of the default parameters, and the order does not matter.

Def personal_details (name= "Jimmy" age=28,city= "Berlin"): print (f "I am {name}, {age} years old and live in {city}") # We can do:personal_details () # output:#I am Jimmy,28 years old and live in Berlinpersonal_details (age=30) # I am Jimmy,30 years old and live in Berlinpersonal_details (city= "Athens", name= "Ben", age=24) # # I am Ben,24 years old and live in Athens

Default parameters can be combined with non-default parameters in a function call.

This is a function that takes two arguments: a positional, non-default (name) and an optional, default (language).

Def fave_language (name,language= Python): print (f "My name is {name} and my favorite programming language is {language}!") Fave_language ("Dionysia") # output:# "My name is Dionysia and my favorite programming language is Python!"

The default parameter langyage= "Python" is optional. But the position parameter, name always needs. If no other language is passed in, the value will always default to Python.

Another thing to mention here is that when default and non-default values are used together, the order in which they are defined in the function definition is important.

All positional parameters come first, followed by default parameters.

This will not work:

Def fave_language (language= "Python", name): print (f "My name is {name} and my favorite programming language is {language}!") Fave_language ("Dionysia")

Output:

File ", line 1SyntaxError: non-default argument follows default argument Thank you for your reading, the above is the content of" what is the method of Python parameter declaration and call ". After the study of this article, I believe you have a deeper understanding of what the method of Python parameter declaration and call is, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report