Python Programming Basics Guide
Python Programming Basics Guide
An Autonomous Institution
Computer Workshop – II (103SB)
(LTP = 0-0-4)
➢ Advantages of Python
1. Easy to Learn and Use: Python’s straightforward syntax mimics natural language, making
it accessible to beginners.
2. Versatility: It supports multiple programming paradigms, including procedural, object-
oriented, and functional programming.
3. Extensive Libraries: Python has a rich standard library and thousands of third-party
modules for tasks ranging from web development to data analysis.
4. Platform Independence: Python programs can run on various operating systems without
requiring modification.
5. Active Community Support: The extensive Python community provides ample resources,
tutorials, and forums for troubleshooting and learning.
6. Integration Capabilities: Python can easily integrate with other languages and
technologies, such as C, C++, and Java, and supports APIs for seamless interaction.
7. Automation and Scripting: Python excels in automating repetitive tasks and building
robust scripts.
1
BVM 103SB(CW-2)
➢ Applications of Python
1. Web Development: Frameworks like Django, Flask, and Pyramid allow developers to
build scalable and secure web applications.
2. Data Science and Analytics: Python is a dominant language for data analysis,
visualization, and machine learning, with libraries like Pandas, NumPy, and Scikit-learn.
3. Artificial Intelligence and Machine Learning: Python’s flexibility and powerful
libraries, such as TensorFlow and PyTorch, make it ideal for AI projects.
4. Scientific Computing: Researchers and scientists use Python for simulations,
computational tasks, and numerical analysis with tools like SciPy and Matplotlib.
5. Game Development: Libraries such as Pygame allow developers to create games and
interactive applications.
6. Automation and Scripting: Python is widely used for automating system tasks, data
scraping, and test scripting.
7. Embedded Systems: Python can interface with hardware components and is used in
Internet of Things (IoT) projects.
8. Desktop Application Development: GUI frameworks like Tkinter, PyQt, and Kivy enable
the development of cross-platform desktop applications.
Python’s adaptability and efficiency continue to make it one of the most sought-after programming
languages across diverse industries, shaping the future of technology and innovation.
2
BVM 103SB(CW-2)
4. Install Required Libraries:
• Use pip, Python’s package manager, to install libraries.
For example:
pip install numpy pandas matplotlib
1. Case Sensitivity: Python is case-sensitive. For example, Variable and variable are two
different identifiers.
3. Comments:
• Single-line comments begin with #.
• Multi-line comments use triple quotes (''' or """).
# This is a single-line comment
"""
This is a multi-line comment
spanning multiple lines.
"""
3
BVM 103SB(CW-2)
4. Variables: Variables in Python are dynamically typed and do not require explicit
declaration.
x = 10 # Integer
y = 3.14 # Float
name = "Python" # String
5. Statements: Python typically executes one statement per line. To write multiple statements
on a single line, use a semicolon (;).
print("Hello"); print("World")
6. Keywords: Python has a set of reserved keywords that cannot be used as variable names
(e.g., if, else, while, import).
import keyword
print([Link]) # Displays all keywords
8. Basic Data Types: int, float, str, bool, list, tuple, dict, and set are commonly used.
age = 25 # int
pi = 3.14159 # float
is_valid = True # bool
colors = ["red", "green", "blue"] # list
Problem Statement: Write a Python program to display the message "Hello, Python!".
Solution:
print("Hello, Python!")
4
BVM 103SB(CW-2)
➢ Exercise 2: Input Name and Age
Problem Statement: Create a program that asks the user for their name and age, then prints a
message using the input.
Solution:
Problem Statement: Write a Python program to demonstrate the use of multi-line comments.
Solution:
"""
This program demonstrates the use of multi-line comments.
Author: Your Name
Date: Today's Date
"""
print("Multi-line comments are useful for documentation.")
5
BVM 103SB(CW-2)
❖ Variable Types in Python
In Python, variables are used to store data, and their type is determined automatically based on
the value assigned. Python supports several built-in data types that can be broadly categorized
into the following:
1. Numeric Types
x = 10 # int
y = 3.14 # float
z = 2 + 3j # complex
2. Sequence Types
name = "Python"
• range: immutable sequence of numbers, commonly used for looping a specific number of
times in for loops.
# Example
for i in range(1, 10, 2):
print(i)
6
BVM 103SB(CW-2)
3. Set Types
4. Mapping Types
5. Boolean Type
is_active = True
6. None Type
result = None
x = 42
print(type(x)) # Output: <class 'int'>
• Convert between types using functions like int(), float(), str(), etc.
num = "123"
num_int = int(num) # Converts string to integer
7
BVM 103SB(CW-2)
➢ Exercise 4: Create Variables of Different Types
Problem Statement: Create variables of different data types (int, float, str, list, tuple, set, dict,
bool) and print their values.
Solution:
x = 42 # int
y = 3.14 # float
name = "Python" # str
colors = ["red", "green", "blue"] # list
coordinates = (10, 20, 30) # tuple
unique_numbers = {1, 2, 3} # set
person = {"name": "Alice", "age": 25} # dict
is_active = True # bool
# Print values
print("Integer:", x)
print("Float:", y)
print("String:", name)
print("List:", colors)
print("Tuple:", coordinates)
print("Set:", unique_numbers)
print("Dictionary:", person)
print("Boolean:", is_active)
Problem Statement: Write a program to check the type of a variable using type().
Solution:
x = 42
name = "Python"
is_active = True
8
BVM 103SB(CW-2)
➢ Exercise 6: String to Integer and Float Conversion
Problem Statement: Convert a string containing a number (e.g., "45") into an integer and a
float.
Solution:
num_str = "123"
num_int = int(num_str) # Convert to integer
num_float = float(num_str) # Convert to float
print("String:", num_str)
print("Integer:", num_int)
print("Float:", num_float)
Problem Statement: Create a list of numbers and calculate their sum using the sum()
function.
Solution:
print("Numbers:", numbers)
print("Sum:", result)
Problem Statement: Define a dictionary with at least three key-value pairs and display its
keys and values.
Solution:
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
9
BVM 103SB(CW-2)
print("Keys:", [Link]())
print("Values:", [Link]())
❖ Numbers in Python
Python provides robust support for numerical data types and operations. Numbers in Python
can be categorized into different types:
1. Integer (int):
• Whole numbers, positive or negative, without decimals.
• Examples: 5, -10, 0.
2. Floating Point (float):
• Numbers with decimal points or in exponential form.
• Examples: 3.14, -0.001, 1.2e3.
3. Complex Numbers (complex):
• Numbers with a real and an imaginary part.
• Represented as a + bj, where a is the real part and b is the imaginary part.
• Example: 3 + 4j.
• Arithmetic Operators:
Operator Description Example Result
+ Addition 5+3 8
- Subtraction 10 - 4 6
* Multiplication 2*3 6
/ Division 8/2 4.0
// Floor Division 7 // 2 3
% Modulus (Remainder) 10 % 3 1
** Exponentiation 2 ** 3 8
10
BVM 103SB(CW-2)
• Built-in Functions for Numbers:
11
BVM 103SB(CW-2)
➢ Exercise 9: Arithmetic Operations
Problem Statement: Write a Python program that performs the following operations on two
user-provided numbers:
1. Calculates and prints their sum, difference, product, and division result.
2. Finds and displays the remainder when the first number is divided by the second.
3. Calculates and prints the result of raising the first number to the power of the second.
Solution:
Solution:
# Convert to integer
int_num = int(float_num)
print("Integer value:", int_num)
12
BVM 103SB(CW-2)
print("Converted back to float:", converted_float)
13
BVM 103SB(CW-2)
Practical 1: Collecting and Displaying Student Details
Problem Statement: Write a Python program that Problem Statement: Write a Python
program that collects basic student details and displays them in a structured format. The program
should:
1. Ask the user to enter their full name, age, course preference, and expected graduation
year.
2. Store the data in variables.
3. Use arithmetic operations to calculate the number of years left until graduation.
4. Print the details in a well-formatted output, displaying:
Objective:
• To understand how to take user input in Python.
• To store and manipulate variables.
• To perform basic arithmetic operations.
• To display formatted output using print statements.
Theory (Recap):
Python provides various ways to collect and manipulate user input. The input() function is used
to receive input from the user, which is stored as a string. Numeric data can be converted using
int() or float(). Basic arithmetic operations such as subtraction (-) can be used to calculate values
like the years left until graduation. Python also supports formatted output using multiple print()
statements.
Key concepts used in this program:
1. Input Handling: input() function.
2. Data Types: Strings and Integers.
3. Arithmetic Operations: Subtraction.
4. Formatted Output: Using multiple print() statements.
14
BVM 103SB(CW-2)
Procedure:
1. Start the Python script.
2. Use the input() function to collect the student's full name, age, course preference, and
expected graduation year.
3. Convert the numeric input values (age and graduation year) to integers using int().
4. Compute the years left until graduation by subtracting the current age from the expected
graduation year.
5. Display the collected details in a structured format using multiple print() statements.
6. Execute the program and verify the output.
1. Students are required to implement this practical on their own using the above procedure.
2. After successful execution, students must:
• Manually write the source code (Python) in their record book.
• Write the expected output in their record book.
3. Save the Python files and results in the college server at the following location:
• Server Path: \\[Link]
• Folder: New Anonymous Share > 103SB CW-2 > Division Folder (e.g., D12 or
D03) > Batch Folder
• Create a folder inside the batch folder with your Enrollment ID (e.g., 24CP01).
• Inside your folder, create a subfolder named Python > Practical_1.
• Save the Python file in this folder.
Conclusion:
Students must write the conclusion in their record book themselves based on their experience and
understanding of the practical.
15
BVM 103SB(CW-2)
❖ Strings in Python
Strings in Python are sequences of characters enclosed in single quotes ('), double quotes ("),
or triple quotes (''' or """). They are immutable, meaning once a string is created, it cannot be
modified.
➢ Creating Strings
# Single-quoted string
a = 'Hello'
# Double-quoted string
b = "World"
print(a, b, c)
s = "Python"
print(s[0]) # Output: P
print(s[1:4]) # Output: yth
print(s[-1]) # Output: n (last character)
16
BVM 103SB(CW-2)
➢ String Operations
➢ String Methods
➢ String Formatting
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
17
BVM 103SB(CW-2)
2. Using f-Strings (Python 3.6+):
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
➢ Escape Characters
18
BVM 103SB(CW-2)
❖ Date and Time in Python
Handling date and time is essential in programming for applications like logging, scheduling, or
measuring durations. Python provides the datetime module to manage date and time efficiently.
To work with date and time, you need to import the datetime module:
import datetime
The datetime module provides methods to retrieve the current date and time:
• [Link]() gives the current date and time.
• [Link]() gives the current date without the time.
import datetime
You can create custom date or time objects using the datetime class:
• [Link](year, month, day)
• [Link](hour, minute, second)
• [Link](year, month, day, hour, minute, second)
19
BVM 103SB(CW-2)
import datetime
Use the strftime method to format dates and times into readable strings:
import datetime
now = [Link]()
formatted = [Link]("%A, %B %d, %Y %H:%M:%S")
print("Formatted Date and Time:", formatted)
Use the strptime method to parse strings into date or datetime objects:
import datetime
20
BVM 103SB(CW-2)
# Parse a date string
date_string = "2024-12-25"
date_object = [Link](date_string, "%Y-%m-%d")
print("Parsed Date Object:", date_object)
➢ Date Arithmetic
The timedelta class allows you to perform date and time arithmetic, such as adding or
subtracting days:
import datetime
# Current date
today = [Link]()
# Add 7 days
a_week_later = today + [Link](days=7)
print("A Week Later:", a_week_later)
# Subtract 30 days
thirty_days_ago = today - [Link](days=30)
print("Thirty Days Ago:", thirty_days_ago)
You can extract individual components (year, month, day, etc.) from a date or datetime object:
import datetime
now = [Link]()
print("Year:", [Link])
print("Month:", [Link])
print("Day:", [Link])
print("Hour:", [Link])
print("Minute:", [Link])
print("Second:", [Link])
21
BVM 103SB(CW-2)
➢ Key Points to Remember
1. Display the current date and time in the format: Weekday, Month Day, Year
Hour:Minute:Second.
2. Calculate the number of days left until the user-specified date (e.g., New Year).
3. Add 45 days to the current date and display the result in YYYY-MM-DD format.
Solution:
import datetime
22
BVM 103SB(CW-2)
❖ Basic Operators in Python
Operators in Python are special symbols or keywords that perform operations on operands. They
are classified into several types based on the operation they perform.
➢ Types of Operators
1. Arithmetic Operators
Used to perform basic mathematical operations.
+ Addition 5+3 8
- Subtraction 5-3 2
* Multiplication 5*3 15
** Exponentiation 5 ** 3 125
// Floor Division 5 // 3 1
Example:-
x = 10
y = 3
print(x + y) # Output: 13
print(x - y) # Output: 7
print(x * y) # Output: 30
print(x / y) # Output: 3.333...
print(x % y) # Output: 1
print(x ** y) # Output: 1000
print(x // y) # Output: 3
23
BVM 103SB(CW-2)
2. Comparison (Relational) Operators
Used to compare two values. The result is a Boolean value (True or False).
== Equal to 5 == 3 False
Example:
a = 10
b = 20
3. Logical Operators
Used to perform logical operations. The result is a Boolean value.
24
BVM 103SB(CW-2)
Example:
x = True
y = False
4. Assignment Operators
Used to assign values to variables.
25
BVM 103SB(CW-2)
Example:
x = 5
x += 3 # Equivalent to x = x + 3
print(x) # Output: 8
x -= 3 # Equivalent to x = x - 3 ,here the x = 8
print(x) # Output: 5
x *= 3 # Equivalent to x = x * 3 ,here the x = 5
print(x) # Output: 15
x /= 3 # Equivalent to x = x * 3 ,here the x = 15
print(x) # Output: 5.0
5. Bitwise Operators
Used to perform operations on binary numbers.
<< Zero fill left Shift left by pushing zeros in from the right and let the
x << 2
shift leftmost bits fall off
>> Signed right Shift right by pushing copies of the leftmost bit in
x >> 2
shift from the left, and let the rightmost bits fall off
Example:
a = 5 # Binary: 101
b = 3 # Binary: 011
26
BVM 103SB(CW-2)
6. Membership Operators
Used to test membership in sequences like strings, lists, or tuples.
Example:
x = 'apple'
print('a' in x) # Output: True
print('x' not in x) # Output: True
7. Identity Operators
Used to compare memory locations of two objects.
Example:
x = [1, 2, 3]
y = x
z = [1, 2, 3]
27
BVM 103SB(CW-2)
➢ Exercise 12: Arithmetic and Logical Operators
Problem Statement : Write a Python program that takes three numbers as input from the user.
Perform the following operations:
Solution
# Display results
print("Sum of numbers:", sum_of_numbers)
print("Product of numbers:", product_of_numbers)
print("Difference of numbers:", difference)
# Logical operations
all_positive = (num1 > 0) and (num2 > 0) and (num3 > 0)
print("All numbers are positive:", all_positive)
1. Performs bitwise AND, OR, and XOR operations on two user-provided integers.
2. Verifies if two variables point to the same object in memory.
28
BVM 103SB(CW-2)
Solution
# Bitwise operations
print("Bitwise AND:", num1 & num2)
print("Bitwise OR:", num1 | num2)
print("Bitwise XOR:", num1 ^ num2)
print("Bitwise NOT (num1):", ~num1)
print("Bitwise Left Shift (num1 by 2):", num1 << 2)
print("Bitwise Right Shift (num2 by 2):", num2 >> 2)
# Identity operation
x = [num1]
y = [num1]
z = x
29
BVM 103SB(CW-2)
Practical: 2 Automated Billing System for a Coffee Shop
Problem Statement: Design a Python program that simulates an automated billing system for
a coffee shop. The program should:
1. Display a menu with prices (e.g., Coffee - ₹70, Tea - ₹50, Sandwich - ₹100).
2. Ask the user to enter the item name and quantity.
3. Calculate the total bill using arithmetic operators. Apply 18% GST on the total. Display
final bill amount after tax. (For computation, do not use if statements or any other concepts
beyond what has been covered so far.)
4. Display the current date and time when generating the bill.
5. Format and display the bill in a structured manner using string manipulation.
Objective:
Theory:
Python provides various functionalities to create a simple billing system using basic concepts such
as:
30
BVM 103SB(CW-2)
Procedure:
1. Students are required to implement this practical on their own using the above procedure.
2. After successful execution, students must:
• Manually write the source code (Python) in their record book.
• Write the expected output in their record book.
3. Save the Python files and results in the college server at the following location:
• Server Path: \\[Link]
• Folder: New Anonymous Share > 103SB CW-2 > Division Folder (e.g., D12 or
D03) > Batch Folder
• Create a folder inside the batch folder with your Enrollment ID (e.g., 24CP01).
• Inside your folder, create a subfolder named Python > Practical_2.
• Save the Python file in this folder.
Conclusion:
Students must write the conclusion in their record book themselves based on their experience and
understanding of the practical.
31
BVM 103SB(CW-2)
❖ Control Structures
Control structures in Python dictate the flow of execution within a program. They include:
1. Sequential Control
2. Selection Control (Decision Making)
3. Iteration Control (Loops)
1. Sequential Control
Sequential control means that statements execute one after another in the order they appear.
Example:
print("Welcome to Python")
name = input("Enter your name: ")
print("Hello,", name)
a) if Statement
Syntax:
if condition:
# Indented block executes if condition is True
statement(s)
Python uses indentation (typically 4 spaces) to define the block of code that belongs
to the if statement.
32
BVM 103SB(CW-2)
How Conditions Work: A condition in an if statement is an expression that evaluates
to a Boolean value (True or False). Python considers the following values as False
(Falsy values):
• None
• False
• 0 (Integer or Float)
• "" (Empty String)
• [] (Empty List)
• {} (Empty Dictionary)
• () (Empty Tuple)
• set() (Empty Set) All other values are considered True (Truthy values).
Example:
if 50:
print("This statement will execute.")
# Output:
This statement will execute.
x = 10
if x > 5:
print("x is greater than 5")
x = 0
if x:
print("This won't be printed")
x = 10
y = 20
if x < y:
print("x is less than y")
33
BVM 103SB(CW-2)
Python supports various comparison operators in if conditions, such as:
o == (Equal to)
o != (Not equal to)
o > (Greater than)
o < (Less than)
o >= (Greater than or equal to)
o <= (Less than or equal to)
▪ Logical Operators in if: Logical operators (and, or, not) can be used to combine
multiple conditions.
x = 15
y = 10
if x > 10 and y < 20:
print("Both conditions are True")
▪ if with Membership Operators: Membership operators (in, not in) check if a value
exists in a sequence.
name = "Python"
if 'y' in name:
print("'y' is present in the string")
num = 10
if num > 0:
if num % 2 == 0:
print("Positive even number")
b) if-else Statement
The if-else statement in Python is used when a program needs to execute one block
of code if a condition is True and a different block if the condition is False. It extends
the basic if statement by providing an alternative path of execution.
Syntax
if condition:
# Executes if the condition is True
statement(s)
else:
# Executes if the condition is False
statement(s)
34
BVM 103SB(CW-2)
The else block must be indented at the same level as the corresponding if block.
Example:
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even Number")
else:
print("Odd Number")
▪ Nested if-else: An if-else statement inside another if-else is called a nested if-else.
▪ Short Hand If ... Else: If you have only one statement to execute, one for if, and one
for else, you can put it all on the same line
a = 11
b = 510
You can also have multiple else statements on the same line:
a = 221
b = 221
35
BVM 103SB(CW-2)
c) if-elif-else Statement
The if-elif-else statement in Python is used for multiple conditional checks. It allows
a program to evaluate multiple conditions sequentially and execute the block of code
corresponding to the first True condition. If none of the conditions are met, the else
block executes.
Syntax
if condition1:
# Executes if condition1 is True
statement(s)
elif condition2:
# Executes if condition2 is True (only if condition1 is
False)
statement(s)
else:
# Executes if none of the above conditions are True
statement(s)
Example:
36
BVM 103SB(CW-2)
print("Grade: D")
else:
print("Grade: F")
Problem: Write a Python program that asks the user for their age. If the age is 18 or above,
print "You are eligible to vote".
Solution:
Problem: Write a Python program that asks the user for their exam score. If the score is 40
or more, print "Pass", otherwise print "Fail".
Solution:
37
BVM 103SB(CW-2)
➢ Exercise 16: if-elif Statement
Problem: Write a Python program that asks the user for the temperature in Celsius and
classifies it as "Cold", "Warm", or "Hot" based on the following conditions:
Solution:
Problem: Write a Python program that asks the user for a year and checks whether it is a
leap year or not. A year is a leap year if:
• It is divisible by 4, and
• If it is a century year (ending in 00), it must also be divisible by 400.
Solution:
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(year, "is a leap year")
else:
print(year, "is not a leap year")
else:
print(year, "is a leap year")
else:
print(year, "is not a leap year")
38
BVM 103SB(CW-2)
Practical:3 University Admission Eligibility Check
Problem Statement:
Write a Python program that checks if a student is eligible for university admission. The program
should:
1. Ask the user to enter their percentage marks in three subjects.
2. Calculate the average marks.
3. If the average is above 75%, print "Eligible for Admission"; otherwise, print "Not
Eligible".
4. If the student scores above 90%, display a message saying "You qualify for a
scholarship!".
5. Handle edge cases (e.g., if the user enters marks below 0 or above 100, display an error
message).
Objective:
Theory (Recap):
39
BVM 103SB(CW-2)
• If the average is above 75%, the student is eligible for admission.
• If the average is above 90%, they qualify for a scholarship.
Procedure:
1. Students are required to implement this practical on their own using the above procedure.
2. After successful execution, students must:
• Manually write the source code (Python) in their record book.
• Write the expected output in their record book.
3. Save the Python files and results in the college server at the following location:
• Server Path: \\[Link]
• Folder: New Anonymous Share > 103SB CW-2 > Division Folder (e.g., D12 or
D03) > Batch Folder
• Create a folder inside the batch folder with your Enrollment ID (e.g., 24CP01).
• Inside your folder, create a subfolder named Python > Practical_3.
• Save the Python file in this folder.
Conclusion:
Students must write the conclusion in their record book themselves based on their experience and
understanding of the practical.
40
BVM 103SB(CW-2)
3. Iteration Control (Loops)
Iteration control, also known as loops, allows a program to execute a block of code multiple
times. Python provides two main types of loops:
1. for loop – Used for iterating over a sequence (e.g., list, tuple, dictionary, string, or range).
2. while loop – Repeats execution as long as a condition remains True.
Loops help automate repetitive tasks and essential in programming, as they help reduce
redundancy, improve efficiency, and enhance code readability.
The for loop in Python is used for iterating over sequences (like lists, tuples, dictionaries,
sets, or strings). It executes the block of code once for each element in the sequence.
Syntax:
41
BVM 103SB(CW-2)
Example 2: Using range() with for Loop
for i in range(5):
print(i)
#Output
0
1
2
3
4
(The range(5) generates numbers from 0 to 4 (excluding 5).)
word = "Python"
for letter in word:
print(letter)
#Output
P
y
t
h
o
n
#Output
name : John
age : 20
course : Computer Science
42
BVM 103SB(CW-2)
2. The while Loop
The while loop executes a block of code as long as the given condition is True.
Syntax:
while condition:
# loop body
count = 1
while count <= 5:
print("Count:", count)
count += 1
#Output
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
while True:
print("This is an infinite loop!")
• Warning: This loop runs indefinitely because the condition True never changes.
• Solution: Use break to exit the loop when a specific condition is met
43
BVM 103SB(CW-2)
➢ Loop Control Statements
1. break Statement
The break statement is used to exit the loop prematurely when a certain condition is
met.
num = 1
while num <= 10:
if num == 5:
break
print(num)
num += 1
#Output
1
2
3
4
(The loop terminates when num reaches 5.)
2. continue Statement
The continue statement skips the current iteration and moves to the next iteration of the
loop.
#Output
1
2
4
5
(When num is 3, the continue statement skips that iteration.)
44
BVM 103SB(CW-2)
3. else Clause in Loops
Python allows an else block to be used with loops. The else block executes after the
loop completes normally (without a break).
for i in range(5):
print(i)
else:
print("Loop completed successfully!")
#Output
0
1
2
3
4
Loop completed successfully!
num = 1
while num < 5:
print(num)
num += 1
else:
print("Loop finished normally!")
#Output
1
2
3
4
Loop finished normally!
45
BVM 103SB(CW-2)
➢ Nested Loops
#Output
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=2, j=2
i=2, j=3
i=3, j=1
i=3, j=2
i=3, j=3
i = 1
while i <= 3:
j = 1
while j <= 3:
print(f"i={i}, j={j}")
j += 1
i += 1
#Output
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=2, j=2
i=2, j=3
i=3, j=1
i=3, j=2
i=3, j=3
• This structure is useful for working with multi-dimensional data like matrices.
46
BVM 103SB(CW-2)
➢ Exercise 18: while Loop
Problem:
Write a Python program that asks the user for a number and calculates the factorial of that
number using a while loop.
Solution:
47
BVM 103SB(CW-2)
Practical 4: Basic ATM Simulation
Problem Statement:
Create a Python program that acts as a basic ATM. The program should:
1. Display an initial balance (e.g., ₹5000).
2. Allow the user to withdraw money, ensuring they do not withdraw more than the available
balance.
3. Use a loop to allow multiple transactions until the user exits.
4. Deduct the amount and display the remaining balance after each transaction.
5. If the balance goes below ₹100, warn the user about a low balance.
Objective:
• To practice loops for repeated user interactions.
• To implement if-else conditions for checking withdrawal limits.
• To work with user input and numeric calculations.
• To simulate a simple banking system.
Theory (Recap):
• Loops (while loop): Used to repeatedly execute a block of code until a specific condition
is met. It helps in scenarios where continuous execution is required until the user decides
to stop.
• Conditional Statements (if, if-else, if-elif): Allow decision-making in programs. These
statements check conditions and execute different blocks of code based on whether the
condition is True or False.
• Nested if-else: When an if or else statement contains another if-else, it helps in handling
multiple levels of conditions, ensuring detailed decision-making.
• User Input Handling: The input() function is used to accept user data, which can be
validated to ensure correct values are processed.
• Mathematical Calculations: Variables are updated dynamically based on arithmetic
operations, ensuring that computed values are accurate as per given conditions.
48
BVM 103SB(CW-2)
Procedure:
1. Initialize the account balance (e.g., ₹5000).
2. Use a while loop to allow continuous transactions.
3. Prompt the user to enter a withdrawal amount.
4. Check if the withdrawal is valid:
• If the withdrawal amount exceeds the balance, display an error.
• Otherwise, deduct the amount and update the balance.
5. Warn the user if the balance falls below ₹100.
6. Ask the user if they want another transaction or want to exit.
1. Students are required to implement this practical on their own using the above procedure.
2. After successful execution, students must:
• Manually write the source code (Python) in their record book.
• Write the expected output in their record book.
3. Save the Python files and results in the college server at the following location:
• Server Path: \\[Link]
• Folder: New Anonymous Share > 103SB CW-2 > Division Folder (e.g., D12 or
D03) > Batch Folder
• Create a folder inside the batch folder with your Enrollment ID (e.g., 24CP01).
• Inside your folder, create a subfolder named Python > Practical_4.
• Save the Python file in this folder.
Conclusion:
Students must write the conclusion in their record book themselves based on their experience and
understanding of the practical
49
BVM 103SB(CW-2)
Practical 5: Pattern Printing using Loops
Problem Statement: Write a Python program that prints the following three patterns using
loops. The program should:
*
** 1 EDCBA
*** 12 DCBA
**** 123 CBA
*** 1234 BA
** 12345 A
* 123456
Objective:
• To practice the use of for loops and while loops for pattern generation.
• To understand nested loops and how they control printed output.
• To take user input (n) to create dynamic patterns.
Theory:
• Loops (for and while): Used to iterate through a sequence of numbers, printing characters
or numbers in a structured format.
• Nested Loops: The outer loop controls the rows, while the inner loop controls the number
of elements printed in each row.
• Mathematical Calculations: The pattern structures are derived using incremental or
decremental logic, ensuring correct formatting and positioning of elements.
50
BVM 103SB(CW-2)
Procedure:
1. Take user input n to define the number of rows for the patterns.
2. Use nested loops to generate each pattern based on logical conditions.
3. Print the patterns while ensuring correct formatting and alignment.
1. Students are required to implement this practical on their own using the above procedure.
2. After successful execution, students must:
• Manually write the source code (Python) in their record book.
• Write the expected output in their record book.
3. Save the Python files and results in the college server at the following location:
• Server Path: \\[Link]
• Folder: New Anonymous Share > 103SB CW-2 > Division Folder (e.g., D12 or
D03) > Batch Folder
• Create a folder inside the batch folder with your Enrollment ID (e.g., 24CP01).
• Inside your folder, create a subfolder named Python > Practical_5.
• Save the Python file in this folder.
Conclusion:
Students must write the conclusion in their record book themselves based on their experience and
understanding of the practical.
51
BVM 103SB(CW-2)
❖ List
A list in Python is a mutable, ordered collection of elements that can hold items of different
data types. Lists are one of the most commonly used data structures in Python because of their
flexibility and ease of use. List items are ordered, changeable, and allow duplicate values.
Characteristics of Lists
• Ordered: Items have a specific order, and they maintain this order unless modified.
• Mutable: Elements in a list can be modified (added, removed, or changed).
• Heterogeneous: A list can store different types of elements (integers, strings, floats, even
other lists).
• Indexing: Supports both positive and negative indexing.
• Slicing: Supports retrieving a subset of elements using slicing.
➢ Creating a List
# Empty list
empty_list = []
Example: Indexing
52
BVM 103SB(CW-2)
print(fruits[0]) # Output: apple
print(fruits[-1]) # Output: cherry (Negative indexing)
the first item has index [0], the second item has index [1] etc. Negative indexing means start
from the end. -1 refers to the last item, -2 refers to the second last item etc.
Example: Slicing
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.
➢ Modifying Lists
Adding Elements
To append elements from another list to the current list, use the extend() method.
[Link](tropical)
Removing Elements
53
BVM 103SB(CW-2)
• The pop() method removes the specified index. If you do not specify the index,
the pop() method removes the last item.
• The del keyword also removes the specified index
• The clear() method empties the list. The list still remains, but it has no content.
Updating Elements
➢ List Operations
# Concatenation
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = list1 + list2 # Output: [1, 2, 3, 4, 5, 6]
# Repetition
repeat = ["Hello"] * 3 # Output: ['Hello', 'Hello', 'Hello']
# Membership
print(2 in list1) # Output: True
➢ List Comprehensions
List comprehension offers a shorter syntax when you want to create a new list based on
the values of an existing list.
Example:
Based on a list of fruits, you want a new list, containing only the fruits with the letter "a"
in the name.
Without list comprehension you will have to write a for statement with a conditional test
inside:
for x in fruits:
54
BVM 103SB(CW-2)
if "a" in x:
[Link](x)
print(newlist)
With list comprehension you can do all that with only one line of code:
Syntax:
The return value is a new list, leaving the old list unchanged.
print(newlist)
Problem Statement:
Solution:
55
BVM 103SB(CW-2)
[Link]("History")
❖ Tuples
A tuple is an immutable, ordered collection of elements. It is similar to a list, but once a
tuple is created, its elements cannot be changed.
Characteristics of Tuples
➢ Creating Tuples
# Empty tuple
empty_tuple = ()
56
BVM 103SB(CW-2)
➢ Accessing Tuple Elements
Example: Indexing
Example: Slicing
➢ Tuple Operations
# Concatenation
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
result = tuple1 + tuple2 # Output: (1, 2, 3, 4, 5, 6)
# Repetition
repeat = ("Hello",) * 3 # Output: ('Hello', 'Hello',
'Hello')
# Membership
print(2 in tuple1) # Output: True
Problem Statement:
1. Create a tuple numbers containing (5, 10, 15, 20, 25, 30).
2. Access and print the third element from the tuple.
3. Use slicing to extract and print elements from the second to the fifth position.
4. Try to modify the fourth element (observe what happens).
5. Concatenate another tuple (50, 60, 70) with numbers.
57
BVM 103SB(CW-2)
Solution:
# Step 1: Create a tuple
numbers = (5, 10, 15, 20, 25, 30)
❖ Dictionary
A dictionary is an unordered collection of key-value pairs. Dictionaries are mutable and
provide efficient data retrieval.
Characteristics of Dictionaries
• Unordered: Elements do not have a fixed order (Python 3.7+ maintains insertion
order).
• Key-Value Pairs: Each key maps to a specific value.
• Mutable: Elements can be modified.
• Keys Must Be Unique: Duplicate keys are not allowed.
➢ Creating a Dictionary
# Empty dictionary
empty_dict = {}
58
BVM 103SB(CW-2)
"course": "Computer Science"
}
➢ Modifying a Dictionary
Adding Elements
Updating Elements
Removing Elements
➢ Dictionary Methods
# Output
name : Rajan
age : 23
city : New York
59
BVM 103SB(CW-2)
➢ Exercise 21: Dictionary Operations
Problem statement:
Solution:
60
BVM 103SB(CW-2)
Practical 6: University Course Management System
Problem Statement: Create a Python program that manages courses offered in a university.
The program should:
1. Store a list of courses using a list (e.g., ["Python", "Java", "C++", "Data Science"]).
2. Allow the user to add a new course.
3. Allow the user to remove an existing course.
4. Use a tuple to store immutable information (e.g., university name, established year).
5. Use a dictionary to store course details (e.g., {"Python": "3 months", "Java": "4 months"})
and allow the user to search for a course duration.
Objective:
• Understand the use of lists, tuples, and dictionaries in Python.
• Perform CRUD (Create, Read, Update, Delete) operations on lists and dictionaries.
• Learn how to work with user input and manipulate data structures dynamically.
Theory:
1. Lists in Python
• A list is a mutable data structure used to store multiple items in a single variable.
• Lists allow dynamic modification (adding/removing elements).
2. Tuples in Python
3. Dictionaries in Python
• A dictionary stores data in key-value pairs, making it easy to look up values using keys.
• Used to store course details with course name as key and duration as value.
61
BVM 103SB(CW-2)
Procedure:
1. Students are required to implement this practical on their own using the above procedure.
2. After successful execution, students must:
• Manually write the source code (Python) in their record book.
• Write the expected output in their record book.
3. Save the Python files and results in the college server at the following location:
• Server Path: \\[Link]
• Folder: New Anonymous Share > 103SB CW-2 > Division Folder (e.g., D12 or
D03) > Batch Folder
• Create a folder inside the batch folder with your Enrollment ID (e.g., 24CP01).
• Inside your folder, create a subfolder named Python > Practical_6.
• Save the Python file in this folder.
Conclusion:
Students must write the conclusion in their record book themselves based on their experience and
understanding of the practical.
62
BVM 103SB(CW-2)
❖ NumPy and Pandas
Data manipulation and numerical computing are essential in programming, especially in fields like
data science, machine learning, and scientific computing. NumPy (Numerical Python) and
Pandas are two of the most powerful Python libraries that allow us to efficiently handle and
process large datasets.
• NumPy is used for numerical computations, providing fast array processing, mathematical
functions, and multi-dimensional data handling.
• Pandas is a data analysis library that offers powerful tools for handling structured data,
including DataFrames and Series.
1. NumPy
NumPy (Numerical Python) is a powerful Python library used for working with arrays. It also
provides functions for linear algebra, Fourier transforms, and matrices. Created in 2005 by Travis
Oliphant, NumPy is open-source and freely available.
What is NumPy?
NumPy is a Python library used for numerical operations. It provides:
• Multidimensional arrays (ndarray)
• Mathematical functions for data processing
• Efficient operations compared to Python lists
• Linear algebra, statistics, and random number generation functions
63
BVM 103SB(CW-2)
Advantages of NumPy
Feature Python List NumPy Array
Speed Slower Faster (Optimized in C)
Memory Usage Higher Lower (Efficient
memory handling)
Functionality Basic operations Advanced
mathematical
operations
To import NumPy:
import numpy as np # np is a common alias for NumPy
import numpy as np
# Creating a 1D array
marks = [Link]([75, 88, 92, 67, 80])
print("Student Marks:", marks)
#Output
Student Marks: [75 88 92 67 80]
Array Dimensions:
import numpy as np
# 0-D Array (Scalar):
arr0 = [Link](42)
print(arr0)
64
BVM 103SB(CW-2)
# 2-D Array (Matrix):
arr2 = [Link]([[1, 2, 3], [4, 5, 6]])
print(arr2)
Slicing Arrays
#Slicing in 1-D arrays:
arr1 = [Link]([1, 2, 3, 4, 5, 6, 7])
print(arr1[1:5]) # Output: [2 3 4 5]
print(arr1[:4]) # Elements from beginning to index 4 (exclusive)
print(arr1[-3:-1]) # Negative slicing
print(arr1[1:5:2]) # Step slicing (every second element)
65
BVM 103SB(CW-2)
#Slicing in 2-D arrays:
arr2 = [Link]([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr2[1, 1:4]) # Elements from 2nd row, index 1 to 4
print(arr2[0:2, 2]) # 3rd column from both rows
print(arr2[0:2, 1:4]) # 2-D slice
Example:
import numpy as np
#Output:
Zeros Array:
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
Ones Array:
[[1. 1. 1. 1.]
[1. 1. 1. 1.]]
Identity Matrix:
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
66
BVM 103SB(CW-2)
NumPy extends these with specialized types:
• i: Integer • b: Boolean
• u: Unsigned integer • M: Datetime
• f: Float • O: Object
• c: Complex float • S/U: String/Unicode string
Example:
import numpy as np
marks = [Link]([75, 88, 92, 67, 80])
average = [Link](marks)
maximum = [Link](marks)
minimum = [Link](marks)
67
BVM 103SB(CW-2)
#Output:
Average Marks: 80.4
Highest Marks: 92
Lowest Marks: 67
Problem Statement: Create a dataset that stores the daily temperature readings of a city for a
week and perform the following operations on it.
1. Create a NumPy array to store the temperature data.
2. Find the average temperature for the week.
3. Identify the highest and lowest temperatures recorded.
4. Convert the temperature readings from Celsius to Fahrenheit using the formula:
F=(C×95)+32
5. Extract temperature readings that are above the weekly average.
Solution:
import numpy as np
68
BVM 103SB(CW-2)
2. Pandas
What is Pandas?
Pandas is a powerful open-source Python library designed for data manipulation and analysis. It
provides data structures and functions to efficiently handle structured data, such as tables, matrices,
and time series.
• The name "Pandas" refers to "Panel Data" and "Python Data Analysis."
• Created by Wes McKinney in 2008, Pandas has become an essential tool in data science
and analytics.
Pandas is a data analysis library built on top of NumPy. It provides two primary data structures:
1. Series – A one-dimensional labeled array.
2. DataFrame – A two-dimensional table, similar to an Excel spreadsheet.
Installation of Pandas
If you have Python and PIP installed, install Pandas using the following command:
pip install pandas
Importing Pandas
After installation, import Pandas in your Python script:
import pandas
To confirm that Pandas is installed, check its version:
import pandas as pd
print(pd.__version__)
69
BVM 103SB(CW-2)
➢ Pandas Series
A Pandas Series is a one-dimensional labeled array capable of holding data of any type (integer,
string, float, etc.).
a = [1, 7, 2]
myvar = [Link](a)
print(myvar)
#Output:
0 1
1 7
2 2
dtype: int64
#Output:
Neel 85
Meet 90
geet 78
Jeet 92
dtype: int64
#Output:
day1 420
day2 380
day3 390
dtype: int64
70
BVM 103SB(CW-2)
➢ Pandas DataFrame
A Pandas DataFrame is a two-dimensional data structure, similar to a table with rows and
columns.
data = {
"calories": [420, 380, 390],
"duration": [50, 40, 45]
}
df = [Link](data)
print(df)
#Output:
calories duration
0 420 50
1 380 40
2 390 45
df = pd.read_csv("[Link]")
print(df.to_string()) # Prints the entire DataFrame
71
BVM 103SB(CW-2)
➢ Data Cleaning and Manipulation
#Checking for Missing Data
print([Link]().sum()) # Counts missing values in each column
Example:
import pandas as pd
72
BVM 103SB(CW-2)
df = [Link](data)
#Output:
Dataset Information:
<class '[Link]'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 4 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Employee 5 non-null object
1 Department 5 non-null object
2 Salary 5 non-null int64
3 Experience (Years) 5 non-null int64
dtypes: int64(2), object(2)
memory usage: 292.0+ bytes
None
Summary Statistics:
Salary Experience (Years)
count 5.000000 5.000000
73
BVM 103SB(CW-2)
mean 62400.000000 6.400000
std 10784.247772 2.302173
min 50000.000000 4.000000
25% 55000.000000 5.000000
50% 60000.000000 6.000000
75% 72000.000000 7.000000
max 75000.000000 10.000000
Example: Filtering Employees with High Salaries , Suppose we want to filter employees who earn
more than 60,000.
import pandas as pd
df = [Link](data)
#Output:
Employees earning more than 60,000:
Employee Department Salary Experience (Years)
2 Mike Finance 75000 10
3 Emma IT 72000 6
74
BVM 103SB(CW-2)
➢ Sorting and Displaying Top n Records
Sorting helps us organize a dataset based on the values in a specific column. We can sort the
data in ascending (smallest to largest) or descending (largest to smallest) order.
df = [Link](data)
#Output:
Top 3 Highest-Paid Employees:
Employee Department Salary Experience (Years)
2 Mike Finance 75000 10
3 Emma IT 72000 6
0 John IT 60000 5
75
BVM 103SB(CW-2)
➢ Exercise 23: Creating and Manipulating DataFrames
Problem Statement: A small car dealership maintains a record of the cars they have in stock. The
dataset contains the following information for each car:
• Car Brand (e.g., BMW, Ford, Toyota)
• Model Year (e.g., 2019, 2020, 2021)
• Price (in Rupees)
• Mileage (in km)
Your tasks:
1. Create a Pandas DataFrame for the given data.
2. Display the first few rows of the dataset.
3. Find the average price of the cars.
4. Identify the most expensive and the cheapest car.
5. Filter and display cars that have a price above the average.
Solution:
import pandas as pd
76
BVM 103SB(CW-2)
# Step 5: Filter cars with price above the average
expensive_cars = df[df["Price"] > average_price]
print("\nCars priced above average:")
print(expensive_cars)
#Output:
Car Inventory DataFrame:
Brand Model_Year Price Mileage
0 Mercedes 2019 35000000 12
1 Tata 2020 1220000 20
2 Toyota 2021 2700000 17
3 Audi 2022 15500000 15
4 BMW 2021 12600000 16
77
BVM 103SB(CW-2)
Practical 7: Student Marks Analysis using NumPy and Pandas
Problem Statement: Develop a Python program using NumPy and Pandas to analyze student
marks. The program should:
1. Create a NumPy array to store marks of students in 5 subjects.
2. Calculate and display the average, maximum, and minimum marks using NumPy
functions.
3. Read a CSV file containing student names and marks using Pandas.
4. Display students who have scored above 80%.
5. Sort and display the top 3 students based on total marks.
Objective:
• Understand how to use NumPy arrays for mathematical operations.
• Learn how to handle CSV files using Pandas for data analysis.
• Apply sorting and filtering techniques to extract meaningful insights.
Theory:
• NumPy (numpy): A powerful library used for numerical computations. It provides
functions like mean(), max(), and min() to analyze data efficiently.
• Pandas (pandas): A data manipulation library used for reading, filtering, and sorting
datasets from CSV files. The DataFrame structure allows easy access and processing of
tabular data.
• CSV File Handling: Data is stored in a structured format (.csv), which can be read, written,
and manipulated using Pandas.
Procedure:
1. Create a CSV file ([Link]) with the following columns:
• Student Name
• Marks in 5 Subjects
• Total Marks
• Percentage
2. Load student marks into a NumPy array and perform basic calculations.
3. Use Pandas to read the CSV file and analyze the data.
4. Apply conditions to filter students with above 80% marks.
5. Sort the data based on total marks and display the top 3 students.
78
BVM 103SB(CW-2)
Implementation and Result:
1. Students are required to implement this practical on their own using the above procedure.
2. After successful execution, students must:
• Manually write the source code (Python) in their record book.
• Write the expected output in their record book.
3. Save the Python files and results in the college server at the following location:
• Server Path: \\[Link]
• Folder: New Anonymous Share > 103SB CW-2 > Division Folder (e.g., D12 or
D03) > Batch Folder
• Create a folder inside the batch folder with your Enrollment ID (e.g., 24CP01).
• Inside your folder, create a subfolder named Python > Practical_7.
• Save the Python file in this folder.
Conclusion:
Students must write the conclusion in their record book themselves based on their experience and
understanding of the practical.
79
BVM 103SB(CW-2)