Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
3 views6 pages

UNIT-II Functions Lab Programs

Uploaded by

mnlakshmi540
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views6 pages

UNIT-II Functions Lab Programs

Uploaded by

mnlakshmi540
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

🔢 Program 1: Function with Multiple Return Values

📘 Topic Description:
In Python, functions can return multiple values by packing them into a tuple. This is useful when you want to
return related results—like a calculation summary or multiple outputs from a single process.

🧾 Program:
def calculate_rectangle_properties(length, width):
area = length * width
perimeter = 2 * (length + width)
return area, perimeter

# Example usage
l = 10
w=5
area, perimeter = calculate_rectangle_properties(l, w)

print(f"Rectangle with length={l} and width={w}")


print(f"Area: {area}")
print(f"Perimeter: {perimeter}")

🧠 Bit-Level Explanation:
 def calculate_rectangle_properties(length, width):
→ Defines a function with two parameters: length and width.
 area = length * width
→ Calculates the area of the rectangle.
 perimeter = 2 * (length + width)
→ Calculates the perimeter using the formula.
 return area, perimeter
→ Returns both values as a tuple.
 l = 10, w = 5
→ Assigns values to be passed into the function.
 area, perimeter = ...
→ Unpacks the returned tuple into two variables.
 print(...)
→ Displays the results using formatted strings.

Sample Output:
Rectangle with length=10 and width=5
Area: 50
Perimeter: 30
⚙️Program 2: Function Using Default Arguments
📘 Topic Description:
Default arguments allow a function to be called with fewer inputs than it’s defined to accept. If a value isn’t
provided, Python uses the default. This is useful for optional settings like quantity, discount, or configuration
flags.

🧾 Program:
def generate_invoice(product_name, unit_price, quantity=1, discount=0.0):
total_price = unit_price * quantity
discount_amount = total_price * (discount / 100)
final_price = total_price - discount_amount

print(f"Product: {product_name}")
print(f"Unit Price: ₹{unit_price}")
print(f"Quantity: {quantity}")
print(f"Discount: {discount}%")
print(f"Final Price: ₹{final_price:.2f}")
return final_price

# Example usage
generate_invoice("Digital Thermometer", 250.0)
generate_invoice("Pulse Oximeter", 1200.0, quantity=2, discount=10)

🧠 Bit-Level Explanation:
 def generate_invoice(...)
→ Defines a function with four parameters. quantity and discount have default values.
 unit_price * quantity
→ Calculates total price before discount.
 discount_amount = total_price * (discount / 100)
→ Converts percentage to decimal and calculates discount.
 final_price = total_price - discount_amount
→ Applies discount to get final price.
 print(...)
→ Displays formatted invoice details using f-strings.
 return final_price
→ Returns the computed final price.
 generate_invoice(...)
→ First call uses defaults; second call overrides them.

Sample Output:
Product: Digital Thermometer
Unit Price: ₹250.0
Quantity: 1
Discount: 0.0%
Final Price: ₹250.00

Product: Pulse Oximeter


Unit Price: ₹1200.0
Quantity: 2
Discount: 10%
Final Price: ₹2160.00

🔤 Program 3: Find Length of String Without Using len()


📘 Topic Description:
Strings in Python are sequences of characters. To find the length manually, we iterate through each character
and count them—mimicking the behavior of the built-in len() function.

🧾 Program:
def manual_string_length(input_string):
count = 0
for _ in input_string:
count += 1
return count

# Example usage
user_input = "Tenali Medical Hub"
length = manual_string_length(user_input)

print(f"Input String: '{user_input}'")


print(f"Calculated Length: {length}")

🧠 Bit-Level Explanation:
 def manual_string_length(input_string):
→ Defines a function that takes a string as input.
 count = 0
→ Initializes a counter.
 for _ in input_string:
→ Loops through each character in the string.
 count += 1
→ Increments the counter for each character.
 return count
→ Returns the final count.
 user_input = "Tenali Medical Hub"
→ Sample string input.
 length = ...
→ Stores the result of the function.
 print(...)
→ Displays the result.

Sample Output:
Input String: 'Tenali Medical Hub'
Calculated Length: 18
🔍 Program 4: Check if Substring is Present in a String
📘 Topic Description:

