Coding Challenges - SRM Coding Bootcamp
Coding Challenges - SRM Coding Bootcamp
Coding Bootcamp
Contents
Sequence Programming ..........................................................................................................................4
Coding Challenge 1: Program to find the sum and average of two variables .....................................4
Coding Challenge 2: Program to calculate simple interest ................................................................. 4
Coding Challenge 3: Program to calculate the discount on the total amount ................................... 4
Coding Challenge 4: Program to swap two numbers ..........................................................................5
Coding Challenge 5: Farmer Problem Statement ................................................................................5
Decision Making ......................................................................................................................................6
Coding Challenge 6: Program to check if a number is even or odd .................................................... 6
Coding Challenge 7: Program to accept name and salary. Check if their salary is >3L and display if
they must pay tax ................................................................................................................................ 6
Coding Challenge 8: To find the largest of 3 numbers ........................................................................7
Coding Challenge 9: Program to check if a year given is a leap year or not ....................................... 7
Coding Challenge 10: Student Report Card Problem ..........................................................................7
Tax Calculator Problem– Hackathon ...................................................................................................... 8
Coding Challenge 11: Basic Input and Salary Calculation ................................................................... 8
Coding Challenge 12: Taxable Income Calculation ............................................................................. 9
Coding Challenge 13: Tax and Rebate Calculation ..............................................................................9
Coding Challenge 14: Net Salary Calculation .................................................................................... 10
Coding Challenge 15: Report Generation ......................................................................................... 11
Coding Challenge 16: Input Validation Rules .................................................................................... 11
Loops and Iterations .............................................................................................................................. 13
Coding Challenge 17: Display the Series 1,2,3,4,5,6…N ....................................................................13
Coding Challenge 18: Display the Series 1,3,5,7,9…N .......................................................................13
Coding Challenge 19: Display the Series 4,16,36,64…N ....................................................................13
Coding Challenge 20: Display the Series 1,2,4,7,11,16,22…N ...........................................................14
Coding Challenge 21: Display the Series 1,4,9,25,36,49,81…N .........................................................14
Coding Challenge 22: Display the Series 1,4,7,12,23…N ...................................................................15
Coding Challenge 23: Display the Series 1,5,9,13,21,25,29,37,41…N ...............................................15
Coding Challenge 24: Display the Series 1,1,2,3,5,8,13,21…N ..........................................................15
Coding Challenge 25: Generating the Series: 2, -4, 6, -8, 10, … N .................................................... 16
Coding Challenge 26: Generating Prime Numbers: 2, 3, 5, 7, 11, 13, … N ........................................16
Coding Challenge 27: Generating the Series: 2, 3, 7, 14, 24, 37, 53, 72, 94, 119, 147, ……….N ....... 17
Coding Challenge 28: Write a program to do the following : ........................................................... 17
Input: 270176
Output: Two Seven Zero One Seven Six
TalenciaGlobal HandsOn Framework - THLF
Coding Challenge 29: Write a program to find the 1st, 2nd and 4th multiples of 7 which gives the
reminder 1 when divided by 2,3,4,5,6 .............................................................................................. 18
Retail Shopping– Hackathon ................................................................................................................ 18
Coding Challenge 30: Basic Item Entry and Total Calculation ...........................................................18
Coding Challenge 31: Iterative Item Entry and Grand Total ............................................................. 19
Coding Challenge 32: Applying Discounts ......................................................................................... 19
Coding Challenge 33: Membership Discounts .................................................................................. 20
Coding Challenge 34: Tax Calculation Based on Purchase Amount ...................................................... 21
Coding Challenge 35: Promotional Discounts on Specific Items .......................................................21
Coding Challenge 36: Payment Mode Rules ..................................................................................... 22
Coding Challenge 37: Minimum Purchase Requirements .................................................................22
Coding Challenge 38: Loyalty Points ................................................................................................. 22
Pattern Programming and Nested Loops ............................................................................................. 23
Coding Challenge 39: Printing Star Pattern (N Rows) ....................................................................... 23
Coding Challenge 40: Printing Number Pattern (N Rows) ................................................................ 23
Coding Challenge 41: Printing Number Pattern (N Rows) ................................................................ 24
Coding Challenge 42: Printing * Increasing Pattern (N Rows) .......................................................... 24
Coding Challenge 43: Printing number Increasing Pattern (N Rows) ............................................... 24
Coding Challenge 44: Printing number Increasing Pattern (N Rows) ............................................... 25
Coding Challenge 45: Fibonacci Series Pattern (N Rows) ................................................................. 25
Coding Challenge 46: Printing Pattern of Perfect Squares with Alternating Signs in N Rows .......... 26
Coding Challenge 47: Printing Pattern of Factorials in N Rows ........................................................ 26
Coding Challenge 48: Convert Number to Words Using Mathematical Logic .................................. 26
Coding Challenge 49: Generate Series - 1, -5, 9, -13, 17, -21, ... N ................................................... 27
Coding Challenge 50: Whole and Fraction value separation ............................................................ 28
Coding Challenge 51: Reverse of a number ...................................................................................... 28
Working with Arrays ............................................................................................................................. 28
Coding Challenge 52: Level 0: Write a program to accept n and store the elements into the array
of size n. .............................................................................................................................................28
Coding Challenge 53: Level 1: Find the Sum of all elements in the array .........................................29
Coding Challenge 54: Level 2: Find the Minimum value of all elements in the array ...................... 29
Coding Challenge 55: Level 3: Find the Maximum value of all elements in the array ......................29
Coding Challenge 56: Level 4: Search the given element from the array .........................................29
Coding Challenge 57: Level 5: Display the number of odd and even numbers from the array ........30
Sort and Search Arrays ......................................................................................................................... 30
Coding Challenge 58: Level 0: Write a program to accept n and store the elements into the array
of size n. .............................................................................................................................................30
TalenciaGlobal HandsOn Framework - THLF
Sequence Programming
Coding Challenge 1: Program to find the sum and average of two variables
Solution:
1. # Get input for the two variables
2. num1 = float(input("Enter the first number: "))
3. num2 = float(input("Enter the second number: "))
4.
5. # Calculate the sum
6. sum_of_numbers = num1 + num2
7.
8. # Calculate the average
9. average_of_numbers = sum_of_numbers / 2
10.
11. # Print the results
12. print("Sum:", sum_of_numbers)
13. print("Average:", average_of_numbers)
Solution:
1. # Get input from the user
2. principal = float(input("Enter the principal amount: "))
3. rate = float(input("Enter the annual interest rate (in percentage): "))
4. time = float(input("Enter the time period (in years): "))
5.
6. # Calculate simple interest
7. simple_interest = (principal * rate * time) / 100
8.
9. # Calculate the total amount (principal + interest)
10. total_amount = principal + simple_interest
11.
12. # Print the results
13. print("Simple Interest:", simple_interest)
14. print("Total Amount:", total_amount)
Solution:
1. # Get the total amount and discount percentage from the user
2. total_amount = float(input("Enter the total amount: "))
3. discount_percentage = float(input("Enter the discount percentage: "))
4.
5. # Calculate the discount amount
6. discount_amount = (total_amount * discount_percentage) / 100
7.
8. # Calculate the final amount after discount
9. final_amount = total_amount - discount_amount
10.
11. # Print the results
12. print("Discount amount:", discount_amount)
13. print("Final amount after discount:", final_amount)
TalenciaGlobal HandsOn Framework - THLF
Solution:
1. # Get input for the two numbers
2. num1 = int(input("Enter the first number: "))
3. num2 = int(input("Enter the second number: "))
4.
5. print("Original numbers:")
6. print("Number 1:", num1)
7. print("Number 2:", num2)
8.
9. # Swap the numbers using a temporary variable
10. temp = num1
11. num1 = num2
12. num2 = temp
13.
14. # Print the swapped numbers
15. print("\nSwapped numbers:")
16. print("Number 1:", num1)
17. print("Number 2:", num2)
Solution:
1. # Land and Crop Information
2. total_land = 80 # in acres
3. segments = 5
4. segment_land = total_land / segments # area per segment
5. # Crop Information (yield in tonnes, price per kg)
6. crops = {
7. "tomatoes": {"yield_per_acre_30": 10, "yield_per_acre_70": 12, "price_per_kg": 7},
8. "potatoes": {"yield_per_acre": 10, "price_per_kg": 20},
9. "cabbage": {"yield_per_acre": 14, "price_per_kg": 24},
10. "sunflower": {"yield_per_acre": 0.7, "price_per_kg": 200},
11. "sugarcane": {"yield_per_acre": 45, "price_per_ton": 4000},
12. }
13. # Part (a) Calculate overall sales from the entire land (80 acres)
14. total_sales = 0
15. # Calculate for tomatoes (30% and 70% split)
16. yield_30 = crops["tomatoes"]["yield_per_acre_30"] * segment_land * 0.30 # 30% of land
17. yield_70 = crops["tomatoes"]["yield_per_acre_70"] * segment_land * 0.70 # 70% of land
TalenciaGlobal HandsOn Framework - THLF
Decision Making
Solution:
1. # Input: Take a number from the user
2. number = int(input("Enter a number: "))
3.
4. # Check if the number is even or odd using a single if condition
5. if number % 2 == 0:
6. print("Even")
7. else:
8. print("Odd")
Coding Challenge 7: Program to accept name and salary. Check if their salary is >3L
and display if they must pay tax
Solution:
1. # Accept employee details
2. name = input("Enter employee's name: ")
3. salary = float(input("Enter employee's annual salary: "))
4.
5. # Check if salary is greater than 3,00,000
6. if salary > 300000:
TalenciaGlobal HandsOn Framework - THLF
Solution:
1. # Input three numbers
2. num1 = 10
3. num2 = 25
4. num3 = 15
5.
6. # Find the largest
7. if num1 >= num2 and num1 >= num3:
8. print("The largest number is:", num1)
9. elif num2 >= num1 and num2 >= num3:
10. print("The largest number is:", num2)
11. else:
12. print("The largest number is:", num3)
Solution:
1. year = 2024
2. if year % 4 == 0:
3. if year % 100 == 0:
4. if year % 400 == 0:
5. print("Leap year")
6. else:
7. print("Not a leap year")
8. else:
9. print("Leap year")
10. else:
11. print("Not a leap year")
Solution:
1. # Input student name and scores
2. name = input("Enter the student's name: ")
3. score1 = float(input("Enter score for subject 1: "))
4. score2 = float(input("Enter score for subject 2: "))
5. score3 = float(input("Enter score for subject 3: "))
6.
7. # Check if the student passed in each subject
8. if score1 < 35 or score2 < 35 or score3 < 35:
9. result = "Fail"
10. else:
11. # Calculate total and average
12. total = score1 + score2 + score3
13. average = total / 3
TalenciaGlobal HandsOn Framework - THLF
14.
15. # Determine the class
16. if average >= 60:
17. result = "1st Class"
18. elif average >= 50:
19. result = "2nd Class"
20. elif average >= 35:
21. result = "Pass Class"
22. else:
23. result = "Fail"
24.
25.
26. # Display the results
27. print("\nStudent Report Card")
28. print("Name:", name)
29. if result == "Fail":
30. print("Result:", result)
31. else:
32. print("Total:", total)
33. print("Average:", average)
34. print("Result:", result)
Solution:
1. # Accepting employee details
2. name = input("Enter employee's name: ")
3. emp_id = input("Enter employee ID: ")
4. basic_salary = float(input("Enter basic monthly salary: "))
5. special_allowances = float(input("Enter monthly special allowances: "))
6. bonus_percentage = float(input("Enter annual bonus percentage (as a % of gross salary):
"))else:
7. # Calculate gross monthly salary
8. gross_monthly_salary = basic_salary + special_allowances
9.
10. # Calculate annual gross salary
11. annual_gross_salary = (gross_monthly_salary * 12) + (gross_monthly_salary * bonus_percentage
/ 100)
12. # Output the details
13. print("\nEmployee Details:")
14. print(f"Name: {name}")
15. print(f"Employee ID: {emp_id}")
16. print(f"Gross Monthly Salary: ₹{gross_monthly_salary:,.2f}")
17. print(f"Annual Gross Salary: ₹{annual_gross_salary:,.2f}")
Solution:
1. # Define the standard deduction amount
2. standard_deduction = 50000
3.
4. # Calculate the taxable income after standard deduction
5. taxable_income = annual_gross_salary - standard_deduction
6.
7. # Output the details
8. print("\nTaxable Income Calculation:")
9. print(f"Annual Gross Salary: ₹{annual_gross_salary:,.2f}")
10. print(f"Standard Deduction: ₹{standard_deduction:,.2f}")
11. print(f"Taxable Income: ₹{taxable_income:,.2f}")
Solution:
1. # Input taxable income
2. taxable_income = float(input("Enter taxable income (₹): "))
3.
4. # Initialize variables
5. tax = 0
6.
7. # Calculate tax based on sCoding Challenges
8. if taxable_income > 1500000:
9. tax += (taxable_income - 1500000) * 0.30
10. taxable_income = 1500000
11. if taxable_income > 1200000:
12. tax += (taxable_income - 1200000) * 0.20
13. taxable_income = 1200000
14. if taxable_income > 900000:
15. tax += (taxable_income - 900000) * 0.15
16. taxable_income = 900000
17. if taxable_income > 600000:
18. tax += (taxable_income - 600000) * 0.10
19. taxable_income = 600000
20. if taxable_income > 300000:
21. tax += (taxable_income - 300000) * 0.05
22.
23. # Apply Section 87A rebate
24. if taxable_income <= 700000:
25. tax = 0
26.
27. # Add 4% Health and Education Cess
28. cess = tax * 0.04
29. total_tax_payable = tax + cess
30.
31. # Display detailed tax breakdown
32. print("\n--- Tax Breakdown ---")
33. print(f"Base Tax: ₹{tax:.2f}")
34. print(f"Health and Education Cess (4%): ₹{cess:.2f}")
35. print(f"Total Tax Payable: ₹{total_tax_payable:.2f}")
Solution:
1. # Compute Net Salary
2. annual_net_salary = annual_gross_salary - total_tax_payable
3.
4. # Display results
5. print("\n--- Net Salary Details ---")
6. print(f"Annual Gross Salary: ₹{annual_gross_salary:.2f}")
7. print(f"Total Tax Payable: ₹{total_tax_payable:.2f}")
8. print(f"Annual Net Salary: ₹{annual_net_salary:.2f}")
TalenciaGlobal HandsOn Framework - THLF
Solution:
1. # Display the report
2. print("\n--- Employee Tax Report ---")
3. print(f"{'Field':<25}{'Details':<20}")
4. print("-" * 45)
5. print(f"{'Name':<25}{employee_name:<20}")
6. print(f"{'EmpID':<25}{employee_id:<20}")
7. print(f"{'Gross Monthly Salary':<25}₹{gross_monthly_salary:,.2f}")
8. print(f"{'Annual Gross Salary':<25}₹{annual_gross_salary:,.2f}")
9. print(f"{'Taxable Income':<25}₹{taxable_income:,.2f}")
10. print(f"{'Tax Payable':<25}₹{total_tax_payable:,.2f}")
11. print(f"{'Annual Net Salary':<25}₹{annual_net_salary:,.2f}")
Solution:
1. # Input validation for employee details
2. while True:
3. name = input("Enter employee name: ")
4. if not name or not name.isalpha() or len(name) > 50:
5. print("Error: Name must be non-empty, contain only alphabets, and be at most 50
characters long.")
6. else:
7. break
8.
9. while True:
10. emp_id = input("Enter employee ID: ")
11. if not emp_id.isalnum() or not (5 <= len(emp_id) <= 10):
12. print("Error: Employee ID must be alphanumeric and 5–10 characters long.")
13. else:
14. break
15. # Input validation for salary
16. while True:
17. try:
18. basic_salary = float(input("Enter basic monthly salary: "))
19. if basic_salary <= 0 or basic_salary > 10000000:
20. print("Error: Basic salary must be a positive number and not exceed
₹1,00,00,000.")
21. else:
22. break
23. except ValueError:
24. print("Error: Please enter a valid number.")
25.
26. # Input validation for special allowances
27. while True:
28. try:
29. special_allowances = float(input("Enter special allowances: "))
30. if special_allowances < 0 or special_allowances > 10000000:
31. print("Error: Special allowances must be non-negative and not exceed
₹1,00,00,000.")
32. else:
33. break
34. except ValueError:
35. print("Error: Please enter a valid number.")
36.
37. # Input validation for bonus percentage
38. while True:
39. try:
40. bonus_percentage = float(input("Enter annual bonus percentage: "))
41. if not (0 <= bonus_percentage <= 100):
42. print("Error: Bonus percentage must be between 0 and 100.")
43. else:
44. break
45. except ValueError:
46. print("Error: Please enter a valid number.")
47.
48. # Derived calculations validation
TalenciaGlobal HandsOn Framework - THLF
Solution:
# Get input from the user for N
N = int(input("Enter the value of N: "))
Solution:
1. # # Program to generate odd numbers up to N
2.
3. # Get input from the user for N
4. N = int(input("Enter the value of N: "))
5.
6. # Validate the input (ensure N is a positive integer)
7. if N <= 0:
8. print("N must be a positive integer.")
9. else:
10. # Generate and print the odd numbers
11. for i in range(1, N + 1, 2): #incrementing i by 2 in every iteration
12. print(i, end=" ")
13. print()
Solution:
1. # Program to generate the sequence 4, 16, 36, 64, ... up to N
2.
3. # Get input from the user for N
4. N = int(input("Enter the value of N: "))
5.
6. # Validate the input (ensure N is a positive integer)
7. if N <= 0:
8. print("N must be a positive integer.")
9.
TalenciaGlobal HandsOn Framework - THLF
10. else:
11.
12. i = 1
13. term = 4 #Initialize with first term
14.
15.
16. while term <= N: #loop until term is less than equal to n
17. print(term, end=" ")
18.
19.
20. term = (2*i + 2)**2 #find the next term by squaring 2i+2
21. i += 1 #Increment i to generate next values
22.
23. print()
Solution:
1. # Program to generate the sequence 1, 2, 4, 7, 11, 16, 22, ... up to N
2.
3. # Get input from the user for N
4. N = int(input("Enter the value of N: "))
5.
6. # Validate the input (ensure N is a positive integer)
7. if N <= 0:
8. print("N must be a positive integer.")
9. else:
10. term = 1 #initialize term
11. increment = 1 #initialize increment variable
12. while term <= N:
13. print(term, end=" ")
14. increment += 1 #increase increment variable by one each time
15. term += increment #add increment variable to the term
16. print()
Solution:
1. # Program to generate the sequence 1, 4, 9, 25, 36, 49, 81, ... up to N (perfect squares)
2.
3. # Get input from the user for N
4. N = int(input("Enter the value of N: "))
5.
6. # Validate the input (ensure N is a positive integer)
7. if N <= 0:
8. print("N must be a positive integer.")
9.
10. else:
11. i = 1
12. square = 1 #initialize square with 1
13. while square <= N: #loop until square is less than or equal to n
14. print(square, end=" ")
15. i += 1 #increment i in every loop by 1
16. square = i * i # Calculate the next perfect square
17.
18. print()
TalenciaGlobal HandsOn Framework - THLF
Solution:
1. # Input: Number of terms (N)
2. N = int(input("Enter the number of terms (N): "))
3. # Initializing the first term and counter
4. current = 1
5. increment = 3
6. term_count = 1
7. print("Generated Series: ", end="")
8. while term_count <= N:
9. # Print the current term
10. print(current, end=", " if term_count < N else "\n")
11. # Update the current term and increment
12. current += increment
13. # Pattern increases the increment by 2 each time after first step
14. increment += 2 if term_count > 1 else 1
15. # Increment the term counter
16. term_count += 1
Solution:
1. # Input: Number of terms (N)
2. N = int(input("Enter the number of terms (N): "))
3. # Initialize the first term, increment, and counter
4. current = 1
5. term_count = 1
6. print("Generated Series: ", end="")
7. while term_count <= N:
8. # Print the current term
9. print(current, end=", " if term_count < N else "\n")
10. # Update the current term based on the position
11. if term_count % 4 == 0: # Every 4th term increments by 8
12. current += 8
13. else: # Other terms increment by 4
14. current += 4
15. # Increment the term counter
16. term_count += 1
Solution:
1. # Get input from the user for N
2. N = int(input("Enter the value of N: "))
3.
4. # Validate the input (ensure N is a positive integer)
5. if N <= 0:
6. print("N must be a positive integer.")
7. else:
8. # Generate and print the numbers
9. for i in range(1, N + 1):
10. print(i, end=" ") # Print numbers on the same line, separated by spaces
11. print() # Add a newline at the end for cleaner output
TalenciaGlobal HandsOn Framework - THLF
Solution:
1. # Input: Number of terms (N)
2. N = int(input("Enter the number of terms (N): "))
3. # Initialize the first term and counter
4. current = 2
5. term_count = 1
6. print("Generated Series: ", end="")
7. while term_count <= N:
8. # Print the current term
9. print(current, end=", " if term_count < N else "\n")
10. # Update the term (toggle sign and increase magnitude)
11. current = -current + (2 if current < 0 else 0)# Increment the term counter
12. term_count += 1
Solution:
1. import math
2. # Input: Number of terms (N)
3. N = int(input("Enter the number of terms (N): "))
4. # Initialize prime count and starting number
5. count = 0
6. num = 2
7. print("Generated Prime Numbers: ", end="")
8. while count < N:
9. # Check if the number is prime
10. is_prime = True
11. for i in range(2, int(math.sqrt(num)) + 1):
12. if num % i == 0:
13. is_prime = False
14. break
15. if is_prime:
16. # Print the prime number
17. print(num, end=", " if count < N - 1 else "\n")
18. count += 1
TalenciaGlobal HandsOn Framework - THLF
Coding Challenge 27: Generating the Series: 2, 3, 7, 14, 24, 37, 53, 72, 94, 119,
147, ……….N
Solution:
1. # Input: Number of terms (N)
2. N = int(input("Enter the number of terms (N): "))
3. # Initialize the first term, increment, and counter
4. current = 2
5. increment = 1
6. term_count = 1
7. print("Generated Series: ", end="")
8. while term_count <= N:
9. # Print the current term
10. print(current, end=", " if term_count < N else "\n")
11. # Update the term and increment
12. increment += 1 if term_count > 1 else 0 # Increment starts increasing after the second term
13. current += increment
14. # Increment the term counter
15. term_count += 1
Solution:
1. # Program to convert numbers into words
2.
3. def number_to_words(number_str):
4. """Converts a string of digits to its word representation."""
5.
6. # Dictionary mapping digits to words
7. digit_map = {
8. '0': "Zero", '1': "One", '2': "Two", '3': "Three", '4': "Four",
9. '5': "Five", '6': "Six", '7': "Seven", '8': "Eight", '9': "Nine"
10. }
11. words = [] #initialize an empty list named words
12.
13. for digit in number_str: #loop through the input digit string
14. word = digit_map.get(digit) #get the word form of the number from dictionary
15.
16. if word: #if word is valid digit append to list
17. words.append(word)
18.
19. else:
20. return "Invalid input. Not a digit" #if input is invalid return this message
21.
22.
23.
24. return " ".join(words) # Join the words with spaces
25.
26.
27.
28. # Example usage
29. number_string = input("Enter a number: ") # Get input as a string
30. result = number_to_words(number_string) #call number_to_words function to convert to words
31.
32. print("Output:",result)
TalenciaGlobal HandsOn Framework - THLF
Coding Challenge 29: Write a program to find the 1st, 2nd and 4th multiples of 7 which
gives the reminder 1 when divided by 2,3,4,5,6
Solution:
1. # Program to find 1st, 2nd, and 4th multiples of 7 with specific remainder conditions
2.
3. def find_multiples():
4. """Finds multiples of 7 satisfying the given remainder conditions."""
5.
6. count = 0 #initialize count
7. multiple_count = 0 #to track how many such numbers are found
8. num = 7 #start the checking with the number 7
9.
10.
11. while multiple_count<4: #loop should continue until 4 multiples are found
12.
13. if (num % 2 == 1 and num % 3 == 1 and num % 4 == 1 and num % 5 == 1 and num % 6 ==
1):
14.
15. count += 1 #increment count every time a multiple is found
16.
17. if count == 1 or count == 2 or count==4: #check if it is first, second, or
fourth multiple
18.
19. multiple_count += 1 #increment multiple_count
20. print(f"{count}st/nd/th multiple: {num}")
21.
22.
23.
24. num += 7 #check multiples of 7 by incrementing num by 7
25.
26.
27.
28. # Call the function
29. find_multiples()
30.
Solution:
1. # Level 1: Basic Item Entry and Total Calculation
2. item_code = input("Enter item code: ")
3. description = input("Enter item description: ")
4. quantity = int(input("Enter quantity: "))
5. price = float(input("Enter price per unit: "))
TalenciaGlobal HandsOn Framework - THLF
6.
7. item_total = quantity * price
8. print(f"Item Total: ₹{item_total:.2f}")
Solution:
1. grand_total = 0 # Level 2: Iterative Item Entry and Grand Total
2. while True:
3. item_code = input("Enter item code: ")
4. description = input("Enter item description: ")
5. quantity = int(input("Enter quantity: "))
6. price = float(input("Enter price per unit: "))
7.
8. item_total = quantity * price
9. grand_total += item_total
10. print(f"Item Total: ₹{item_total:.2f}")
11.
12. another_item = input("Add another item? (y/n): ")
13. if another_item.lower() != 'y':
14. break
15. print(f"Grand Total: ₹{grand_total:.2f}")
Solution:
1. # Level 3: Applying Discounts
2. grand_total = 0
3. total_quantity = 0
4.
5. while True:
6. item_code = input("Enter item code: ")
7. description = input("Enter item description: ")
8. quantity = int(input("Enter quantity: "))
9. price = float(input("Enter price per unit: "))
10.
11. item_total = quantity * price
12. grand_total += item_total
13. total_quantity += quantity
14. print(f"Item Total: ₹{item_total:.2f}")
15.
16. another_item = input("Add another item? (y/n): ")
17. if another_item.lower() != 'y':
18. break
19.
20. if grand_total > 10000:
TalenciaGlobal HandsOn Framework - THLF
Solution:
1. # Level 4: Membership Discounts
2. grand_total = 0
3. total_quantity = 0
4.
5. while True:
6. item_code = input("Enter item code: ")
7. description = input("Enter item description: ")
8. quantity = int(input("Enter quantity: "))
9. price = float(input("Enter price per unit: "))
10.
11. item_total = quantity * price
12. grand_total += item_total
13. total_quantity += quantity
14. print(f"Item Total: ₹{item_total:.2f}")
15.
16. another_item = input("Add another item? (y/n): ")
17. if another_item.lower() != 'y':
18. break
19.
20. if grand_total > 10000:
21. discount = grand_total * 0.10
22. grand_total -= discount
23. print(f"10% Discount applied: ₹{discount:.2f}")
24.
25. if total_quantity > 20:
26. quantity_discount = grand_total * 0.05
27. grand_total -= quantity_discount
28. print(f"5% Quantity Discount applied: ₹{quantity_discount:.2f}")
29.
30. membership = input("Is the customer a member? (y/n): ")
31. if membership.lower() == 'y':
32. member_discount = grand_total * 0.02
33. grand_total -= member_discount
34. print(f"2% Membership Discount applied: ₹{member_discount:.2f}")
35.
36. print(f"Final Grand Total after all adjustments: ₹{grand_total:.2f}")
TalenciaGlobal HandsOn Framework - THLF
Solution:
1. # Level 5: Tax Calculation Based on Purchase Amount
2. # Assuming grand_total from previous levels
3.
4. if grand_total < 5000:
5. tax = grand_total * 0.05
6. elif 5000 <= grand_total <= 20000:
7. tax = grand_total * 0.10
8. else:
9. tax = grand_total * 0.15
10.
11. grand_total += tax
12. print(f"Tax Applied: ₹{tax:.2f}")
13. print(f"Final Grand Total after tax: ₹{grand_total:.2f}")
Solution:
1. PROMO_CODE = "PROMO10"
2. promo_discount_total = 0 # To track total promotional discounts
3. while True:
4. item_code = input("Enter item code: ")
5. description = input("Enter item description: ")
6. quantity = int(input("Enter quantity: "))
7. price = float(input("Enter price per unit: "))
8.
9. item_total = quantity * price
10. if item_code == PROMO_CODE:
11. promo_discount = item_total * 0.10
12. item_total -= promo_discount
13. promo_discount_total += promo_discount
14. print(f"10% Promotional Discount applied: ₹{promo_discount:.2f}")
15.
16. grand_total += item_total
17. print(f"Item Total after promo: ₹{item_total:.2f}")
18.
19. another_item = input("Add another item? (y/n): ")
20. if another_item.lower() != 'y':
TalenciaGlobal HandsOn Framework - THLF
21. break
Solution:
1. # Level 7: Payment Mode Rules
2. payment_mode = input("Select payment method (cash/card): ").lower()
3. if payment_mode == "card":
4. surcharge = grand_total * 0.02
5. grand_total += surcharge
6. print(f"2% Surcharge for card payment applied: ₹{surcharge:.2f}")
7.
8. print(f"Final Payable Amount: ₹{grand_total:.2f}")
Solution:
1. # Level 8: Minimum Purchase Requirements
2. if grand_total < 500:
3. print("Minimum purchase value of ₹500 is required to generate an invoice.")
4. else:
5. print(f"Invoice Generated. Final Amount: ₹{grand_total:.2f}")
Solution:
1. # Level 9: Loyalty Points
2. loyalty_points = int(grand_total // 100)
3. print(f"Loyalty Points Earned: {loyalty_points}")
Solution:
1. N = int(input("Enter the number of rows: "))
2.
3. # Loop to print * pattern in N rows
4. for row in range(1, N + 1):
5. for num in range(1, N + 1):
6. print(“*”, end="")
7. print() # Move to next line after each row
Solution:
1. N = int(input("Enter the number of rows: "))
2.
3. # Loop to print number pattern in N rows
4. for row in range(1, N + 1):
5. for num in range(1, N + 1):
6. print(row, end="")
7. print() # Move to next line after each row
TalenciaGlobal HandsOn Framework - THLF
Solution:
1. N = int(input("Enter the number of rows: "))
2.
3. # Loop to print number pattern in N rows
4. for row in range(1, N + 1):
5. for num in range(1, N + 1):
6. print(number, end="")
7. print() # Move to next line after each row
Solution:
1. # Printing Star Pattern (Increasing Stars) using Nested Loops
2. N = int(input("Enter the number of rows: "))
3.
4. # Outer loop for the rows
5. for row in range(1, N + 1):
6. # Inner loop for printing '*' in each row
7. for col in range(1, row + 1):
8. print('*', end='')
9. print() # Move to the next line after each row
Solution:
1. # Printing Star Pattern (Increasing Stars) using Nested Loops
2. N = int(input("Enter the number of rows: "))
3.
4. # Outer loop for the rows
5. for row in range(1, N + 1):
6. # Inner loop for printing number in each row
7. for col in range(1, row + 1):
8. print(row, end='')
9. print() # Move to the next line after each row
Solution:
1. # Printing Star Pattern (Increasing Stars) using Nested Loops
2. N = int(input("Enter the number of rows: "))
3.
4. # Outer loop for the rows
5. for row in range(1, N + 1):
6. # Inner loop for printing number in each row
7. for col in range(1, row + 1):
8. print(col, end='')
9. print() # Move to the next line after each row
Solution:
1. # Printing Fibonacci Pattern in Rows
2. N = int(input("Enter the number of rows: "))
3. # Initialize the first two Fibonacci numbers
4. a, b = 1, 1
5.
6. # Outer loop for the rows
7. for row in range(1, N + 1):
8. # Inner loop to print Fibonacci numbers in each row
9. for col in range(1, row + 1):
10. print(a, end=" ")
11. # Update Fibonacci numbers
12. a, b = b, a + b
13. print() # Move to the next line after each row
TalenciaGlobal HandsOn Framework - THLF
Coding Challenge 46: Printing Pattern of Perfect Squares with Alternating Signs in N
Rows
1
-4 9
-16 25 -36
49 -64 81 -100
.
N rows
Solution:
1. # Printing Pattern of Perfect Squares with Alternating Signs in Rows
2. N = int(input("Enter the number of rows: "))
3. # Variable to track the sign (1 or -1)
4. sign = 1
5.
6. # Outer loop for the rows
7. for row in range(1, N + 1):
8. # Inner loop to print perfect squares in each row
9. for col in range(1, row + 1):
10. print(sign * (col * col), end=" ")
11. # Switch the sign for the next number
12. sign *= -1
13. print() # Move to the next line after each row
Solution:
1. # Printing Pattern of Factorials in Rows
2. N = int(input("Enter the number of rows: "))
3.
4. # Outer loop for the rows
5. for row in range(1, N + 1):
6. factorial = 1
7. # Inner loop to print factorials in each row
8. for col in range(1, row + 1):
9. # Calculate factorial iteratively
10. factorial = factorial * col
11. print(factorial, end=" ")
12. print() # Move to the next line after each row
Solution:
1. # Input number
2. num = int(input("Enter a number: "))
3.
4. # Initializing an empty string for the word output
5. words = ""
6.
7. # Loop until the number becomes 0
8. while num > 0:
9. # Get the last digit of the number
10. digit = num % 10
11.
12. # Convert digit to corresponding word
13. if digit == 0:
14. words = "Zero " + words
15. elif digit == 1:
16. words = "One " + words
17. elif digit == 2:
18. words = "Two " + words
19. elif digit == 3:
20. words = "Three " + words
21. elif digit == 4:
22. words = "Four " + words
23. elif digit == 5:
24. words = "Five " + words
25. elif digit == 6:
26. words = "Six " + words
27. elif digit == 7:
28. words = "Seven " + words
29. elif digit == 8:
30. words = "Eight " + words
31. elif digit == 9:
32. words = "Nine " + words
33.
34. # Remove the last digit from the number
35. num = num // 10
36.
37. # Display the result
38. print(words.strip())
Coding Challenge 49: Generate Series - 1, -5, 9, -13, 17, -21, ... N
Solution:
1. # Input for N (the number of terms in the sequence)
2. n = int(input("Enter the number of terms: "))
3.
4. # Initializing the first term
5. term = 1
6.
7. # Loop through and generate the series
8. for i in range(n):
9. print(term, end=" ")
10.
11. # Switch sign and add 4 for the next term
12. term = term + 4 if i % 2 == 0 else term – 4
TalenciaGlobal HandsOn Framework - THLF
Solution:
1. # Accept a double value from the user
2. num = float(input("Enter a double value: "))
3.
4. # Separate the whole part and fractional part using mathematical logic
5. whole_part = int(num) # Extract the whole part (integer part)
6. fractional_part = num - whole_part # Calculate the fractional part by subtracting the whole
part
7.
8. # Display the results
9. print(f"Whole part: {whole_part}")
10. print(f"Fractional part: {fractional_part:.6f}") # Displaying the fractional part with 6
decimal places
Solution:
1. # Input the number
2. num = int(input("Enter a number: "))
3. original_num = num # Store the original number for display
4. reverse = 0 # Initialize the reverse variable
5.
6. # Reverse the number using mathematical operations
7. while num > 0:
8. digit = num % 10 # Extract the last digit
9. reverse = reverse * 10 + digit # Append the digit to the reversed number
10. num = num // 10 # Remove the last digit from the number
11.
12. # Display the result
13. print(f"The reverse of {original_num} is {reverse}.")
Coding Challenge 52: Level 0: Write a program to accept n and store the elements into
the array of size n.
Solution:
1. n = int(input("Enter the size of the array (n): "))
2.
3. my_array = []
4.
5. print("Enter the elements:")
6. for _ in range(n):
7. element = int(input()) # Get input for each element
8. my_array.append(element)
9.
10. print("Elements stored in the array:")
11. for element in my_array:
12. print(element, end=" ")
13. print()
TalenciaGlobal HandsOn Framework - THLF
Coding Challenge 53: Level 1: Find the Sum of all elements in the array
Solution:
1. my_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Example array
2. sum_of_elements = 0 # Initialize the sum
3. # Iterate through the array and add each element to the sum.
4. for element in my_array:
5. sum_of_elements = sum_of_elements + element
6. print("Sum of elements:", sum_of_elements)
Coding Challenge 54: Level 2: Find the Minimum value of all elements in the array
Solution:
1. my_array = [3, 7, 1, 9, 2, 5]
2. minimum = my_array[0]
3. for element in my_array:
4. if element < minimum:
5. minimum = element
6. print("Minimum:", minimum)
Coding Challenge 55: Level 3: Find the Maximum value of all elements in the array
Solution:
1. my_array = [3, 7, 1, 9, 2, 5]
2. maximum = my_array[0]
3. for element in my_array:
4. if element > maximum:
5. maximum = element
6. print("Maximum:", maximum)
Coding Challenge 56: Level 4: Search the given element from the array
Solution:
1. my_array = [10, 20, 30, 40, 50]
2. target_element = 30 # The element to search for
3.
4. element_exists = False # Initialize a flag to track if the element exists
5.
6. # Iterate through the array and check if the target element is present
7. for element in my_array:
8. if element == target_element:
9. element_exists = True # Set the flag to True if the element is found
10. break # Exit the loop early once the element is found
11.
12. # Print the result
13. if element_exists:
14. print(target_element, "exists in the array.")
15. else:
16. print(target_element, "does not exist in the array.")
TalenciaGlobal HandsOn Framework - THLF
Coding Challenge 57: Level 5: Display the number of odd and even numbers from the
array
Solution:
1. my_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2.
3. even_count = 0
4. odd_count = 0
5.
6. # Iterate through the array and check each element
7. for element in my_array:
8. if element % 2 == 0: # Check if the element is divisible by 2
9. even_count += 1
10. else:
11. odd_count += 1
12.
13. print("Number of even elements:", even_count)
14. print("Number of odd elements:", odd_count)
Coding Challenge 58: Level 0: Write a program to accept n and store the elements into
the array of size n.
Solution:
1. n = int(input("Enter the size of the array (n): "))
2.
3. my_array = []
4.
5. print("Enter the elements:")
6. for _ in range(n):
7. element = int(input()) # Get input for each element
8. my_array.append(element)
9.
10. print("Elements stored in the array:")
11. for element in my_array:
12. print(element, end=" ")
13. print()
Coding Challenge 60: Level 2: Sort the array in ascending or descending order based
on input of user
Solution:
1. # Bubble Sort with order control
2. length = 0
3. for _ in my_array:
4. length += 1
5.
6. for i in range(length - 1):
7. for j in range(length - 1 - i):
8. if sort_order.lower() == 'a': # Ascending order
9. if my_array[j] > my_array[j + 1]:
10. temp = my_array[j]
11. my_array[j] = my_array[j + 1]
12. my_array[j + 1] = temp
13. elif sort_order.lower() == 'd': # Descending order
14. if my_array[j] < my_array[j + 1]: # Reverse the comparison for descending
15. temp = my_array[j]
16. my_array[j] = my_array[j + 1]
17. my_array[j + 1] = temp
18. else:
19. print("Invalid input. Please type either 'a' or 'd'")
20.
21. print("Sorted array:")
22. for element in my_array:
23. print(element, end=" ")
24. print()
Solution:
1. # Sort the array (using bubble sort as before) - Binary Search requires a sorted array.
2. length = 0
3. for _ in my_array:
4. length += 1
5.
6. for i in range(length - 1):
7. for j in range(length - 1 - i):
8. if my_array[j] > my_array[j + 1]:
9. temp = my_array[j]
10. my_array[j] = my_array[j + 1]
11. my_array[j + 1] = temp
12.
13. print("Sorted array:", my_array) # Display the sorted array
14.
15.
16. # Binary Search
17. search_number = int(input("Enter the number to search for: "))
18.
19.
20. low = 0
21. high = length - 1
22. found = False
23.
24.
25. while low <= high: #set the condition of while loop
26.
27. mid = (low + high) // 2 #find the middle element
28.
29.
30. if my_array[mid] == search_number:
31. found = True
32. break
33.
TalenciaGlobal HandsOn Framework - THLF
2D Arrays
Coding Challenge 62: Write a program to create a 2D array and display its elements
row-wise
Solution:
1. # Program to create and display a 2D array row-wise
2.
3. # Create a 2D array (list of lists)
4. rows = int(input("Enter the number of rows: "))
5. cols = int(input("Enter the number of columns: "))
6.
7. # Initialize the array
8. array = []
9.
10. # Input elements into the 2D array
11. print("Enter the elements row by row:")
12. for i in range(rows):
13. row = []
14. for j in range(cols):
15. element = int(input(f"Enter element for row {i+1}, column {j+1}: "))
16. row.append(element)
17. array.append(row)
18.
19. # Display the elements row-wise
20. print("\nThe 2D array row-wise:")
21. for row in array:
22. print(row)
Coding Challenge 63: Create a program to compute the sum of all elements in a 2D
array.
Solution:
1. # Create a 2D array (list of lists)
2. rows = int(input("Enter the number of rows: "))
3. cols = int(input("Enter the number of columns: "))
4.
5. array = []
6. # Input elements into the 2D array
7. print("Enter the elements row by row:")
8. for i in range(rows):
9. row = []
10. for j in range(cols):
11. element = int(input(f"Enter element for row {i+1}, column {j+1}: "))
12. row.append(element)
13. array.append(row)
TalenciaGlobal HandsOn Framework - THLF
14.
15. # Calculate the sum of all elements
16. total_sum = 0
17. for row in array:
18. total_sum += sum(row)
19.
20. # Display the total sum
21. print("\nThe sum of all elements in the 2D array is:", total_sum)
Coding Challenge 64: Write a program to check if a given element exists in a 2D array
Solution:
1. # Program to check if a given element exists in a 2D array
2.
3. # Create a 2D array (list of lists)
4. rows = int(input("Enter the number of rows: "))
5. cols = int(input("Enter the number of columns: "))
6.
7. # Initialize the array
8. array = []
9.
10. # Input elements into the 2D array
11. print("Enter the elements row by row:")
12. for i in range(rows):
13. row = []
14. for j in range(cols):
15. element = int(input(f"Enter element for row {i+1}, column {j+1}: "))
16. row.append(element)
17. array.append(row)
18.
19. # Input the element to search for
20. search_element = int(input("\nEnter the element to search for: "))
21.
22. # Check if the element exists in the array
23. found = False
24. for row in array:
25. if search_element in row:
26. found = True
27. break
28.
29. # Display the result
30. if found:
31. print(f"\nThe element {search_element} exists in the 2D array.")
32. else:
33. print(f"\nThe element {search_element} does not exist in the 2D array.")
Solution:
1. # Program to store elements in a matrix and display its transpose
2.
3. # Input the dimensions of the matrix
4. rows = int(input("Enter the number of rows (M): "))
5. cols = int(input("Enter the number of columns (N): "))
6.
7. # Initialize the matrix
8. matrix = []
9.
10. # Input elements into the matrix
11. print("Enter the elements row by row:")
12. for i in range(rows):
13. row = []
TalenciaGlobal HandsOn Framework - THLF
Solution:
1. # Input the dimensions of the matrices
2. rows = int(input("Enter the number of rows: "))
3. cols = int(input("Enter the number of columns: "))
4.
5. # Input the first matrix
6. print("\nEnter the elements of the first matrix:")
7. matrix1 = []
8. for i in range(rows):
9. row = []
10. for j in range(cols):
11. element = int(input(f"Enter element for row {i+1}, column {j+1}: "))
12. row.append(element)
13. matrix1.append(row)
14.
15. # Input the second matrix
16. print("\nEnter the elements of the second matrix:")
17. matrix2 = []
18. for i in range(rows):
19. row = []
20. for j in range(cols):
21. element = int(input(f"Enter element for row {i+1}, column {j+1}: "))
22. row.append(element)
23. matrix2.append(row)
24.
25. # Initialize matrices for addition and subtraction
26. addition = [[0 for _ in range(cols)] for _ in range(rows)]
27. subtraction = [[0 for _ in range(cols)] for _ in range(rows)]
28.
29. # Perform addition and subtraction
30. for i in range(rows):
31. for j in range(cols):
32. addition[i][j] = matrix1[i][j] + matrix2[i][j]
33. subtraction[i][j] = matrix1[i][j] - matrix2[i][j]
34.
35. # Display the results
36. print("\nMatrix 1:")
37. for row in matrix1:
38. print(row)
39. print("\nMatrix 2:")
40. for row in matrix2:
41. print(row)
42.
43. print("\nAddition of the matrices:")
44. for row in addition:
TalenciaGlobal HandsOn Framework - THLF
45. print(row)
46. print("\nSubtraction of the matrices:")
47. for row in subtraction:
48. print(row)
Solution:
1. # Input the dimensions of the matrices
2. rows1 = int(input("Enter the number of rows in the first matrix: "))
3. cols1 = int(input("Enter the number of columns in the first matrix: "))
4. rows2 = int(input("Enter the number of rows in the second matrix: "))
5. cols2 = int(input("Enter the number of columns in the second matrix: "))
6.
7. # Ensure that the number of columns in the first matrix matches the number of rows in the
second matrix
8. if cols1 != rows2:
9. print("\nMatrix multiplication is not possible. The number of columns in the first
matrix must equal the number of rows in the second matrix.")
10. else:
11. # Input the first matrix
12. print("\nEnter the elements of the first matrix:")
13. matrix1 = []
14. for i in range(rows1):
15. row = []
16. for j in range(cols1):
17. element = int(input(f"Enter element for row {i+1}, column {j+1}: "))
18. row.append(element)
19. matrix1.append(row)
20.
21. # Input the second matrix
22. print("\nEnter the elements of the second matrix:")
23. matrix2 = []
24. for i in range(rows2):
25. row = []
26. for j in range(cols2):
27. element = int(input(f"Enter element for row {i+1}, column {j+1}: "))
28. row.append(element)
29. matrix2.append(row)
30.
31. # Initialize the resulting matrix
32. result = [[0 for _ in range(cols2)] for _ in range(rows1)]
33.
34. # Perform matrix multiplication
35. for i in range(rows1):
36. for j in range(cols2):
37. for k in range(cols1):
38. result[i][j] += matrix1[i][k] * matrix2[k][j]
39.
40. # Display the resulting matrix
41. print("\nResultant Matrix after multiplication:")
42. for row in result:
43. print(row)
· CT Scan
· MRI
Once the services are set, the hospital welcomes patients who require seamless and efficient billing
processes. The objective is to build a robust system where patient information, service selection,
billing, and tax calculations are handled smoothly while keeping the user experience intuitive and
error-free.
Consider these 2 arrays (Declare them initially)
Services: ["General Consultation", "Blood Test", "Covid Test", "X-Ray", "CT Scan", "MRI"]
Costs: [500, 300, 800, 1500, 4000, 7000]
Requirements & Levels
Solution:
1. # HealWell Care Hospital Patient Management System - Level 1
2. # --- Initial Data (Arrays) ---
3. services = ["General Consultation", "Blood Test", "Covid Test", "X-Ray", "CT Scan", "MRI"]
4. costs = [500, 300, 800, 1500, 4000, 7000]
5. # --- Patient Details Input ---
6. name = input("Enter patient name: ")
7. age = int(input("Enter patient age: "))
8. gender = input("Enter patient gender: ")
9. contact = input("Enter patient contact number: ") # Store as string for flexibility
Solution:
1. # HealWell Care Hospital Patient Management System - Level 2
2.
3. # --- Display Available Services ---
4. print("\n--- Available Services ---")
5. for i in range(len(services)):
6. print(f"{i+1}. {services[i]}")
7.
TalenciaGlobal HandsOn Framework - THLF
Solution:
1. # HealWell Care Hospital Patient Management System - Level 3
2.
3. # ... (Code from Level 1 and 2) ...
4.
5.
6. # --- Fetching Costs of Selected Services ---
7. selected_costs = []
8. for selected_service in selected_services:
9. for i in range(len(services)): #loop through the services list
10. if services[i] == selected_service: #find the cost of the matching service
11. selected_costs.append(costs[i]) #append cost to selected_costs
12. break # Exit inner loop once the service is found
13.
14. # --- Display Selected Services and Costs ---
15. print("\n--- Selected Services and Costs ---")
16. for i in range(len(selected_services)):
17. print(f"{selected_services[i]}: {selected_costs[i]}")
TalenciaGlobal HandsOn Framework - THLF
Solution:
1. # HealWell Care Hospital Patient Management System - Level 4
2.
3. # ... (Code from Level 1, 2, and 3) ...
4.
5. # --- Calculating Total Cost ---
6. total_cost = 0
7. for cost in selected_costs:
8. total_cost += cost
9.
10. patient_details["total_cost"] = total_cost # Update the patient's total cost
11.
12. # --- Display Total Cost ---
13. print("\n--- Total Cost (Before Tax) ---")
14. print(f"₹{total_cost}")
Solution:
1. # HealWell Care Hospital Patient Management System - Level 5
2.
3. # ... (Code from Level 1, 2, 3, and 4) ...
4.
5. # --- Applying GST ---
6. gst_percentage = 18
7. gst_amount = (total_cost * gst_percentage) / 100
8. grand_total = total_cost + gst_amount
9.
10.
11. # --- Display Bill with GST ---
12. print("\n--- Final Bill ---")
13. print(f"Total Cost (Before Tax): ₹{total_cost}")
14. print(f"GST ({gst_percentage}%): ₹{gst_amount}") #GST amount calculated
15. print(f"Grand Total: ₹{grand_total}")
Contact: 9876543210
Services Availed:
1. General Consultation: ₹500
2. X-Ray: ₹1500
Subtotal: ₹2000
GST (18%): ₹360
Grand Total: ₹2360
Thank you for choosing HealWell Care Hospital!
-----------------------------------------------
Solution:
1. # HealWell Care Hospital Patient Management System - Level 6 (Using variables)
2.
3. # ... (Code for Levels 1, 2, 3, 4, and 5 remains the same) ...
4.
5. # --- Generating and Displaying the Invoice ---
6. print("-----------------------------------------------")
7. print("HealWell Care Hospital")
8. print("Patient Invoice")
9. print("-----------------------------------------------\n")
10.
11. print("Patient Information:")
12. print(f"Name: {name}")
13. print(f"Age: {age}")
14. print(f"Gender: {gender}")
15. print(f"Contact: {contact}")
16. print()
17.
18. print("Services Availed:")
19. for i in range(len(selected_services)):
20. print(f"{i+1}. {selected_services[i]}: ₹{selected_costs[i]}")
21. print()
22.
23. print(f"Subtotal: ₹{total_cost}")
24. print(f"GST ({gst_percentage}%): ₹{gst_amount}")
25. print(f"Grand Total: ₹{grand_total}\n")
26.
27. print("Thank you for choosing HealWell Care Hospital!")
28. print("-----------------------------------------------")
Coding Challenge 74: Setting Up the Services of the Day (Admin Task)
The admin prepares the hospital system by entering the available services into the system. Hospital
wants the flexibility to configure the services. This list is stored in an array. Each service has a name,
and its corresponding cost is stored in a separate array for flexibility.
· Array 1: Stores the names of services (services array).
· Array 2: Stores the costs of the services (costs array).
Example Input:
Services: ["General Consultation", "Blood Test", "Covid Test", "X-Ray", "CT Scan", "MRI"]
Costs: [500, 300, 800, 1500, 4000, 7000]
Objective: Ensure services and costs are paired for seamless retrieval.
Solution:
1. # HealWell Care Hospital Patient Management System - Level 7 (Admin Setup)
2.
3. # --- Admin Service Setup ---
4.
5. num_services = int(input("Enter the number of services available today: "))
6.
7. services = []
TalenciaGlobal HandsOn Framework - THLF
8. costs = []
9.
10. print("Enter the services and their costs:")
11. for i in range(num_services):
12. service_name = input(f"Enter service name {i+1}: ")
13. services.append(service_name)
14.
15. while True: #input validation loop
16. try:
17. service_cost = int(input(f"Enter cost for {service_name}: "))
18. if service_cost > 0: #basic check if cost makes sense
19. costs.append(service_cost)
20. break
21. else:
22. print("Invalid cost, please enter amount > 0")
23.
24. except ValueError:
25. print("Invalid input. Please enter a valid integer.")
Solution:
1. # HealWell Care Hospital Patient Management System - Level 8 (Discounts)
2. # ... (Code from Level 1, 2, 3, 4, 5, and 7) ...
3.
4. # --- Discounts ---
5. discount_percentage = 0
6.
7. if age >= 60:
8. discount_percentage += 10 # Senior citizen discount
9. print("---senior discount applied")
10.
11. if total_cost > 5000:
12. discount_percentage += 5 # High-bill discount
13. print("---high bill discount applied")
14.
15. discount_amount = (total_cost * discount_percentage) / 100
16. total_cost_after_discount = total_cost - discount_amount
17.
18. # --- Applying GST (after discounts) ---
19. gst_percentage = 18
20. gst_amount = (total_cost_after_discount * gst_percentage) / 100
21. grand_total = total_cost_after_discount + gst_amount
22.
23. # --- Generating and Displaying the Invoice (modified for discounts) ---
24. # ... (Same as Level 6, but now print total_cost_after_discount if there's a discount) ...
25.
26. print("-----------------------------------------------")
27. print("HealWell Care Hospital")
28. print("Patient Invoice")
29. print("-----------------------------------------------\n")
TalenciaGlobal HandsOn Framework - THLF
30.
31. # ... (Patient information - same as before)
32.
33. print("Services Availed:")
34. for i in range(len(selected_services)):
35. print(f"{i+1}. {selected_services[i]}: ₹{selected_costs[i]}")
36. print()
37.
38. if discount_percentage>0: #print discount information in invoice only if discount is applied
39. print(f"Subtotal: ₹{total_cost}")
40. print(f"Discount ({discount_percentage}%): -₹{discount_amount}")
41. print(f"Total After Discount: ₹{total_cost_after_discount}")
42.
43.
44. else: #print total cost normally if there is no discount
45. print(f"Total Cost (before GST): ₹{total_cost}")
46.
47.
48. print(f"GST ({gst_percentage}%): ₹{gst_amount}")
49. print(f"Grand Total: ₹{grand_total}\n")
50.
51. print("Thank you for choosing HealWell Care Hospital!")
52. print("-----------------------------------------------")
Coding Challenge 76: Write a Function to display “Welcome to the world of functions”
Solution:
1. def display_welcome_message():
2. """Displays a welcome message.""" # Docstring (good practice!)
3.
4. print("Welcome to the world of functions")
5.
6. # Call the function to display the message
7. display_welcome_message()
Solution:
1. def add_two_numbers(num1, num2):
2. """Adds two numbers and returns the sum."""
3.
4. sum_result = num1 + num2
5. return sum_result
6.
7.
8. # Example usage:
9. number1 = 10
10. number2 = 20
11. sum_of_numbers = add_two_numbers(number1, number2) # Call the function
12. print("Sum:", sum_of_numbers)
Solution:
1. def check_even_odd(number):
2. """Checks if a number is even or odd and prints the result."""
3.
4. if number % 2 == 0:
TalenciaGlobal HandsOn Framework - THLF
5. print(f"{number} is even")
6. else:
7. print(f"{number} is odd")
8.
9. # Example usage
10. check_even_odd(10) # Output: 10 is even
11. check_even_odd(7) # Output: 7 is odd
Solution:
1. def celsius_to_fahrenheit(celsius):
2. """Converts Celsius to Fahrenheit and returns the result."""
3.
4. fahrenheit = (celsius * 9/5) + 32
5. return fahrenheit
6.
7. # Example usage
8. celsius_temp = 25
9. fahrenheit_temp = celsius_to_fahrenheit(celsius_temp)
10. print(f"{celsius_temp}°C is equal to {fahrenheit_temp}°F")
Solution:
1. def factorial(n):
2. """Calculates the factorial of a non-negative integer."""
3.
4. if n < 0:
5. print("Factorial is not defined for negative numbers.")
6. return None # Or raise an exception (ValueError)
7.
8. elif n == 0:
9. return 1
10. else:
11. fact = 1
12. for i in range(1, n + 1):
13. fact *= i # Equivalent to fact = fact * i
14. return fact
15.
16. # Example usage
17. number = 5
18. result = factorial(number)
19. if result is not None: # Check if factorial is defined
20. print(f"The factorial of {number} is {result}")
21.
22. number = -3
23. factorial(number) #this will print the print statement inside the function
Coding Challenge 81: Write a program to accept a student’s name and scores in three
subjects.
Display the total, average, and class secured based on the following criteria:• 1st Class:
Average score of 60 and above. • 2nd Class: Average score of 50 and above. • Pass
Class: Average score of 35 and above. • Fail: Average score less than 35. Function to
accept name and marks Function to calculate result Function to display name, marks
in 3 subjects and result
TalenciaGlobal HandsOn Framework - THLF
Solution:
1. def get_student_details():
2. """Gets student name and marks in three subjects."""
3.
4. name = input("Enter student name: ")
5. marks = []
6. for i in range(3): # Loop for 3 subjects
7. while True:
8. try:
9. mark = float(input(f"Enter marks for subject {i+1}: "))
10. if 0 <= mark <= 100: # Validate marks (0-100)
11. marks.append(mark)
12. break
13. else:
14. print("Invalid marks. Marks should be between 0 and 100.")
15. except ValueError:
16. print("Invalid input. Please enter a number.")
17. return name, marks
18.
19.
20. def calculate_result(marks):
21. """Calculates total, average, and class based on marks."""
22.
23. total = sum(marks)
24. average = total / len(marks)
25.
26. if average >= 60:
27. class_secured = "1st Class"
28. elif average >= 50:
29. class_secured = "2nd Class"
30. elif average >= 35:
31. class_secured = "Pass Class"
32. else:
33. class_secured = "Fail"
34.
35. return total, average, class_secured
36.
37.
38. def display_result(name, marks, total, average, class_secured):
39. """Displays student details and results."""
40.
41. print("\n--- Student Result ---")
42. print("Name:", name)
43. for i, mark in enumerate(marks): #prints the marks in all the three subjects
44. print(f"Subject {i + 1}: {mark}")
45.
46. print("Total:", total)
47. print("Average:", average)
48. print("Class:", class_secured)
49.
50. # Main program
51. name, marks = get_student_details()
52. total, average, class_secured = calculate_result(marks)
53. display_result(name, marks, total, average, class_secured)