In this article, we will dive into the concept of user-defined functions in Python and explore how to define and use them effectively. The video tutorial linked below will guide you through the process and provide a visual representation of the concepts discussed.
Explanation for the video
Click here to watch the video!
Key Concepts Explanation
Key Concept 1
User-defined functions allow us to create our own functions with specific functionality. Here’s an example of defining a simple function in Python:
def greet_user():
print("Hello, User!")
Key Concept 2
Functions can take arguments and return values. Here’s an example of a function that takes two arguments and returns their sum:
def add_numbers(a, b):
return a + b
Hands-On Tasks
Let’s practice defining and using user-defined functions with the following tasks:
- Create a function called
calc
that performs basic arithmetic operations based on the provided operation code. - Develop a function named
sum_n
to calculate the sum of integers from 1 to a given numbern
. - Implement a function
sum_of_integers
to find the sum of integers within a given range from lower boundlb
to upper boundub
.
Conclusion
In this article, we explored the fundamentals of user-defined functions in Python and practiced implementing functions for various tasks. We encourage you to try out the exercises provided and further engage with the Python community for continued learning and growth.
Exercise - User Defined Functions
Simple Calculator
Let us develop a function called as calc.
-
It should take 3 arguments
-
First argument - a of type int
-
Second argument - b of type int
-
Third argument - op of type int
-
If op is 1, the function should return sum of a and b
-
If op is 2, the function should subtract b from a and return the result
-
If op is 3, the function should multiply a with b and return the result
-
If op is 4, the function should divide a by b and return the result
-
If op is any other number, the function should print saying that invalid op and return nothing
def calc(a, b, op):
if op == 1:
return a + b
elif op == 2:
return a - b
elif op == 3:
return a * b
elif op == 4:
return a / b
else:
print("Invalid op")
Validation
Please run this code to validate the function calc
.
a = int(input("Enter first value of type integer: "))
b = int(input("Enter second value of type integer: "))
op = int(input("Enter 1 for add, 2 for sub, 3 for mul and 4 for div: "))
res = calc(a, b, op)
Sum of Integers from 1 to n
Develop functions to get sum of integers within a range of 1 to n.
-
Function Name: sum_n
-
Argument: n
-
Perform below validations. If not, raise an exception.
-
Check if n is integer or not.
-
Check if n is positive integer or not.
-
-
Exception should say {n} is not a valid integer.
-
The function should return the sum of integers from 1 to n. The logic should be implemented using formula.
def sum_n(n):
if not isinstance(n, int) or n <= 0:
raise Exception(f'{n} is not a valid integer')
return n * (n + 1) // 2
Sum of Integers within a range
Develop functions to get sum of integers within a range of lower bound and upper bound.
-
Function Name: sum_of_integers
-
Argument Names: lb and ub
-
Check if lb and ub are integers or not. If not, raise an exception. Exception should be Either {lb} or {ub} are not integers.
-
Check if lb is less than ub or not. If not, raise an exception. Exception should say {lb} is not lower than {ub}.
-
The function should return the sum of integers from lb and ub. The function should use sum_n to get sum of integers between 1 and upper bound as well as 1 and lower bound.
def sum_of_integers(lb, ub):
if not isinstance(lb, int) or not isinstance(ub, int):
raise Exception(f'Either {lb} or {
[Watch the video tutorial here](https://www.youtube.com/watch?v=4VQYPjdR7Bk)