0% found this document useful (0 votes)
23 views56 pages

Basic Python Programming

The document provides an introduction to basic Python programming concepts, including syntax, variables, data types, and input/output operations. It covers essential elements such as indentation, comments, keywords, and the use of built-in functions for handling data. Additionally, it discusses file I/O operations and type casting, emphasizing the importance of understanding data types for effective programming.

Uploaded by

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

Basic Python Programming

The document provides an introduction to basic Python programming concepts, including syntax, variables, data types, and input/output operations. It covers essential elements such as indentation, comments, keywords, and the use of built-in functions for handling data. Additionally, it discusses file I/O operations and type casting, emphasizing the importance of understanding data types for effective programming.

Uploaded by

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

3.Introduction to Summary of what I learned during the course (e.g.

, programming
languages, tools, etc.)

Basic Python Programming:-

 Syntax, Variables, Data types (int, float, string, boolean)

Python Syntax: The Foundation of the Language

Python syntax refers to the set of rules that governs the structure of a program. It's the grammar of the
language, dictating how to write code that the Python interpreter can understand and execute.

Indentation

One of the most distinctive features of Python syntax is its use of indentation to define code blocks. Unlike
many other programming languages that use curly braces {} to group statements, Python uses whitespace.
The number of spaces or tabs must be consistent within a single block. A standard is to use four spaces for
each level of indentation.

 Correct:

Python

if True:
print("This code is inside the if block.")

 Incorrect (IndentationError):

Python

if True:
print("This code is inside the if block.")
print("This will cause an error.")

Comments

Comments are lines of text within a program that are ignored by the Python interpreter. They are used to
explain the code and make it more readable for humans.

 Single-line comments start with the hash symbol #.

Python

