Python Function:
- A function in Python is a reusable block of code that performs a specific task. It starts with the def keyword, followed by the function name and parentheses. Functions can accept inputs (parameters) and return outputs, helping to organize and simplify code.
Function Syntax in Python:
def function_name(parameters): # Code to perform a task return output
Basic Example:
Simple example of a function that adds two numbers:
Program :
def add_numbers(a, b): result = a + b # Add the two numbers return result # Return the result # Calling the function sum = add_numbers(3, 5) print(sum) # Output: 8
Question 1 :
Create a function called add(), sub(), mul(), div() in Python. Each function should take user inputs for a and b, perform the respective arithmetic operation, and print the result.
Program:
def add(): a = float(input("Enter the first number for addition: ")) b = float(input("Enter the second number for addition: ")) result = a + b print("Addition Result:", result) def sub(): a = float(input("Enter the first number for subtraction: ")) b = float(input("Enter the second number for subtraction: ")) result = a - b print("Subtraction Result:", result) def mul(): a = float(input("Enter the first number for multiplication: ")) b = float(input("Enter the second number for multiplication: ")) result = a * b print("Multiplication Result:", result) def div(): a = float(input("Enter the first number for division: ")) b = float(input("Enter the second number for division: ")) if b != 0: result = a / b print("Division Result:", result) else: print("Error: Cannot divide by zero.") # Call the functions add() sub() mul() div()
Output :
Enter the first number for addition: 1 Enter the second number for addition: 2 Addition Result: 3.0 Enter the first number for subtraction: 3 Enter the second number for subtraction: 2 Subtraction Result: 1.0 Enter the first number for multiplication: 2 Enter the second number for multiplication: 3 Multiplication Result: 6.0 Enter the first number for division: 7 Enter the second number for division: 3 Division Result: 2.3333333333333335
Question 2:
Write a Python function that calculates the area of a rectangle. The program should ask the user to enter the length and width of the rectangle and then display the result.
Program :
def calculate_area(length, width): area = length * width return area length = float(input("Enter the length of the rectangle: ")) width = float(input("Enter the width of the rectangle: ")) area = calculate_area(length, width) print(f"The area of the rectangle is: {area} square units.")
Output:
Enter the length of the rectangle: 7 Enter the width of the rectangle: 3 The area of the rectangle is: 21.0 square units.
0 Comments