
Understanding User-Defined Functions
In Python, a user-defined function is a block of reusable code that performs a specific task. These functions are created by the user to encapsulate a sequence of statements and can be called multiple times throughout the program. Let's explore user-defined functions in a beginner-friendly manner.
User-defined functions, as the name suggests, are functions defined by the user to perform a specific task. They allow you to break down your code into smaller, manageable pieces, promoting code reusability and modularity. User-defined functions enhance the readability and maintainability of your code.
You can create a user-defined function in Python using the def keyword followed by the function name and parentheses containing optional parameters. Here's a simple example of defining a function to greet the user:
print("Hello,", name)
# Calling the function
greet("Alice") # Output: Hello, Alice
In this example, greet is the function name, and name is the parameter passed to the function.
User-defined functions can accept parameters, which are values passed to the function to perform operations. Additionally, functions can return values using the return statement. Here's an example of a function that calculates the square of a number and returns the result:
return num ** 2
# Calling the function and storing the result
result = square(5)
print("Square of 5:", result) # Output: Square of 5: 25
In this example, the square function accepts a parameter num and returns the square of that number.
Once a function is defined, you can call it multiple times throughout your program, promoting code reusability. Here's an example of calling the greet function multiple times:
greet("Charlie") # Output: Hello, Charlie
Each time the greet function is called with a different name, it prints a personalized greeting message.
1. Temperature Conversion:
Q. You need to convert temperatures from Celsius to Fahrenheit and vice
versa for weather forecasting applications.
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5/9
# Example usage
celsius_temp = 20
fahrenheit_temp = celsius_to_fahrenheit(celsius_temp)
print("20°C in Fahrenheit:", fahrenheit_temp)
fahrenheit_temp = 68
celsius_temp = fahrenheit_to_celsius(fahrenheit_temp)
print("68°F in Celsius:", celsius_temp)
2. Grade Calculation:
Q. You are developing a grading system for students, and you need to
calculate their final grades based on their exam scores.
if score >= 90:
return 'A'
elif score >= 80:
return 'B'
elif score >= 70:
return 'C'
elif score >= 60:
return 'D'
else:
return 'F'
# Example usage
exam_score = 85
grade = calculate_grade(exam_score)
print("Final grade:", grade)
3. ATM Withdrawal Limit Check:
Q. You want to implement a function to check if a user's requested
withdrawal amount exceeds the daily withdrawal limit set by the bank.
if requested_amount <= daily_limit:
return True
else:
return False
# Example usage
daily_limit = 500
withdrawal_amount = 300
is_within_limit = check_withdrawal_limit(withdrawal_amount, daily_limit)
if is_within_limit:
print("Withdrawal approved.")
else:
print("Withdrawal amount exceeds daily limit.")
4. Shopping Cart Total Calculation:
Q. You are developing an e-commerce application and need to calculate the
total cost of items in a user's shopping cart.
total_cost = sum(prices)
return total_cost
# Example usage
cart_prices = [25.99, 14.50, 10.75, 8.99]
total_cost = calculate_total_cost(cart_prices)
print("Total cost of items in the shopping cart:", total_cost)
These examples demonstrate how user-defined functions can be applied to solve real-life problems, such as temperature conversion, grade calculation, ATM withdrawal limit checks, and shopping cart total calculation. User-defined functions provide a modular and reusable approach to implementing common tasks in Python programming.
User-defined functions are a fundamental concept in Python programming, allowing you to encapsulate code, promote code reusability, and enhance the readability and maintainability of your programs. By creating user-defined functions, you can break down complex tasks into smaller, manageable pieces, making your code more organized and efficient.