0% found this document useful (0 votes)
6 views11 pages

Python Functions Explained: A Guide

The document provides a comprehensive overview of functions in Python, including their definition, syntax, and various types such as functions with parameters, return values, and the use of *args and **kwargs. It also explains the difference between pure and impure functions, as well as the distinction between functions and methods. Additionally, it includes practical examples and a mini project idea for a bill calculator.

Uploaded by

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

Python Functions Explained: A Guide

The document provides a comprehensive overview of functions in Python, including their definition, syntax, and various types such as functions with parameters, return values, and the use of *args and **kwargs. It also explains the difference between pure and impure functions, as well as the distinction between functions and methods. Additionally, it includes practical examples and a mini project idea for a bill calculator.

Uploaded by

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

Gowtham SB

[Link]/in/sbgowtham/ Instagram - @dataengineeringtamil

🎯 Topic: Functions in Python

✅ 1. What is a Function?
A function is a block of reusable code that performs a specific task.
It lets you write once, use many times.

📦 Think of it like a machine: You give input, it gives output.

✅ 2. Defining a Function (with def)


🔧 Syntax:

def function_name():
# code block

📘 Example:

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

greet() # Calling the function

🧠 Output:

Hello, welcome to Python!

✅ 3. Function with Parameters (Passing Inputs)


📘 Example:
Gowtham SB
[Link]/in/sbgowtham/ Instagram - @dataengineeringtamil

def greet(name):
print(f"Hello {name}, welcome!")

greet("Gowtham") # Output: Hello Gowtham, welcome!

✅ This helps make your function dynamic.

✅ 4. Return Values from Functions


A function can return a result using the return keyword.

📘 Example:

def add(a, b):


return a + b

result = add(5, 3)
print("Sum:", result)

🧠 Output:

Sum: 8

✅ You can store and reuse the result.

✅ 5. *args → Accept Multiple Positional


Arguments
*args allows you to pass any number of values into a function.

📘 Example:
Gowtham SB
[Link]/in/sbgowtham/ Instagram - @dataengineeringtamil

def add_all(*args):
total = 0
for num in args:
total += num
return total

print(add_all(1, 2, 3, 4)) # Output: 10

🧠 Internally, args is a tuple.

✅ 6. **kwargs → Accept Multiple Keyword


Arguments
**kwargs allows passing named arguments (like key=value pairs).

📘 Example:

def print_info(**kwargs):
for key, value in [Link]():
print(f"{key}: {value}")

print_info(name="Gowtham", age=30)

🧠 Internally, kwargs is a dictionary.

🖨 Output:

name: Gowtham
age: 30

✅ Real-Life Example: Profile Generator


📘 Code:
Gowtham SB
[Link]/in/sbgowtham/ Instagram - @dataengineeringtamil

def create_profile(**kwargs):
print("User Profile:")
for key, value in [Link]():
print(f"{[Link]()}: {value}")

create_profile(name="Nandini", age=28, city="Madurai",


profession="Designer")

✅ 7. Default Parameter Values


You can assign default values to parameters.

📘 Example:

def greet(name="Guest"):
print(f"Hello, {name}!")

greet() # Hello, Guest!


greet("Nila") # Hello, Nila!

🧠 Summary Table:
Concep Description Syntax Example
t

def Define a function def greet():

() Call the function greet()

return Send result back from function return a + b

*args Multiple unnamed values def fun(*args):

**kwar Multiple named values def fun(**kwargs):


Gowtham SB
[Link]/in/sbgowtham/ Instagram - @dataengineeringtamil

gs

defaul Pre-filled values if nothing def


t passed greet(name="Guest"
):

🧪 Mini Project Idea (for your video)


🎯 Bill Calculator:

def calculate_bill(*items):
total = sum(items)
return total

def show_user(**details):
print("Customer Info:")
for k, v in [Link]():
print(f"{k}: {v}")

show_user(name="Rahul", city="Chennai")
print("Total Bill:", calculate_bill(100, 250, 75))

✅ What does return do in a function?


The return statement is used to send data (output) back from a function
to the place where it was called.

📘 Example 1: Using return


def add(a, b):
return a + b
Gowtham SB
[Link]/in/sbgowtham/ Instagram - @dataengineeringtamil

result = add(10, 5)
print("Result is:", result)

🧠 What happens here:

● return a + b → sends the result (15) back to the caller

● You store it in result and can use it later

❓ Why not just use print()?


Because:

● print() only shows the output on the screen

● It does NOT give the value back to the code

📘 Example 2: Using print() only


