Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Coding Challenges - SRM Coding Bootcamp

The document outlines a series of coding challenges designed for a coding bootcamp, categorized into various programming concepts such as sequence programming, decision making, loops, arrays, and more. Each challenge includes a problem statement and a solution, providing practical coding exercises for learners. The challenges cover a range of topics from basic arithmetic operations to more complex data structures and algorithms.

Uploaded by

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

Coding Challenges - SRM Coding Bootcamp

The document outlines a series of coding challenges designed for a coding bootcamp, categorized into various programming concepts such as sequence programming, decision making, loops, arrays, and more. Each challenge includes a problem statement and a solution, providing practical coding exercises for learners. The challenges cover a range of topics from basic arithmetic operations to more complex data structures and algorithms.

Uploaded by

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

Coding Challenges

Coding Bootcamp

TalenciaGlobal Coding Challenges


TalenciaGlobal HandsOn Framework - THLF

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

Coding Challenge 59: Level 1: Reverse the given array. ................................................................... 30


Coding Challenge 60: Level 2: Sort the array in ascending or descending order based on input of
user ....................................................................................................................................................31
Coding Challenge 61: Level 3: Implement Binary Search on the array. ............................................31
2D Arrays ...............................................................................................................................................32
Coding Challenge 62: Write a program to create a 2D array and display its elements row-wise .... 32
Coding Challenge 63: Create a program to compute the sum of all elements in a 2D array. .......... 32
Coding Challenge 64: Write a program to check if a given element exists in a 2D array ................. 33
Coding Challenge 65: Write a program to store elements into a M * N matrix of integer. Display
the matrix and its transpose. ............................................................................................................ 33
Coding Challenge 66: Write a program to store elements into a M * N matrix of integer. Display
the matrix and its transpose. ............................................................................................................ 34
Coding Challenge 67: Write a program to multiply two matrices .................................................... 35
Setting the Scene: A Day at HealWell Care Hospital .........................................................................35
Coding Challenge 68: Patient Walks In and Shares Their Details ..................................................... 36
Coding Challenge 69: Displaying Services for Patient Selection ....................................................... 36
Coding Challenge 70: Fetching Costs of Selected Services ............................................................... 37
Coding Challenge 71: Calculating the Total Cost ...............................................................................38
Coding Challenge 72: Applying GST to the Bill .................................................................................. 38
Coding Challenge 73: Generating and Displaying the Invoice .......................................................... 38
Coding Challenge 74: Setting Up the Services of the Day (Admin Task) ...........................................39
Coding Challenge 75: Providing Discounts (Optional Enhancements) ............................................. 40
Working with Arrays ............................................................................................................................. 41
Coding Challenge 76: Write a Function to display “Welcome to the world of functions” ............... 41
Coding Challenge 77: Write a Function to add two numbers ...........................................................41
Coding Challenge 78: Write a Function check if a Number is Even or Odd ...................................... 41
Coding Challenge 81: Write a program to accept a student’s name and scores in three subjects. .42
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

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)

Coding Challenge 2: Program to calculate simple interest

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)

Coding Challenge 3: Program to calculate the discount on the 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

Coding Challenge 4: Program to swap two numbers

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)

Coding Challenge 5: Farmer Problem Statement


Mahesh is a farmer and owns 80 acres of land. His land is equally divided into 5 segments. He grows
tomatoes in the 1st segment, potatoes in the 2nd segment, cabbage in the 3rd segment, sunflower in
the 4th segment and sugarcane in the 5th segment. He is converting his land from chemical-driven
farming to chemical-free farming. Mahesh starts with the conversion of vegetables into chemical-
free
produce. He spends the first 6 months doing the same. He then converts the sunflower land bank
into chemical-free farming. This takes him another 4 months. Finally, he converts sugarcane into
chemical-free farming over the next 4 months. He gets a yield of the following for tomatoes. 30% of
his tomato land gives him 10 tonne yield per acre. The remaining 70% of his tomato land gives him
12 tonnes yield per acre. The selling price of tomato is Rs. 7 per Kg. The yield of potatoes is 10 tonnes
per acre. He sells each kg at Rs. 20. The yield of cabbage is 14 tonnes per acre. He sells each kg at Rs.
24. The yield of sunflowers is 0.7 tonnes per acre. He sells each kg at Rs. 200. The yield of sugarcane
is 45 tonnes per acre. He sells each tonne at Rs. 4,000. All the crops are sowed at the same time.
Mahesh gets the above yield at the above-mentioned rate in one crop cycle across his entire land of
80 acres.
What is
a. The overall sales achieved by Mahesh from the 80 acres of land.
b. Sales realisation from chemical-free farming at the end of 11 months

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

