0% found this document useful (0 votes)
5 views15 pages

Python Functions

The document provides a comprehensive overview of Python functions, including their definition, creation, calling, and various types of arguments. It explains the importance of functions for code reuse, readability, and organization, along with examples of different function types such as recursive and lambda functions. Additionally, it covers key concepts like return values, default parameters, and the distinction between mutable and immutable objects in the context of function arguments.

Uploaded by

ravikumar24
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views15 pages

Python Functions

The document provides a comprehensive overview of Python functions, including their definition, creation, calling, and various types of arguments. It explains the importance of functions for code reuse, readability, and organization, along with examples of different function types such as recursive and lambda functions. Additionally, it covers key concepts like return values, default parameters, and the distinction between mutable and immutable objects in the context of function arguments.

Uploaded by

ravikumar24
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Functions

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


A function can return data as a result.
A function helps avoiding code repetition.

Creating a Function
In Python, a function is defined using the def keyword, followed by a function
name and parentheses:

The syntax to declare a function is:

Example
def my_function():
print("Welcome to Axis")
This creates a function named my_function that prints " Welcome to Axis " when
called.

The code inside the function must be indented. Python uses indentation to define code
blocks.
Output
Welcome to Axis

Calling a Function
To call a function, write its name followed by parentheses:

Page 1 of 15
Example
def my_function():
print("Hello class")

my_function()
You can call the same function multiple times:

Example
def my_function():
print("Hello from a function")

my_function()
my_function()
my_function()

Function Names
Function names follow the same rules as variable names in Python:

 A function name must start with a letter or underscore


 A function name can only contain letters, numbers, and underscores
 Function names are case-sensitive (myFunction and myfunction are
different)

Example
Valid function names:
calculate_sum()
_private_function()
myFunction2()
It's good practice to use descriptive names that explain what the function does.

Why Use Functions?


Imagine you need to convert temperatures from Fahrenheit to Celsius several times
in your program. Without functions, you would have to write the same calculation
code repeatedly:

Example

Page 2 of 15
Without functions - repetitive code:
temp1 = 77
celsius1 = (temp1 - 32) * 5 / 9
print(celsius1)

temp2 = 95
celsius2 = (temp2 - 32) * 5 / 9
print(celsius2)

temp3 = 50
celsius3 = (temp3 - 32) * 5 / 9
print(celsius3)

With functions, you write the code once and reuse it:

Example
With functions - reusable code:
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5 / 9

print(fahrenheit_to_celsius(77))
print(fahrenheit_to_celsius(95))
print(fahrenheit_to_celsius(50))

Return Values
Functions can send data back to the code that called them using
the return statement.

When a function reaches a return statement, it stops executing and sends the result
back:

Example
A function that returns a value:
def get_greeting():
return "Hello from a function"

message = get_greeting()
print(message)

Page 3 of 15
 You can use the returned value directly:

Example
Using the return value directly:

def get_greeting():
return "Hello from a function"

print(get_greeting())

If a function doesn't have a return statement, it returns None by default.

The pass Statement


Function definitions cannot be empty. If you need to create a function
placeholder without any code, use the pass statement:

Example
def my_function():
pass

The pass statement is often used when developing, allowing you to define the
structure first and implement details later.

Function Arguments
Arguments are the values passed inside the parenthesis of the function. A
function can have any number of arguments separated by a comma.

Syntax

def function_name(parameters):
"""Docstring"""
# body of the function
return expression

 def function_name(parameters): Declares a function with optional input


parameters.
 Docstring ("""..."""): (Optional) Used to describe what the function does.

Page 4 of 15
 return expression: (Optional) Returns a value to the caller. If omitted, the
function returns None.
We will create a function to check whether the number passed as an argument to
the function is even or odd.
def evenOdd(x):
if (x % 2 == 0):
return "Even"
else:
return "Odd"

print(evenOdd(16))
print(evenOdd(7))

Output
Even
Odd

Types of Function Arguments