def add(a, b):
print(a + b)

x = add(10, 5)
print("x:", x)

🖨 Output:

15
x: None

⚠️Because print() just prints and returns nothing (None)


Gowtham SB
[Link]/in/sbgowtham/ Instagram - @dataengineeringtamil

✅ Key Differences:
Feature return print()

Gives value ✅ Yes, sends output to the ❌ No, just displays on


caller screen

Can reuse ✅ Yes (store, calculate, ❌ No


compare)

For real ✅ Must use return 🚫 Only for


apps debugging/output

🎯 Think of it like this:


Concep Example
t

return Giving a gift back (you can use it)

print( Just showing the gift (can’t use it


) again)

✅ When to use return?

● Calculators

● API results

● Data processing

● Any function where you need to use the result again

🧼 What is a Pure Function?


A pure function is a function that:

1. Always returns the same output for the same input


Gowtham SB
[Link]/in/sbgowtham/ Instagram - @dataengineeringtamil

2. Does not change anything outside itself (no side effects)

🧠 It’s like a math formula:


Input goes in → Output comes out → That’s it!
No print, no database updates, no file writes.

✅ Pure Function Example:


def add(a, b):
return a + b

💡 Every time you call add(2, 3), it always gives 5.


It doesn't touch anything outside the function.

❌ Impure (Normal) Function Example:


total = 0

def add_to_total(amount):
global total
total += amount
print("Total is:", total)

😵 This is not a pure function because:

● It modifies a global variable (total)

● It prints (causes a side effect)

Even if you give the same input, the output will change every time based on total.

🎯 Summary: Pure vs Normal (Impure) Function


Gowtham SB
[Link]/in/sbgowtham/ Instagram - @dataengineeringtamil

Feature Pure Impure Function (Normal)


Function

Same input = same ✅ Yes ❌ Not always


output

Changes outside data ❌ Never ✅ Can modify global or


external

Side effects ❌ None ✅ Can print, write, update,


etc

Easy to test/debug ✅ Yes ❌ Harder

🧠 When to Use Pure Functions?


● ✅ In data processing

● ✅ For predictable, reusable code

● ✅ In functional programming and unit testing

✅ Difference Between Function and Method


Feature Function Method

Definition A block of code that A function that is associated with an


performs a task object or class

Called with Just by name (e.g. add(5, With object or class (e.g.
3)) [Link]())
Gowtham SB
[Link]/in/sbgowtham/ Instagram - @dataengineeringtamil

Belongs to Independent (not tied to a Belongs to an object/class


class)

Defined def keyword Defined using def inside a class


using

Example def greet(): def greet(self): inside a class

About the Author


Gowtham SB is a Data Engineering expert, educator, and content creator with a
passion for big data technologies, as well as cloud and Gen AI . With years of
experience in the field, he has worked extensively with cloud platforms, distributed
systems, and data pipelines, helping professionals and aspiring engineers master the
art of data engineering.
Gowtham SB
[Link]/in/sbgowtham/ Instagram - @dataengineeringtamil

Beyond his technical expertise, Gowtham is a renowned mentor and speaker, sharing
his insights through engaging content on YouTube and LinkedIn. He has built one of
the largest Tamil Data Engineering communities, guiding thousands of learners to
excel in their careers.

Through his deep industry knowledge and hands-on approach, Gowtham continues to
bridge the gap between learning and real-world implementation, empowering
individuals to build scalable, high-performance data solutions.

𝐒𝐨𝐜𝐢𝐚𝐥𝐬

𝐘𝐨𝐮𝐓𝐮𝐛𝐞 - [Link]

𝐈𝐧𝐬𝐭𝐚𝐠𝐫𝐚𝐦 - [Link]

𝐈𝐧𝐬𝐭𝐚𝐠𝐫𝐚𝐦 - [Link]

𝐂𝐨𝐧𝐧𝐞𝐜𝐭 𝐟𝐨𝐫 𝟏:𝟏 - [Link]

𝐋𝐢𝐧𝐤𝐞𝐝𝐈𝐧 - [Link]

𝐖𝐞𝐛𝐬𝐢𝐭𝐞 - [Link]

𝐆𝐢𝐭𝐇𝐮𝐛 - [Link]

𝐖𝐡𝐚𝐭𝐬 𝐀𝐩𝐩 - [Link]

𝐄𝐦𝐚𝐢𝐥 - [Link]@[Link]

𝐀𝐥𝐥 𝐌𝐲 𝐒𝐨𝐜𝐢𝐚𝐥𝐬 - [Link]