18. total_yield_tomatoes = yield_30 + yield_70


19. total_sales += total_yield_tomatoes * 1000 * crops["tomatoes"]["price_per_kg"] # kg to tonne
20. conversion
21. # Calculate for potatoes
22. total_yield_potatoes = crops["potatoes"]["yield_per_acre"] * segment_land
23. total_sales += total_yield_potatoes * 1000 * crops["potatoes"]["price_per_kg"]
24.
25. # Calculate for cabbage
26. total_yield_cabbage = crops["cabbage"]["yield_per_acre"] * segment_land
27. total_sales += total_yield_cabbage * 1000 * crops["cabbage"]["price_per_kg"]
28.
29. # Calculate for sunflower
30. total_yield_sunflower = crops["sunflower"]["yield_per_acre"] * segment_land
31. total_sales += total_yield_sunflower * 1000 * crops["sunflower"]["price_per_kg"]
32.
33. # Calculate for sugarcane
34. total_yield_sugarcane = crops["sugarcane"]["yield_per_acre"] * segment_land
35. total_sales += total_yield_sugarcane * crops["sugarcane"]["price_per_ton"]
36.
37. # Part (b) Sales realisation from chemical-free farming after 11 months
38. chemical_free_sales = 0
39.
40. # After 6 months, vegetables (tomatoes, potatoes, cabbage) are chemical-free
41. chemical_free_sales += total_yield_tomatoes * 1000 * crops["tomatoes"]["price_per_kg"]
42. chemical_free_sales += total_yield_potatoes * 1000 * crops["potatoes"]["price_per_kg"]
43. chemical_free_sales += total_yield_cabbage * 1000 * crops["cabbage"]["price_per_kg"]
44.
45. # After 10 months, sunflowers are also chemical-free
46. chemical_free_sales += total_yield_sunflower * 1000 * crops["sunflower"]["price_per_kg"]
47.
48. # After 11 months, sugarcane is also chemical-free
49. chemical_free_sales += total_yield_sugarcane * crops["sugarcane"]["price_per_ton"]
50.
51. # Results
52. print(f"Overall sales achieved by Mahesh from 80 acres: Rs. {total_sales:,.2f}")
53. print(f"Sales realisation from chemical-free farming after 11 months: Rs.
{chemical_free_sales:,.2f}")

Decision Making

Coding Challenge 6: Program to check if a number is even or odd

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

7. print(f"{name} has an annual salary of ₹{salary}.")


8. print(f"{name} has to pay taxes.")
9. else:
10. print(f"{name} has an annual salary of ₹{salary}.")
11. print(f"{name} does not have to pay taxes.")

Coding Challenge 8: To find the largest of 3 numbers

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)

Coding Challenge 9: Program to check if a year given is a leap year or not

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")

Coding Challenge 10: Student Report Card Problem


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.

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)

Tax Calculator Problem– Hackathon


GlobalNext Solutions, a rapidly growing IT company, employs a diverse workforce ranging from entry-
level developers to senior executives. The HR department wants to streamline the tax calculation
process for employees under the New Tax Regime (2023). They’ve decided to build a tax calculation
program that computes salaries, taxes, and net incomes while ensuring compliance with the latest
tax laws.
As a software developer in GlobalNext’s HR-Tech team, you are tasked with developing this program.
The system should process employee salary details, validate inputs, calculate taxes, and generate
detailed reports.
The program should:
1. Accept employee details, including monthly salary components.
2. Calculate gross and taxable income according to the New Tax Regime (2023).
3. Compute the tax payable using the appropriate tax sCoding Challenges.
4. Apply any applicable standard deductions and rebates.
Generate reports detailing gross salary, taxable income, tax payable, and net salary.

Coding Challenge 11: Basic Input and Salary Calculation


Objective: Capture employee details and calculate the gross salary.
Tasks:
 Accept the following inputs for an employee:
o Name
o EmpID
o Basic Monthly Salary
o Special Allowances (Monthly)
o Bonus Percentage (Annual Bonus as % of Gross Salary)
 Calculate:
o Gross Monthly Salary = Basic Salary + Special Allowances
o Annual Gross Salary = (Gross Monthly Salary × 12) + Bonus
 Output: Display the employee details, gross monthly salary, and annual gross salary.
TalenciaGlobal HandsOn Framework - THLF

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}")

Coding Challenge 12: Taxable Income Calculation


Objective: Calculate taxable income after standard deductions.
Tasks:
 Deduct a Standard Deduction of ₹50,000 from the annual gross salary.
 Compute the Taxable Income and display all intermediate calculations.
Output: Display gross salary, standard deduction and taxable income.

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}")

Coding Challenge 13: Tax and Rebate Calculation


Objective: Compute tax payable using the New Tax Regime (2023) .
Tasks:
1. Calculate tax based on the following sCoding Challenges:
o ₹0 - ₹3,00,000: 0%
o ₹3,00,001 - ₹6,00,000: 5%
o ₹6,00,001 - ₹9,00,000: 10%
o ₹9,00,001 - ₹12,00,000: 15%
o ₹12,00,001 - ₹15,00,000: 20%
o Above ₹15,00,000: 30%

2. Apply Section 87A Rebate:


o Taxable income ≤ ₹7,00,000 → 100% rebate (tax payable = ₹0).
3. Add a 4% Health and Education Cess to the calculated tax.
Output: Display a detailed tax breakdown, including sCoding Challenges, cess, and total tax payable.
TalenciaGlobal HandsOn Framework - THLF

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}")

Coding Challenge 14: Net Salary Calculation


Objective: Calculate annual net salary after tax deductions.
Tasks:
1. Compute Net Salary = Annual Gross Salary - Total Tax Payable.
2. Display:
o Annual Gross Salary
o Total Tax Payable (including cess)
o Annual Net Salar

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

Coding Challenge 15: Report Generation


Objective: Generate a detailed report for employees.
Tasks:
1. Summarize all computed details:
o Employee Details (Name, EmpID)
o Gross Monthly Salary
o Annual Gross Salary
o Taxable Income
o Tax Payable (with breakdown)
o Annual Net Salary
2. Format the output as a report for better readability.
Output:
 Provide a clean, tabular report for employees.

Example Output (For Reports Level)


Employee Tax Report
Field Details
Name John Doe
EmpID E12345
Gross Monthly Salary ₹85,000
Annual Gross Salary ₹10,20,000
Taxable Income ₹9,70,000
Tax Payable ₹76,800
Annual Net Salary ₹9,43,200

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}")

Coding Challenge 16: Input Validation Rules


Objective: Validate all inputs to ensure accuracy and correctness.
Validation Rules:
1. Employee Details:
o Name: Non-empty, alphabets only, max 50 characters.
o EmpID: Alphanumeric, 5–10 characters.
2. Salary Inputs:
o Basic Salary: Positive number, max ₹1,00,00,000.
TalenciaGlobal HandsOn Framework - THLF

oSpecial Allowances: Non-negative, max ₹1,00,00,000.


o Bonus Percentage: Numeric value, 0–100.
3. Derived Calculations:
o Gross Monthly Salary must be greater than zero.
o Annual Gross Salary should not exceed realistic values.
4. General:
o Reject invalid inputs with a clear error message.
o Provide re-entry prompts for invalid data.
Output:
 Indicate if any inputs are invalid and prompt for correction.

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

49. gross_monthly_salary = basic_salary + special_allowances


50. if gross_monthly_salary <= 0:
51. print("Error: Gross monthly salary must be greater than zero.")
52.
53. annual_gross_salary = (gross_monthly_salary * 12) + ((gross_monthly_salary *
bonus_percentage) / 100)
54. if annual_gross_salary > 100000000:
55. print("Warning: Annual gross salary exceeds realistic values.")

Loops and Iterations

Coding Challenge 17: Display the Series 1,2,3,4,5,6…N

Solution:
# Get input from the user for N
N = int(input("Enter the value of N: "))

# Validate the input (ensure N is a positive integer)


if N <= 0:
print("N must be a positive integer.")
else:
# Generate and print the numbers
for i in range(1, N + 1):
print(i, end=" ") # Print numbers on the same line, separated by spaces
print() # Add a newline at the end for cleaner output

Coding Challenge 18: Display the Series 1,3,5,7,9…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()

Coding Challenge 19: Display the Series 4,16,36,64…N

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()

Coding Challenge 20: Display the Series 1,2,4,7,11,16,22…N

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()