# This is a single-line comment.

 Multi-line comments can be created by using three single or double quotes ''' or """. This is often
called a docstring when used at the beginning of a function, class, or module.

Python

"""
This is a multi-line comment.
It can span across multiple lines.
"""

Keywords

Keywords are reserved words in Python that have a specific meaning and cannot be used as variable
names. Examples include if, else, for, while, def, class, import, and True, False, None.

Statements

A statement is a single logical instruction that Python can execute. Examples include variable assignments,
function calls, and control flow structures. Each statement is typically written on a new line.

Variables: Storing Data

A variable is a named location in memory used to store data. In Python, you create a variable the moment
you first assign a value to it. Python is dynamically typed, meaning you do not need to declare a variable's
type before using it. The type is inferred from the value it holds.

Naming Rules

 Variable names must start with a letter (a-z, A-Z) or an underscore (_).
 The rest of the name can contain letters, numbers (0-9), and underscores.
 Names are case-sensitive (my_variable is different from My_Variable).
 Variable names should be descriptive and follow PEP 8, the official Python style guide. For example,
snake_case (lowercase with underscores) is the convention for variable and function names.

Assignment

The assignment operator is the equal sign (=).

Python
my_age = 30 # Assigns the integer 30 to the variable my_age.
name = "Alice" # Assigns the string "Alice" to the variable name.

Data Types: Classifying Data

A data type classifies the kind of values a variable can hold. Understanding data types is crucial because
they determine what operations can be performed on the data. Python has several built-in data types, but
the most fundamental are integers, floats, strings, and booleans.

1. Integers (int)

An integer is a whole number, positive or negative, without a decimal point. Integers in Python have
arbitrary precision, meaning they can be as large as your system's memory allows.

 Creation:

Python

age = 25
year = -2023
large_number = 99999999999999999999

 Operations: You can perform standard arithmetic operations like addition (+), subtraction (-),
multiplication (*), and division (/). The result of int division is a float. For integer division (where the
result is an integer, discarding the remainder), use //.

Python

result_add = 10 + 5 # 15
result_div = 10 / 3 # 3.3333... (float)
result_int_div = 10 // 3 # 3

2. Floating-Point Numbers (float)

A float (or floating-point number) is a number with a decimal point. Floats are used to represent real
numbers and are often used for calculations involving fractions or precise measurements.

 Creation:

Python

pi = 3.14159
temperature = 25.5

 Operations: Standard arithmetic operations apply. Be aware that floating-point arithmetic can
sometimes have precision issues due to how computers store these numbers.

Python

area = 2.5 * 4.0 # 10.0

3. Strings (str)

A string is an ordered sequence of characters, used to store text. Strings are immutable, meaning once a
string is created, its contents cannot be changed.

 Creation: Strings are created by enclosing text in single quotes ('...'), double quotes ("..."), or triple
quotes ('''...''' or """..."""). Using triple quotes allows for multi-line strings.

Python

greeting = "Hello, world!"


name = 'Charlie'
message = """This is a
multi-line string."""

 Operations:
o Concatenation: Joining strings using the + operator.

Python

full_name = "John" + " " + "Doe" # "John Doe"


o Indexing: Accessing individual characters using square brackets []. The first character is at
index 0.

Python

first_char = greeting[0] # 'H'

o Slicing: Extracting a substring.

Python

substring = greeting[0:5] # "Hello"

o Methods: Strings have many built-in methods for manipulation, such as upper(), lower(), strip(),
split(), and replace().

Python

upper_case = greeting.upper() # "HELLO, WORLD!"

4. Booleans (bool)

A boolean is a data type that can only have one of two values: True or False. Booleans are fundamental for
conditional logic and control flow.

 Creation:

Python

is_sunny = True
is_raining = False

 Operations: Booleans are used in comparison operators (==, !=, <, >, <=, >=) and logical operators
(and, or, not).

Python

# Comparison
is_equal = (5 == 5) # True
is_not_equal = (5 != 10) # True

# Logical
is_valid = is_sunny and not is_raining # True

Boolean values are also the result of many conditional statements and expressions. They are at the heart
of if statements and while loops, determining the flow of a program.
 Input/output operations

Input/Output (I/O) operations are a fundamental part of almost every programming language, including
Python. They are the processes by which a program communicates with the outside world.

 Input is the process of a program receiving data from an external source, such as a user, a file, or
another program.
 Output is the process of a program sending data to an external destination, such as the screen
(console), a file, or a network.

Python provides built-in functions and methods to handle these operations efficiently.

Standard Input and Output

The most common I/O operations involve the standard streams: standard input (stdin), standard output
(stdout), and standard error (stderr).

 Standard Input (stdin): The source from which a program reads input. By default, this is the
keyboard.
 Standard Output (stdout): The destination to which a program writes its output. By default, this is
the console or terminal.
 Standard Error (stderr): The destination to which a program writes error messages. By default, this
is also the console.

The print() Function for Output

The print() function is the most common way to display output on the console. It's a versatile function that
can output text, numbers, variables, and the results of expressions.

Basic Usage: The simplest form of print() takes one or more arguments and prints them to the console,
followed by a newline.

Python
print("Hello, world!")
print(123)

Multiple Arguments: You can pass multiple arguments to print(), separated by commas. The function will
convert each argument to a string and separate them with a space by default.

Python
name = "Alice"
age = 30
print("My name is", name, "and my age is", age)
# Output: My name is Alice and my age is 30

Customizing Output: The print() function has two optional keyword arguments that offer powerful
customization:

 sep (separator): Specifies the string to use between arguments. The default is a single space ' '.
 end: Specifies the string to append at the end of the output. The default is a newline character '\n'.
Python
# Using `sep` to change the separator
print("Python", "is", "awesome", sep="-")
# Output: Python-is-awesome

# Using `end` to prevent a newline


print("Starting...", end=" ")
print("Done!")
# Output: Starting... Done!

# A more complex example


print("Path:", "C:", "Users", "Documents", sep="/", end="\n\n")
# Output: Path:/C:/Users/Documents
# (Followed by an extra newline)

Formatting Output: For more control over string formatting, especially when combining variables with
text, you can use:

 f-strings (Formatted String Literals): Introduced in Python 3.6, f-strings are the modern and most
readable way to format strings. You prefix a string with f and embed expressions inside curly braces
{}.

Python

item = "apple"
price = 1.25
print(f"The cost of an {item} is ${price:.2f}.")
# Output: The cost of an apple is $1.25.

The :.2f is a format specifier that rounds the float to two decimal places.

 .format() method: An older but still widely used method. It uses curly braces as placeholders, which
are then filled by arguments passed to the .format() method.

Python

print("The cost of a {} is ${:.2f}.".format(item, price))


# Output: The cost of an apple is $1.25.

The input() Function for Input

The input() function is used to read a line of text from the standard input (the keyboard). It pauses the
program's execution until the user types something and presses Enter.

Basic Usage: The function takes a single optional argument, which is a prompt displayed to the user before
they enter their input. The value returned by input() is always a string, regardless of what the user types.

Python
# Simple input
user_input = input("Please enter your name: ")
print("Hello,", user_input)

Handling Different Data Types: Since input() always returns a string, you must explicitly convert the input
to the desired data type if you need to perform numerical operations. You can use type casting functions
like int() or float().
Python
# Getting a number from the user
age_str = input("Please enter your age: ")
age_int = int(age_str)

# Using the converted integer


next_year_age = age_int + 1
print(f"You will be {next_year_age} next year.")

# Handling potential errors (e.g., if the user enters text)


try:
number = int(input("Enter a number: "))
print(f"You entered the number {number}.")
except ValueError:
print("That was not a valid number!")

The try...except block is a crucial way to handle potential ValueError exceptions that can occur if the user
provides input that cannot be converted to an integer.

File I/O Operations

Beyond the console, a program often needs to read from or write to files. This is essential for tasks like
data persistence, configuration management, and processing large datasets.

Opening and Closing Files

To perform any file operation, you must first open the file using the built-in open() function. This function
returns a file object, which is used to interact with the file.

The open() function takes two main arguments:

 file: The path to the file.


 mode: A string indicating the purpose of opening the file (e.g., reading, writing, appending).

Common modes include:

 'r' (read): Default mode. Opens a file for reading. The file must exist.
 'w' (write): Opens a file for writing. Creates a new file if it doesn't exist, or overwrites the contents if
it does.
 'a' (append): Opens a file for writing, but appends new data to the end of the file instead of
overwriting.
 'r+': Opens a file for both reading and writing.
 't' (text): Default mode. Opens the file in text mode.
 'b' (binary): Opens the file in binary mode.

It is crucial to close a file after you are done with it to free up system resources and ensure all data is
written to the disk. You use the .close() method on the file object.

Python
# Open a file for writing
file_writer = open('my_notes.txt', 'w')
file_writer.write("This is my first line.\n")
file_writer.close()
The with Statement: The Best Practice

Manually closing files can be error-prone, especially if an error occurs before the .close() call. The with
statement is the recommended way to handle file I/O because it automatically ensures the file is closed,
even if an exception occurs.

Python
with open('my_notes.txt', 'w') as file_writer:
file_writer.write("This is a new line.\n")
file_writer.write("This will overwrite the old content.\n")
# The file is automatically closed here

Reading from Files

Once a file is open for reading ('r'), you can use various methods to read its content:

 .read(): Reads the entire file content into a single string. This can be inefficient for very large files.

Python

with open('my_notes.txt', 'r') as file_reader:


content = file_reader.read()
print(content)

 .readline(): Reads a single line from the file.

Python

with open('my_notes.txt', 'r') as file_reader:


line1 = file_reader.readline()
line2 = file_reader.readline()
print(line1)
print(line2)

 .readlines(): Reads all lines into a list of strings.

Python

with open('my_notes.txt', 'r') as file_reader:


lines_list = file_reader.readlines()
print(lines_list)

 Iterating over the file object: This is the most memory-efficient way to read a file line-by-line,
especially for large files.

Python

with open('my_notes.txt', 'r') as file_reader:


for line in file_reader:
print(line.strip()) # .strip() removes leading/trailing whitespace including the newline

Writing to Files

When a file is opened for writing ('w'), you use the .write() method to write a string to the file.

Python
with open('shopping_list.txt', 'w') as file_writer:
file_writer.write("Milk\n")
file_writer.write("Eggs\n")
file_writer.write("Bread\n")

If you use the 'a' (append) mode, the new content will be added to the end of the file.

Python
with open('shopping_list.txt', 'a') as file_writer:
file_writer.write("Cheese\n")

The combination of standard I/O (console) and file I/O operations gives a Python program the capability to
interact with users and manage data in a persistent and scalable manner.
 Type casting and basic operators
Type casting, also known as type conversion, is the process of changing the data type of a variable from one
type to another. It's a fundamental operation in Python because different data types support different
operations. For example, you can't perform mathematical calculations on a string, and you can't join a
number to a string without converting it first.

Python is a dynamically typed language, meaning you don't declare a variable's type when you create it; the
interpreter infers it. However, you often need to manually convert types to perform specific tasks.

The Need for Type Casting

Consider a program that takes user input. The input() function always returns a string. If you want to use
the input in a numerical calculation, you must convert it to an integer or a float.

Python
user_age_str = input("Enter your age: ")
# The variable user_age_str is a string, e.g., '25'

# This would cause a TypeError:


# new_age = user_age_str + 1

# Type casting to perform the calculation


user_age_int = int(user_age_str)
new_age = user_age_int + 1
print(f"Next year, you will be {new_age}.")

Common Type Casting Functions

Python provides built-in functions for converting between common data types.

 int(): Converts a value into an integer.


o Can convert a string containing a whole number, a float, or a boolean.
o It truncates floats (discards the decimal part).

Python

int('100') # 100
int(3.14) # 3
int(True) # 1

⚠️Note: int() will raise a ValueError if the string doesn't represent a valid integer (e.g.,
int('hello')).

 float(): Converts a value into a floating-point number.


o Can convert a string containing a number, an integer, or a boolean.

Python

float('99.5') # 99.5
float(50) # 50.0
float(False) # 0.0

 str(): Converts a value into a string.


o This is useful for concatenating numbers with text.
Python

str(123) # '123'
str(4.56) # '4.56'

Python

item_count = 5
message = "We have " + str(item_count) + " items left."
print(message)
# Output: We have 5 items left.

 bool(): Converts a value into a boolean (True or False).


o The boolean value is determined by the "truthiness" of the input.
o False for: 0 (integer), 0.0 (float), '' (empty string), [] (empty list), () (empty tuple), {}
(empty dictionary), and None.
o True for all other non-empty or non-zero values.

Python

bool(0) # False
bool(10) # True
bool('') # False
bool('hello') # True

Basic Operators in Python

Operators are special symbols that perform operations on values and variables. The values an operator
works on are called operands. Python supports a wide range of operators, which can be categorized into
groups.

1. Arithmetic Operators

These are used to perform mathematical calculations.

Operator Description Example Result


+ Addition 10 + 5 15
- Subtraction 10 - 5 5
* Multiplication 10 * 5 50
/ Division 10 / 3 3.333...
// Floor Division 10 // 3 3
% Modulus (Remainder) 10 % 3 1
** Exponentiation 2 ** 3 8
Export to Sheets

2. Assignment Operators

These are used to assign values to variables.

Operator Description Example Equivalent to


= Assigns a value x = 5 x = 5
+= Adds and assigns x += 3 x = x + 3
-= Subtracts and assigns x -= 3 x = x - 3
*= Multiplies and assigns x *= 3 x = x * 3
Operator Description Example Equivalent to
/= Divides and assigns x /= 3 x = x / 3
//= Floor divides and assigns x //= 3 x = x // 3
%= Modulus and assigns x %= 3 x = x % 3
**= Exponentiation and assigns x **= 3 x = x ** 3
Export to Sheets

3. Comparison (Relational) Operators

These are used to compare two values and return a boolean result (True or False).

Operator Description Example Result


== Equal to 10 == 10 True
!= Not equal to 10 != 5 True
> Greater than 10 > 5 True
< Less than 10 < 5 False
>= Greater than or equal to 10 >= 10 True
<= Less than or equal to 10 <= 5 False
Export to Sheets

4. Logical Operators

These are used to combine conditional statements and evaluate their logical relationship.

 and: Returns True if both operands are True.

Python

(5 > 3) and (10 == 10) # True


(5 > 3) and (10 == 5) # False

 or: Returns True if at least one operand is True.

Python

(5 > 3) or (10 == 5) # True

 not: Reverses the logical state of the operand.

Python

not(5 > 3) # False

5. Identity and Membership Operators

 Identity Operators (is, is not): Compare the memory location of two objects. They check if the
operands are the exact same object.

Python

x = [1, 2, 3]
y = [1, 2, 3]
z = x
print(x is y) # False (different objects in memory)
print(x is z) # True (z refers to the same object as x)
 Membership Operators (in, not in): Test if a sequence (like a string, list, or tuple) contains a
specific value.

Python

my_list = ['apple', 'banana', 'orange']


print('banana' in my_list) # True
print('grape' not in my_list) # True

Understanding how to use these operators and perform type casting is essential for writing effective and
functional Python programs.

2. Control Structures
 Conditional Statements: The if, elif, and else

Conditional statements are a core part of programming logic. They allow a program to make decisions and
execute different blocks of code based on whether a certain condition is True or False. This is how
programs can respond dynamically to different inputs and states.

The if Statement

The if statement is the most basic conditional. It executes a block of code only if the condition is True.

 Syntax:

Python

if condition:
# code to be executed if the condition is True

 Explanation:
o condition: This is a boolean expression that evaluates to either True or False.
o A colon : marks the end of the if statement.
oThe code block to be executed is indented. Indentation is mandatory in Python to define the
scope of the code.
 Example:

Python

age = 20
if age >= 18:
print("You are an adult.")

Since the condition age >= 18 is True, the print statement is executed.

The else Statement

The else statement is used to execute a block of code when the if condition is False. It provides an
alternative path for the program to follow.

 Syntax:

Python

if condition:
# code if condition is True
else:
# code if condition is False

 Example:

Python

age = 15
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")

In this case, age >= 18 is False, so the code under the else block is executed.
The elif Statement

The elif statement (short for "else if") allows you to check multiple conditions sequentially. Python checks
the conditions from top to bottom, and the first one that evaluates to True has its corresponding code block
executed. The rest are skipped.

 Syntax:

Python

if condition1:
# code if condition1 is True
elif condition2:
# code if condition2 is True
elif condition3:
# code if condition3 is True
else:
# code if none of the above are True

An if...elif...else block can have as many elif statements as needed, and the else block is
optional.

 Example:

Python

score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")

The program first checks if score >= 90 (False). Then it checks score >= 80 (True), so it prints
"Grade: B" and skips the remaining checks.
A response of 6000 words is not necessary to explain control structures in Python. Here is a comprehensive
and detailed explanation of conditional statements, looping structures, and loop control statements,
presented concisely.

Looping Structures: for and while

Loops are used to execute a block of code repeatedly. They are essential for tasks like iterating over a list of
items, performing calculations a specific number of times, or reading data from a file line by line.

The for Loop

The for loop is used to iterate over a sequence (like a list, tuple, string, or range) or any other iterable
object. It executes the code block for each item in the sequence.

 Syntax:

Python

for item in sequence:


# code to be executed for each item

 Explanation:
o item: A temporary variable that holds the current item from the sequence during each
iteration.
o sequence: The iterable object you want to loop over.
 Examples:
o Iterating over a list:

Python

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


for fruit in fruits:
print(f"I like {fruit}.")

o Iterating using range(): The range() function generates a sequence of numbers.

Python

for i in range(5): # Generates numbers from 0 to 4


print(i)

The range() function can also take a start and a step. range(start, stop, step).

The while Loop

The while loop executes a block of code as long as a specified condition is True. The condition is checked
at the beginning of each iteration.

 Syntax:

Python

while condition:
# code to be executed as long as the condition is True

 Explanation:
o The loop continues indefinitely until the condition becomes False.
o You must ensure that the condition will eventually become False to avoid an infinite loop.
This is typically done by modifying a variable inside the loop.
 Example:

Python

count = 0
while count < 5:
print(f"Count is: {count}")
count += 1 # This line is crucial to eventually make the condition False

The loop will run five times (for count 0, 1, 2, 3, 4), and then stop.

Loop Control Statements

Loop control statements change the execution flow of a loop from its normal sequence. They give you
more granular control over when to exit a loop or skip an iteration.

break

The break statement is used to exit a loop prematurely. When break is encountered, the program
immediately jumps to the code that follows the loop, completely ignoring any remaining iterations.

 Usage: break is often used within an if statement to stop a loop when a specific condition is met.
 Example:

Python

for number in range(10):


if number == 5:
break # Exit the loop when number is 5
print(number)
# Output:
# 0
# 1
# 2
# 3
# 4

continue

The continue statement is used to skip the current iteration of the loop and move on to the next one.
When continue is encountered, the rest of the code in the current iteration is skipped, and the loop
continues with the next item or condition check.

 Usage: continue is useful for filtering or skipping unwanted items during an iteration.
 Example:

Python

for number in range(10):


if number % 2 == 0:
continue # Skip even numbers
print(number)
# Output:
# 1
# 3
# 5
# 7
# 9

pass

The pass statement is a placeholder statement that does nothing. It's a null operation. It's used when the
syntax requires a statement but you don't want to execute any code.

 Usage: pass is often used when defining an empty function, class, or loop to avoid a SyntaxError.
 Example:

Python

# Placeholder for a future loop


for number in range(10):
# We don't have code for this loop yet
pass

Python

# Placeholder for an if block


if some_condition:
pass
else:
print("Condition was false.")

The pass statement keeps the program syntactically correct, allowing you to fill in the code later.
3. Data Structures in Python
 Lists, Tuples, Sets, and Dictionaries
 Indexing, slicing, and built-in functions
 Nested data structures

Data Structures in Python: An Overview

In Python, a data structure is a way of organizing and storing data so it can be accessed and modified
efficiently. They are a fundamental building block of programming, allowing you to handle collections of
data in a structured manner. The four most common built-in data structures are Lists, Tuples, Sets, and
Dictionaries.

1. Lists

A list is an ordered, mutable collection of items. "Ordered" means the items have a defined position or
index, and "mutable" means you can change the list after it's created (add, remove, or modify elements).
Lists can contain items of different data types.

Creation

Lists are created using square brackets [] with items separated by commas.

Python
my_list = [1, 2, 3, "apple", True]

Indexing and Slicing

 Indexing: Access a single item by its position (index). Indexes start at 0 for the first item. Negative
indexes count from the end (-1 is the last item).

Python

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


print(fruits[0]) # Output: apple
print(fruits[-1]) # Output: cherry

 Slicing: Extract a portion of the list. The syntax is [start:stop:step]. The slice includes the item
at start but excludes the item at stop.

Python

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[2:5]) # Output: [2, 3, 4]
print(numbers[:3]) # Output: [0, 1, 2] (from beginning)
print(numbers[7:]) # Output: [7, 8, 9] (to end)
print(numbers[::2]) # Output: [0, 2, 4, 6, 8] (every second item)

Built-in Functions and Methods

Lists have many useful methods.

 append(): Adds an item to the end of the list.


 insert(): Inserts an item at a specified index.
 remove(): Removes the first occurrence of a value.
 pop(): Removes and returns the item at a specified index (or the last item).
 sort(): Sorts the list in place.
 len(): A built-in function that returns the number of items.

2. Tuples

A tuple is an ordered, immutable collection of items. "Immutable" means you cannot change, add, or
remove items after the tuple is created. This makes tuples faster than lists and useful for storing data that
should not change.

Creation

Tuples are created using parentheses ().

Python
my_tuple = (1, "hello", 3.14)

A single-item tuple requires a trailing comma: (1,).

Indexing and Slicing

Indexing and slicing work exactly the same as with lists.

Python
coordinates = (10, 20, 30, 40)
print(coordinates[1]) # Output: 20
print(coordinates[1:3]) # Output: (20, 30)

However, since tuples are immutable, you cannot assign a new value to an index (e.g., coordinates[0] =
5 would cause an error).

Built-in Functions

Tuples have fewer built-in methods than lists because they are immutable.

 count(): Returns the number of times a value appears.


 index(): Returns the index of the first occurrence of a value.
 len(): Returns the number of items.

3. Sets

A set is an unordered, mutable collection of unique items. "Unordered" means items have no defined index,
so you cannot access them using a number. "Unique" means duplicate values are automatically removed.
Sets are highly efficient for membership testing.

Creation

Sets are created using curly braces {} or the set() constructor.


Python
my_set = {1, 2, 3, 3, 4, 4}
print(my_set) # Output: {1, 2, 3, 4}

An empty set must be created using set(), as {} creates an empty dictionary.

Operations

Sets do not support indexing or slicing. They are used for mathematical set operations.

 add(): Adds a single item.


 remove(): Removes an item.
 union() (|): Combines two sets.
 intersection() (&): Returns common items.
 difference() (-): Returns items in the first set but not the second.
 len(): Returns the number of items.

4. Dictionaries

A dictionary is an unordered, mutable collection of key-value pairs. Each item has a unique key, and the
key is used to access its associated value. Dictionaries are optimized for retrieving values based on their
keys.

Creation

Dictionaries are created using curly braces {} with key-value pairs separated by colons :.

Python
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}

Keys must be unique and immutable (e.g., strings, numbers, or tuples). Values can be of any data type.

Accessing and Modifying

 Accessing: Use the key inside square brackets [] to get the value.

Python

print(person["name"]) # Output: Alice

 Modifying/Adding: Assign a new value to a key.

Python

person["age"] = 31
person["email"] = "[email protected]" # Adds a new key-value pair

 Removing: Use del or the pop() method.

Python
del person["city"]

Built-in Functions and Methods

 keys(): Returns a view object of all keys.


 values(): Returns a view object of all values.
 items(): Returns a view object of all key-value pairs as tuples.
 get(): A safer way to access a value that returns None (or a specified default) if the key doesn't
exist.

Nested Data Structures

Data structures can be nested, meaning they can contain other data structures as elements. This allows for
the creation of complex and powerful structures.

Examples

 List of Lists (2D array): Useful for representing grids or matrices.

Python

matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[0][1]) # Output: 2

 List of Dictionaries: A common way to store a collection of records.

Python

students = [
{"name": "Alice", "age": 20},
{"name": "Bob", "age": 22}
]
print(students[0]["name"]) # Output: Alice

 Dictionary of Dictionaries:

Python

database = {
"user1": {"name": "Alice", "status": "active"},
"user2": {"name": "Bob", "status": "inactive"}
}
print(database["user1"]["status"]) # Output: active

Nested structures require careful indexing to access the correct data. The key is to chain the indexing
operations, moving from the outer structure inward.
Indexing in Python

Indexing is the process of accessing a single element from a sequence (like a string, list, or tuple) by its
position. Every element in an ordered sequence is assigned a unique index, which is an integer value.

How Indexing Works

 Positive Indexing: Python uses zero-based indexing, meaning the first element is at index 0, the
second at 1, and so on. This is the most common way to access elements.

Python

my_list = ['A', 'B', 'C', 'D', 'E']


print(my_list[0]) # Output: A
print(my_list[2]) # Output: C

 Negative Indexing: Python also supports negative indexing, which is a convenient way to access
elements from the end of the sequence. The last element is at index -1, the second-to-last at -2, and
so on.

Python

my_string = "Python"
print(my_string[-1]) # Output: n
print(my_string[-3]) # Output: h

 IndexError: If you try to access an index that is outside the bounds of the sequence, Python will
raise an IndexError.

Python

my_list = [1, 2, 3]
# This will cause an IndexError
# print(my_list[3])

Slicing in Python

Slicing is the process of extracting a subsequence (a portion) from a sequence. Instead of a single element,
slicing returns a new sequence containing a range of elements.

Slicing Syntax

The basic syntax for slicing is [start:stop:step].

 start: The starting index of the slice (inclusive). If omitted, it defaults to the beginning of the
sequence (0).
 stop: The ending index of the slice (exclusive). The element at this index is not included. If omitted,
it defaults to the end of the sequence.
 step: The number of items to skip between each element. If omitted, it defaults to 1.

Examples of Slicing

 Basic Slice: Get a range of elements.


Python

my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(my_list[2:5]) # Output: [2, 3, 4]

 Slicing with Omitted Parameters:

Python

print(my_list[:4]) # From the beginning up to index 4 (exclusive). Output: [0,


1, 2, 3]
print(my_list[6:]) # From index 6 to the end. Output: [6, 7, 8, 9]
print(my_list[:]) # A copy of the entire list. Output: [0, 1, 2, 3, 4, 5, 6,
7, 8, 9]

 Slicing with a step:

Python

my_string = "abcdefghi"
print(my_string[1:8:2]) # From index 1 to 8, in steps of 2. Output: bdfh
print(my_string[::3]) # From start to end, in steps of 3. Output: adg

 Reversing a Sequence: A common and powerful use of slicing is to reverse a sequence.

Python

my_list = [1, 2, 3, 4, 5]
reversed_list = my_list[::-1]
print(reversed_list) # Output: [5, 4, 3, 2, 1]

Here, the step of -1 moves backward through the sequence.

Built-in Functions

Python provides a rich set of built-in functions that perform common tasks. These functions are always
available and don't require any special import. They are a crucial part of the language and are often used to
inspect and manipulate data structures.

Common Built-in Functions for Data Structures

 len(): Returns the number of items in an object. It works on all sequence types (strings, lists, tuples)
as well as sets and dictionaries.

Python

my_list = ["apple", "banana"]


print(len(my_list)) # Output: 2

my_string = "Hello"
print(len(my_string)) # Output: 5

my_dict = {"a": 1, "b": 2}


print(len(my_dict)) # Output: 2

 type(): Returns the type of an object. This is useful for debugging and understanding the data you
are working with.
Python

a = 10
b = 3.14
c = "Python"
print(type(a)) # Output: <class 'int'>
print(type(b)) # Output: <class 'float'>
print(type(c)) # Output: <class 'str'>

 print(): The most common built-in function, used to display output to the console.
 min() and max(): Return the smallest and largest items in an iterable.

Python

numbers = [10, 5, 20, 8]


print(min(numbers)) # Output: 5
print(max(numbers)) # Output: 20

 sum(): Returns the sum of all items in a numeric iterable.

Python

numbers = [1, 2, 3, 4, 5]
print(sum(numbers)) # Output: 15

 sorted(): Returns a new, sorted list from the items in an iterable. Unlike the .sort() method,
sorted() does not modify the original list.

Python

unsorted_list = [3, 1, 4, 1, 5, 9]
sorted_list = sorted(unsorted_list)
print(sorted_list) # Output: [1, 1, 3, 4, 5, 9]
print(unsorted_list) # The original list is unchanged.

 list(), tuple(), set(), dict(): These are not just constructors for creating new data structures;
they can also be used to convert an object from one type to another.

Python

my_string = "Python"
my_list = list(my_string) # Converts the string to a list of characters
print(my_list) # Output: ['P', 'y', 't', 'h', 'o', 'n']

my_tuple = tuple(my_list)
print(my_tuple) # Output: ('P', 'y', 't', 'h', 'o', 'n')

my_set = set(my_list) # Creates a set, duplicates are removed


print(my_set) # Output: {'n', 'P', 'y', 'h', 't', 'o'}
4.Functions and Modules
 Creating and calling functions

 Arguments and return values

 Built-in modules (e.g., math, random)

 Importing external modules

Functions in Python

A function is a block of reusable code that performs a specific task. Functions allow you to break down a
large program into smaller, manageable, and organized parts, which promotes code reuse, readability, and
maintainability.

Creating and Calling Functions

To define a function, you use the def keyword, followed by the function name, parentheses (), and a colon
:. The code block for the function must be indented. To execute the function, you call it by its name
followed by parentheses.

Python
# Function definition
def greet():
print("Hello, welcome to the program!")

# Function call
greet() # Output: Hello, welcome to the program!

Arguments and Return Values

Functions can be made more flexible by using arguments to pass data into them and return values to send
data back out.

Arguments (Parameters)

Arguments are values passed into a function when it is called. The function's definition specifies
parameters, which are the variables that receive these values.

Python
# The 'name' and 'age' are parameters
def greet_person(name, age):
print(f"Hello, {name}! You are {age} years old.")

# 'Alice' and 30 are arguments


greet_person("Alice", 30)
# Output: Hello, Alice! You are 30 years old.

 Positional Arguments: Arguments passed in the order they are defined.


 Keyword Arguments: Arguments passed by explicitly naming the parameter. This improves
readability and allows you to change the order.

Python
greet_person(age=30, name="Alice") # Same output

 Default Arguments: You can provide a default value for a parameter. If the argument is not
provided in the function call, the default value is used.

Python

def power(number, exponent=2):


print(number ** exponent)

power(5) # Output: 25 (uses default exponent)


power(5, 3) # Output: 125

Return Values

A function can send data back to the calling code using the return keyword. This allows the result of a
function to be stored in a variable or used in an expression. A function that does not have a return
statement implicitly returns None.

Python
def add_numbers(x, y):
result = x + y
return result

sum_of_numbers = add_numbers(10, 5)
print(sum_of_numbers) # Output: 15

You can return multiple values by separating them with commas. Python automatically packs them into a
tuple.

Python
def get_stats(numbers):
total = sum(numbers)
count = len(numbers)
return total, count

my_total, my_count = get_stats([10, 20, 30])


print(f"Total: {my_total}, Count: {my_count}") # Output: Total: 60, Count: 3

Modules in Python

A module is simply a file containing Python code, such as function definitions, class definitions, and
variables. Modules are used to organize code and prevent namespace collisions.

Built-in Modules

Python comes with a vast Standard Library, which is a collection of built-in modules. You can use these
modules to perform a wide range of tasks without installing any extra software.

 The math Module: Provides mathematical functions and constants.

Python

import math

print(math.pi) # Output: 3.14159...


print(math.sqrt(16)) # Output: 4.0
print(math.ceil(4.1)) # Output: 5
 The random Module: Provides functions for generating random numbers and sequences.

Python

import random

print(random.randint(1, 10)) # A random integer between 1 and 10 (inclusive)


my_list = ['A', 'B', 'C']
random.shuffle(my_list) # Shuffles the list in place
print(my_list)

Importing External Modules

To use a module, you must first import it. There are several ways to import.

 import module_name: Imports the entire module. You must use the module name followed by a dot
. to access its contents.

Python

import math
print(math.sqrt(25))

 from module_name import item1, item2: Imports specific items from a module. You can then
use these items directly without the module name prefix.

Python

from math import sqrt, pi


print(sqrt(25))
print(pi)

 from module_name import *: Imports all items from a module. This is generally discouraged as it
can lead to namespace clashes and make it difficult to determine where a function came from.
 import module_name as alias: Imports a module and gives it a shorter alias. This is common
with popular libraries like NumPy (import numpy as np).

Python

import random as rnd


print(rnd.randint(1, 100))
5.File Handling
 Reading and writing text files
 Opening files in different modes (r, w, a)
 Handling file exceptions

File Handling in Python

File handling is a crucial aspect of programming that allows your program to interact with the file system. It
enables you to read data from files and write data to files, providing a way for your program to store and
retrieve information persistently.

The open() Function

To work with a file, you must first open it using the built-in open() function. This function returns a file
object, which acts as a channel for communication between your program and the file.

The open() function takes two main arguments: the file path and the mode in which to open the file.

Python
file_object = open("filename.txt", "mode")

Reading and Writing Text Files

Writing to a File

To write data to a file, you open it in write mode ('w') and use the .write() method of the file object. The
.write() method takes a single string as an argument.

 Overwriting Content: When you open a file in 'w' mode, if the file already exists, its entire content
is erased, and the new data is written from the beginning. If the file does not exist, a new one is
created.

Python
# Open the file in write mode
file_writer = open("my_notes.txt", "w")

# Write a single line of text


file_writer.write("Hello, this is the first line.\n")

# Write another line


file_writer.write("This line will be on a new line.\n")

# Close the file to save the changes and free resources


file_writer.close()

Reading from a File

To read data from a file, you open it in read mode ('r') and use methods like .read(), .readline(), or
.readlines().

 The .read() method: Reads the entire content of the file into a single string. This can be inefficient
for very large files.
Python

file_reader = open("my_notes.txt", "r")


content = file_reader.read()
print(content)
file_reader.close()

 The .readline() method: Reads one line from the file at a time. This is useful when you need to
process a file line by line.

Python

file_reader = open("my_notes.txt", "r")


line1 = file_reader.readline()
print(f"First line: {line1}")
file_reader.close()

 Iterating over the file object: This is the most common and memory-efficient way to read a file line
by line.

Python

with open("my_notes.txt", "r") as f:


for line in f:
print(line.strip()) # .strip() removes leading/trailing whitespace,
including the newline character.

Opening Files in Different Modes

The mode argument in the open() function determines what you can do with the file.

 'r' (Read Mode):


o Default mode.
o Opens a file for reading.
o The file must exist; otherwise, a FileNotFoundError will be raised.
o The file pointer is at the beginning of the file.
 'w' (Write Mode):
o Opens a file for writing.
o Creates the file if it does not exist.
o Truncates (erases) the content of the file if it already exists.
o The file pointer is at the beginning of the file.
 'a' (Append Mode):
o Opens a file for writing, but any new content is appended to the end of the file.
o Creates the file if it does not exist.
o The file pointer is at the end of the file. This is useful for adding new entries to a log file, for
example.

Python

with open("log.txt", "a") as log_file:


log_file.write("New log entry at 2025-08-25.\n")

 'x' (Exclusive Creation):


o Opens a file for exclusive creation.
o Raises an FileExistsError if the file already exists.
o This is useful to ensure that you are creating a new file and not accidentally overwriting an
existing one.
 '+' (Read/Write Mode):
o Can be combined with other modes, e.g., 'r+' or 'w+'.
o 'r+': Opens a file for both reading and writing. The file must exist.
o 'w+': Opens a file for both reading and writing. Creates the file if it doesn't exist and
overwrites its content if it does.

Handling File Exceptions

File operations can fail for many reasons (e.g., file not found, permission denied). To prevent your program
from crashing, you must handle these exceptions gracefully using try...except blocks.

FileNotFoundError

This error occurs when you try to open a file for reading that does not exist.

Python
try:
with open("non_existent_file.txt", "r") as f:
content = f.read()
except FileNotFoundError:
print("Error: The file was not found.")

PermissionError

This error occurs when the program does not have the necessary permissions to read from or write to a file
or directory.

Python
try:
with open("/root/secret.txt", "w") as f: # Assuming insufficient permissions
f.write("Some data.")
except PermissionError:
print("Error: You do not have permission to write to this file.")

The with Statement: Best Practice for File Handling

The with statement is the most recommended way to handle files. It automatically handles the closing of the
file, even if an exception occurs within the with block. This prevents resource leaks and ensures data is
written to the disk.

Python
try:
with open("my_notes.txt", "r") as file_reader:
content = file_reader.read()
print(content)
except FileNotFoundError:
print("The file could not be found.")

# The file is automatically closed here, no need for file_reader.close()

The with statement simplifies file management and makes your code more robust and reliable.
6.Object-Oriented Programming (OOPs)
 Classes and Objects
 Constructors (__init__ method)
 Inheritance and Polymorphism
 Encapsulation

Object-Oriented Programming (OOP) in Python

Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to
organize and structure code. Instead of focusing on functions and logic, OOP models real-world entities by
combining data (attributes) and behaviors (methods) into a single unit. This approach promotes code
reusability, modularity, and maintainability.

Classes and Objects

Classes

A class is a blueprint or a template for creating objects. It defines the common attributes and methods that
all objects of that type will have. Think of a class as the design for a car: it specifies that all cars will have a
color, a number of wheels, and the ability to drive and brake, but it doesn't represent any specific car.

 Syntax: A class is defined using the class keyword.

Python

class Car:
# Attributes
color = "red"

# Method
def start_engine(self):
print("Engine started!")

Objects

An object is an instance of a class. It is a concrete entity created from the class blueprint. Each object has its
own unique set of attribute values. Using the car analogy, an object would be a specific car, such as a "blue
sedan" or a "red sports car."

 Creating an object: To create an object, you call the class name followed by parentheses.

Python

# Create an object (an instance) of the Car class


my_car = Car()

# Access attributes and methods of the object


print(my_car.color) # Output: red
my_car.start_engine() # Output: Engine started!

Constructors (__init__ method)


A constructor is a special method in a class that is automatically called when a new object is created. Its
purpose is to initialize the object's attributes with the values passed during object creation.

In Python, the constructor method is named __init__ (short for "initialize").

 Syntax:

Python

class Car:
# The constructor method
def __init__(self, color, brand):
# `self` refers to the instance being created
self.color = color
self.brand = brand
self.is_running = False

def start_engine(self):
self.is_running = True
print(f"The {self.brand} engine started.")

# Create objects by passing arguments to the constructor


car1 = Car("blue", "Toyota")
car2 = Car("red", "Ford")

print(f"Car 1 is a {car1.color} {car1.brand}.") # Output: Car 1 is a blue Toyota.


car1.start_engine() # Output: The Toyota engine
started.

 The self keyword is a reference to the instance of the class. It is the first parameter of every instance
method, including the constructor, and allows the method to access and modify the object's
attributes.

Inheritance and Polymorphism

Inheritance

Inheritance is a mechanism that allows a new class (the child or subclass) to inherit the attributes and
methods of an existing class (the parent or superclass). This creates a hierarchy and promotes code reuse,
as the child class can use the parent's code without having to rewrite it.

 Example: A SportsCar is a type of Car. It inherits all the properties of a Car but can also have its
own unique attributes (e.g., top_speed) and methods (turbo_boost).

Python

class Vehicle: # Parent class


def __init__(self, wheels):
self.wheels = wheels

def drive(self):
print("Vehicle is driving.")

class Car(Vehicle): # Child class, inherits from Vehicle


def __init__(self, wheels, brand):
super().__init__(wheels) # Calls the parent's constructor
self.brand = brand

class SportsCar(Car): # Grandchild, inherits from Car


def __init__(self, wheels, brand, top_speed):
super().__init__(wheels, brand)
self.top_speed = top_speed

sports_car = SportsCar(4, "Porsche", 300)


sports_car.drive() # Uses the drive method from the Vehicle class
print(sports_car.top_speed)

The super().__init__() call is essential for calling the parent class's constructor to properly
initialize the inherited attributes.

Polymorphism

Polymorphism (meaning "many forms") is the ability of an object to take on many forms. In the context of
inheritance, it allows methods with the same name to be used on objects of different classes, with each
method behaving in a way appropriate for its own class.

 Example: If both the parent and child classes have a method with the same name, the method in the
child class will override the one in the parent class.

Python

class Animal:
def make_sound(self):
print("Generic animal sound.")

class Dog(Animal):
def make_sound(self): # Overrides the parent method
print("Woof!")

class Cat(Animal):
def make_sound(self): # Overrides the parent method
print("Meow!")

# A list of different animal objects


animals = [Dog(), Cat(), Animal()]

# The same method call `make_sound()` behaves differently for each object
for animal in animals:
animal.make_sound()
# Output:
# Woof!
# Meow!
# Generic animal sound.

Encapsulation

Encapsulation is the concept of bundling data (attributes) and the methods that operate on that data into a
single unit (a class). It also involves restricting direct access to some of an object's components, which is
known as data hiding.

 Why Encapsulate?
o Data Integrity: It prevents outside code from accidentally changing an object's data in an
invalid way.
o Modularity: It makes the class's internal state a "black box," so other parts of the program
don't need to know how it works.
 Implementation in Python: Unlike languages like Java or C++, Python does not have strict private
attributes. Instead, it uses a convention of prefixing attribute names with underscores to indicate their
intended privacy.
o Single Underscore (_): A convention for a "protected" attribute. It suggests that the attribute
should not be accessed directly from outside the class, but it is not enforced by the interpreter.
o Double Underscore (__): Triggers name mangling, a mechanism that makes an attribute
harder to access from outside the class. The interpreter renames the attribute to
_ClassName__attributeName. While not truly private, it effectively prevents accidental
modification.

Python

class BankAccount:
def __init__(self, balance):
self.__balance = balance # "Private" attribute due to name mangling

def deposit(self, amount):


if amount > 0:
self.__balance += amount

def get_balance(self): # Public method to access the private attribute


return self.__balance

account = BankAccount(100)
account.deposit(50)
print(account.get_balance()) # Output: 150

# This will not work as expected due to name mangling


# print(account.__balance) # Raises an AttributeError
# It can be accessed indirectly, but it's discouraged
# print(account._BankAccount__balance)

By using methods like get_balance() (a "getter") and deposit() (a "setter"), you control how the internal
data of the object is accessed and modified, which is the essence of encapsulation.
7.Error Handling
 Exceptions and try-except blocks
 Raising custom errors

Error Handling in Python

Error handling is a crucial aspect of writing robust and reliable programs. It involves anticipating and
managing errors that may occur during program execution, rather than letting the program crash. In Python,
errors that occur during runtime are called exceptions.

Exceptions and try-except Blocks

An exception is an event that disrupts the normal flow of a program's instructions. When an exception
occurs, Python creates an exception object and "raises" it. If this exception is not handled, the program will
terminate and display an error message (traceback).

The try-except block is the primary mechanism for handling exceptions. It allows you to "try" a block of
code and "catch" any exceptions that are raised.

 The try Block: This is where you place the code that might raise an exception.
 The except Block: This block is executed only if an exception occurs in the try block. It contains
the code to handle the error gracefully.

Basic Syntax

Python
try:
# Code that might raise an exception
numerator = int(input("Enter a numerator: "))
denominator = int(input("Enter a denominator: "))
result = numerator / denominator
print(f"The result is: {result}")
except ValueError:
# Code to handle a specific exception (e.g., if input is not a number)
print("Error: Invalid input. Please enter a valid number.")
except ZeroDivisionError:
# Code to handle another specific exception (e.g., if the denominator is zero)
print("Error: Cannot divide by zero.")

Multiple except Blocks

You can have multiple except blocks to handle different types of exceptions. Python checks them in order.
You can also handle multiple exceptions with a single except block by listing them in a tuple.

Python
try:
# Code to try
my_list = [1, 2, 3]
print(my_list[5]) # This will raise an IndexError
except (ValueError, IndexError):
print("An input or index error occurred.")

The else and finally Blocks


 The else Block: The else block is optional and is executed only if the try block completes
without any exceptions. This is useful for placing code that should run only when no errors occur.
 The finally Block: The finally block is optional and is always executed, regardless of whether
an exception occurred or not. It's typically used for cleanup actions, such as closing a file or a
database connection.

Python
try:
file = open("my_file.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found.")
else:
print("File was read successfully!")
print(content)
finally:
# This code will always run
if 'file' in locals() and not file.closed:
file.close()
print("File operation complete.")

Raising Custom Errors

While Python's built-in exceptions cover many common errors, there are times when you need to create and
raise your own specific exceptions. This is useful for making your code more descriptive and for handling
application-specific errors.

The raise Statement

The raise statement allows you to manually trigger an exception. You can raise a built-in exception or a
custom one.

Python
def check_age(age):
if age < 0:
raise ValueError("Age cannot be a negative number.")
elif age > 150:
raise ValueError("Age is unrealistic.")
else:
print("Age is valid.")

try:
check_age(-5)
except ValueError as e:
print(f"Caught an error: {e}")

Creating Custom Exceptions

To create a custom exception, you define a new class that inherits from Python's built-in Exception class
(or one of its subclasses). This allows your custom exception to be handled by try-except blocks just like
built-in exceptions.

Python
# Define a custom exception class
class InvalidEmailError(Exception):
"Raised when an email address is not in a valid format."
pass

def validate_email(email):
if "@" not in email or "." not in email:
raise InvalidEmailError(f"'{email}' is not a valid email address.")

return "Email is valid."

try:
validate_email("[email protected]")
except InvalidEmailError as err:
print(f"Email validation failed: {err}")

By creating a custom InvalidEmailError, you provide more specific and meaningful information about
why an error occurred, which can make debugging and error handling easier for developers using your code.
8.Libraries and Tools
 numpy for numerical operations
 matplotlib for data visualization
 pandas for handling data (optional based on course depth)

Libraries and Tools in Python

In data science and scientific computing, Python's built-in capabilities are often not enough. Libraries
provide specialized tools and functions that extend Python's functionality. NumPy, Matplotlib, and Pandas
are three of the most essential libraries for numerical operations, data visualization, and data handling.

1. NumPy for Numerical Operations

NumPy (Numerical Python) is the foundational library for scientific computing in Python. It provides a
high-performance multidimensional array object, and tools for working with these arrays. The core of
NumPy is the ndarray object, which is significantly faster and more memory-efficient than standard Python
lists for numerical operations.

Key Features

 N-dimensional arrays (ndarray): A fast and flexible container for large datasets. Operations on
these arrays are performed element-wise and are highly optimized.
 Broadcasting: A powerful feature that allows NumPy to work with arrays of different shapes when
performing arithmetic operations.
 Mathematical functions: A comprehensive set of mathematical functions for array operations.

Basic Usage

To use NumPy, you must first import it, typically with the alias np.

Python
import numpy as np

# Create a NumPy array from a list


my_array = np.array([1, 2, 3, 4, 5])
print(my_array) # Output: [1 2 3 4 5]
print(type(my_array))# Output: <class 'numpy.ndarray'>

# Create a 2D array (matrix)


matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix)
# Output:
# [[1 2 3]
# [4 5 6]]

# Perform element-wise operations (much faster than loops)


array1 = np.array([10, 20, 30])
array2 = np.array([1, 2, 3])
result = array1 * array2
print(result) # Output: [10 40 90]

2. Matplotlib for Data Visualization


Matplotlib is a powerful and highly customizable plotting library. It is widely used to create static,
animated, and interactive visualizations in Python. It provides a variety of plots, from simple line graphs to
complex 3D plots.

Key Features

 Variety of plots: Supports line plots, bar charts, scatter plots, histograms, and more.
 Customization: Almost every element of a plot (lines, colors, labels, legends) can be customized.
 pyplot module: The most commonly used module within Matplotlib, providing a MATLAB-like
interface for simple plotting.

Basic Usage

To use Matplotlib, you typically import the pyplot module with the alias plt.

Python
import matplotlib.pyplot as plt
import numpy as np

# Create some sample data


x = np.linspace(0, 10, 100) # 100 points between 0 and 10
y = np.sin(x)

# Create a line plot


plt.figure(figsize=(8, 6)) # Set the figure size
plt.plot(x, y)

# Add title and labels


plt.title("Sine Wave")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")

# Display the plot


plt.grid(True)
plt.show()

The plt.show() function displays all open figures. You can create multiple plots by calling plotting
functions and then displaying them all at once.

3. Pandas for Data Handling

Pandas is a library built on top of NumPy, designed for data manipulation and analysis. It introduces two
primary data structures: Series and DataFrame, which make working with structured data intuitive and
efficient.

Key Features

 DataFrame: A 2-dimensional labeled data structure with columns of potentially different types.
Think of it as a spreadsheet or a SQL table.
 Series: A 1-dimensional labeled array. It can be seen as a single column of a DataFrame.
 Data alignment: Pandas automatically aligns data based on labels, which is a major advantage over
raw NumPy arrays.
 Handling missing data: Provides tools to handle missing data (NaN).
 Reading/writing data: Can read and write data from various formats, including CSV, Excel, and
SQL databases.
Basic Usage

You typically import Pandas with the alias pd.

Python
import pandas as pd

# Create a DataFrame from a dictionary


data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}
df = pd.DataFrame(data)
print(df)
# Output:
# Name Age City
# 0 Alice 25 New York
# 1 Bob 30 Los Angeles
# 2 Charlie 35 Chicago

# Access a single column (returns a Series)


print("\nAge column:")
print(df['Age'])
# Output:
# 0 25
# 1 30
# 2 35
# Name: Age, dtype: int64

# Select rows based on a condition


print("\nFiltered by Age > 25:")
filtered_df = df[df['Age'] > 25]
print(filtered_df)
# Output:
# Name Age City
# 1 Bob 30 Los Angeles
# 2 Charlie 35 Chicago

Pandas provides a vast number of methods for cleaning, transforming, and analyzing data, making it an
indispensable tool for anyone working with datasets.
4.Project
Introduction:-

The project Cycle Ride Tracker is developed as part of


the vocational course BCA 261 (CS105: Introduction to
Python). The main purpose of this project is to apply the
concepts of Python programming to a real-life scenario and
to gain hands-on experience in solving practical problems
using programming skills. Cycling is one of the most
common physical activities, and many people like to keep
a record of their rides, including distance, time, and speed.
This project provides a simple yet effective way to record
and analyze cycling performance.
The program is designed in Python 3, which is known for
its simplicity and wide use in software development. It is a
menu-driven application that allows the user to add ride
details, view summaries, and analyze performance over
time. Each ride stores details such as distance, total time
(in hours, minutes, seconds), and average speed. The
program then calculates total distance, total time, and
overall average speed.
For visualization, the project uses the matplotlib library,
which displays data in a graphical format. Blue bars
represent the distance covered, while a red line represents
the average speed. This combination of numerical
summary and graphical representation makes the analysis
more effective, user-friendly, and visually clear.
Aim & Objectives:-
The primary aim of the "Cycle Ride Tracker" project is to develop and implement a
practical, user-centric application using Python. This application will enable cyclists to
effectively monitor, analyze, and visualize their riding performance over time. It serves as a
digital solution for tracking physical activities, providing users with a simple yet powerful
tool to document their progress. The core goal is to apply fundamental Python concepts—
such as data structures, control flow, and external libraries—to solve a real-world problem,
thereby bridging the gap between theoretical knowledge and practical application.

The project's specific objectives are meticulously defined to achieve this aim:

 Data Entry: Create a simple, menu-driven interface that guides the user through the
process of logging a ride. This feature will allow for the input of key metrics,
including distance, duration (in hours, minutes, and seconds), and average speed. The
interface will be designed to be intuitive, ensuring that even a novice user can input
their data without difficulty.
 Computation: Implement mathematical logic to process the entered data. The
application will be capable of calculating key performance indicators such as the total
distance covered across all rides, the cumulative time spent cycling, and the overall
average speed. These computations will provide
 users with a comprehensive summary of their cycling activity, offering valuable
insights into their progress.
 Storage: Organize and store the ride data in a structured format that is both easy to
manipulate and retrieve. This will be achieved using Python's built-in data structures,
specifically lists and tuples. A list will be used to hold individual ride records, with
each record stored as a tuple containing the ride's details. This structured approach
ensures data integrity and simplifies future processing.
 Visualization: Utilize the Matplotlib library to generate a visual representation of the
collected data. The application will create a plot that displays distance as a series of
blue bars and average speed as a red line, offering a clear, graphical overview of the
user’s performance over time. This visual component is crucial for quickly identifying
trends and patterns in their cycling habits.
 Skill Development: Serve as a practical exercise for enhancing core programming
competencies. By working on this project, the developer will strengthen their
problem-solving abilities, refine their logical thinking, and gain hands-on experience
with fundamental Python features. The process of designing the application, writing
the code, and debugging will solidify their understanding of how these concepts work
together in a functional application.

These objectives collectively ensure the project not only delivers a functional tool but also
serves as a comprehensive learning experience, transforming abstract programming concepts
into a tangible and useful application.
Methodology:-

The project's implementation followed a modular and structured approach,


focusing on breaking down the problem into smaller, manageable components.
The choice of Python 3 was a strategic one, primarily due to its clear syntax and
extensive ecosystem of libraries that streamline development. The entire program
is designed as a menu-driven application, which provides a user-friendly and
intuitive interface for interaction.

A key aspect of the project's data management is the use of native Python data
structures. Each individual ride's data—specifically distance, total time, and
average speed—is stored as a tuple. These tuples are then contained within a list,
creating a structured and easily iterable collection of all ride records. This
approach is both efficient for data handling and aligns with Python's best
practices for managing simple datasets.

To provide meaningful insights, the project performs several mathematical


computations. The program aggregates data from all stored rides to calculate
overall statistics such as total distance covered, cumulative time spent, and a
comprehensive average speed. These calculations turn raw data into valuable
performance metrics.

The project's final and most impactful component is its data visualization. It
leverages the powerful matplotlib library to create a combined chart that offers a
clear analytical view. The visual representation consists of a bar chart that uses
blue bars to illustrate the distance of each ride and a line chart that uses a red
line to plot the average speed. This dual-axis visualization allows users to easily
identify correlations and trends, such as how increased distance might affect
average speed.

In essence, the methodology blends modular programming for clean code


organization, mathematical computation for data analysis, and data
visualization for intuitive insights. This integrated approach not only delivers a
complete and functional application but also serves as a strong demonstration of
the practical application of Python's core features in a real-world scenario.
Code & Screenshots:-
Cycle Ride Tracker – Code with Explanations

import matplotlib.pyplot as plt

👉 We import the matplotlib.pyplot library, which is used to create graphs. Without this, we cannot show
distance and average speed visually.

rides = []

👉 An empty list is created to store all rides. Each ride will be saved as a tuple with values: (distance, time,
average speed).

def add_ride():
try:
distance = float(input("Enter distance (km): "))
hrs = int(input("Enter time (hours): "))
mins = int(input("Enter time (minutes): "))
secs = int(input("Enter time (seconds): "))
total_time = hrs * 60 + mins + (secs / 60) # convert time into minutes

👉 Function add_ride() takes input from the user.

 Distance is entered in kilometers.


 Time is entered as hours, minutes, and seconds, which is converted into minutes for easier
calculation.

avg_speed = float(input("Enter average speed (km/h): "))

if avg_speed > 0:
total_time = (distance / avg_speed) * 60

👉 User is asked to enter average speed.

 If average speed is given, then time is re-calculated using formula:


Time = Distance ÷ Speed

rides.append((distance, total_time, avg_speed))


print("✅ Ride saved!")

👉 The ride details are saved inside the rides list as a tuple. Example: (20, 70, 17).
👉 A confirmation message is shown.

except ValueError:
print("❌ Invalid input! Please enter numbers only.")
input("\nPress Enter to continue...")
👉 If the user types wrong input (like text instead of numbers), the program shows an error message.

def show_summary():
if not rides:
print("⚠ No rides added yet!")

👉 Function show_summary() checks if rides exist. If no rides are saved, it shows a warning.

else:
total_distance = sum(r[0] for r in rides)
total_time = sum(r[1] for r in rides)
avg_speed = (total_distance / (total_time / 60)) if total_time > 0 else 0

👉 If rides exist:

 Total Distance = sum of all distances


 Total Time = sum of all times (in minutes)
 Average Speed = Total Distance ÷ Total Time (converted to hours)

print("\n📊 Ride Summary 📊")


print(f"Total Rides: {len(rides)}")
print(f"Total Distance: {total_distance:.2f} km")
print(f"Total Time: {total_time/60:.2f} hrs")
print(f"Average Speed: {avg_speed:.2f} km/h")

👉 The ride summary is displayed in a clean format showing:

 Total rides
 Total distance covered
 Total time in hours
 Average speed

distances = [r[0] for r in rides]


avg_speeds = [r[2] for r in rides]
x = range(1, len(rides) + 1)

👉 Preparing data for graph:

 distances → list of all distances


 avg_speeds → list of all average speeds
 x → ride numbers (1, 2, 3, …)

fig, ax1 = plt.subplots()


ax1.bar(x, distances, color="skyblue", label="Distance (km)")
ax1.set_xlabel("Ride Number")
ax1.set_ylabel("Distance (km)", color="blue")

👉 First axis (ax1) is created for bar chart (blue bars) to show distance per ride.
ax2 = ax1.twinx()
ax2.plot(x, avg_speeds, color="red", marker="o", label="Avg Speed (km/h)")
ax2.set_ylabel("Avg Speed (km/h)", color="red")

👉 A second axis (ax2) is created for the line chart (red line) to show average speed per ride.

plt.title("Cycle Ride Tracker: Distance & Avg Speed")


fig.legend(loc="upper left", bbox_to_anchor=(0.1, 0.9))
plt.grid(True, linestyle="--", alpha=0.6)
plt.show()

👉 The graph is given a title, legend, and grid. Then it is displayed to the user.

while True:
print("\n🚴 Cycle Ride Tracker 🚴")
print("1. Add Ride")
print("2. Show Summary")
print("3. Exit")
choice = input("Enter choice: ")

👉 This is the main menu. It keeps repeating until the user chooses Exit.

if choice == "1":
add_ride()
elif choice == "2":
show_summary()
elif choice == "3":
print("👋 Goodbye! Keep riding 🚴💨")
break
else:
print("❌ Invalid choice!")
input("\nPress Enter to continue...")

👉 Menu options:

 1 → Add Ride
 2 → Show Summary
 3 → Exit Program
 Any other input → Invalid choice

✅ In short:

 add_ride() → Takes input and saves ride.


 show_summary() → Shows statistics + graph.
 Menu loop → Keeps program running.

screenshots of Project:-
OUTPUT:-
Bibliography:-

 https://www.google.com
 https://www.saylor.org
5. Stepwise Modules:-
Input/Output Module

The Input/Output (I/O) module was crucial for user interaction. The input() function was used to collect data from the user,
specifically for recording ride details such as distance, time (broken down into hours, minutes, and seconds), and average speed.
To present the results clearly and professionally, the print() function was employed, utilizing formatted output (f-strings) to
ensure readability and a clean presentation of statistics and messages.

Decision Making & Looping

Control flow was managed through decision-making and looping structures. An if-else statement was implemented to
handle conditions such as validating user input and checking whether any ride data exists before attempting to display a summary.
A while True loop was the foundation of the program's menu-driven structure. This loop ensures the application continues to
run and presents the main menu to the user repeatedly until a specific exit option is selected, making the program interactive and
persistent.

Data Structures Module

The project's data management relies on two fundamental data structures. A list, named rides, was used as the primary
container to store multiple ride records. To ensure each ride's data was kept together in a structured and immutable format, each
record was stored as a tuple containing (distance, total_time, avg_speed). This approach guarantees that the
individual ride details remain unchanged, and the overall list of rides is easy to manage and iterate through.

Functions Module

The program was built using a modular approach, dividing the code into distinct functions. Functions like add_ride(),
show_summary(), and visualize_data() were created to encapsulate specific tasks. This practice not only makes the
code significantly easier to maintain and debug but also improves its readability and allows for future expansion without
disrupting the core logic.

Mathematical Computation

To provide meaningful analytics, the program performs essential mathematical computations. The total time was calculated by
converting hours and minutes into seconds. The average speed was determined using the formula: Average Speed = Distance ÷
Total Time. These calculations transform raw user input into valuable performance metrics.

Visualization Module (Matplotlib Library)

The Matplotlib library was integrated to provide a powerful visualization component. By using this external module, the project
was able to generate a clear and insightful graph. The visualization combines a bar chart (colored blue) to represent the distance
of each ride with a line chart (colored red) to show the corresponding average speed. This dual representation helps users easily
analyze their performance trends.
6. Conclusion:-
The development of the project Cycle Ride Tracker has been a highly valuable and
enriching learning experience. As part of the vocational course BCA 261 (CS105:
Introduction to Python), this project provided me with the opportunity to practically
implement the theoretical concepts that I had studied during the course. The main purpose
was to design and develop a Python-based application that records and analyzes cycling
rides, but through this process, I was able to explore much more than just programming.

From the very beginning, I learned how to analyze a real-world problem and then design a
structured solution using programming. The problem chosen was simple but practical: a
cyclist should be able to record his or her distance, time, and speed during each ride. By
breaking this down into smaller parts such as input, computation, storage, and visualization, I
was able to develop a modular and efficient Python program. This approach taught me the
importance of planning and logical thinking before jumping directly into coding.

Technically, I gained hands-on experience in Python programming, particularly in


handling input/output operations, data structures, functions, loops, and conditional
statements. I learned how to take input in a user-friendly format, such as entering time in
hours, minutes, and seconds, and then converting it into a suitable format for calculations. I
also improved my ability to handle errors by using exception handling (try-except blocks)
to ensure that the program does not crash on invalid input.

A major skill developed during this project was working with data structures. I used lists to
store multiple rides and tuples to keep the details of each ride structured. This taught me
how Python can organize data efficiently and how these structures can be used in real
applications. The use of functions made my code modular and reusable, which is an
important practice in software development.

Another important part of this project was the use of the matplotlib library for data
visualization. This was my first time working with a visualization tool in Python, and I
realized how important graphical representation is in data analysis. By combining a bar
chart for distance and a line chart for average speed in one graph, I made the results easy
to understand and visually appealing. This skill of presenting data in a visual format is
extremely useful not just in academic projects but also in professional software development.

On a personal level, this project boosted my confidence in coding and problem-solving. I


developed a better understanding of how to transform theoretical concepts into a working
solution. I also learned the importance of debugging and testing, as the program had to be
checked with multiple inputs to ensure accuracy.

In conclusion, this project not only enhanced my technical skills in Python but also
improved my analytical thinking, logical reasoning, and problem-solving ability. I am
now more confident in my ability to use Python for real-world applications. The knowledge
gained from this project will serve as a strong foundation for future courses, advanced
programming, and even professional projects in the field of software development and data
science.

You might also like