PROGRAMMING FUNDAMENTALS NOTES
UNIT – 1 TO 4
⭐ UNIT – 1
1. Introduction to Programming
Programming refers to the process of designing and writing instructions (called
code) that a computer can execute to solve a problem. A program must be written
in a language the computer understands, known as a programming language.
Introduction to Computers
A computer is an electronic device that accepts data as input, processes it, and
produces meaningful output.
Basic functions:
Input (keyboard/mouse)
Processing (CPU)
Storage (memory units)
Output (monitor/printer)
2. Types of Programming Languages
Programming languages are broadly classified as:
1. Low-Level Languages
Directly understood by the machine
Hard to write
Examples: Machine Language (0s and 1s), Assembly Language
2. High-Level Languages
Easy to read, write, and understand
Portable
Examples: Python, Java, C, C++
3. Object-Oriented Languages
Based on objects and classes
Examples: Python, Java, C++
4. Scripting Languages
Used for automation and quick tasks
Examples: Python, JavaScript
3. Algorithms
An algorithm is a step-by-step procedure to solve a problem.
Good algorithms should be simple, clear, efficient, and must always terminate.
Example Algorithm:
To find the largest of two numbers
1. Start
2. Input numbers A and B
3. If A > B, display A
4. Else, display B
5. Stop
4. Flowcharts
A flowchart is a diagram that visually represents the steps of an algorithm.
Common Flowchart Symbols
Oval → Start/Stop
Parallelogram → Input/Output
Rectangle → Process
Diamond → Decision
Flowchart Example: Largest of Two Numbers
(I will give a simple, clean, exam-friendly version)
Start
|
Input A, B
|
Is A > B ?
/ \
Yes No
| |
Print A Print B
|
Stop
You can draw this neatly in the exam using proper symbols.
5. Data Types in Python
Python has several built-in data types:
Type Meaning Example
int Integer numbers 10, -5
float Decimal numbers 3.14
str Sequence of characters "Hello"
bool True/False values True
complex Complex numbers 2+3j
6. Variables and Assignment
A variable is a name used to store a value.
Example:
x = 10
name = "Aarav"
Immutable Variables
Immutable means once a value is created, it cannot be changed in place.
Examples: int, float, str, tuple
Example:
a=5
a = a + 2 # new value assigned (memory changes)
7. Arithmetic Operators and Expressions
Operator Meaning Example
+ Addition 5+3
- Subtraction 9-2
* Multiplication 4*2
/ Division 8/3
// Floor division 8//3 = 2
% Modulus 10%3 = 1
** Exponent 2**3 = 8
8. Comments and Error Messages
Comments
Used to explain code:
# This is a comment
Common Error Types
Error Meaning
SyntaxError Wrong syntax used
IndentationError Wrong indentation
NameError Variable not defined
TypeError Wrong data type operation
9. Conditions and Boolean Logic
If-Else Example
x = 10
if x > 0:
print("Positive")
else:
print("Negative")
Logical Operators
and – True if both conditions are true
or – True if at least one condition true
not – Reverses the condition
10. Range and Loops
Range
Used in loops:
range(1,6) # 1 to 5
For Loop
for i in range(5):
print(i)
While Loop
count = 1
while count <= 5:
print(count)
count += 1
11. Introduction to OOP
OOP (Object-Oriented Programming) is a programming style that revolves around
objects containing data and methods.
Class and Object
A class is a blueprint;
An object is an instance of a class.
Example:
class Student:
pass
s1 = Student()
12. Constructor Method (__init__)
Called automatically when an object is created.
class Student:
def __init__(self, name):
self.name = name
13. Class vs Instance Attributes
Class Attribute Instance Attribute
Shared among all objects Unique for each object
Defined outside methods Inside __init__()
14. Encapsulation
Wrapping data and functions into a single unit.
Private variables are declared using double underscore (__).
Example:
class Bank:
def __init__(self):
self.__balance = 1000
15. Inheritance
Mechanism where one class acquires properties of another.
class A:
def show(self):
print("A")
class B(A):
pass
16. Polymorphism
Different objects responding differently to the same function.
Example:
print(len("Hello")) # length of string
print(len([1,2,3])) # length of list
⭐ UNIT – 2
Strings, Lists, Tuples, Dictionaries
1. STRINGS
A string is a sequence of characters enclosed in single (‘ ’), double (“ ”), or triple
quotes.
Accessing Characters
Characters are accessed using indexing.
s = "PYTHON"
print(s[0]) # P
print(s[-1]) # N
Accessing Substrings
Using slicing:
s[1:4] # YTH
s[:3] # PYT
s[3:] # HON
Strings and Number System
Python supports:
Binary → prefix 0b
Octal → prefix 0o
Hexadecimal → prefix 0x
Example:
a = 0b111 # binary
b = 0o17 # octal
c = 0x1A # hex
Common String Methods
Method Description Example
upper() Converts to uppercase s.upper()
lower() Converts to lowercase s.lower()
strip() Removes spaces s.strip()
replace(a,b) Replace substring s.replace("a","b")
split() Splits into list s.split()
Method Description Example
find() Returns index s.find("a")
Example:
s = "hello world"
print(s.upper())
print(s.find("world"))
Searching and Manipulating Strings
s = "programming"
print("pro" in s) # True
print(s.count("m")) # 2
print(s.index("g")) # position
2. LISTS
A list is an ordered, mutable collection of items.
lst = [10, 20, 30]
List Slicing
lst[1:3] # elements from index 1 to 2
lst[:2] # first two elements
lst[::2] # skip pattern
Basic List Operations
Operation Example
Concatenation list1 + list2
Repetition list1 * 2
Membership x in list1
Built-In List Methods
Method Meaning
append(x) adds at end
insert(i,x) inserts at index
Method Meaning
remove(x) removes first occurrence
pop(i) removes element at index
sort() sorts list
reverse() reverses list
Example:
lst = [3,1,4]
lst.sort()
Copying Lists
Shallow copy: new = old.copy()
Deep copy: using copy module
Two-Dimensional Lists
matrix = [
[1,2,3],
[4,5,6]
]
print(matrix[1][2]) # 6
3. TUPLES
A tuple is an immutable collection of items.
t = (10,20,30)
Basic Tuple Operations
Concatenation → t1 + t2
Repetition → t1 * 2
Membership → x in t
Indexing and Slicing
t[1]
t[1:3]
Built-in Tuple Functions
Function Meaning
len(t) length
max(t) maximum
min(t) minimum
tuple(list) convert list → tuple
4. DICTIONARIES
A dictionary is an unordered collection of key-value pairs.
d = {"name":"Aarav", "age":20}
Dictionary Literals
Defined using { }.
Adding and Removing Keys
d["city"] = "Delhi" # add key
del d["age"] # remove key
Accessing and Replacing Values
print(d["name"])
d["name"] = "Kaira"
Traversing a Dictionary
for key in d:
print(key, d[key])
⭐ UNIT – 3
Functions, Modules, Recursion
1. Functions
A function is a block of reusable code.
Function Definition
def greet():
print("Hello")
Function Call
greet()
Return Statement
def add(x,y):
return x+y
Scope and Lifetime of Variables
Local variables → inside function
Global variables → outside function
x = 10 # global variable
def f():
y = 5 # local variable
Default Arguments
def greet(name="User"):
print("Hello", name)
Keyword Arguments
student(name="Asha", age=20)
***args and kwargs
args → multiple arguments
def total(*numbers):
print(sum(numbers))
kwargs → keyworded arguments
def info(**details):
print(details)
Commonly Used Modules
Module Purpose
math mathematical functions
random random numbers
os system operations
datetime date/time functions
Generating Random Numbers
import random
print(random.randint(1,10))
Command Line Arguments
Using sys.argv:
import sys
print(sys.argv[1])
2. Recursion
Recursion is the process where a function calls itself.
Example: Factorial Using Recursion
def factorial(n):
if n == 1:
return 1
return n * factorial(n-1)
Properties of Recursion
Base case
Recursive step
Stack memory used
⭐ UNIT – 4
Files, Modules, Packages
1. Files in Python
Types of Files
1. Text files (.txt, .csv)
2. Binary files (.dat, .bin)
Creating and Reading Text Files
Write Mode
f = open("data.txt", "w")
f.write("Hello")
f.close()
Read Mode
f = open("data.txt", "r")
print(f.read())
f.close()
File Methods
Method Purpose
read() reads entire file
readline() reads one line
write() writes text
close() closes file
Binary Files
f = open("sample.bin","wb")
f.write(b"ABC")
Pickle Module
Used for object serialization.
import pickle
data = {"name":"Aarav"}
f = open("file.dat","wb")
pickle.dump(data,f)
Reading and Writing CSV Files
import csv
with open("data.csv","w",newline='') as f:
w = csv.writer(f)
w.writerow(["Name","Marks"])
w.writerow(["Aarav",90])
2. Exception Handling
try:
x = 10/0
except ZeroDivisionError:
print("Cannot divide")
finally:
print("Done")
3. Python Modules
math Module
import math
print(math.sqrt(16))
random Module
import random
print(random.random())
os and os.path
import os
print(os.getcwd())
datetime/time
import datetime
print(datetime.datetime.now())
4. Python Packages
Numpy
Used for numerical computations.
import numpy as np
arr = np.array([1,2,3])
Pandas
Used for data handling (tables).
import pandas as pd
df = pd.DataFrame({"Name":["Arohi"], "Marks":[90]})
Matplotlib
Used for plotting.
import matplotlib.pyplot as plt
plt.plot([1,2,3],[3,2,5])
plt.show()
Keras
Used for deep learning models.
from keras.models import Sequential
from keras.layers import Dense
What do Python packages do?
A Python package is a collection of modules grouped together to organize
code and provide ready-made functionalities. Packages help us reuse code
instead of writing everything from scratch.
They make programming easier by offering pre-built functions for tasks like:
Mathematical operations (NumPy)
Data handling and analysis (Pandas)
Plotting graphs and visualizations (Matplotlib)
Machine learning and deep learning (Keras, TensorFlow)
Working with files, dates, system operations (os, datetime, csv, etc.)
⭐ Simple line you can say in viva:
“Python packages provide pre-written code for specific tasks so that we don’t
have to build everything from scratch. They help in organizing code and allow
us to perform complex operations easily.”
⭐ Examples (very important for viva)**
NumPy package → numerical computing, arrays
Pandas package → data analysis, tables
Matplotlib package → graphs and charts
Keras package → deep learning models
PROGRAMMING FUNDAMENTALS LAB VIVA
QUESTIONS
✅ 1) Remainder of two numbers (modulo operator)
What I did:
Used % operator to find remainder.
Easy Example:
10 % 4 = 2
Output I got:
Remainder = 2
✅ 2) Check if two lists have a common member
What I did:
Compared items of one list with another using a loop.
Easy Example:
list1 = [1, 5, 9]
list2 = [3, 4, 5]
Common element = 5
Output I got:
True
✅ 3) Sort a dictionary by values
What I did:
Used sorted() with lambda to sort values.
Easy Example:
d = {"a": 3, "b": 1, "c": 2}
Output I got:
Ascending → {'b':1, 'c':2, 'a':3}
Descending → {'a':3, 'c':2, 'b':1}
✅ 4) Demonstrate input(), print(), sep, end, format()
What I did:
Took user input and printed using sep, end, and format.
Easy Example:
Input: name = "Aman"
print("Hello", name, sep="---", end="!!!")
Output I got:
Hello---Aman!!!
✅ 5) Count letters and digits
What I did:
Used isdigit() and isalpha() to count.
Easy Example:
Input: "a1b2"
Letters = 2, Digits = 2
Output I got:
Letters: 2
Digits: 2
✅ 6) Substring from 3rd to 5th character
What I did:
Used slicing: string[2:5]
Easy Example:
String = "PYTHON"
Substring = "THO"
Output I got:
THO
✅ 7) Remove a key-value pair from a dictionary
What I did:
Used del to remove a specific key.
Easy Example:
Before: {"name": "Amit", "age": 20}
Delete "age"
Output I got:
{"name": "Amit"}
✅ 8) Read and write a binary file
What I did:
Opened file in "wb" and "rb" modes.
Easy Example:
Wrote: b"ABC"
Output I got:
Reading file → b'ABC'
✅ 9) Handle FileNotFoundError
What I did:
Used try–except when file doesn’t exist.
Easy Example:
Tried to open "abc.txt" (not present)
Output I got:
File does not exist.
✅ 10) Handle index out of range
What I did:
Used try–except to catch list index error.
Easy Example:
list = [10, 20, 30]
Access list[5]
Output I got:
Index out of range.
✅ 11) Student Class using str and len
What I did:
Returned readable text using __str__
Returned name length using __len__
Easy Example:
Student("Riya", "A")
Output I got:
Riya - A
Length = 4
✅ 12) Car Class (brand & model)
What I did:
Created Car class and printed attributes.
Easy Example:
Car("Honda", "City")
Output I got:
Brand: Honda
Model: City
✅ 13) Function to return sum of list elements
What I did:
Created a function that adds all elements.
Easy Example:
List = [5, 5, 10]
Output I got:
Sum = 20
✅ 14) operate() function using lambda
What I did:
Used lambda expressions for +, -, *, /
Easy Example:
operate(8, 2, "divide")
Output I got:
4.0
✅ 15) Plot sine wave from 0 to 2π
What I did:
Used numpy to generate values and matplotlib to plot sin(x).
Easy Example:
x = 0 to 6.28
y = sin(x)
Output I got:
A smooth sine wave graph.
✅ 16) NumPy array + mean, median, std deviation
What I did:
Created array using np.arange() and used numpy functions.
Easy Example:
Array = [1 2 3 4 5 6 7 8 9 10]
Output I got:
Mean = 5.5
Median = 5.5
Std Dev ≈ 2.87