Python Programming Notes for B.Tech 1st Year (Unit-wise, All Universities)

|CodeKitab Editorial Team
Python Programming Notes for B.Tech 1st Year – unit-wise notes by CodeKitab

Unit-wise Python notes for first-year engineering, BCA and B.Sc students — every topic your university syllabus lists, explained with Indian examples and runnable code. Updated for Python 3.14.

Almost every Indian university now teaches Python in the first year: AKTU calls it Python Programming (BCC-302/402), RGPV lists it under Basic Computer Engineering, VTU has Introduction to Python Programming (BPLCK105B), GTU and Mumbai University run it as a second-semester core, and BCA programmes cover it in semester 2 or 3. The syllabi differ in order, but the topics are the same five units. These notes cover all of them in one place, so you can revise unit by unit before the sessional or the end-semester exam.

The examples below are taken from Python Programming for Indian Students, the CodeKitab textbook. The book has 10 chapters, 180 full-colour pages, 20+ mini projects (railway fare calculator, UPI transaction manager, GST calculator, student result system) and solved practice questions after every chapter. These notes give you the theory and one worked program per topic; the practice questions with answers are in the book.

What these notes cover

  1. Unit 1 — Introduction to Python, variables, data types, operators
  2. Unit 2 — Decision making and loops
  3. Unit 3 — Strings, lists, tuples, sets and dictionaries
  4. Unit 4 — Functions, modules and packages
  5. Unit 5 — Object-oriented programming, file handling and exceptions
  6. University syllabus map (AKTU, RGPV, VTU, GTU, MU, BCA)
  7. How to prepare for the exam with these notes
  8. Frequently asked questions

Unit 1 — Introduction to Python, variables, data types and operators

What is Python and why do universities teach it first?

Python is a high-level, interpreted, general-purpose language created by Guido van Rossum and released in 1991. Three properties make it the first language in most Indian syllabi:

  • Readable syntax. Blocks are marked by indentation, not braces, so a beginner's program looks like structured English.
  • Interpreted and dynamically typed. You run code line by line without a compile step, and you never declare a variable's type.
  • Huge standard library and ecosystem. The same language runs data science (NumPy, pandas), web apps (Django, Flask), automation and AI tooling, so what you learn in first year is reused in placements.

Exam tip: a 2-mark question on "features of Python" wants five bullet points — simple, interpreted, dynamically typed, object-oriented, portable, large library. Learn them as a list.

Your first program and taking input

print("Welcome to Python")
name = input("Enter your name: ")
print("Hello,", name)

input() always returns a string. If you need a number you must convert it — this is the single most common first-year bug:

marks = int(input("Enter marks: "))   # convert text to integer
print(marks + 5)

Variables and naming rules

A variable is a named box in memory. Think of the labelled steel dabbas in an Indian kitchen: the label is the variable name, the contents are the value.

student_name = "Rahul"
college = "Delhi Technical College"
upi_balance = 2500
salary = 45000.50
print(student_name)
print("UPI Balance:", upi_balance)
Rahul
UPI Balance: 2500

Python variables explained as labelled containers – student_name, marks, upi_balance, salary with their data types

Rules you must know for the exam:

  • Only letters, digits and underscore; cannot start with a digit (2marks is invalid).
  • No spaces or symbols (student-name is read as subtraction).
  • Case-sensitive: marks, Marks and MARKS are three variables.
  • Keywords (class, for, if…) cannot be used. Python 3.14 has 35 keywords; print them with import keyword; print(keyword.kwlist).
  • Convention: snake_case for variables and functions, UPPERCASE for constants like GST_RATE = 18.

Data types

Python data types chart – int, float, str, bool, None, list, tuple, set, dict with examples

Type Example Used for
int roll_no = 42 Whole numbers (unlimited size in Python)
float price = 499.0 Decimal numbers
str city = "Jaipur" Text; immutable
bool passed = True True / False
NoneType result = None "No value yet"
list [90, 85, 77] Ordered, changeable collection
tuple (28.6, 77.2) Ordered, unchangeable collection
set {"Delhi", "Pune"} Unique items, unordered
dict {"name": "Asha", "marks": 91} Key–value pairs

