How to Create and Work Python Functions?

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

Best Python Training Institute in Noida

Creating a Function

In Python a function is defined using the def keyword:

Example

Def my_function():
  
print("Hello from a function")

Calling a Function

To call a function, use the function name followed by parenthesis:

Example

Def my_function():
  
print("Hello from a function")

my_function()

Arguments

Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name:

Example

Def my_function(fname):
 
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

Passing a List as an Argument

You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.

E.g. if you send a List as an argument, it will still be a List when it reaches the function:

Example

Def my_function(food):
 
for x in food:
   
print(x)

fruits = [
"apple", "banana", "cherry"]

my_function(fruits)

Get More Information About Python Training and Certification Course Visit Here.


Thanks for Reading

Written By Puneet Kumar

Comments