✨ Mastering Python Functions ✨
Today I explored Python Functions, an essential part of writing reusable, clean, and efficient code. Below are the key topics I learned with simple explanations and example programs.
What is a Function?
A function is a block of code that performs a specific task and runs only when it is called.
def greet():
print("Hello, welcome to Python!")
greet()
Benefits of Using Functions
- Increases code reusability
- Makes the code modular and readable
- Easier to debug and manage
Function Declaration and Syntax
def function_name(parameters):
# block of code
return result
Example:
def add(a, b):
return a + b
print(add(5, 3)) # Output: 8
Function Keywords
-
def
: Used to define a function -
return
: Sends back the result -
*args
: For variable number of positional arguments -
**kwargs
: For variable number of keyword arguments
Types of Functions
- Built-in Functions
print(len("Python")) # Output: 6
- User-defined Functions
def square(n):
return n * n
print(square(4)) # Output: 16
Types of Arguments
- Positional Arguments
def greet(name):
print("Hello", name)
greet("Ramya")
- Keyword Arguments
def student(name, age):
print(name, age)
student(age=21, name="Ramya")
- Default Arguments
def country(name="India"):
print("Country:", name)
country()
country("USA")
- *Arbitrary Arguments (*args)*
def total(*numbers):
print(sum(numbers))
total(1, 2, 3, 4)
- **Arbitrary Keyword Arguments (kwargs)
def info(**data):
for key, value in data.items():
print(key, ":", value)
info(name="Ramya", age=21)
Docstring (Documentation String)
Used to describe what a function does.
def add(a, b):
"""This function adds two numbers."""
return a + b
print(add.__doc__)
Anonymous Functions (Lambda)
square = lambda x: x * x
print(square(5)) # Output: 25
Function with Default Arguments
def greet(name="Guest"):
print("Hello", name)
greet()
greet("Ramya")
Today’s Tasks
1. Find Minimum and Maximum in a List
numbers = [10, 4, 25, 1, 99]
def find_min_max(nums):
return min(nums), max(nums)
minimum, maximum = find_min_max(numbers)
print("Min:", minimum)
print("Max:", maximum)
2. Check if a Number is Prime
python
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
print(is_prime(7)) # Output: True
print(is_prime(10)) # Output:
False
Top comments (0)