Python supports various types of arguments that can be passed at the time of the
function call. Below are types of function argument types:.
1. Default Arguments: A default argument is a parameter that assumes a
default value if a value is not provided in the function call for that
argument.
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)

myFun(10)

Output
x: 10
y: 50

2. Keyword Arguments: values are passed by explicitly specifying the


parameter names, so the order doesn’t matter.
def student(fname, lname):
print(fname, lname)

student(fname='Amit', lname='Kumar')
student(lname='Parth', fname='Shukla')

Page 5 of 15
Output
Amir Kumar
Parth Shukla

3. Positional Arguments: values are assigned to parameters based on


their order in the function call.
def nameAge(name, age):
print("Hi, I am", name)
print("My age is ", age)

print("Case-1:")
nameAge("Olivia", 27)

print("\nCase-2:")
nameAge(27, "Olivia")

Output
Case-1:
Hi, I am Olivia
My age is 27

Case-2:
Hi, I am 27
My age is Olivia

4. Arbitrary Arguments: allow a function to accept a variable number of


inputs. This is done using two special symbols:
 *args: collects extra positional (non-keyword) arguments as a tuple.
 **kwargs: collects extra keyword arguments as a dictionary.
This code separately shows non-keyword (*args) and keyword (**kwargs)
arguments in the same function.

def myFun(*args, **kwargs):


print("Non-Keyword Arguments (*args):")
for arg in args:
print(arg)

print("\nKeyword Arguments (**kwargs):")


for key, value in [Link]():
print(f"{key} == {value}")

Page 6 of 15
myFun('Hey', 'Welcome', first='Geeks', mid='for', last='Geeks')

Output
Non-Keyword Arguments (*args):
Hey
Welcome
Keyword Arguments (**kwargs):
first == Geeks
mid == for
last == Geeks

lambda/Anonymous Functions
An anonymous function means that a function is without a name. As we
know, def keyword is used to define the normal functions
and lambda keyword is used to create anonymous functions.

def c1(x): return x*x*x


c2 = lambda x : x*x*x

print(c1(7))
print(c2(7))

Output
343
343

Return Statement
The return statement ends a function and sends a value back to the caller. It
can return any data type, multiple values (packed into a tuple), or None if no
value is given.
Syntax:
return [expression]

Parameters: return ends the function, [expression] is the optional value to


return (defaults to None).

Page 7 of 15
def sq_value(num):
"""This function returns the square
value of the entered number"""
return num**2

print(sq_value(2))
print(sq_value(-4))

Output
4
16

Pass by Reference and Pass by Value


Variables are references to objects. When we pass them to a function,
behavior depends on whether the object is mutable (like lists, dictionaries) or
immutable (like integers, strings, tuples).
 Mutable objects: Changes inside the function affect the original object.
 Immutable objects: The original value remains unchanged.

def myFun(x):
x[0] = 20

lst = [10, 11, 12, 13]


myFun(lst)
print(lst)

def myFun2(x):
x = 20

a = 10
myFun2(a)
print(a)

Output
[20, 11, 12, 13]
10

Note: Python always passes objects by reference. If the object is


changeable (like a list), the function can modify it. If it’s not
changeable (like a number or string), the function cannot change it.

Page 8 of 15
Recursive Functions
A recursive function is a function that calls itself to solve a problem. It is
commonly used in mathematical and divide-and-conquer problems. Always
include a base case to avoid infinite recursion.

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

print(factorial(4))

Output
24

A function in Python is a block of reusable code that performs a specific task. Instead of
writing the same code again and again, you define a function once and call it whenever
needed.

🔹 1. Why use functions?


 Code reuse (write once, use many times)
 Makes code readable and organized
 Easy debugging and maintenance
 Breaks large problems into smaller parts

🔹 2. Syntax of a Function
def function_name(parameters):
# body of function
return value

 def → keyword to define a function


 function_name → name of function
 parameters → inputs (optional)
 return → sends output (optional)

Page 9 of 15
🔹 3. Types of Functions
✅ (A) Function without parameters and without return value

def greet():
print("Hello, Welcome to Python!")

greet() # function call

🔹 Output: Hello, Welcome to Python!

