Comprehensive Python Programming Fundamentals: A Structured Guide, Study notes of Computer Science

This revision guide is a well-organized, beginner-to-intermediate Python study resource that covers essential programming concepts through a combination of theoretical explanations and practical code examples. The document serves as a foundational reference for understanding Python's core functionality and object-oriented principles.

Typology: Study notes

2025/2026

Available from 01/06/2026

debarghaaa
debarghaaa 🇮🇳

2 documents

1 / 25

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Python:
Variables:
In Python, a variable is a name that refers to a value stored in the computer's memory. It's like a container that holds data which can be modified
during program execution.
Variables in Python:
Are created when you assign a value using the equal sign (=)
Do not need explicit declaration or type definition
Can store different types of data (integers, floats, strings, lists, etc.)
Follows naming conventions (start with a letter or underscore, can't use reserved keywords)
# Examples of variable assignment in Python
name = "John" # String variable
age  25 # Integer variable
height  1.75 # Float variable
is_student  True # Boolean variable
fruits = ["apple", "banana", "cherry"] # List variable
# Python variables are dynamically typed
x  10 # x is an integer
x = "hello" # x is now a string
Variables in Python are dynamically typed, meaning the type of a variable is determined at runtime based on the value it currently holds, and can
change throughout the program.
Data Types:
Python has several built-in data types that are categorized into different groups:
Numeric Types:
Python:
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19

Partial preview of the text

Download Comprehensive Python Programming Fundamentals: A Structured Guide and more Study notes Computer Science in PDF only on Docsity!

Python:

Variables:

In Python, a variable is a name that refers to a value stored in the computer's memory. It's like a container that holds data which can be modified during program execution.

Variables in Python:

Are created when you assign a value using the equal sign (=) Do not need explicit declaration or type definition Can store different types of data (integers, floats, strings, lists, etc.) Follows naming conventions (start with a letter or underscore, can't use reserved keywords)

Examples of variable assignment in Python

name = "John" # String variable age  25 # Integer variable height  1.75 # Float variable is_student  True # Boolean variable fruits = ["apple", "banana", "cherry"] # List variable

Python variables are dynamically typed

x  10 # x is an integer x = "hello" # x is now a string

Variables in Python are dynamically typed, meaning the type of a variable is determined at runtime based on the value it currently holds, and can change throughout the program.

Data Types:

Python has several built-in data types that are categorized into different groups:

Numeric Types:

int : Represents integer values (e.g., 10, -5, 0) float : Represents floating-point numbers (e.g., 3.14, -0.001, 2.0) complex : Represents complex numbers (e.g., 3+4j, 2-1j)

Numeric types examples

x  10 # int y  3.14 # float z  2  3j # complex

print(type(x)) # print(type(y)) # print(type(z)) #

Sequence Types:

str : Represents a sequence of characters (text) list : Ordered, mutable (alterable) collection of items tuple : Ordered, immutable (non alterable) collection of items

Sequence types examples

text = "Hello, Python!" # str numbers = 1, 2, 3, 4, 5 # list coordinates = 10, 20 # tuple

String operations

print(len(text)) # 14 print(text[05]) # "Hello" ; it starts from the index 0 upto (but not including) index 5

List operations (mutable)

numbers.append(6) # 1, 2, 3, 4, 5, 6 numbers[0]  10 # 10, 2, 3, 4, 5, 6

Tuple operations (immutable)

coordinates[0]  30 # Error! Tuples cannot be modified

Mapping Type:

dict : Collection of key-value pairs

Dictionary example

person = { "name": "Alice", "age" 30, "is_student" False }

Accessing dictionary values

print(person["name"]) # "Alice" person["age"]  31 # Update value person["city"] = "New York" # Add new key-value pair

As we know, string is just a series of characters, therefore, we’ll learn about string functions by performing a few program executions.

name=input("Enter your full name:")

#first string method - using len() function

result=len(name) print(result) #returns the length (as an intiger) of the string "name" once the input has been given by the user

 Enter your full name: Debargha Brahma  15

#second string method - using .find() method name=input("Enter your full name:")

result=name.find(" ") #returns the position of the first occurance of any character in a string, here in this case is a spac e print(result)

 Enter your full name: Debargha Brahma  8

#if there are no associated results, then the find method returns 1 as a result

#third string method- using .rfind() , i.e. reverse find method name=input("Enter your full name:")

result=name.rfind("a") #returns the position of the last occurance of any character in a string, here in this case is an a print(result)

 Enter your full name: Debargha Brahma  14

#considering another example case

name=input("Enter your full name:")

result=name.rfind("q") print(result)

 Enter your full name: Debargha Brahma >>>  1 #if there are no associated results, then the rfind method returns 1 as a result

#fourth string method- .capitalize()

name=input("Enter your full name:")

name=name.capitalize() #returns the string after capitalizing the first element print(name)

 Enter your full name: debargha brahma  Debargha brahma

#fifth string method- .upper() name=input("Enter your full name:")

name=name.upper() #unlike the capitalize function, upper method returns the capitalized version of the original string print(name)

 Enter your full name: Debargha Brahma  DEBARGHA BRAHMA

#sixth string method- .lower() name=input("Enter your full name:")

name=name.lower() #lower method returns the lowercase version of the original string print(name)

 Enter your full name: DEBARGHA BRAHMA >>> debargha brahma Enter your full name: Debargha Brahma >>>debargha brahma

#seventh string method- .isdigit() ; returns either True or False name=input("Enter your full name:")

result=name.isdigit() #if the string is compraised of digits, the result is either true or false print(result)

Enter your full name: Debargha Brahma  False  Enter your full name: Debargha  False

#the reult only returns true if the string only contains digits

#eighth string method- .isalpha() ; returns True or False

name=input("Enter your full name:")

result=name.isalpha() #checks and returns a Boolean, True or False depending upon if the string is compraised of only alphabets or not print(result)

Enter your full name: Debargha Brahma  False #since the full name contains a white space which is not an alphabetical character  Enter your full name: Debargha  False  Enter your full name: Debargha  True  Enter your full name: DebarghaBrahma

Method Description Method Description Method Description Method Description where it was found

#validate user input exercise #1. username is no more than 12 charecters #2. username must not contain spaces #3. username must not contain digits

username= input("Enter your username:")

username.find(" ") username.isalpha()

if len(username)  12  print("username cannot exceed 12 characters") elif not username.find(" ") ==  1  print("the username cannot contain spaces") elif not username.isalpha(): print("the username cannot contain digits") else: print(f"Welcome{username}")

 Enter your username: debargha  Welcome debargha  Enter your username: debargha >>> the username cannot contain digits >>> username cannot exceed 12 characters  Enter your username: debargha 1105 >>> the username cannot contain spaces >>> the username cannot contain digits

Conditionals and Booleans:

Equal: == Not Equal: ! Greater than: > Less than: < Greater or equal: >= Less or equal: <= Object identity: is

Conditionals:

#example 1. language = input("Enter a language:")

if language == "Python": print(f"you're using {language} now") else:

print("No match")

 Enter a language  C  No Match  Enter a language  Python >>> you're using Python now

#example 2. language = input("Enter a language:")

if language == "Python": print(f"you're using {language} now") elif language == "C" : print(f"you're using {language} now")

else: print("No match")

#example 3. a= 1,2,3 b= 1,2,3

print (a is b)

 False

a= 1,2,3 b= a

print(id(a)) print(id(b)) print (a is b) # is equal to saying print (id(a) == id(b))

 2512644544768  2512644544768  True

Booleans:

And : and Or : or Not : not False values : false , none , zero (any numeric type) , ‘ʼ , ( ) , [ ] (any empty list) , { } (any empty mapping)

#example 1. user = "Admin" logged_in  True

if user == "Admin" and logged_in :

>>> banana >>> cherry

is a control flow statement that repeatedly executes a block of code a set number of times. It's used when you know the number of iterations in advance and is composed of three main parts: an initialization, a condition, and an increment or decrement

example 2 iterator in a for loop

count  0 while count  5  print(f"The current count is: {count}") count  1 # Increment 'count' to eventually make the condition false

print("Loop finished.")

 The current count is: 0  The current count is: 1  The current count is: 2  The current count is: 3  The current count is: 4  Loop finished.

while loop is a control flow statement in programming that repeatedly executes a block of code as long as a specified Boolean condition remains true. It is an "entry-controlled" loop, meaning the condition is evaluated before each iteration of the loop body

Example 3 Creating a custom iterator class

class MyNumbers: def init(self): self.a  1

def iter(self): return self

def next(self): if self.a < 5  x = self.a self.a  1 return x else: raise StopIteration

myclass  MyNumbers() myiter = iter(myclass)

for x in myiter: print(x)

 1  2  3  4  5

Example 4 StopIteration exception

my_list = 1, 2, 3 my_iter = iter(my_list)

print(next(my_iter)) print(next(my_iter)) print(next(my_iter)) print(next(my_iter)) # This will raise StopIteration

 1  2  3  Traceback (most recent call last): File "<stdin>", line 1, in <module>  StopIteration

Common Built-in Iterators

Python provides several built-in functions that return iterators:

range() (^) - generates a sequence of numbers enumerate() - returns an iterator of tuples containing indices and values zip() - combines multiple iterables into tuples reversed() - returns a reversed iterator map() - applies a function to every item of an iterable filter() (^) - filters items based on a condition

Example: Using enumerate()

fruits = ['apple', 'banana', 'cherry']

for index, fruit in enumerate(fruits): print(f"{index}: {fruit}")

 0  apple  1  banana  2  cherry

Example: Using zip()

names = ['Alice', 'Bob', 'Charlie'] ages = 25, 30, 35

for name, age in zip(names, ages): print(f"{name} is {age} years old")

 Alice is 25 years old  Bob is 30 years old  Charlie is 35 years old

Functions:

length = len(marks) print("Length of the list:", length) sum_marks = sum(marks) print("Sum of all marks:", sum_marks) average = sum_marks / length print("Average of marks:", average) max_mark = max(marks) print("Maximum mark:", max_mark) min_mark = min(marks) print("Minimum mark:", min_mark) sorted_marks = sorted(marks) print("Sorted marks:", sorted_marks)

Length of the list: 11 Sum of all marks: 825 Average of marks: 75. Maximum mark: 100 Minimum mark: 50 Sorted marks: 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100

#Exam grade calculator example:

marks = [] for i in range (int(input("Enter the number of subjects: "))):

mark = float(input(f"Enter marks for subject {i+1}: ")) marks.append(mark)

sum_marks = sum(marks) length = len(marks) average = sum_marks / length print("Average of marks:", average)

def calculate_grade(average): if average>=80 return "A" elif average>=60 return "B" elif average>=50 return "C" else: return "D"

grade=calculate_grade(average) print("Grade:", grade)

Enter the number of subjects: 5 Enter marks for subject 1 60 Enter marks for subject 2 90 Enter marks for subject 3 66 Enter marks for subject 4 35

Enter marks for subject 5 70 Average of marks: 64. Grade: B

Dictionaries:

In Python, a dictionary is an unordered collection of data stored as key-value pairs. It's one of the most powerful and flexible built-in data structures, allowing you to store and retrieve data using unique keys rather than numeric indices.

Key characteristics of dictionaries:

They are defined using curly braces {}^ with key-value pairs separated by colons Keys must be unique and immutable (strings, numbers, or tuples) Values can be of any data type and can be duplicated They are mutable, meaning you can add, modify, or remove key-value pairs after creation They provide fast lookup times for accessing values by their keys

Creating Dictionaries:

Basic dictionary creation

student = { "name": "Hitesh", "age" 25, "course": "Python" } print(student)

Empty dictionary

empty_dict = {}

or

empty_dict = dict()

Accessing Dictionary Values

Access using keys

print(student["name"]) # Output: Hitesh

Using get() method (safer approach)

print(student.get("age")) # Output: 25 print(student.get("grade", "Not Found")) # Returns default if key doesn't exist

Modifying Dictionaries

Adding new key-value pair

student["grade"] = "A"

Modifying existing value

student["age"]  26

Removing items

del student["course"] # Removes specific key-value pair

Accessing nested values

print(students["student1"]["name"]) # Output: Hitesh

Key Points

Dictionaries are mutable and unordered (in Python 3.6+, insertion order is maintained) Keys must be unique and of immutable type (strings, numbers, tuples) Dictionaries provide O(1) average time complexity for lookups Use get() method instead of bracket notation to avoid KeyError Dictionaries are ideal for storing related data with descriptive keys

Exception handling:

Exception handling in Python is a mechanism that allows you to gracefully handle errors and unexpected situations that may occur during program execution. Instead of letting your program crash when an error occurs, exception handling lets you catch these errors and respond to them appropriately.

Key components of exception handling:

Uses try^ , except^ , else^ , and finally^ blocks to manage errors Prevents program crashes by catching and handling runtime errors Allows you to provide meaningful error messages to users Helps maintain program flow even when unexpected situations occur

Common Python exceptions and how to handle them:

  1. ZeroDivisionError Occurs when attempting to divide a number by zero.

ZeroDivisionError example

try: numerator  10 denominator  0 result = numerator / denominator print(result) except ZeroDivisionError: print("Error: Cannot divide by zero!") print("Please enter a non-zero denominator.")

 Error: Cannot divide by zero! Please enter a non-zero denominator.

  1. ValueError

Occurs when a function receives an argument of the correct type but inappropriate value.

ValueError example

try: age = int(input("Enter your age: ")) print(f"You are {age} years old") except ValueError:

print("Error: Please enter a valid number!")

 Enter your age: twenty Error: Please enter a valid number!

  1. TypeError

Occurs when an operation is performed on incompatible data types.

TypeError example

try: result = "Hello"  5 print(result) except TypeError: print("Error: Cannot concatenate string with integer!") print("Convert the integer to string first.")

 Error: Cannot concatenate string with integer! Convert the integer to string first.

  1. IndexError

Occurs when trying to access an index that doesn't exist in a list or sequence.

IndexError example

try: numbers = 1, 2, 3, 4, 5 print(numbers[10]) except IndexError: print("Error: Index out of range!") print(f"The list only has {len(numbers)} elements.")

 Error: Index out of range! The list only has 5 elements.

  1. KeyError

Occurs when trying to access a dictionary key that doesn't exist.

KeyError example

try: student = {"name": "Hitesh", "age" 25  print(student["grade"]) except KeyError: print("Error: Key not found in dictionary!") print("Available keys:", list(student.keys()))

 Error: Key not found in dictionary! Available keys: ['name', 'age']

  1. FileNotFoundError

Occurs when trying to open a file that doesn't exist.

FileNotFoundError example

except Exception as e: print(f"An unexpected error occurred: {e}")

 Enter first number: 10 Enter second number: 0 Error: Cannot divide by zero!

Using else and finally

The else block executes if no exception occurs, and finally always executes regardless of exceptions.

Complete exception handling with else and finally

try: file = open("data.txt", "r") content = file.read() print(content) except FileNotFoundError: print("Error: File not found!") else: print("File read successfully!") finally: print("Execution completed.")

Clean up operations go here

try: file.close() except: pass

>>> Error: File not found! Execution completed.

Best Practices

Be specific about which exceptions you're catching Don't use bare except: clauses as they catch all exceptions including system exits Use finally for cleanup operations like closing files or database connections Provide meaningful error messages to help users understand what went wrong Log exceptions for debugging purposes in production environments

OOP in Python:

Object-Oriented Programming (OOP) in Python is a programming paradigm that structures code by bundling related properties and behaviours into individual objects, allowing you to model real-world entities and their interactions. Python is an object-oriented language that lets you organize your code using classes and objects for better organization, reusability, and maintainability.

#Example of a Student class: class Student: def init(self, roll=0, name="", marks=None): if marks is None: marks =  0  * 5

ensure exactly 5 marks

marks = (marks +  0 *5 5 

self.roll = roll self.name = name self.marks = marks self.total = sum(self.marks) self.grade = 'F' self.calculateGrade()

def calculateGrade(self): average = self.total / 5 if average  90  self.grade = 'A' elif average  80  self.grade = 'B' elif average  70  self.grade = 'C' elif average  60  self.grade = 'D' else: self.grade = 'F'

def display(self): print("Roll Number:", self.roll) print("Name:", self.name) print("Marks:", self.marks) print("Total:", self.total) print("Grade:", self.grade)

if name == "main": n = int(input("Enter number of students: ")) students = [] for i in range(n): r = int(input("Enter roll number: ")) name = input("Enter name: ") m = [] for j in range(5): mark = int(input(f"Enter marks for subject {j+1}: ")) m.append(mark) student  Student(r, name, m) students.append(student)

print("\nStudent details:") for s in students: s.display() print("-" * 20 >>> Student details: Roll Number: 2 Name: ansh Marks: 7, 16, 82, 55, 13 Total: 173 Grade: F

Roll Number: 3