Skip to content
New Milap Nagar, Ambala City

Home Courses

Practical course guide · Ambala, Haryana

Python Course in Ambala

Learn Python from the basics and build a script that reads CSV data, handles errors and summarises results.

What you build in Python training

Build a program that reads an expense file, checks each record and reports how much was spent in each category. The practice starts with short exercises on variables, strings and loops. You then combine those pieces in a command-line project that someone else can run. Learners in Ambala can use the same techniques to summarise fictional club expenses, equipment records or workshop registrations. The sample data lets you check results without sharing anyone's personal information.

By the end, aim to explain how the program reads the file, why it rejects a record and what it reports when the input cannot be opened. Run it on a deliberately untidy sample, check the answers by hand and write a one-page guide that another beginner can follow. The important progression is learning a concept, practising it on a few values, building a small application and revising it after a test.

Prepare the workspace and run your first file

Keep the script and practice files together

Create a folder named expense-practice. Put the script expense_report.py and the fictional input file expenses.csv there. Save both as UTF-8 text. On Windows, try py --version in a terminal if the Python launcher is available. On systems where Python 3 is started with python3, use python3 --version. On a setup where python points to Python 3, that command also works. Use the same interpreter when running all commands for the lesson.

Write print("Expense practice") in the Python file and run py expense_report.py, using your Python command as appropriate. Save changes before rerunning. If the terminal reports a missing file, confirm its current folder and the filename's extension. A file saved as expense_report.py.txt may appear to be a Python script when the file manager hides extensions. Resolve that issue before adding project logic.

This project uses standard library modules, which are included with Python. If you continue to a project that does install external packages, practise creating an environment for that project and describe the dependency setup in its instructions. For this example, record the interpreter version and the commands you actually used. Ask another learner to try them on a fresh copy of the project.

Read the error message before changing code

Make a small syntax error such as deleting the closing parenthesis from your print call. Read the location identified in the message and inspect nearby lines for unfinished expressions. Fix it, then try print(report_title) before assigning that variable. In this case the line is valid Python syntax, while the name does not yet have a value when the program runs. Distinguishing these two situations helps you decide what to inspect first.

When an expression produces an unexpected value, print the intermediate values in a practice run. Use repr() to make invisible spaces and line breaks easier to see. If the value is coming from a file, compare the original record with the representation after each transformation. Remove or replace temporary print statements before sharing the finished report so ordinary output stays easy to read.

Practise the fundamentals on a few expenses

Choose types that match the information

A text amount like "75.50" can be displayed or joined with other text but must be interpreted as a number before addition. Dates and categories serve different purposes. A category label such as "Food" names a group, while a date tells when the expense occurred. Store different fields separately so filtering or updating one does not require splitting a long phrase again.

For money in this practice, use Decimal from the standard library and construct it from the source text. Combining Decimal("75.50") and Decimal("24.50") yields an exact total of 100.00. Practise comparing the string values "75.50" and "100.00", then compare the converted values. Text is ordered by characters. A numeric type is necessary when the question is which amount is higher.

Use lists for records and dictionaries for totals

Write four expense records by hand before reading a file. Try a list of dictionaries with keys for date, category and amount. Use a loop to read one record at a time and accumulate totals in a dictionary keyed by category. The first time a category appears, add its amount to zero. The next time, add it to the saved subtotal. With food amounts of 75.50 and 24.50 and a travel expense of 40.00, the subtotal dictionary should contain food 100.00 and travel 40.00.

from decimal import Decimal

totals = {}
examples = [("food", "75.50"), ("travel", "40.00"), ("food", "24.50")]
for category, amount_text in examples:
    amount = Decimal(amount_text)
    totals[category] = totals.get(category, Decimal("0.00")) + amount

for category, total in sorted(totals.items()):
    print(f"{category}: {total:.2f}")

Step through the loop on paper. After the first record, the food key holds 75.50. The travel key is created on the second record. The third record updates food without changing travel. Try resetting the dictionary inside the loop and see why this loses earlier totals. Move the initialisation back before the loop. Explain why the loop variable represents one current record and the dictionary represents everything accepted so far.

