Overview
The Python def function explores the concept of the def function. We have two types to create the def function in Python, i.e., by using the own custom function and using the built-in function. Also, consider how to work with the arguments.
What’s Next!
In this comprehensive Python def function Project, we will look deeply at the Python def concept and solve several Python def problems based on def various arguments.
Table of Contents
Project 1: Greeting Function
Create a function that takes a name as a required argument and a greeting message as a default argument. The function should print the greeting message along with the name.
def user_name(name):
return name
def greet_user(message='Good Morning.'):
return message
print("Hello!", user_name(name= 'Sumit'), greet_user())
Explanation: The program starts with a function user_name(name) to ask for the Name of the user, the parameter ‘name’ is a required argument.
In another function, greet_user(), the function takes a parameter ‘message’ which holds a default greeting value ‘Good Morning.’
Finally, by using the print() function the statement is executed.
Let’s move further a bit more in this greeting function and explore the above question in different argument cases.
#Greeting Function with default argument-value
def user_name(name="Alex"):
return name
def greet_user(message="Good Morning"):
return message
print("Hello", user_name(), greet_user())
Explanation: In this case, both functions user_name(name) and greet_user(message) hold the argument values as a default argument. Therefore, we do not need to define the new value while calling the function. Both functions will consider their default values for the arguments to execute the statement.
#Greeting Function with keyword argument-value
def user_name(greet='Hello',name='Alexo'):
print(greet,name)
user_name(name= 'John', greet='Good Morning!')
Explanation: In this case, the parameter is defined as keyword argument-value form, meaning that the default value is passed to the parameters as keywords (greet, name) argument-values (Hello, Alexo).
The function returns a message in which the user is greeted with the name. If we do not define the new argument values while calling the function, then the default value will be considered otherwise the new values defined by the user.
Project 2: Simple Calculator Function
Write a function that takes two numbers as required arguments and an operator as a default argument (e.g., “+”, “-“, “*”, “/”). The function should perform the specified operation on the two numbers and return the result.
def numbers(a,b):
return a,b
n1 = int(input("Enter first number: "))
n2 = int(input("Enter second number: "))
oprtr = input("Enter the operation (+,-,*,/): ")
if oprtr == "+":
print(f"The sum of {n1} + {n2} is : {numbers(n1,n2)[0] + numbers(n1,n2)[1]}")
elif oprtr == "-":
print(f"The result of {n1} - {n2} is : {numbers(n1,n2)[0] - numbers(n1,n2)[1]}")
elif oprtr == "*":
print(f"The result of {n1} * {n2} is : {numbers(n1,n2)[0] * numbers(n1,n2)[1]}")
else:
print(f"The result of {n1} / {n2} is : {numbers(n1,n2)[0] / numbers(n1,n2)[1]}")
Explanation: The program starts with asking the two numbers and an operator to perform the calculation. The function numbers() is defined with 2 parameters a, and b. The variables n1 and n2 are defined as the values of the parameters a, and b.
Finally, after taking the inputs from the user, the condition statement is checked with the inputs and according to the user’s inputs, whichever condition is matched, is executed by the print() function.
Let’s take another look as well on Python calculator project
def calculate(num1, num2, operator):
if operator == "+":
return num1 + num2
elif operator == "-":
return num1 - num2
elif operator == "*":
return num1 * num2
elif operator == "/":
if num2 != 0:
return num1 / num2
else:
return "Division by zero is not allowed"
# Example usage
num1 = 20
num2 = 5
print("Addition:", calculate(num1, num2, "+"))
print("Subtraction:", calculate(num1, num2, "-"))
print("Multiplication:", calculate(num1, num2, "*"))
print("Division:", calculate(num1, num2, "/"))
Explanation: In this case, the user is not asked to enter the inputs, instead the inputs are already defined. The program starts with the calculate() function which takes 3 parameters i.e., num1, num2, and operator. All the parameters are the required arguments.
Once the program is executed, the calculate() function takes the inputs and operator and sends them to the conditional statements to operate with return statements, and then the return values are transferred to the print() function and the statements are executed.
Project 3: Power Function
Develop a function that takes a base number as a required argument and an exponent as a default argument. The function should return the result of raising the base number to the exponent.
def base_number(N):
return N
def exponent(e=3):
return e
print("Default exponent (3):",base_number('2'),'**',exponent(),'=' ,base_number(2)**exponent())
print("Exponent (2):",base_number('2'),'**',exponent(2),'=' ,base_number(2)**exponent(2))
print("Exponent (4):",base_number('2'),'**',exponent(4),'=' ,base_number(2)**exponent(4))
Explanation: The program starts with 2 functions base_number() and exponent(). The base_number() function is defined with a required argument and exponent() is defined as a default function.
There are three statements to execute, The number as an input is taken in all 3 statements. But in the case of exponents(), 1st statement operates by taking the default value (i.e., 3) whereas 2nd and 3rd statement takes the exponent values from the users.
Project 4: Sum of Numbers Function
Create a function that takes a list of numbers as a required argument and an initial sum as a default argument. The function should return the sum of all numbers in the list starting from the initial sum.
def sum_numbers(numbers, initial_sum=0):
return initial_sum+sum(numbers)
numbers = [1,2,3,4]
print("Sum with initial sum:",sum_numbers(numbers))
print("Sum without initial sum:",sum_numbers(numbers, initial_sum=1))
Explanation: The program starts with a function sum_numbers() that takes 2 parameters, whereas numbers is a required argument and initial_sum is a default argument.
Once the program is executed the return statement performs the command that sum of all numbers in the list starting from the initial sum. The value is then transferred to the print() function, where two statements are executed, first with the default initial_sum value, and second with the new value.
Project 5: Factorial Function
Write a function that takes a number as a required argument and a boolean flag as a default argument. The function should return the factorial of the number if the flag is set to True, and the number itself if the flag is set to False.
def factorial_number(Facto_num, bool=True):
if Facto_num < 0:
print("Error! The input must be a positive integer.")
elif Facto_num == 0:
print("The factorial of",Facto_num,"is:",1)
else:
factorial = 1
if bool:
for x in range(1,Facto_num+1):
factorial = x*factorial
print("The factorial of",Facto_num,"is:",factorial)
else:
print('The number is:', Facto_num)
factorial_number(4)
Explanation: The program starts with a function factorial_number() which takes 2 parameters, first (Facto_num) as required whereas second (bool) as default.
If the user enters a negative number then no factorial, if the number is 0 or 1, 1 is factorial. But number is greater than 1 then according to the factorial formula, the factorial is calculated based on the bool value.
If bool is True, then the factorial of the number is displayed and if bool is False, then the number itself is displayed.