Check any value's type with type(x). Convert with int(), float(), str(), bool(). int("12.5") raises a ValueError — convert via float() first.

Operators

Seven families appear in every question paper:

  • Arithmetic: + - * / // % **. Remember / always gives a float (7 / 2 → 3.5), // is floor division (7 // 2 → 3), % is remainder, ** is power.
  • Comparison: == != > < >= <= → always return a bool.
  • Assignment: = += -= *= /=.
  • Logical: and or not.
  • Membership: in, not in — "Delhi" in cities.
  • Identity: is, is not — same object, not just equal value.
  • Bitwise: & | ^ ~ << >> — asked in AKTU and VTU papers.
# GST on a mobile phone
price = 15999
gst = price * 18 / 100
total = price + gst
print("GST:", gst)
print("Total payable:", total)
GST: 2879.82
Total payable: 18878.82

Operator precedence (highest first): ** → unary - + → * / // % → + - → comparisons → not → and → or. A 2-mark question will ask you to evaluate an expression like 2 + 3 * 4 ** 2 // 5 — work it out as 2 + ((3 × 16) // 5) = 2 + 9 = 11.

Unit 2 — Decision making and loops

if, if-else, if-elif-else, nested if

marks = int(input("Enter marks: "))
if marks >= 90:
    grade = "A+"
elif marks >= 75:
    grade = "A"
elif marks >= 60:
    grade = "B"
elif marks >= 40:
    grade = "C"
else:
    grade = "Fail"
print("Grade:", grade)

Flowchart of if elif else in Python choosing a grade from marks

Indentation is the syntax. Four spaces per level, never mix tabs and spaces. Python has no switch statement in the traditional sense; use if-elif chains, or match-case (Python 3.10+) when the question explicitly mentions it.

while loop

# ATM withdrawal simulator
balance = 5000
while balance > 0:
    amount = int(input("Withdraw: "))
    if amount > balance:
        print("Insufficient balance")
        continue
    balance -= amount
    print("Remaining:", balance)
print("Account empty")

for loop and range()

for roll in range(1, 4):
    print("Roll number", roll)

for n in range(2, 11, 2):     # start, stop (excluded), step
    print(n, end=" ")
Roll number 1
Roll number 2
Roll number 3
2 4 6 8 10

range(stop), range(start, stop) and range(start, stop, step) — the stop value is never included. A negative step counts down: range(10, 0, -1).

break, continue, pass and the loop-else

  • break exits the loop immediately.
  • continue skips the rest of the current iteration.
  • pass is a placeholder that does nothing.
  • Python's for … else runs the else block only if the loop was not broken — a favourite 2-mark trick question.

Pattern programs (asked in every lab exam)

rows = 4
for i in range(1, rows + 1):
    print("*" * i)
*
**
***
****

The book's Chapter 4 covers nine loop patterns (pyramid, inverted, number triangle, Floyd's triangle) with the thinking behind each, plus the Student Attendance Counter and Number Guessing Game projects.

Unit 3 — Strings, lists, tuples, sets and dictionaries

Strings

Strings are immutable sequences of characters. Indexing starts at 0; negative indices count from the end; slicing is s[start:stop:step].

city = "Bengaluru"
print(city[0], city[-1])      # B u
print(city[0:3])              # Ben
print(city.upper())           # BENGALURU
print(len(city))              # 9
print("galore" in city)       # False
print(city.replace("Bengaluru", "Bangalore"))

Methods to memorise: upper() lower() strip() split() join() find() replace() count() startswith() isdigit(). f-strings are the modern way to format: f"Total: ₹{total:.2f}".

Lists

marks = [78, 92, 65, 88]
marks.append(70)          # add at end
marks.insert(0, 95)       # add at index
marks.remove(65)          # remove by value
marks.sort()
print(marks, max(marks), sum(marks) / len(marks))

List comprehension — one line that creates a list — appears in almost every paper: squares = [x * x for x in range(1, 6)] gives [1, 4, 9, 16, 25].

Tuples

Like lists but immutable (cannot be changed after creation). Used for fixed records such as coordinates or RGB colours, and as dictionary keys. location = (28.6139, 77.2090). A one-item tuple needs a trailing comma: (5,).