Put related decisions into small functions

Create a function that receives a category and returns its cleaned label. For the example, remove leading and trailing spaces and use casefold so " Food " and "food" contribute to the same group. Try applying the function twice and check that the result stays the same. If a real team needs to preserve chosen capitalisation, store a display label separately from the normalised key.

Create another function that receives a record and either returns the fields needed for aggregation or reports which field needs a correction. Test it with one complete record and one missing amount before adding the file reader. Short tests are easier to understand when a function has no file, terminal or network dependency. Keep the function name connected to the action it performs, such as parse_expense.

Read and check a real CSV structure

Write the input contract

Use the four headers date,category,amount,description. Dates use the year-month-day format shown in the sample. Categories must contain text after trimming spaces. An amount is a nonnegative value in rupees, with at most nine digits before the decimal point and up to two decimal places. There are no currency symbols or thousands separators in this input. The text description is useful for review but optional for the summary. Refunds would need an agreed sign or separate record type before being added to this design.

date,category,amount,description
2026-08-02,Food,75.50,Snacks
2026-08-03,Travel,40.00,"Bus fare, round trip"
2026-08-04, food ,24.50,Tea
2026-08-06,Stationery,120.00,Paper
2026-08-07,Training,,Incomplete record

The quoted travel description contains a comma. If you split the line with split(","), the field appears to occupy two columns. Use the csv module so it handles quoted fields according to CSV rules. Open the file with newline="" when passing it to the CSV reader. With utf-8-sig the reader can accept a UTF-8 file with or without an initial byte-order mark, which helps when a spreadsheet export adds one.

Reject malformed records and keep useful reasons

Make each validation explain the next step. An incomplete amount should say that a nonnegative amount with at most two decimal places is required rather than printing only “invalid data.” A record with too many or too few fields needs a column-count message. Check the header before processing the rows, because known headers are required to find the fields reliably. For a structural CSV parsing failure, stop and explain the file error because the following record boundaries may be unclear.

Use DictReader to associate each value with its column name. With the defaults, an extra field can appear under the key None and a missing field value can appear as None. These are useful checks before attempting to trim text. Where quoted fields span several physical lines, the reader's line number refers to the most recent line read, so report it as the line where parsing reached the end of the record.

Run a complete expense summary script

Replace the first print example with the script below. Run py expense_report.py expenses.csv, or the equivalent command for your Python setup. The file-reading function returns a dictionary of accepted totals and a list of line numbers with reasons. The command prints the accepted totals and sends rejected-row notes to the error stream. Keep invalid data out of the calculation and address reported rows before relying on the result for a real decision.

import argparse
import csv
import re
import sys
from datetime import date
from decimal import Decimal

REQUIRED_FIELDS = {"date", "category", "amount", "description"}
ZERO = Decimal("0.00")


def parse_expense(row):
    if None in row or None in row.values():
        raise ValueError("Check the number of columns")

    date_text = row["date"].strip()
    try:
        expense_date = date.fromisoformat(date_text)
    except ValueError as error:
        raise ValueError("Use a real date in YYYY-MM-DD format") from error
    if expense_date.isoformat() != date_text:
        raise ValueError("Use YYYY-MM-DD format")

    category = row["category"].strip().casefold()
    if not category:
        raise ValueError("Enter a category")

    amount_text = row["amount"].strip()
    if not re.fullmatch(r"[0-9]{1,9}(\.[0-9]{1,2})?", amount_text):
        raise ValueError("Enter a nonnegative amount with up to two decimal places")
    return category, Decimal(amount_text)


def summarise_expenses(path):
    totals = {}
    rejected = []
    with open(path, encoding="utf-8-sig", newline="") as source:
        reader = csv.DictReader(source, strict=True)
        headers = reader.fieldnames or []
        if len(headers) != len(REQUIRED_FIELDS) or set(headers) != REQUIRED_FIELDS:
            raise ValueError("Expected date, category, amount and description headers")

        for row in reader:
            try:
                category, amount = parse_expense(row)
            except ValueError as error:
                rejected.append((reader.line_num, str(error)))
                continue
            totals[category] = totals.get(category, ZERO) + amount
    return totals, rejected