Substring detection is a fundamental string operation. Python provides the in keyword and .find() method to
check if a smaller string (substring) exists within a larger one. This is useful for search filters, keyword
detection, and text validation.

🧾 Program:
def is_substring_present(main_string, sub_string):
if sub_string in main_string:
print(f"✅ '{sub_string}' is present in the string.")
return True
else:
print(f"❌ '{sub_string}' is NOT present in the string.")
return False

# Example usage
description = "This pharmacy stocks digital thermometers, pulse oximeters, and
sanitizers."
search_term = "pulse oximeter"
is_substring_present(description.lower(), search_term.lower())

🧠 Bit-Level Explanation:
 def is_substring_present(...)
→ Defines a function with two parameters: the full string and the substring to search for.
 if sub_string in main_string:
→ Uses Python’s in operator to check if the substring exists.
 print(...)
→ Displays a message based on whether the substring was found.
 return True / False
→ Returns a boolean result for further use.
 description.lower()
→ Converts the main string to lowercase for case-insensitive comparison.
 search_term.lower()
→ Converts the search term to lowercase.

Sample Output:
✅ 'pulse oximeter' is present in the string.

📦 Program 5: Perform List Operations – Addition, Insertion, Slicing


📘 Topic Description:

Lists are mutable sequences in Python. You can add elements using append(), insert them at specific positions
using insert(), and extract sublists using slicing (list[start:end]). These operations are essential for
managing collections of data.

🧾 Program:
def manage_inventory():
inventory = ["Thermometer", "Pulse Oximeter", "Sanitizer"]
print("Initial Inventory:", inventory)

inventory.append("Face Mask")
print("After Addition:", inventory)

inventory.insert(1, "Gloves")
print("After Insertion at index 1:", inventory)

sliced_inventory = inventory[0:3]
print("Sliced Inventory (first 3 items):", sliced_inventory)

# Run the function


manage_inventory()

🧠 Bit-Level Explanation:
 inventory = [...]
→ Initializes a list with three items.
 inventory.append("Face Mask")
→ Adds a new item to the end of the list.
 inventory.insert(1, "Gloves")
→ Inserts "Gloves" at index 1, shifting other items.
 inventory[0:3]
→ Slices the list to get the first three items (index 0 to 2).
 print(...)
→ Displays the list after each operation.

Sample Output:
Initial Inventory: ['Thermometer', 'Pulse Oximeter', 'Sanitizer']
After Addition: ['Thermometer', 'Pulse Oximeter', 'Sanitizer', 'Face Mask']
After Insertion at index 1: ['Thermometer', 'Gloves', 'Pulse Oximeter', 'Sanitizer', 'Face
Mask']
Sliced Inventory (first 3 items): ['Thermometer', 'Gloves', 'Pulse Oximeter']

📊 Program 6: Perform 5 Built-in Functions on a List


📘 Topic Description:
Python provides built-in functions to operate on lists efficiently. Common ones include len() for length, max()
and min() for extremes, sum() for totals, and sorted() for ordering. These are widely used in analytics,
dashboards, and data processing.

🧾 Program:
def analyze_stock_levels(stock_quantities):
print("Stock Quantities:", stock_quantities)
print("Total Items:", len(stock_quantities))
print("Highest Stock Level:", max(stock_quantities))
print("Lowest Stock Level:", min(stock_quantities))
print("Total Inventory:", sum(stock_quantities))
print("Sorted Stock Levels:", sorted(stock_quantities))

# Example usage
stock_list = [120, 45, 300, 75, 200]
analyze_stock_levels(stock_list)

🧠 Bit-Level Explanation:
 stock_list = [...]
→ Initializes a list of integers representing stock quantities.
 len(stock_quantities)
→ Returns the number of items in the list.
 max(stock_quantities)
→ Finds the highest value.
 min(stock_quantities)
→ Finds the lowest value.
 sum(stock_quantities)
→ Adds all values together.
 sorted(stock_quantities)
→ Returns a new list with items sorted in ascending order.
 print(...)
→ Displays each result clearly.

Sample Output:
Stock Quantities: [120, 45, 300, 75, 200]
Total Items: 5
Highest Stock Level: 300
Lowest Stock Level: 45
Total Inventory: 740
Sorted Stock Levels: [45, 75, 120, 200, 300]

You might also like