Coding Challenge 21: Display the Series 1,4,9,25,36,49,81…N

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

Coding Challenge 22: Display the Series 1,4,7,12,23…N

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

Coding Challenge 23: Display the Series 1,5,9,13,21,25,29,37,41…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 = 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

Coding Challenge 24: Display the Series 1,1,2,3,5,8,13,21…N

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

Coding Challenge 25: Generating the Series: 2, -4, 6, -8, 10, … N

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

Coding Challenge 26: Generating Prime Numbers: 2, 3, 5, 7, 11, 13, … N

Solution:

Code: Version 1: Simple Approach

1. # Input: Number of terms (N)


2. N = int(input("Enter the number of terms (N): "))
3. # Initialize prime count and starting number
4. count = 0
5. num = 2
6. print("Generated Prime Numbers: ", end="")
7. while count < N:
8. # Check if the number is prime
9. is_prime = True
10. for i in range(2, num):
11. if num % i == 0:
12. is_prime = False
13. break
14. if is_prime:
15. # Print the prime number
16. print(num, end=", " if count < N - 1 else "\n")
17. count += 1
18. # Move to the next number
19. num += 1

Code: Version 2: Optimized Approach

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

19. # Move to the next number


20. num += 1

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

Coding Challenge 28: Write a program to do the following :


Input: 270176
Output: Two Seven Zero One Seven Six

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.

Retail Shopping– Hackathon


Retail Shopping Application with Enhanced Rules
You are tasked with developing a retail shopping application for generating itemized invoices,
applying business rules for discounts, surcharges, and quantities, and providing a seamless customer
experience. The application unfolds across levels, each introducing new functionality, culminating in
a complete solution that includes invoice generation and a breakdown of purchases.

Coding Challenge 30: Basic Item Entry and Total Calculation


Objective: Allow the user to input item details (code, description, quantity, price) and calculate the
total cost for the item.
Key Steps:
1. Accept item code, description, quantity, and price.
2. Compute the total for a single item.
3. Display the total for the item.

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}")

Coding Challenge 31: Iterative Item Entry and Grand Total


Objective: Enable multiple items to be added iteratively, and compute the grand total for all items.
Key Steps:
1. Use a loop to accept details for multiple items.
2. Compute the grand total by summing individual totals.
3. Display the grand total after all items have been entered.

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}")

Coding Challenge 32: Applying Discounts


Objective: Introduce business rules for modifying the grand total based on conditions.
Rules Implemented:
1. Discount: If the grand total exceeds ₹10,000, apply a 10% discount.
2. Quantity Discount: If the total quantity exceeds 20, apply an additional 5% discount on the
grand total (after other discounts).
Key Steps:
1. Check conditions for discounts.
2. Adjust the grand total accordingly.
3. Display the modified total with adjustments explained.

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

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. print(f"Final Grand Total after discounts: ₹{grand_total:.2f}")

Coding Challenge 33: Membership Discounts


Objective: Introduce a membership system where customers get an additional discount.
Rules Implemented:
1. If the customer is a member (choice: 'y'), apply an additional 2% discount on the grand total
after all other adjustments.
Key Steps:
1. Prompt the user for membership status.
2. Apply the membership discount if applicable.
3. Update and display the final grand total.

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

Coding Challenge 34: Tax Calculation Based on Purchase Amount


Objective: Introduce tiered tax rates based on the grand total.
Rules Implemented
1. If the grand total is below ₹5,000, apply 5% tax.
2. If the grand total is between ₹5,000 and ₹20,000, apply 10% tax.
3. If the grand total exceeds ₹20,000, apply 15% tax.
Key Steps
1. Calculate the tax based on the applicable tier.
2. Add the tax to the grand total.
3. Display the tax amount and updated grand total.

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}")

Coding Challenge 35: Promotional Discounts on Specific Items


Objective: Introduce promotional discounts on specific items identified by their code.
Rules Implemented
1. If the item code matches a promotional code (e.g., PROMO10), apply a 10% discount on that
item.
2. Compute the grand total considering the discounts on applicable items.
Key Steps
1. Check if the item code matches the promotional code.
2. Apply the discount to the item total.
3. Update the grand total and display the final value.

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

Coding Challenge 36: Payment Mode Rules


Objective: Incorporate business rules based on the selected payment method.
Rules Implemented
1. If the customer chooses Cash, no surcharge applies.
2. If the customer chooses Credit Card, apply a flat 2% surcharge on the final grand total after
all adjustments.
Key Steps
1. Prompt the user to select the payment method.
2. Apply the surcharge if the method is Credit Card.
3. Display the payment method, surcharge amount, and final payable amount.

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}")