Common questions

Powered by AI

The 'return' statement and 'print()' function serve different purposes within Python functions. 'Return' sends a value back to the caller of the function, allowing the program to save, manipulate, or use this value in further operations . It is essential for functions that need to provide a result that can be used in the program, such as when building applications or performing calculations. In contrast, 'print()' is used only to display output on the screen and does not send anything back to the function’s caller, which means the value displayed cannot be reused in the program . Essentially, 'return' allows for data to be reused and manipulated programmatically, while 'print()' is primarily for display and debugging purposes .

Pure functions offer several advantages in data processing by ensuring consistent and predictable outputs, which is critical for accuracy and reliability. Because pure functions do not produce side effects or alter external states, they simplify debugging and testing, allowing easier identification of errors in processing sequences . They promote reusability and function chaining, as outputs are not dependent on external modifications. This ensures that data transformations are transparent and dependable, facilitating data processing pipelines that are easier to manage, parallelize, and reproduce across different environments or datasets .

A function defined with 'def' outside of a class in Python is a standalone block of code that is not associated with any object or class. It is independent and called directly using its name . In contrast, a function defined within a class is known as a method and is associated with the objects or instances of that class. Methods generally require at least one parameter, usually 'self', to access the instance's attributes and other methods. Therefore, methods are called on objects or class instances and can operate on the object's data, reflecting the object-oriented nature of programming .

*args and **kwargs are used in Python functions to handle variable numbers of arguments. *args allows a function to accept any number of positional arguments, which are passed as a tuple. This is useful for functions that need to operate on a series of values of the same type . On the other hand, **kwargs accepts multiple keyword arguments and passes them as a dictionary, allowing functions to process named inputs where key-value pairs can provide more descriptive and flexible input data . The primary difference is that *args deals with positional arguments, allowing aggregation of arguments into a tuple, while **kwargs aggregates named arguments into a dictionary.

The concept of a pure function correlates to mathematical functions in that both consistently produce the same output given identical inputs, embodying the deterministic nature of mathematical operations . This correlation is beneficial in programming because it introduces predictability, allowing developers to reason about code behavior effortlessly, much like calculating a value with a known mathematical formula. In contexts such as functional programming, where functions are first-class citizens, using pure functions encourages immutability, supports easier testing, debugging, and facilitates parallel processing. The absence of side effects and dependency on external state further strengthens the modular and reusable nature of code, offering significant advantages for maintenance and scalability .

Functions with default parameter values enhance flexibility and usability by allowing function calls without explicitly passing all argument values. This is particularly useful for optional parameters, enabling the function to run with default settings or adapt to specific input requirements without additional code complexity . For example, a function defined as def greet(name='Guest') can greet users by name if provided, or default to 'Guest' when no name is given, thus catering to varied usage scenarios seamlessly .

The concept of 'return' in functions can be compared to giving a gift back, as it represents the idea of providing something valuable that the recipient (or calling program) can keep, reuse, or build upon later . Just like a tangible gift which the receiver can use again, modify, or incorporate into other activities, the return value provides data that can be stored and utilized in further computations, helping to maintain the continuity of operations in larger programs or applications . This analogy highlights the utility and continuity that 'return' offers, enabling dynamic and productive programming practices in Python.

Using a pure function is more beneficial in scenarios that require consistency and predictability. Pure functions always produce the same output given the same input without side effects, which makes them ideal for data processing, functional programming, and unit testing . They are beneficial when creating reusable code that needs to be reliable, since their output is consistent and doesn't depend on or alter external state. This means they are easier to test and debug, as their behavior is entirely self-contained, providing transparency and reliability in repeated operations .

The primary drawback of using print() instead of return in a function designed for calculations is that print() only displays the output without returning the calculated result to the calling code. This lack of return value means that the result cannot be reused, stored, or further manipulated within the program . For calculation functions, this severely limits their utility in maintaining a continuous data flow in an application. With print(), the data is effectively output only for observation, making the function unsuitable for any function where results are expected to be integrated into further operations or used programmatically .

A programmer might choose to use a function rather than a method when the operation being performed is not tied to any particular object or class instance. Functions are ideal for generic tasks that operate on parameters passed to them without requiring access to or modification of object state . This makes functions suitable for utilities or operations that apply to various data types and structures, providing versatility and reusability without the overhead of class or object scopes. Functions facilitate modular design by promoting independent and reusable logic, especially in procedural programming paradigms or when performing tasks that do not benefit from object-oriented features .

You might also like