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

Day3 (Python Function)

This guide provides a comprehensive overview of Python functions, covering their definition, advantages, and various types including parameters, return values, and argument types. It explains key concepts such as variable scope, recursion, and includes examples for clarity. The document serves as a complete resource for understanding and utilizing functions in Python programming.

Uploaded by

rajuucet123
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 views6 pages

Day3 (Python Function)

This guide provides a comprehensive overview of Python functions, covering their definition, advantages, and various types including parameters, return values, and argument types. It explains key concepts such as variable scope, recursion, and includes examples for clarity. The document serves as a complete resource for understanding and utilizing functions in Python programming.

Uploaded by

rajuucet123
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

Python Functions - A Complete Guide

Functions are one of the most important concepts in Python, allowing you to write reusable,
modular, and well-structured code. In this guide, we will cover function types, arguments, return
values, scope, recursion, and lambda functions in detail.

🔹 1. What is a Function?

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

✅ Advantages of Functions

✔ Code Reusability – Write once, use multiple times.


✔ Modularity – Makes code easier to manage.
✔ Improved Readability – Breaks complex tasks into simpler functions.
✔ Avoids Repetition – Reduces redundancy in code.

🔹 2. Defining and Calling Functions

A function is defined using the def keyword.

🔸 Function Syntax

def function_name(parameters):

"""Optional Docstring"""

# Function body

return value # (Optional)

Example: Defining and Calling a Function

Example

def greet():

print("Hello, Welcome to Python!")

greet() # Output: Hello, Welcome to Python!

✅ Key Points:

 def greet(): defines the function.

 greet() calls the function.

 The function does not return a value (it only prints).


🔹 3. Function with Parameters (Arguments)

Functions can accept parameters (inputs) to perform operations.

python

def greet(name):

print(f"Hello, {name}!")

greet("Alice") # Output: Hello, Alice!

greet("Bob") # Output: Hello, Bob!

✅ Key Points:

 name is a parameter (input to the function).

 "Alice" and "Bob" are arguments (actual values passed).

🔹 4. Function with Return Value

A function can return a result using the return keyword.

python

def add(a, b):

return a + b # Returns the sum

result = add(5, 3)

print(result) # Output: 8

✅ Key Points:

 return sends back the result to the caller.

 The returned value is stored in result.

🔹 5. Types of Function Arguments

Python supports different types of function arguments:

🔸 1. Positional Arguments

Arguments are passed in order.

python

def subtract(a, b):


return a - b

print(subtract(10, 5)) # Output: 5

print(subtract(5, 10)) # Output: -5 (order matters)

✅ Order of arguments is important in positional arguments.

🔸 2. Default Arguments

Provides default values if no argument is passed.

python

def greet(name="Guest"):

print(f"Hello, {name}!")

greet("Alice") # Output: Hello, Alice!

greet() # Output: Hello, Guest! (default value)

✅ Key Point:

 If no argument is given, it uses the default value ("Guest").

🔸 3. Keyword Arguments

Arguments are passed with their names, making order irrelevant.

python

def info(name, age):

print(f"Name: {name}, Age: {age}")

info(age=25, name="John") # Output: Name: John, Age: 25

✅ Order does not matter in keyword arguments.

🔸 4. Arbitrary Arguments (*args)

Used when the number of arguments is unknown.

python
def add_numbers(*args):

return sum(args)

print(add_numbers(2, 3, 4)) # Output: 9

print(add_numbers(1, 5, 10, 20)) # Output: 36

✅ *args collects multiple arguments into a tuple.

🔸 5. Arbitrary Keyword Arguments (**kwargs)

Used when the number of named arguments is unknown.

python

def student_info(**kwargs):

for key, value in [Link]():

print(f"{key}: {value}")

student_info(name="Alice", age=22, course="Python")

✅ **kwargs collects multiple keyword arguments into a dictionary.

🔹 6. Variable Scope (LEGB Rule)

Variables in Python have different scopes (where they can be accessed).

Scope Description

Local Variables inside a function.

Enclosing Variables in enclosing functions (nested).

Global Variables outside any function.

Built-in Predefined Python variables.

🔸 Example: Local and Global Scope

python

x = 10 # Global variable
def my_function():

x = 5 # Local variable

print("Inside function:", x)

my_function() # Output: Inside function: 5

print("Outside function:", x) # Output: Outside function: 10

✅ Local and global variables are different even if they have the same name.

🔹 7. Recursive Functions

A function calling itself is called recursion.

🔸 Example: Factorial using Recursion

python

def factorial(n):

if n == 1:

return 1

return n * factorial(n - 1)

print(factorial(5)) # Output: 120

✅ Recursion simplifies complex problems, but excessive recursion can cause errors.

🔥 Summary of Function Concepts

Concept Description

Function Definition def func(): defines a function.

Function Call func() executes the function.

Return Statement Returns a value from a function.

Arguments Positional, default, keyword, *args, **kwargs.

Scope Local, global, enclosing, built-in (LEGB).

Recursion Function calling itself.


++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Example

Sum of Digits Code

def sum_of_digits(n):

"""Returns the sum of digits of a number."""

total = 0

while n > 0:

total += n % 10 # Extract last digit and add to total

n //= 10 # Remove last digit

return total

# Taking user input

num = int(input("Enter a number: "))

# Calling function

result = sum_of_digits(num)

# Displaying result

print(f"Sum of digits of {num} is {result}")

output

Enter a number: 1234

Sum of digits of 1234 is 10

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

You might also like