Python Function

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

Python Function

In Python, a function is like a recipe. It's a


set of instructions that you can reuse
whenever you need to do a particular task.
You give the function some inputs (like
ingredients for a recipe), and it gives you
back some outputs (like a delicious dish).

Now, a variable is like a container. It holds


some value, like a number or a piece of text.
So, when we talk about a "function in a
variable," it means that we can store a
function inside a variable, just like you can
store something in a container.
In Python, a function can be assigned to a
variable, just like any other value. This
means you can use a variable to refer to a
function, and then call that function using
the variable name. Here's a simple
explanation with syntax:

def: This keyword signals the start of a


function definition in Python. It tells Python
that you're about to define a new function.
function_name: This is where you name your
function. Following Python's naming
conventions, function names should start
with a lowercase letter and use underscores
to separate words for better readability.
parameters (optional): These are
placeholders for the data that your function
will operate on. They are listed within
parentheses and separated by commas.
Parameters are optional, meaning you can
define functions without them if the function
doesn't need any input data.
Docstring (optional): This is a string literal
enclosed in triple quotation marks that
provides documentation for your function.
It's good practice to include a brief
description of what the function does, any
parameters it expects, and how to use it.
While not mandatory, including a docstring
improves code readability and helps other
developers understand your code.
# statements: This is where you write the
actual code that the function will execute.
The code block is indented under the
function definition line and begins with a
hash symbol (#). You can have multiple lines
of code within this block.
return expression (optional): The return
statement specifies the value that the
function should return after executing its
code block. It's optional, and if omitted, the
function returns None by default. The return
keyword is followed by an expression whose
value will be returned to the caller of the
function.

Key Points:

 def keyword: This keyword signals the start of a function definition in Python.
 Function Name: Following def comes a descriptive name for your function. It
should adhere to Python's naming conventions (lowercase letters with
underscores for separation).
 Functionality: The indented block of code below the definition line houses
the instructions or functionalities the function performs.
 Flexibility: Functions can handle various tasks and incorporate different
properties as needed.

Example:

# A simple Python function


def fun():
print("Welcome to learn python with me")

# Driver code to call a function


fun()

In this example, the add function takes two


parameters, x and y, and returns their sum
using the return statement. When you call
the add function and pass values for x and
y, it calculates their sum and returns it:
Function With parameter
def add(x, y):
return x + y
result = add(3, 5)
print(result) # Output: 8

def add(x, y):


This line defines a function named add that
takes two parameters: x and y.
Inside the function body, it returns the sum
of x and y.
result = add(3, 5):
This line calls the add function with
arguments 3 and 5.
These arguments are passed to the
parameters x and y of the add function.
The function computes the sum of 3 and 5,
which is 8.
The result of the computation (i.e., 8) is
returned from the add function and assigned
to the variable result.
print(result) # Output: 8:
This line prints the value stored in the result
variable, which is 8.
This value represents the sum of 3 and 5,
calculated by the add function.
In summary, this code defines a function
add that takes two parameters x and y,
computes their sum, and returns the result.
Then, it calls the add function with
arguments 3 and 5, stores the result in the
variable result, and finally prints the result,
which is 8.

Types of Argument :
Default Argument:
A default argument is a parameter that has
a default value assigned to it in the function
definition.
If a value is not provided for this parameter
during a function call, the default value will
be used.
This allows the function to be called with
fewer arguments than the number of
parameters defined.
Here's an example:

def greet(name="World"):
print("Hello, " + name + "!")

Positional Arguments and Order Dependence:

In Python, functions can accept arguments, which are values passed to the function
when it's called. When you define a function with positional arguments, the order in
which you specify the arguments during the function call matters.

def greet(name, age):


"""This function prints a greeting
message with name and age."""
print(f"Hello, {name}! You are {age}
years old.")

# Case 1: Correct order (matches


parameter order)
greet("Alice", 30) # Output: Hello,
Alice! You are 30 years old.

# Case 2: Incorrect order (switched


arguments)
greet(27, "Suraj") # Output: Hello,
27! You are Suraj years old. (Incorrect
age assignment)

 Explore yourself : Arbitrary


arguments (variable-length arguments *args and
**kwargs)

You might also like