Coding Challenge 37: Minimum Purchase Requirements


Objective
Add a condition to enforce a minimum purchase value to generate an invoice.
Rules Implemented
1. If the final grand total (after discounts and taxes) is below ₹500, inform the user that the
minimum purchase amount is not met.
Key Steps
1. Check the final grand total.
2. If below ₹500, display an appropriate message and terminate the process.
3. Otherwise, proceed to generate the invoice.

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}")

Coding Challenge 38: Loyalty Points


Objective: Introduce a loyalty program where customers earn points based on the final grand total.
Rules Implemented
1. For every ₹100 spent, the customer earns 1 loyalty point.
2. Display the total loyalty points earned.
Key Steps
1. Calculate loyalty points (points = grand_total // 100).
2. Display the earned points along with the invoice.
TalenciaGlobal HandsOn Framework - THLF

Solution:
1. # Level 9: Loyalty Points
2. loyalty_points = int(grand_total // 100)
3. print(f"Loyalty Points Earned: {loyalty_points}")

Pattern Programming and Nested Loops


Coding Challenge 39: Printing Star Pattern (N Rows)
*****
*****
*****
*****
.
.
N rows

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

Coding Challenge 40: Printing Number Pattern (N Rows)


11111
22222
33333
44444
.
.
N rows

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

Coding Challenge 41: Printing Number Pattern (N Rows)


12345
12345
12345
12345
.
.
N rows

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

Coding Challenge 42: Printing * Increasing Pattern (N Rows)


*
**
***
****
.
.
N rows

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

Coding Challenge 43: Printing number Increasing Pattern (N Rows)


1
22
333
4444
.
.
N rows
TalenciaGlobal HandsOn Framework - THLF

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

Coding Challenge 44: Printing number Increasing Pattern (N Rows)


1
12
123
1234
.
.
N rows

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

Coding Challenge 45: Fibonacci Series Pattern (N Rows)


1
12
358
13 21 34 55
.
N rows

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

Coding Challenge 47: Printing Pattern of Factorials in N Rows


1
12
6 24 120
.
N rows

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

Coding Challenge 48: Convert Number to Words Using Mathematical Logic


a. Input: 270176
b. Output: Two Seven Zero One Seven Six
TalenciaGlobal HandsOn Framework - THLF

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

Coding Challenge 50: Whole and Fraction value separation


Write a program to accept a double value. Separate the whole value from the fractional value and
store them in two variables. Display the same.

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

Coding Challenge 51: Reverse of a number


Write a program to find the reverse of a number. Store the reverse value in a different variable.
Display the reverse.

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}.")

Working with Arrays

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)

Sort and Search Arrays

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 59: Level 1: Reverse the given array.


Solution:
1. my_array = [1, 2, 3, 4, 5]
2.
3. reversed_array = [] # Initialize an empty list to store the reversed elements
4.
5. length = 0 #initialize length to zero
6.
7. #loop through the array to find its length
8. for element in my_array:
9. length += 1
10.
11. #loop from the last element to the first and append the elements to reversed array
12. for i in range(length -1, -1,-1):
13. reversed_array.append(my_array[i])
14.
15. print("Original array:", my_array)
16. print("Reversed array:", reversed_array)
TalenciaGlobal HandsOn Framework - THLF

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()

Coding Challenge 61: Level 3: Implement Binary Search on the array.

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

34. elif my_array[mid] < search_number:


35. low = mid + 1 #if the element to be searched is on right side of the middle element
36.
37.
38. else:
39. high = mid - 1 #if the element to be searched is on left side of the middle element
40.
41.
42. if found:
43. print(search_number, "is found at index", mid) #if element is found print the index
44. else:
45. print(search_number, "is not found in the array")
46.

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.")

Coding Challenge 65: Write a program to store elements into a M * N matrix of


integer. Display the matrix and its transpose.

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

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. matrix.append(row)
18.
19. # Display the matrix
20. print("\nThe original matrix:")
21. for row in matrix:
22. print(row)
23.
24. # Compute the transpose of the matrix
25. transpose = [[matrix[j][i] for j in range(rows)] for i in range(cols)]
26.
27. # Display the transpose
28. print("\nThe transpose of the matrix:")
29. for row in transpose:
30. print(row)

