Python Functions

 Block of reusable code to perform a specific action.

Reusing Code

Using an existing code without writing it every time we need.

Code

def greet():
print("Hello")
name = input()
print(name)
PYTHON

Input

Teja

Output

Teja

Defining a Function

Function is uniquely identified by the

function_name

Code

def greet():
print("Hello")
name = input()
print(name)
PYTHON

Input

Teja

Output

Teja

Calling a Function

The functional block of code is executed only when the function is called.

Code

def greet():
print("Hello")
name = input()
greet()
print(name)
PYTHON

Input

Teja

Output

Hello
Teja

Defining & Calling a Function

A function should be defined before it is called.

Code

name = input()
greet()
print(name)
def greet():
print("Hello")
PYTHON

Input

Teja

Output

NameError: name 'greet' is not defined

Printing a Message

Consider the following scenario, we want to create a function, that prints a custom message, based on some variable that is defined outside the function. In the below code snippet, we want to access the value in the variable

name
at line 2 in place of the
?
.

Code

def greet():
msg = "Hello " + ?
print(msg)
name = input()
greet()
PYTHON

Input

Teja

Desired Output

Hello Teja

We use the concept of Function Arguments for these types of scenarios.

Function With Arguments

We can pass values to a function using an Argument.

Code

def greet(word):
msg = "Hello " + word
print(msg)
name = input()
greet(word=name)
PYTHON

Input

Teja

Output

Hello Teja

Variables Inside a Function

A variable created inside a function can only be used in it.

Code

def greet(word):
msg = "Hello " + word
name = input()
greet(word=name)
print(msg)
PYTHON

Input

Teja

Output

NameError: name 'msg' is not defined

Returning a Value

To return a value from the function use

return
keyword.

Exits from the function when return statement is executed.

Code

def greet(word):
msg = "Hello " + word
return msg
name = input()
greeting = greet(word=name)
print(greeting)
PYTHON

Input

Teja

Output

Hello Teja

Code written after

return
statement will not be executed.

Code

def greet(word):
msg = "Hello "+word
return msg
print(msg)
name = input()
greeting = greet(word=name)
print(greeting)
PYTHON

Input

Teja

Output

Hello Teja

Built-in Functions

We are already using functions which are pre-defined in Python. Built-in functions are readily available for reuse

  • print()
  • int()
  • str()
  • len()

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form