Hello Friends,
Python Functions
A function in Python is a reusable block of code that performs a specific task. Functions help reduce code duplication, improve readability, and make programs easier to maintain.
Why Use Functions?
- Reuse code multiple times
- Make programs modular
- Improve readability and maintenance
- Reduce errors
Syntax of a Function
def function_name(parameters):
statements
return value
- def – keyword to define a function
- function_name – name of the function
- parameters – inputs to the function
- return – sends result back to caller
Example 1: Simple Function
def greet():
print("Welcome to Python Functions")
greet()
Output:
Welcome to Python Functions
Explanation:
The function greet() prints a message when called.
Example 2: Function with Parameters
def greet_user(name):
print("Hello", name)
greet_user("Chandan")
Output:
Hello Chandan
Explanation:
The function accepts a parameter name and prints a personalized message.
Example 3: Function with Return Value
def add(a, b):
return a + b
result = add(10, 20)
print(result)
Output:
30
Explanation:
The function returns the sum of two numbers.
Example 4: Default Arguments
Default arguments are used when no value is passed.
def greet(name="Guest"):
print("Hello", name)
greet()
greet("Amit")
Output:
Hello Guest Hello Amit
Example 5: Keyword Arguments
def student_info(name, age):
print("Name:", name)
print("Age:", age)
student_info(age=25, name="Rahul")
Example 6: Arbitrary Arguments (*args)
*args allows passing multiple values.
def total_marks(*marks):
total = 0
for m in marks:
total += m
return total
print(total_marks(70, 80, 90))
Example 7: Arbitrary Keyword Arguments (**kwargs)
**kwargs allows passing key-value pairs.
def employee_details(**details):
for key, value in details.items():
print(key, ":", value)
employee_details(name="Ravi", role="Tester", salary=50000)
Example 8: Function Inside a Function
def outer_function():
def inner_function():
print("Inner Function Executed")
inner_function()
outer_function()
Example 9: Lambda Function
Lambda functions are small anonymous functions.
square = lambda x: x * x print(square(5))
Output:
25
Real-Life Example
Checking pass or fail:
def check_result(marks):
if marks >= 40:
return "Pass"
else:
return "Fail"
print(check_result(55))
Common Mistakes
- Forgetting to call the function
- Incorrect indentation
- Using return incorrectly
- Mismatch in parameters and arguments
Summary
- Functions help reuse code
- Functions can take parameters and return values
- Supports default, keyword, *args, **kwargs
- Lambda functions are short functions
No comments:
Post a Comment