def main():
    parser = argparse.ArgumentParser(description="Summarise expenses by category.")
    parser.add_argument("file", help="Path to a UTF-8 expense CSV")
    args = parser.parse_args()

    try:
        totals, rejected = summarise_expenses(args.file)
    except (OSError, UnicodeError, csv.Error, ValueError) as error:
        print(f"Could not read the report: {error}", file=sys.stderr)
        return 2

    for category, total in sorted(totals.items()):
        print(f"{category}: {total:.2f}")
    print(f"Total accepted: {sum(totals.values(), ZERO):.2f}")
    for line, reason in rejected:
        print(f"Line {line}: {reason}", file=sys.stderr)
    return 1 if rejected else 0


if __name__ == "__main__":
    raise SystemExit(main())

Expected accepted totals are food 100.00, stationery 120.00 and travel 40.00. The accepted total is 260.00. The fifth expense record has a blank amount, so the reported line number is six because the header occupies the first line. The program returns status one when it emits a partial report. Status zero marks a run with no rejected records and status two marks a file-level failure. Keep those meanings in the instructions so a caller knows how to interpret the exit status.

Test mistakes before adding more features

Use small fixtures with a known answer

Make a copy of the sample for each experiment. Give the first copy a leading space in a category and check that its subtotal stays the same. Add another accepted expense with a zero amount and confirm it changes no totals. Give a third copy an impossible date such as 2026-02-30, then check that the required record is rejected and later valid rows still contribute. Introduce an extra comma outside quotes and make sure that record is rejected with a column-count reason.

  • Change the header from amount to cost. The program should report the expected header and return status two without producing a total.
  • Use a nonexistent file path. The program should explain that the file cannot be read and return status two.
  • Correct the last sample amount to 25.00. Training appears in the summary, the total is 285.00 and the return status is zero.
  • Use a file with the valid headers and no transactions. Check that the report shows 0.00 and decide whether a separate message would help your audience distinguish an empty file.
  • Save an amount as 1,200.00 in a properly quoted field. It still fails the input contract, so review the accepted amount format before entering the number again.

Add an automated test after the exercise works by hand. Import parse_expense into a separate test file and feed it a known dictionary. Check that the returned category is lowercase and the amount equals the expected Decimal. Use the built-in unittest module for a test that expects a ValueError on a blank amount. Add an integration test with a temporary fixture when you want to check the file reader and totals together.

Locate the first incorrect intermediate value

If the food subtotal is 75.50, trace the second food line through normalisation and validation. Check whether a category has become a different key or a validation test rejected it. If the total is too high, compare the accepted rows with the source to see whether the same expense was recorded twice. This example allows identical lines because it does not use a transaction ID. If your source has a reliable ID, add a documented duplicate policy and fixtures for both repeated entries and genuine separate purchases.

If the file opens but its header fails, display the raw header on a training copy. Check delimiters and stray whitespace. A spreadsheet exported with semicolon separators needs a matching delimiter setting or a documented export option. If a terminal mixes summary lines and error lines, remember the program uses two streams. Redirect the standard output and standard error to separate files in a practice run, then inspect both files and the exit status.

Try opening the script in an editor with a debugger. Set a breakpoint inside the validation function, run the sample file and advance to the record with the missing amount. Watch how a field moves from the source row to the stripped value. Continue execution and see how the current record's error is stored before the next iteration. Repeat at the header check for an input with a broken schema. The two breakpoints expose the difference between a repairable row and a failure that prevents the report from reading fields correctly.

Practise extending the project with a month filter

Start by writing the rules for the feature