Sets

Unordered collections of unique items. The fastest way to remove duplicates: unique = set(my_list). Set operations: union a | b, intersection a & b, difference a - b. You cannot index a set, and {} creates an empty dictionary, not a set — use set().

Dictionaries

student = {"name": "Asha", "roll": 17, "marks": 91}
print(student["name"])
student["city"] = "Lucknow"          # add a key
for key, value in student.items():
    print(key, "→", value)
print(student.get("phone", "Not given"))   # safe lookup

Dictionaries are the backbone of real programs — the book's Phone Contact Book and Student Marks Management System projects are built on them.

List vs tuple vs set vs dict — the comparison question

List vs tuple vs set vs dictionary in Python – comparison table

List Tuple Set Dictionary
Syntax [ ] ( ) { } {key: value}
Ordered Yes Yes No Yes (insertion order)
Mutable Yes No Yes Yes
Duplicates Allowed Allowed Not allowed Keys unique
Indexing By position By position None By key

Unit 4 — Functions, modules and packages

Defining and calling functions

def calculate_gst(price, rate=18):
    """Return the GST amount for a price and rate (default 18%)."""
    return price * rate / 100

print(calculate_gst(1000))        # 180.0  (default rate)
print(calculate_gst(1000, 5))     # 50.0   (positional)
print(calculate_gst(rate=12, price=2000))   # keyword arguments

Vocabulary the examiner expects: parameter (in the definition) vs argument (in the call); default, keyword and variable-length arguments (*args, **kwargs); return sends a value back; a function with no return gives None.

Scope — local and global

A variable created inside a function is local and vanishes when the function ends. To modify a global inside a function you must write global count — but good code passes values in and returns them instead.

Recursion

def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n - 1)

print(factorial(5))   # 120

Every recursive function needs a base case; without it Python raises RecursionError at about 1,000 calls.

Lambda, map, filter

square = lambda x: x * x
prices = [499, 999, 1499]
with_gst = list(map(lambda p: p * 1.18, prices))
expensive = list(filter(lambda p: p > 900, prices))

Modules and packages

  • A module is any .py file; import it with import math, from math import sqrt, or import math as m.
  • A package is a folder of modules (with an __init__.py).
  • Built-in modules to know for the exam: math, random, datetime, os, sys, statistics.
  • Third-party packages install with pip install requests; use a virtual environment (python -m venv venv) per project.
import random, math
otp = random.randint(100000, 999999)
print("Your OTP is", otp)
print(math.ceil(7.2), math.pi)

Unit 5 — Object-oriented programming, file handling and exceptions

Classes and objects

class Student:
    college = "NIT Trichy"                 # class attribute

    def __init__(self, name, roll):        # constructor
        self.name = name                   # instance attributes
        self.roll = roll

    def introduce(self):                   # method
        return f"I am {self.name}, roll {self.roll}, from {Student.college}"

s1 = Student("Rahul", 101)
print(s1.introduce())

self is the object on which the method was called; Python passes it automatically. __init__ runs once when the object is created.

The four pillars (10-mark question)

  • Encapsulation — data and methods bundled in a class; private names use a leading underscore (_balance, __pin).
  • Inheritance — class EngineeringStudent(Student): reuses the parent; super().__init__() calls the parent constructor.
  • Polymorphism — same method name, different behaviour (method overriding; operator overloading with __add__, __str__).
  • Abstraction — hide the complexity behind a simple interface (abc module, @abstractmethod).

File handling

with open("attendance.txt", "w") as f:
    f.write("Rahul,Present\n")
    f.write("Asha,Absent\n")

with open("attendance.txt", "r") as f:
    for line in f:
        name, status = line.strip().split(",")
        print(name, "is", status)

Modes: r read, w write (overwrites), a append, r+ read-write, add b for binary. Always use with — it closes the file even if an error occurs. CSV files use the csv module; JSON uses json.load() / json.dump().

Exception handling

try:
    amount = int(input("Enter UPI amount: "))
    result = 1000 / amount
except ValueError:
    print("Please enter digits only")
