Python Functions Tutorial for Absolute Beginners

Python Functions Tutorial for Absolute Beginners

Alright, let’s start with what functions actually are.

  • OK, a function is a piece of code.

  • A function may/may not accept input(s).

  • A function may/may not return an output(s).

Why do we need functions in a program?

  • Well, the Reusability of the code in a program is made possible through functions.

  • The program can call these so-called functions, n — number of times.

  • This showcases the best practice in a program called DRY.

DRY — Do not Repeat Yourself

  • A code is said to be DRY if any given code does not repeat certain tasks.

  • A function implements this just by writing once and using it whenever necessary.

A quick intro to functions in python

Creating a function:

  • To create a function we use the keyword def.

  • def must be followed by the function name.

  • followed by a parenthesis filled with formal parameters(optional).

  • The statements that follow up make the body of the function.

  • Note: Any code written inside a function must be indented.

  • Let’s see an example where I thank every one of my readers:

Calling a function:

  • To call a function we use the function name followed by a parenthesis filled with actual parameter also known as arguments.

  • This is when the code inside the function actually gets executed.

  • Let’s see the same example and its output:

  • Output:
Hello there John Doe  
Thank you for taking your time to read my post ;)  
Hello there Jane Doe  
Thank you for taking your time to read my post ;)

Passing arguments to a function:

  • We can pass arguments to a function through the function call.

  • We do this by writing the arguments inside the parenthesis of a function call.

  • Didn’t you notice passing arguments to a function already? Look into the above example closely:

reader("John Doe")  
reader("Jane Doe")
  • The function call reader() passes the strings "John Doe" and "Jane Doe" as arguments to the function.

As we have seen the power of functions, pass statements inside a function can be really helpful whenever we feel lazy to do something and decide to do it later ;)

Note: The body of any statement containing pass statements is ignored by the python interpreter, just like it ignores comments.

There you go, now you can create your own functions and play with them.

Arguments, parameters and return statements in functions

Let me start with a fact: Every function returns a value when called.

Well, I don’t know about you, but I was surprised to know about it in the first place!

Let’s see an example to prove my point:

Output:

Welcome to my blog post  
None

Did you see that? When I called the function, it returned the special type None. The variable post stores it and prints it out in the second line.

Now, we can explicitly return a value from a function by using the return keyword.

return statement

  • The return statement includes a return keyword followed by an expression.

  • An expression is a set of conditions which produces a value.

  • So, the return statement can contain an expression or an explicit value to be returned.

  • A return statement also ends the function execution. This means that any statements inside a function following the return statement will not be executed.

  • Take note that a return statement cannot be used outside a function.

Let’s code a few examples:

1) Single return statement

Output:

21

As you can see in this example, we have given an expression that returns the product of two numbers.

2) Multiple return statements

Output:

21  
3.14  
Try again!

Here, an explicit value is specified in multiple return statements.

3) return statement with multiple values

Output:

(21, 63, 210)

This example returns dynamic values in a tuple based on the given argument.

Arguments and parameters in functions

In general, the terms parameters and arguments are being used interchangeably.

Although, with respect to a function:

parameters are the variables listed inside the parentheses in the function definition. arguments are the values that are sent to the function when it is called.

It turns out that it’s possible to define functions with various types of arguments in python. And there are three types of arguments/parameters, which can be combined.

1) Default Argument Values

The most useful type of argument is to specify a default value for one or more arguments, inside the parenthesis of a function definition. This creates a function which is flexible to use. Because this function can be called with fewer arguments than it is defined to allow.

Let’s look at an example:

Output:

You have 120 minutes!  
Let's watch a action type web series  
You have 150 minutes!  
Let's watch a thriller type web series  
You have 200 minutes!  
Let's watch a horror type movie

This function is called in several ways:

giving only the mandatory argument: popcorn_time(120) giving one of the optional arguments: popcorn_time(150, ‘thriller’) or even giving all arguments: popcorn_time(200, ‘horror’, ‘movie’)

Play with the code here

2) Keyword Arguments

Functions can also be called using keyword arguments of the form kwarg=value. For instance, consider the above example of popcorn_time, a function which accepts one required argument(time) and two optional arguments(genre, watch). This function can be called in any of the following ways:

But take note that, the following function calls would be invalid:

3) Special parameters

By default, arguments may be passed to a Python function either by position or explicitly by keyword. For readability and performance, we can restrict the way arguments can be passed

So, a developer needs to look at the function definition to determine if items are passed by position, by position or keyword, or by keyword.

An advanced function definition may look like the one below:

If you’re interested, check out special parameters python docs for more information.

What if you don’t know how many arguments you want to be passed into your function? Python provides us with a solution: Arbitrary Arguments — args \Arbitrary Keyword Arguments — \*kwargs

Arbitrary Arguments, *args

To specify the argument as an arbitrary argument, you need to just add a *(asterisk) before the parameter name in the function definition. The function, in turn, will receive the arguments and save it as a tuple of arguments, and you can access the items accordingly:

Output:

Largest number: 94

Arbitrary Keyword Arguments, **kwargs

Similarly, to specify the argument as an arbitrary keyword argument, you need to add two asterisks: ** before the parameter name in the function definition. The function, in turn, will receive the arguments and save it as a dictionary of arguments, and you can access the items accordingly:

Output:

Marvel Studios presents - Iron Man  
Starring - Robert Downey Jr.  
Marvel Studios presents - Captain America: The First Avenger  
Starring - Chris Evans  
Marvel Studios presents - Thor  
Starring - Chris Hemsworth

Who Am I?

I’m Aswin Barath, a Software Engineering Nerd who loves building Web Applications, now sharing my knowledge through Blogging during the busy time of my freelancing work life. Here’s the link to all of my craziness categorized by platforms under one place: https://linktr.ee/AswinBarath

Join me to learn Python!

Checkout my Python Programming Series where my mission is to share my knowledge on Python: aswinbarath.hashnode.dev/series/python-prog..

Learn what I know about Python from any of my favourite knowledge sources:

Keep Learning

Now, I guess this is where I say GoodBye👋.
But, hey it’s time for you to start learning with your newfound Knowledge(Power)👨‍💻👩‍💻 .
Good Job that you made it this far 👏👏
Thank you so much for reading my Blog🙂.