Copy the working script before adding the filter. Design an optional --month 2026-08 argument. The report should then show valid expenses dated in August 2026. A run without the option should continue to include all valid dates. Decide how to label the summary and how to distinguish an empty month from a file with no rows. For this exercise, the script still validates every row before filtering, so data-entry issues stay visible even when a neighbouring month is reported.

Try parsing 2026-08 by creating the first day of the selected month. Check that input has the expected year and month shape before converting it, and report that 2026-13 is invalid. To compute the next month, test December specifically. From December 2026 the exclusive boundary is 1 January 2027, so incrementing the month number by one would fail unless you also roll over the year. Since the records already carry valid dates, you can alternatively compare their numeric year and month directly.

Add a focused function and test boundaries

Practise with a function that receives a date and the selected year and month. Run it first on three values created in Python, such as 31 July, 1 August and 1 September. For an August filter, July and September should return false and August should return true. Change parse_expense to return the parsed date as well as the category and amount, then update the caller's unpacking. Review other uses of the function, including tests, to confirm they handle the new return value.

Use three additional sample records: 31 July travel 10.00, 31 August food 30.00 and 1 September travel 70.00. Keep the sample's blank row so you can confirm it still produces a warning. The unfiltered accepted total becomes 370.00. The August accepted total becomes 290.00 and food contributes 130.00. Check both commands after making the change. These figures give you an independent test for the filter and ensure the original no-filter workflow still works.

Record what you changed and why

Add launch examples for the unfiltered and filtered report to the README. Describe that rejected rows are reported even when the selected month contains no valid entries from that row. Test the month argument with a missing value and an unexpected string. Clear validation messages should show the intended format. Ask another learner to choose a month and compare the generated total against the few fictional records in that period.

Try an automation exercise for repeated files

Pass a report path explicitly

Create two fictional files named club-july.csv and club-august.csv. Run the script once per file to make sure the path argument works with names other than expenses.csv. Then practise with a folder containing a space and put the path in quotes when entering the command. Run the command from another directory with an absolute path and compare the results. A relative path is interpreted from the process's working directory, which may be different from the directory containing the Python file.

Redirect a practice run to one summary file and one error file, then inspect each in a text editor. Use only fictional paths where overwriting the output is safe. Once you understand the difference between the two streams, try a small driver program that loops over a list of input paths and calls the summarising function. Keep each report labelled with the source file so a reviewer can connect totals to the original input. Agree on whether different files are distinct periods or overlapping exports before adding grand totals across files.

Keep the interface clear when a batch partly fails

Try a run with one known good file and one missing file. Decide whether the batch should continue and record each failure, or stop if every report is required before making a decision. Write down the policy and test it with a known result. A training run should show which files were processed and which need attention. One useful output is a short manifest with the filename, outcome and accepted total. Before sharing, check that file paths and descriptions do not accidentally expose details from a real directory.

Review category totals when input conventions change

Keep the relationship between a source label and a report label

Suppose the club starts entering snacks separately from food. In the August exercise, add one expense for ₹20.00 under Snacks. The accepted total rises from ₹260.00 to ₹280.00, with Food at ₹100.00 and Snacks at ₹20.00. The organiser then decides to report snacks as part of food. The updated report should show Food at ₹120.00 with Stationery and Travel at their earlier amounts. The accepted total remains ₹280.00. Calculate both versions by hand before touching the script.

For a practice implementation, create a mapping from source labels to approved reporting labels and apply it after trimming and casefolding. Pass an unfamiliar label through as its own group during the exercise. That makes new categories visible for review. Keep a brief note beside the mapping to explain who requested each label change. Save the original CSV unchanged so you can produce the previous report again if someone needs to compare it with the updated one.

Build a check that detects rows counted twice

Assign a running accepted total in a trial copy while reading the input. Add each accepted amount once to that total and also to its final category. Compare the accepted total to the sum of all category totals at the end. If the Snacks line is accidentally grouped twice, the individual categories sum to ₹300.00 while the accepted amounts still add up to ₹280.00. Use that deliberately introduced mistake to show that your check would warn the report owner.