✅ (B) Function with parameters

def greet(name):
print("Hello", name)

greet("Ravi")

📌 Output: Hello Ravi

✅ (C) Function with return value

def add(a, b):


return a + b

result = add(10, 20)


print("Sum =", result)

📌 Output: Sum = 30

✅ (D) Function with parameters and return value

def square(num):
return num * num

print(square(5))

📌 Output: 25

🔹 4. Default Parameters
def greet(name="Guest"):
print("Hello", name)

greet()
greet("Ravi")

Page 10 of 15
📌 Output: Hello Guest
Hello Ravi

🔹 5. Keyword Arguments
def student(name, age):
print("Name:", name)
print("Age:", age)

student(age=21, name="Ravi")

🔹 6. Variable-Length Arguments*****
(A) *args (multiple values)

def add_all(*numbers):
total = 0
for n in numbers:
total += n
return total

print(add_all(1, 2, 3, 4))

📌 Output: 10

(B) **kwargs (key-value pairs)

def details(**info):
for key, value in [Link]():
print(key, ":", value)

details(name="Ravi", age=21)

🔹 7. Lambda Function (Anonymous Function)


square = lambda x: x * x
print(square(6))

📌 Output: 36

Page 11 of 15
🔹 8. Recursive Function
A function that calls itself.

def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)

print(factorial(5))

📌 Output: 120

🔹 9. Advantages of Functions
 Reduces code duplication
 Improves clarity
 Easier testing
 Modular programming

🔹 10. Important Points


 Function must be defined before calling
 Indentation is important
 return ends the function execution
 If no return → function returns None

🔹 11. Real-Life Example


def calculate_salary(basic):
hra = basic * 0.2
da = basic * 0.1
total = basic + hra + da
return total

print("Total Salary =", calculate_salary(25000))

Page 12 of 15
 write a python program to take list of numbers find the sum of all
numbers in the list with and without using function

Here is a clear Python program to find the sum of all numbers in a list in two
ways:

✅1. WITHOUT using function


# Taking input from user
numbers = [ ]

n = int(input("Enter number of elements: "))

for i in range(n):
num = int(input("Enter number: "))
[Link](num)

# Finding sum
total = 0
for i in numbers:
total = total + i

print("List:", numbers)
print("Sum of all elements:", total)

✅2. USING function


# Function to calculate sum----3
def find_sum(lst):
total = 0
for i in lst:
total = total + i
return total

# Taking input----1
numbers = [ ]
n = int(input("Enter number of elements: "))

for i in range(n):
num = int(input("Enter number: "))
[Link](num)

# Function call----2
result = find_sum(numbers)

print("List:", numbers)#----4
print("Sum of all elements:", result)#-----5

Page 13 of 15
✅3. BONUS (Using built-in function)
numbers = [10, 20, 30, 40]
print("Sum =", sum(numbers))

 write a python program to count the frequency of each character in a given string
and return the output in a dictionary: with and without function example
char_frequency("HELLO) returns{"H":1,"E":1,"L":2,"O":1}

Here is a clear Python program to count the frequency of each character in a string and
store the result in a dictionary.

✅1. WITHOUT using function


# Taking input
string = input("Enter a string: ")

# Creating empty dictionary


freq = {}

# Counting frequency
for ch in string:
if ch in freq:
freq[ch] = freq[ch] + 1
else:
freq[ch] = 1

# Display result
print("Character Frequency:", freq)

✅2. USING function


def char_frequency(s):
freq = {}

for ch in s:
if ch in freq:
freq[ch] += 1
else:
freq[ch] = 1

return freq

# Taking input
string = input("Enter a string: ")

# Function call
result = char_frequency(string)

print("Character Frequency:", result)

Page 14 of 15
Example Run
Input: HELLO

Output:
{'H': 1, 'E': 1, 'L': 2, 'O': 1}

✅4. Bonus (Short Method)


string = "HELLO"
freq = {}

for ch in string:
freq[ch] = [Link](ch, 0) + 1

print(freq)

Page 15 of 15

You might also like