Functions in Python

A function is a statement in Python, that performs a specific task and can be reused various times throughout the program. The function will not be executed unless it is called, which means adding () after the name of the function.

The def keyword

In python, the def keyword is used to define a function. Let’s define a function now-

def my_function():
    print("Hello All!")

Here, a function called print("Hello All!"). This means that every time this function is called, Hello All! will be displayed to the user.

Calling a function

A function can be called by writing the name of the function along with () after it. In some cases, the brackets can contain some properties of the function too.

Let’s now call the function defined above-

def my_function():
    print("Hello All!")
my_function()

The output-

Hello All!

Here, my_function() is being called, and hence, Hello All! is displayed as output.

Arguments

You can add arguments inside the brackets of a function too. Arguments are basically used to give information to a function whenever it is called. They are present in the brackets.

You might not understand all this immediately, but trust me, it'll be clear after looking at a few examples.

Let’s look at an example-

#Defining the function
def words(w):
  print(w + " World!")
#Calling the function
words("Hello")
words("Goodbye")

The output-

Hello World!
Goodbye World!

Here, a variable called w is created, and is, you can say, attached to the function words(). So, whenever the function is called, w gets assigned the value given inside the bracket (it may be a string or a numerical value).

You can give multiple arguments to a function, separated by commas.

If you have 2 or more arguments, you will have to specify multiple values while calling the variable, or there will be an error.

The return Keyword

The return keyword can be used to print a certain value after calling a function. When a return statement is executed, the function is terminated.

For example-

def num(n):
  return n*2
print(num(3))
print(num(7))

The output-

6
14


That is all for this post. I shall be continuing about functions in my next post. Stay tuned!

Happy coding,

Aarav Iyer

Aarav Iyer

I am a technology and programming enthusiast, currently a high school student. I love drawing and am quite interested in aeronautics and astrophysics too. My favourite pastimes are reading books, blogging and skywatching with my telescope.

1 Comments

Next Post Previous Post