Reassess after moving the mapping into a small function. Write a test for Snacks, a second test for the approved Food label and a third test for an unfamiliar category such as Equipment. The expected results give another learner a way to verify the change. Add a sample file with a missing category and confirm the record still fails validation before the grouping step. In the README, describe which labels are combined and show the figures from the two versions of the August report.

Prepare the project for a portfolio and interview

Show that someone else can run it

Prepare the script, a fictional input file, two intentionally invalid examples and a README. List the launch command, accepted headers, currency and date rules, output and return status. Record what a blank file does. Share the sample with a partner and let them run it without a walkthrough. Ask them to add a new category and edit one amount into an invalid form. They should be able to trace the results using the instructions.

For a portfolio extension, write a CSV summary that a spreadsheet can open. Use the CSV writer so fields remain valid when a category contains a comma. Run it once with the normal category names and again with a fictional category named “food, snacks” to see how quoting works on output. Keep the original expense file unchanged and check that the summary contains each category once, with a consistent amount format. Include the report's month and source file in the portfolio notes so the CSV can be traced to its inputs.

Practise explaining one technical choice

Answer “Why did you pick a dictionary?” with the example of two food rows contributing to one subtotal. For “Why parse dates before reporting?” show how an impossible date is rejected and explain how a valid date supports later month filters. For “What if the input is broken?” demonstrate a single rejected record and a damaged header with their different exit statuses. Give the interviewer a brief description of the expected result before you run the examples.

If asked how the script scales to a larger file, explain that it reads records one by one and stores one running total per category. It also holds one error entry per rejected record. For a workload with many rejected records, writing errors to a separate reviewed output as they occur could reduce memory usage. Choose an improvement after testing a sample that resembles the real workload. Describe what you would measure and how you would prove the totals still match.

Frequently asked questions about Python training in Ambala

Can I start without programming experience?

Yes. Start with file navigation, a text editor and a terminal, then practise variables, if statements and loops. The project can be broken into short exercises. First print a value, then total three examples, then read one row from a CSV. If setting up Python already feels unfamiliar, ask the centre how the first batch session covers installation and running scripts.

Should I start with Python or HTML and CSS?

Python suits a goal like scripting, file handling or reporting. HTML and CSS are a good starting point for creating visible web pages. If your interest is both, build a small page separately, then try the expense script and identify which questions you would like to keep exploring. Learning one workflow through a complete small example makes it easier to understand how technologies can eventually work together.

What should I show for an entry-level portfolio?

Use a simple project with a clear input, expected output and repeatable tests. The expense report is one example. Show a working result, a deliberately invalid fixture, and a short explanation of your data rules. Explain how feedback changed one part of the project. Interviewers can understand how you solve problems when the steps can be reproduced from your own sample data.

What should I ask before joining a Python batch?

Ask about the next schedule, current fees, course outline, exercises and the Python environment used in class. Describe the kind of tasks you hope to handle, such as working with spreadsheets or automating repetitive file tasks. If you are preparing for an interview, ask when your trainer reviews project code and which practice tasks you can complete beforehand.

Course syllabus

  1. Python syntax and data types

    Use strings, numbers, lists and dictionaries to represent simple information.

  2. Conditions, loops and functions

    Break a task into conditions, loops and functions and test each part.

  3. CSV files and exception handling

    Use the standard library to read CSV records and handle missing or invalid values with exception handling.

  4. Beginner scripting project

    Combine the steps in a small script that produces a readable summary.

What you’ll be able to do

Write a Python script that reads a CSV file, calculates totals by category and reports input errors.

Example practice project

Write an expense summary script

Read expenses from a CSV file, group totals by category and flag incomplete rows without stopping the report.

Prepare to discuss your project in an interview

Practise describing what you built, one choice you made and how you checked the result.

Question to practise
How did you handle unexpected input and check that your result was correct?

See the interview practice guide →

Before you join

Can I start the Python course with no coding experience?

Yes. Start with Python syntax and short exercises, then use what you learn to read a CSV file and write a small report.