Coding Challenge 66: Write a program to store elements into a M * N matrix of


integer. Display the matrix and its transpose.

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)

Coding Challenge 67: Write a program to multiply two matrices

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)

Setting the Scene: A Day at HealWell Care Hospital-Hackathon


At HealWell Care Hospital, the day begins with the admin team preparing the system for patient care.
The admin updates the list of services available for the day, ensuring accuracy and clarity. These
services include a mix of diagnostics and consultations:
· General Consultation
· Blood Test
· Covid Test
· X-Ray
TalenciaGlobal HandsOn Framework - THLF

· 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

Coding Challenge 68: Patient Walks In and Shares Their Details


Patients like Mr. Arjun Kumar visit the hospital. At the reception, their basic details (name, age,
contact, and gender) are collected and stored in variables.
Example Input:
Name: Arjun Kumar
Age: 35
Gender: Male
Contact: 9876543210

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

Coding Challenge 69: Displaying Services for Patient Selection


The system displays the list of services available for the day. The patient selects one or more
services they wish to avail. The selected services are stored in an array (selected_services).
Example Interaction:
Available Services:
1. General Consultation
2. Blood Test
3. Covid Test
4. X-Ray
5. CT Scan
6. MRI
Patient Selected: [1, 4] // General Consultation, X-Ray
Selected Services Array: ["General Consultation", "X-Ray"]

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

8. # --- Service Selection ---


9. selected_indices = []
10. while True: # Input loop
11. try:
12. service_index = int(input("Enter service number (or 0 to finish): "))
13. if 0 <= service_index <= len(services):
14. if service_index == 0:
15. break # Exit input loop if 0 is entered
16. selected_indices.append(service_index - 1) # Adjust index to match list (0-based)
17. else:
18. print("Invalid service number. Please try again.")
19. except ValueError:
20. print("Invalid input. Please enter a number.")
21.
22.
23. # --- Store Selected Services ---
24. selected_services = []
25. for index in selected_indices:
26. selected_services.append(services[index])
27.
28. patient_details["services_availed"] = selected_services # Add selected services to patient
details
29.
30.
31. # --- Display Selected Services --- (For verification)
32. print("\n--- Selected Services ---")
33. for service in selected_services:
34. print(service)

Coding Challenge 70: Fetching Costs of Selected Services


The system iterates through the selected_services array, matches the services with the main
services array, and retrieves the respective costs from the costs array.
Example Output:
Selected Services: ["General Consultation", "X-Ray"]
Selected Costs: [500, 1500]

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

Coding Challenge 71: Calculating the Total Cost


The total cost is calculated by summing up the costs of all selected services.
Example Output:
Total Cost (Before Tax): ₹2000

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}")

Coding Challenge 72: Applying GST to the Bill


An 18% GST is applied to the total cost. The system calculates and adds this to the total bill amount.
Example Output:
GST (18%): ₹360
Grand Total: ₹2360

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}")

Coding Challenge 73: Generating and Displaying the Invoice


The system generates a detailed invoice for the patient, including their details, services availed,
individual costs, and the grand total.
Example Output:
-----------------------------------------------
HealWell Care Hospital
Patient Invoice
-----------------------------------------------
Patient Information:
Name: Arjun Kumar
Age: 35
Gender: Male
TalenciaGlobal HandsOn Framework - THLF

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.")

Coding Challenge 75: Providing Discounts (Optional Enhancements)


HealWell Care Hospital values its patients and strives to provide the best care at affordable rates. To
improve accessibility and express gratitude, the hospital offers discounts in specific scenarios.
Discount Rules
1. Senior Citizen Discount: Patients aged 60 or above are eligible for a 10% discount on the subtotal
(before GST).
2. High-Bill Discount: If the subtotal exceeds ₹5000, an additional 5% discount is applied on the
subtotal (after any other discounts).
Steps
1. Check the patient's age to determine if the senior citizen discount applies.
2. Check the subtotal to determine if the high-bill discount applies.
3. Calculate the final total after applying discounts and GST.

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("-----------------------------------------------")

Working with Arrays

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()

Coding Challenge 77: Write a Function to add two numbers

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)

Coding Challenge 78: Write a Function check if a Number is Even or Odd

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

Coding Challenge 79: Write a Function convert Celsius to Fahrenheit

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")

Coding Challenge 80: Write a Function to find the Factorial of a Number

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)

You might also like