Functions In Python

In this tutorial, we going to look at functions in Python programming language, before this tutorial I suggest you should read Python Tutorial – 1 and Python Tutorial – 2 to prepare.

Function Syntax In Python

In this section, we will look at how to define a simple function in python. Below the syntax, we will explain all the elements of the function. Let’s pass to the function syntax.

def functionName(argument , argument...):
   # Code Block

Above, we defined a function, we added the def keyword then, we created function name after that we open a parenthesis to enter arguments, we can leave a tab blank and start writing your code block.

Example Function Without Arguments

Let’s create a simple function, we will not use an argument, for now, we will just create a plain message function. Let’s write the world on the screen in this function and finish the function.

def Message():
   print("Hello World")


To use the function, you should call the function as in the last, if you did not call the function will not work. This function prints “Hello World” in the console. Now let’s add an argument to this function and make it a little more efficient.

Example Function With Argument

Now we will create a message argument. Let’s print the text added to this argument on the screen.

def Message(message):

Message("Hello World")

To add an argument to the function, a value is written between the brackets, and the message function prints the value of the message it receives on the screen.

Return Statement In Function

The return statement is used at the end of the function to return the value and exit the function, briefly, you can write the output of the function with the return.

def Message(message):
   return message

MessageFunction = Message("Hello World")

We print your message on the screen using the message argument. The reason we do not write print is to write the result on the screen.

Infinite Arguments In Function

You may need to get 100 or 1000 arguments from the user, you can use the * args keyword for this, with this argument the user or programmer can add infinite arguments. To use this argument, you need to know the “For loop”, if you don’t know, read the Control Structures In Python article.

def Message(*argv):
    for messageElement in argv:
        print(messageElement , end =" ")

Message("Hello" , "World" + "!")

We have written all the arguments to the screen one by one. The end argument is used to avoid passing the bottom line every time the loop starts.

Function Practice (Easy – Medium – Hard)


Leave a Reply

Your email address will not be published. Required fields are marked *