[Part IV]Functions in Python๐Ÿ

[Part IV]Functions in Python๐Ÿ

ยท

5 min read

Welcome back to the series "Learn Python with me!"๐Ÿ‘‹๐Ÿ‘‹

As promised we are going to get into functions today! One of the first things a beginner Googles is "Which programming language to start with?" and "Topics to cover in XYZ language ." If you ask someone, more often than not they would scare you about Functions and Data Structures, and Algorithms.

I cannot give a confident opinion about DSA at this moment, but I will assure you that functions will seem like a friend if you stop thinking about what others tell you.

So, let's get started!

What are Functions?

Functions can take data and then return data.

Yes! It is as simple as that.

Fun fact: We have been using functions all along!

#The input function takes information from the user and then returns the response
name = input("Enter your name")

#The abs function takes the value and then returns the absolute number
num = abs(-2)

#The print function takes the information and then displays it in the console
print("My name is " + name)

There are many more like range(), math.sqrt() etc .

We have been writing our code in our main() function all along.

When we use the toaster or the microwave, do we need to know how they work to be able to use them? We just need to know how to switch it on and off and what can be used inside it. We cannot use a fork inside a microwave or toaster, right? It would be a disaster. Do not try this at home. โŒโŒ Maybe now the blog banner makes sense!๐Ÿ˜ Similarly, a function can be called with the information that it needs, and then it gives us the result.

We don't need to know the code written inside input() to be able to use it. This helps us write sophisticated and clean code. We can call a function that someone else defined, and solve problems of our own. This is increasing productivity and code reusability.

Let's define a function

We already know how to define a function. main() is a function.

We define it like this:๐Ÿ‘‡

def main():
    #body

Calling a function

Recall this piece of code :

if __name__ =="__main__" :
    main()

We can call the main function just by writing main() wherever we need it.

We can write our own functions now and explore further.

Let's find the average of two numbers using a function.

def main():
    avg = average(5.0,10.0)
    print(avg)

def average(a,b):
    sum = a+b
    return sum/2.0

if __name__ == "__main__":
    main() #calling main

Let's break this down:

โœ” How many function definitions do we see? 2 right. We can see our old friend main() , and average().

โœ”We know how our program starts. We first go into main(), it is called in the code snippet below, that we are familiar with.

โœ”Inside main(), we can see a variable called avg, which is being assigned with a value generated from a function call. Note that in this case, the function call is being given some information. This information given is called arguments.

โœ” Now that the function is called we go to the place where the function is defined. What is the name of the function? It is average. What is within the parenthesis? a and b represent the information needed by the function. This information needed is called parameters.

โœ”What is happening inside the average function? We can see sum which is a variable storing the value of a+b.

โœ”What is return? It simply returns the value to the function call. We need to return the average of two numbers, which is sum/2.0.

โœ”Our variable avg gets stored with the average of two numbers. In the next line, avg gets printed to the console.

Let's run the program.

average.gif

We can change the arguments to the required result.

We looked at two types of functions:-

  • No parameter, no return type -> The main() function.

  • Parameter, return type -> The average() function.

Let's see an example of the Parameter, no return type.

We will ask the user to enterLuke or Darth Vader and in return display the following messages:

Luke - Obi-Wan. Why didn't you tell me?

Darth Vader - Luke, I am your father!

Let's see the program below:

def dialogue(character):
    if character == "Luke":
        print("Obi-Wan. Why didn't you tell me?")
    elif character == "Darth Vader":
        print("Luke, I am your father!")
    else:
        print("An invalid choice you made.")

def main():
    character = input("Enter 'Luke' or 'Darth Vader': ")
    dialogue(character)

if __name__ == "__main__":
    main()

Star_Wars.gif

Hope that the Star Wars reference was refreshing.

We did not return any value here. We just printed it directly from the function.

There are things to note here.

  • Firstly, I have used the same variable character throughout the program. Is the character in main() the same as the character in dialogue()? The answer is no.

When the function is called inside main(), imagine that a box named dialogue() is created in the memory. It has a variable called character which stores the value, goes through the if-elif-else stack, and then prints our result.

After the control exits our function, that box gets deleted from the memory.

If a function returns a value, a new variable is formed in the box named main().

The only way we can digest all this information is through practice.

We learned about how to use a function today. Next time we will be applying our knowledge in mini-projects. As always, you may ask questions or give suggestions in the comment section below. Let's help each other grow๐Ÿ“ˆ!

May the Force Be with you! Happy Learning!

ย