Python Functions

๐Ÿ Python Functions โ€” Full Tutorial

A function in Python is a block of reusable code that performs a specific task. Functions help reduce code repetition and make programs modular.


๐Ÿ”น 1. Creating a Function

Use the def keyword:

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

Calling the function:

greet()

โœ… Output:

Hello, Welcome!

๐Ÿ”น 2. Function with Parameters

Parameters allow you to pass data to a function:

def greet(name):
print(f"Hello, {name}!")
greet(“Vipul”)

โœ… Output:

Hello, Vipul!

๐Ÿ”น 3. Function with Return Value

Use return to send data back:

def add(a, b):
return a + b
result = add(5, 3)
print(result) # 8


๐Ÿ”น 4. Default Parameters

Provide a default value if argument is not passed:

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


๐Ÿ”น 5. Keyword Arguments

You can pass arguments by name, order doesnโ€™t matter:

def info(name, age):
print(f"Name: {name}, Age: {age}")
info(age=25, name=“Vipul”)


๐Ÿ”น 6. Variable-length Arguments

6.1 *args โ†’ Non-keyword variable arguments

def add(*numbers):
total = 0
for num in numbers:
total += num
return total
print(add(1, 2, 3, 4)) # 10

6.2 **kwargs โ†’ Keyword variable arguments

def info(**details):
for key, value in details.items():
print(f"{key}: {value}")
info(name=“Vipul”, age=25, city=“Surat”)


๐Ÿ”น 7. Lambda (Anonymous) Functions

A lambda function is a small one-line function:

square = lambda x: x ** 2
print(square(5)) # 25
add = lambda a, b: a + b
print(add(10, 5)) # 15


๐Ÿ”น 8. Scope of Variables

8.1 Local Variables

Defined inside a function, accessible only inside.

def func():
x = 10
print(x)
func()
# print(x) # Error โŒ

8.2 Global Variables

Defined outside a function, accessible anywhere.

x = 50

def func():
print(x)

func()
print(x)

8.3 Using global Keyword

Modify global variable inside a function:

x = 10

def change():
global x
x = 20

change()
print(x) # 20


๐Ÿ”น 9. Nested Functions (Inner Functions)

def outer():
def inner():
print("Hello from inner function")
inner()
print("Hello from outer function")
outer()


๐Ÿ”น 10. Recursion (Function Calling Itself)

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
print(factorial(5)) # 120

  • Important: Always define a base case to avoid infinite recursion.


๐Ÿ”น 11. Docstrings (Documentation Strings)

def greet(name):
"""This function greets a person by name."""
print(f"Hello, {name}")
print(greet.__doc__)


๐Ÿ”น 12. Higher-Order Functions

Functions that take other functions as arguments:

def square(x):
return x ** 2
def apply(func, value):
return func(value)

print(apply(square, 5)) # 25

Python built-ins like map(), filter(), and reduce() also use higher-order functions.


๐Ÿ”น 13. Practical Examples

13.1 Calculator Function

def calculator(a, b, op):
if op == "+":
return a + b
elif op == "-":
return a - b
elif op == "*":
return a * b
elif op == "/":
return a / b
else:
return "Invalid operation"
print(calculator(10, 5, “*”)) # 50

13.2 Fibonacci Series Using Function

def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
fibonacci(10)


๐Ÿ”น 14. Summary Table

Feature Example
Function Definition def func():
Parameters def greet(name):
Default Parameters def greet(name="Guest"):
Variable Arguments *args, **kwargs
Return Value return value
Lambda Function lambda x: x**2
Docstring """This is a function"""
Scope Local vs Global

๐Ÿง  Practice Exercises

  1. Create a function to check if a number is prime.

  2. Write a function that returns factorial of a number.

  3. Create a function that counts vowels in a string.

  4. Write a function that checks if a string is a palindrome.

  5. Use *args to sum all numbers in a function call.

CodeCapsule

Sanjit Sinha โ€” Web Developer | PHP โ€ข Laravel โ€ข CodeIgniter โ€ข MySQL โ€ข Bootstrap Founder, CodeCapsule โ€” Student projects & practical coding guides. Email: info@codecapsule.in โ€ข Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *