Skip to content Skip to sidebar Skip to footer

I Defined a Function and It Is Saved in the Variables Tab but How Do I See the Function Code Again

Python has a agglomeration of helpful built-in functions you can use to do all sorts of stuff. And each one performs a specific task.

But did you know that Python also allows y'all to ascertain your own functions?

This commodity will show you how to create and telephone call your own Python functions. It will as well give you lot an overview of how to pass input parameters and arguments to your functions.

What is a Part?

A function is an isolated block of code that performs a specific task.

Functions are useful in programming considering they eliminate needless and excessive copying and pasting of lawmaking throught a program.

If a certain action is required often and in different places, that is a good indicator that yous tin write a part for it. Functions are meant to be reusable.

Functions likewise help organize your lawmaking.

If yous need to make a change, you'll only need to update that sure office. This saves y'all from having to search for different pieces of the same code that have been scattered in different locations in your program past copying and pasting.

This complies with the Dry out (Don't Echo Yourself) principle in software development.

The code inside a function runs only when they the role is called.

Functions can accept arguments and defaults and may or not render values dorsum to the caller one time the code has run.

How to Ascertain a Office in Python

The general syntax for creating a function in Python looks something like this:

                def function_name(parameters):     function trunk                              

Let'south intermission downwardly what's happening here:

  • def is a keyword that tells Python a new function is being defined.
  • Next comes a valid function name of your choosing. Valid names start with a letter or underscore but can include numbers. Words are lowercase and separated past underscores. It'south important to know that function names can't exist a Python reserved keyword.
  • Then nosotros have a prepare of opening and closing parentheses, (). Inside them, there tin be cipher, one, or more optional comma separated parameters with their optional default values. These are passed to the function.
  • Next is a colon, :, which ends the function's definition line.
  • Then there'south a new line followed by a level of indentation (yous tin do this with iv spaces using your keyboard or with 1 Tab instead). Indentation is important since information technology lets Python know what code will belong in the function.
  • Then we have the function'south body. Here goes the code to be executed – the contents with the actions to be taken when the part is called.
  • Finally, there's an optional return statement in the function'southward body, passing back a value to the caller when the function is exited.

Go along in mind that if you forget the parentheses() or the colon : when trying to define a new function, Python volition let y'all know with a SyntaxError.

How to Ascertain and Call a Basic Role in Python

Below is an example of a bones role that has no render statement and doesn't take in whatsoever parameters.

Information technology just prints how-do-you-do globe whenever it is called.

                def hello_world_func():     print("hullo earth")                              

Once y'all've defined a function, the code volition not run on its own.

To execute the lawmaking inside the role, you have make a office invokation or else a function call.

You tin can then call the function as many times as you lot desire.

To phone call a part you need to practise this:

                function_name(arguments)                              

Here'due south a breakup of the lawmaking:

  • Blazon the role proper noun.
  • The part name has to be followed past parentheses. If there are any required arguments, they have to be passed in the parentheses. If the function doesn't have in any arguments, y'all still need the parentheses.

To call the role from the case above, which doesn't accept in whatsoever arguments, practise the following:

                hello_world_func()  #Output #hello world                              

How to Define and Telephone call Functions with Parameters

So far you've seen unproblematic functions that don't actually do much besides printing something to the panel.

What if y'all want to pass in some extra data to the function?

We've used terms here like parameter and arguments.

What are their definitions exactly?

Parameters are a named placeholder that pass information into functions.

They deed equally variables that are defined locally in the office's definition line.

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

In the case above, there is ane parameter, proper name.

We could've used f-string formatting instead – it works the same way as the previous example:

                def hello_to_you(proper name):     print(f"Hello {name}")                              

There can be a list of parameters inside the parentheses, all separated past commas.

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

Here, the parameters in the role are name and age.

When a part is called, arguments are passed in.

Arguments, like parameters, are data passed to functions.

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

Calling the role from a previous example and passing in an argument would await like this:

                def hello_to_you(name):     print(f"Hello {name}")           hello_to_you("Timmy") #Output # How-do-you-do Timmy                              

The function can be called many times, passing in different values each fourth dimension.

                def hello_to_you(proper noun):     impress(f"Hello {proper name}")      hello_to_you("Timmy") hello_to_you("Kristy") hello_to_you("Jackie") hello_to_you("Liv")  #Output: #"Hi Timmy" #"Hullo Kristy" #"Hello Jackie" #"Hi Liv"                              

The arguments presented so far are called positional arguments.

All positional arguments are very much required.

The number of positional arguments matters

When calling functions, you lot need to pass the correct number of arguments, otherwise there will be an fault.

When it comes to positional arguments, the number of arguments passed in to the function call has to be exactly the aforementioned as the number of parameters in the function's definition.

Y'all can't go out whatever out or add in any more.

Say that you accept this office that takes in 2 parameters:

                def hello_to_you(first_name,last_name):     impress(f"How-do-you-do, {first_name} {last_name}")                              

If the function is chosen with just one argument passed in, like this, there will exist an error:

                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 "<stdin>", line i, in <module> TypeError: hello_to_you() missing 1 required positional argument: 'last_name'                              

If the function is called with three arguments passed in, there will again exist an error:

                def hello_to_you(first_name,last_name):     print(f"Hello, {first_name} {last_name}")       hello_to_you("Timmy","Jones",34)                              
                Traceback (almost recent call concluding):   File "<stdin>", line 1, in <module> TypeError: hello_to_you() takes 2 positional arguments but iii were given                              

At that place will also be an fault if nosotros pass in no arguments.

                def hello_to_you(first_name,last_name):     print(f"Hello, {first_name} {last_name}")       hello_to_you()                              
                Traceback (most recent call concluding):   File "<stdin>", line 1, in <module> TypeError: hello_to_you() missing 2 required positional arguments: 'first_name' and 'last_name'                              

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

                def hello_to_you(first_name,last_name):     print(f"How-do-you-do, {first_name} {last_name}")       hello_to_you("Timmy","Jones") #Output: # Howdy,Timmy Jones                              

The order of positional arguments matters

Also including the correct number of arguments, it is important to note that the gild in which the arguments are passed in matters.

Arguments need to be passed in the exact same society as the society of the parameters that have been alleged in the function'south definition.

It works like variable consignment.

The kickoff statement is the value of the beginning parameter in the function'due south definition. The second statement is the value of the 2nd parameter in the function's 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 #How-do-you-do,Timmy Jones  #y'all tin can visualise it like: #first_name = "Timmy" #last_name = "Jones"                              

If the gild is non right, the output might not brand much sense and not be what you intended information technology to be.

                def fave_language(name,language):     print(f"Howdy, I am {name} and my favorite programming language is {language}")       fave_language("Python","Dionysia") #output: #Hello, I am Python and my favorite programming linguistic communication is Dionysia #information technology is similar you did #name="Python" #linguistic communication = "Dionysia"                              

How to use keyword arguments in Python functions

So far y'all've seen ane type of statement, positional arguments.

With positional arguments, functions are called with just the values passed in the office telephone call. At that place, each value directly corresponds with the number, gild, and position of each parameter in the function definition.

However, functions in Python tin can take another type of argument, that is keyword arguments.

In this case, instead of just passing in values in the function telephone call, you instead specify the name of the parameter so the value you want to assign it, in the form of central = value.

Each primal matches each parameter in the part definition.

Explicitely calling the name of parameters and the values they take helps in being actress clear about what you're passing in and avoids whatsoever possible confusion.

                def fave_language(name,language):     print(f"Hello, I am {name} and my favorite programming language is {linguistic communication}")       fave_language(name="Dionysia",language="Python") #output: #How-do-you-do, I am Dionysia and my favorite programming language is Python                              

Keyword arguments, equally seen above, tin exist in a item gild. But they are more flexible than positional arguments in the sense that social club of arguments now does non matter.

So you could exercise this and there would be no errors:

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

Only you notwithstanding have to requite the correct number of arguments.

Y'all tin use both positional and keyword arguments together in a office phone call, similar the example below where there is one positional statement and 1 keyword statement:

                def fave_language(name,language):     impress(f"Hello, I am {name} and my favorite programming language is {language}")       fave_language("dionysia",language="Python") #output: #Howdy, I am dionysia and my favorite programming linguistic communication is Python                              

In this instance, order matters over again.

Positional arguments always come first and all keyword arguments should follow the positional arguments. Otherwise there will be an error:

                def fave_language(name,language):     print(f"Hello, I am {proper name} and my favorite programming linguistic communication is {linguistic communication}")       fave_language(language="Python","dionysia")                              

How to ascertain a parameter with a default value in Python

Role arguments tin likewise have default values. They are known as default or optional arguments.

For a office statement to have a default value, you have to assign a default value to the parameter in the function's definition.

You do this with the cardinal=value form, where value volition be the default value for that parameter.

                def fave_language(linguistic communication="python"):     print(f"My favorite  programming language is {language}!")      fave_language() #output #My favorite  programming language is python!                              

As you run into, default arguments are not required in the role telephone call, and the value of linguistic communication will ever default to Python if another value isn't provided in the telephone call.

Withal, default values can be easily overriden if you provide another value in the part'due south phone call:

                def fave_language(linguistic communication="python"):     print(f"My favorite  programming language is {linguistic communication}!")      fave_language("Coffee") #prints "My favorite  programming linguistic communication is Java!" to the console                              

There tin can be more than one default value passed to the function.

When the function is called, none, one, some, or all of the default arguments tin can be provided and lodge does not affair.

                def personal_details(name="Jimmy",age=28,city="Berlin"):     print(f"I am {proper name},{age} years old and alive in {metropolis}")       #We can exercise:  personal_details() #output: #I am Jimmy,28 years old and live in Berlin  personal_details(age=xxx) #I am Jimmy,thirty years old and alive in Berlin  personal_details(city="Athens",name="Ben",age=24) ##I am Ben,24 years old and alive in Athens                              

Default arguments can exist combined with not-default arguments in the function'southward call.

Here is a office that accepts two arguments: 1 positional, non-default (name) and i optional, default (language).

                def fave_language(proper noun,linguistic communication="Python"):     impress(f"My name is {proper noun} and my favorite  programming language is {language}!")      fave_language("Dionysia") #output: #"My name is Dionysia and my favorite  programming language is Python!"                              

The default argument, langyage="Python", is optional. But the positional argument, name, will always ever required. If another language is non passed in, the value will always default to Python.

Another thing to mention here is that, when defaults and non defaults are used together, the order they are defined in the function defintion matters.

All the positional arguments go offset and are followed past the default arguments.

This volition not work:

                def fave_language(linguistic communication="Python",proper name):     print(f"My proper name is {proper noun} and my favorite  programming linguistic communication is {linguistic communication}!")      fave_language("Dionysia")                              

Output:

                                  File "<stdin>", line 1 SyntaxError: non-default argument follows default argument                              

Conclusion

In this article, yous learned how to declare functions and invoke them with parameters in the Python programming language.

This was an introduction on how to create simple functions and how to laissez passer information into them, with parameters. We also went over the different types of arguments like positional, keyword, and default arguments.

To epitomize:

  • The society and number of positional arguments matters.
  • With keyword arguments, social club does not affair. Number does matter, though, since each keyword argument corresponds with each parameter in the function's definition.
  • Default arguments are entirely optional. You can pass in all of them, some of them, or none at all.

If you are interested in going more in-depth and learning more about the Python programming language, freeCodeCamp has a complimentary Python certification.

Yous'll showtime from the basics and fundamentals of the language and and so progress to more than avant-garde concepts like information structures and relational databases. In the end y'all'll build 5 projects to put to practice what yous've learnt.

Thanks for reading and happy learning.



Larn to code for free. freeCodeCamp'south open source curriculum has helped more than 40,000 people get jobs every bit developers. Become started

edgarsaim1966.blogspot.com

Source: https://www.freecodecamp.org/news/python-function-examples-how-to-declare-and-invoke-with-parameters-2/

Post a Comment for "I Defined a Function and It Is Saved in the Variables Tab but How Do I See the Function Code Again"