except ZeroDivisionError:
    print("Amount cannot be zero")
else:
    print("Transaction OK:", result)
finally:
    print("Session closed")

Python try except else finally order of execution diagram with UPI amount example

Order matters: try → specific except blocks → optional else (runs if no error) → optional finally (always runs). Raise your own with raise ValueError("Invalid PIN"). Common built-in exceptions to list in an exam: ValueError, TypeError, ZeroDivisionError, IndexError, KeyError, FileNotFoundError.

University syllabus map

Use this table to find which units of these notes (and which chapters of the book) your paper actually tests. Verify against your department's current scheme — universities revise syllabi every two to three years.

University / course Paper Units in these notes Book chapters
AKTU (B.Tech 2nd/4th sem) Python Programming BCC-302 / BCC-402 1–5, plus NumPy/pandas basics (see Data Science book) 1–9
RGPV (B.Tech 1st year) Basic Computer Engineering / Python 1–5 1–8
VTU (1st/2nd sem) Introduction to Python Programming BPLCK105B/205B 1–5, with emphasis on files and OOP 1–8, 10
GTU Python for Data Science (3150713) / PPS 1–4 1–6, 9
Mumbai University Python Programming (FE/SE) 1–5 1–8
BCA (most universities, sem 2–3) Programming in Python 1–5 1–10
CBSE Class 11–12 (CS 083 / IP 065) Computer Science / Informatics Practices 1–3 (Class 11), 4–5 + files (Class 12) 1–8

How to prepare for the exam with these notes

  1. Read one unit a day, then type every program by hand — do not copy-paste. Typing is where syntax becomes memory.
  2. Trace outputs on paper. Output-prediction questions are 20–30 % of most papers. Cover the output block above each program and write your answer before looking.
  3. Memorise the comparison tables (data types; list vs tuple vs set vs dict; loop statements; file modes). They are the 2-mark and 5-mark bank.
  4. Do one mini project per unit. The book's Student Result Calculator (Unit 1), ATM Simulator (Unit 2), Contact Book (Unit 3), GST Calculator (Unit 4) and Expense Tracker (Unit 5) map exactly to these notes and double as lab-file programs.
  5. Practise previous-year questions. Each chapter of the book ends with 8–12 coding exercises and a set of solved practice questions in the same pattern as university papers.

Want the full version of these notes with every worked example, 20+ mini projects and solved practice questions?
Python Programming for Indian Students — 180 pages, full colour, every program tested on Python 3.14, written for B.Tech, BCA and CBSE students. Also available as a set with DSA with Python for placement preparation.

Frequently asked questions

Which Python version should I use for B.Tech?

Any Python 3.10 or newer. Universities do not test version-specific features, but install the latest (3.14 at the time of writing) so that match-case and modern f-strings work. Avoid Python 2 entirely.

Is Python enough for placements, or do I need C++/Java?

For service-company placements (TCS, Infosys, Wipro, Accenture, Capgemini) Python is fully accepted in coding rounds. For product companies you additionally need data structures and algorithms — in Python or any language. Start with these notes, then move to a DSA book in the same language.

What is the difference between a list and a tuple?

A list is mutable (you can add, remove and change items) and uses square brackets; a tuple is immutable and uses parentheses. Tuples are slightly faster and can be dictionary keys. Use a list when the data changes, a tuple for fixed records.

Why does my program say "TypeError: can only concatenate str (not int) to str"?

Because input() returns a string and you tried to add a number to it. Convert with int() or float() first, or use print("Marks:", marks) with a comma instead of +.

How many hours does it take to finish the Python syllabus?

Working through these five units with the programs typed out takes most students 25–30 hours. Doing the chapter exercises and one mini project per unit adds another 15–20 hours and is what separates a pass from a distinction.

Are these notes enough to pass the exam?

They cover every topic in the standard syllabus and the questions examiners repeat. For full marks you also need to practise writing programs under time pressure and solve previous-year papers, which is what the textbook's practice sections are designed for.

Written by the CodeKitab editorial team at Study Delight Publications. Every program on this page was run on Python 3.14 and the output shown is the real output. Last reviewed October 2026.