Python Programming Lab Manual
Python Programming Lab Manual
Topics Covered:
1. Variables & Data Types
2. Tuples
3. Operators & Expressions
4. Strings
5. Lists
6. For Loop
7. While Loop
8. Conditional Structures
LAB 1: Variables & Data Types in Python
1. Lab Objectives
By the end of this lab, students will be able to:
• Declare and initialize variables in Python.
• Identify and use different data types (int, float, string, bool).
• Perform type checking using type().
• Apply type casting (int(), float(), str(), bool()).
• Take input from users and convert input types appropriately.
• Understand common type-related errors.
2. Introduction to Variables
A variable is a named memory location used to store data.
Syntax:
variable_name = value
Example:
age = 20
name = "Ali"
height = 5.7
is_student = True
Python is dynamically typed, meaning you do not declare the type explicitly.
3. Declaring Variables
name = "Asmara"
age = 19
cgpa = 3.75
enrolled = True
print(name)
print(age)
print(cgpa)
print(enrolled)
Expected Output:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
Example:
age = input("Enter your age: ")
print(type(age)) # str
To convert to integer:
age = int(input("Enter your age: "))
print(age + 5)
Problem:
Write a program that:
• Takes two numbers as input
• Converts them to float
• Prints their sum
Solution Template:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
sum_result = num1 + num2
print("Sum is:", sum_result)
Example:
x = 10
y = 5
result = x > y
print(result)
print(type(result))
Common Errors
1. Value Error
Occurs when invalid conversion happens.
num = int("abc") # Error
2. Type Error
Occurs when incompatible types are used.
print("Age: " + 20) # Error
Correct version:
print("Age: " + str(20))
5. Practice Exercises
Exercise 1
Take your name and age as input and display: My name is ___ and I am ___ years old.
Exercise 2
Take temperature in Celsius and convert it to Fahrenheit.
Formula: F = (C x 9/5) + 32
Exercise 3
Take a number as input and print:
• Its data type
• Its square
• Whether it is greater than 50
LAB 2: Sequence Data Structures – Tuples
1. Introduction & Theory
In Python, a Tuple is a collection of objects which is ordered and immutable. While they are visually
similar to lists (which use square brackets []), tuples are defined using parentheses ().
Core Properties:
• Immutability: Once a tuple is created, you cannot change its elements. There are no methods to
add (append), remove (pop), or modify elements. This ensures data integrity.
• Ordered: Tuples maintain the order of elements based on their index.
• Memory Efficient: Because they are fixed-size, Python handles them more efficiently in memory
than dynamic lists.
• Heterogeneous: They can store a mix of data types (strings, integers, floats, etc.).
3. Error Identification
Code Snippet Error Observed Reason
t = (1, 2); t[0] = 5 TypeError 'tuple' object does not support item assignment.
t = (1, 2); [Link](3) AttributeError 'tuple' object has no attribute 'append'.
t = (1, 2); del t[0] TypeError 'tuple' object doesn't support item deletion.
4. Practice Tasks
Task 1: The Buffet Menu
Create a tuple called buffet containing 5 food items. Use a loop to print them. Then, try to modify an
item to see the error. Finally, overwrite the variable buffet with a new tuple that replaces two items and
print the new menu.
5. Conclusion
Through this lab, we have established that tuples are essential for storing data that must remain
constant throughout the execution of a program. While they lack the flexibility of lists, their immutability
provides a safeguard against accidental data modification and improves computational performance.
LAB 3: Operators and Expressions in Python
Objectives
By the end of this lab, students will be able to:
• Define operators and expressions in Python.
• Differentiate between different types of operators.
• Apply arithmetic, relational, logical, assignment, bitwise, and membership operators.
• Understand operator precedence and associativity.
• Write small programs using operators to solve real-life problems.
What is an Operator?
Operators are special symbols in Python that perform operations on variables and values.
Code Example:
x = 5
y = 2
print(x + y) # Addition -> 7
Here + is an operator, x and y are operands, and x+y is an expression.
1. Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations.
Operator Meaning Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
// Floor Division x // y
% Modulus (Remainder) x%y
** Exponentiation x ** y
Code Example:
a = 15
b = 4
print("Addition:", a + b) # 19
print("Subtraction:", a - b) # 11
print("Multiplication:", a * b) # 60
print("Division:", a / b) # 3.75
print("Floor Division:", a // b) # 3
print("Modulus:", a % b) # 3
print("Exponentiation:", a ** b) # 50625
2. Relational Operators
Relational (comparison) operators are used to compare values and return a Boolean result (True or
False).
Operator Meaning Example
== Equal to X == y
!= Not equal to X != y
> Greater than X>y
< Less than X<y
>= Greater or equal X >= y
<= Less or Equal X <= y
Code Example:
x = 10
y = 20
print(x == y) # False
print(x != y) # True
print(x > y) # False
print(x < y) # True
print(x >= y) # False
print(x <= y) # True
3. Logical Operators
Logical operators are used to combine conditional statements.
Operator Meaning Example
and True if both are True X > 5 and y < 10
or True if at least one is True X > 5 or y < 10
not Negates the result not(x > 5)
Code Example:
a = True
b = False
print(a and b) # False
print(a or b) # True
print(not a) # False
4. Assignment Operators
Assignment operators are used to assign values to variables. They can also combine assignments with
arithmetic.
Operator Example Equivalent To
= x=5 Assign value
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
**= x **= 2 x = x ** 2
//= x //= 2 x = x // 2
Code Example:
x = 10
print("Initial value:", x)
x += 5
print("After +=:", x) # 15
x -= 3
print("After -=:", x) # 12
x *= 2
print("After *=:", x) # 24
x /= 4
print("After /=:", x) # 6.0
x **= 2
print("After **=:", x) # 36.0
5. Bitwise Operators
Bitwise operators perform operations on binary representations of integers.
Operator Meaning Example
& AND x&y
| OR x|y
^ XOR x^y
~ NOT (1's complement) ~x
<< Left shift x << 2
>> Right shift x >> 2
Code Example:
a = 5 # 0101
b = 3 # 0011
print("a & b:", a & b) # 1
print("a | b:", a | b) # 7
print("a ^ b:", a ^ b) # 6
print("~a:", ~a) # -6
print("a << 1:", a << 1) # 10
print("a >> 1:", a >> 1) # 2
6. Membership Operators
Membership operators are used to test whether a value exists in a sequence (list, string, tuple, etc.).
Operator Meaning Example
in True if value exists "a" in "apple"
not in True if value does not exist "x" not in "apple"
Code Example:
fruits = ["apple", "banana", "mango"]
print("apple" in fruits) # True
print("grapes" in fruits) # False
print("orange" not in fruits) # True
7. Identity Operators
Identity operators are used to compare memory addresses (whether two objects refer to the same
object).
Operator Meaning Example
is True if same object x is y
is not True if not same object x is not y
Code Example:
x = [1, 2, 3]
y = [1, 2, 3]
z = x
print(x == y) # True (values are equal)
print(x is y) # False (different memory Loc)
print(x is z) # True
Expressions in Python
An expression is a combination of operands (variables, constants, values) and operators that produces
a result.
• Operands: The values/variables.
• Operators: The symbols that operate on operands.
• Expression: The complete statement that evaluates to a value.
Types of Expressions
Expression Type Description Example Result
Arithmetic Expression Uses arithmetic operators to 10 + 5 * 2 20
perform calculations.
Relational Expression Compares two values and 10 > 5 True
returns True or False.
Logical Expression Combines multiple (10>5) and (3<2) False
conditions using logical
operators.
Assignment Assigns values to variables, x = 10; x += 5 15
Expression possibly with operations.
Bitwise Expression Operates at the binary (bit) 5&3 1
level.
Membership Checks if a value exists in a "apple" in True
Expression sequence. ["apple","banana"
]
Identity Expression Compares memory location a is b True/False
(object identity). depending on
object
reference
Code Example:
expr = 10 + 2 * 3 ** 2
# Step 1: 3**2 = 9
# Step 2: 2*9 = 18
# Step 3: 10+18 = 28
print(expr) # 28
Practice Tasks
Task 1:
Ask the user for their age. If age is between 18 and 60, print "Eligible for work", otherwise "Not eligible".
Task 2:
Write an expression to calculate the area of a circle: pi * r ** 2.
LAB 4: Strings in Python
1. Introduction
1.1. Aim of the Lab
The aim of this lab is to introduce undergraduate data science students to the fundamentals of string
manipulation in Python. By the end of this lab, students will be proficient in creating strings, accessing
their elements, and using built-in methods to process and analyze text data — a crucial skill in the data
science workflow.
2. Introduction to Strings
In data science, data is rarely purely numerical. It often comes as text: names in a database, tweets
from Twitter, customer reviews, or entire books. In Python, we handle this text using a data type called
a string (str). A string is simply a sequence of characters. Characters can be letters, numbers,
punctuation, or even emojis.
# Double quotes
string2 = "Data Science is fun!"
print(string1)
print(string2)
print(string3)
You can access a single character using square brackets [] and the index.
Code Example:
language = "python"
first_char = language[0] # 'p'
third_char = language[2] # 't'
last_char = language[5] # 'n'
print(f"First character: {first_char}")
print(f"Third character: {third_char}")
print(f"Last character: {last_char}")
# Extract "Data"
sub1 = text[0:4]
print(f"text[0:4] -> '{sub1}'") # Output: 'Data'
# Extract "Science"
sub2 = text[5:12]
print(f"text[5:12] -> '{sub2}'") # Output: 'Science'
8. Lab Exercises
Exercise 1: The Name Formatter
Write a program that does the following:
6. Asks the user to input their full name (first and last).
7. Prints the name in all uppercase letters.
8. Prints the name in all lowercase letters.
9. Prints the name in title case.
10. Prints the length of the name (excluding the space).
Expected Outcomes:
By the end of this lab session, students will be able to:
19. Create and initialize lists.
20. Add and remove items from lists.
21. Access items in lists.
22. Iterate over lists.
Lists in Python
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple,
Set, and Dictionary, all with different qualities and usage.
Lists are created using square brackets: []
For Example:
List1 = ["Welcome", "to", "MUET"]
print(List1)
Output:
["Welcome", "to", "MUET"]
Lists are the simplest containers that are an integral part of the Python language. Lists need not be
homogeneous always which makes it the most powerful tool in Python. A single list may contain Data
Types like Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered even
after their creation.
Access Items
List items are indexed and you can access them by referring to the index number.
Negative Indexing
Negative indexing means start from the end. -1 refers to the last item, -2 refers to the second last item,
etc.
Range of Indexes
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.
For example:
thislist = ["apple", "banana", "cherry"]
[Link]("orange")
print(thislist)
Insert Items
To insert a list item at a specified index, use the insert() method.
Lab Tasks
You are expected to follow the tutorial given in this section and complete all tasks.
Indexing operation
my_list = [2, 4, 6, 8, 10]
# Access the first element of the list
first_item = my_list[0]
print(first_item) # the output will be 2
Slicing
my_list = [2, 4, 6, 8, 10]
# Get the first 3 items from the list
sliced_list = my_list[0:3]
print(sliced_list) # the output will be [2, 4, 6]
Appending
my_list = [2, 4, 6]
# Append a value of 8 to the list
my_list.append(8)
print(my_list) # the output will be [2, 4, 6, 8]
Deleting
One can use either the del statement or the remove() method to delete an item from a list.
Sorting
One can use either the built-in sorted() function or the .sort() method to sort a list.
Pop operation
my_list = [1, 2, 3, 4]
# Remove the last item
my_list.pop(-1)
print(my_list) # output will be [1, 2, 3]
Hardware/Software Tools
• Hardware: Desktop/Computer
• Software Tool: VSCODE/Anaconda
Lab Tasks
Task 1: Print numbers 1 to 20
for number in range(1, 21):
print(number)
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Output:
1 2 3 4
Output:
1 2 3 4 6 7 8 9 10
Output:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21 ... up to 7 x 10 = 70
Output:
Sum = 5050
Output:
Square of 1 is 1
Square of 2 is 4 ... up to Square of 10 is 100
Output:
*
**
***
****
*****
Practice Tasks
33. Count how many vowels are in a string. Input: "programming" -> Output: 3
34. Find factorial of a number n. 5! = 5 x 4 x 3 x 2 x 1
35. Check if a number is prime using a for loop.
36. Print a 3x3 multiplication table using nested loops.
LAB 7: While Loop in Python
Lab Objective
In this lab, students will explore the fundamental concept of while loop and understand why repetition is
essential in programming. They will learn how to use both while loop to execute a block of code multiple
times. Through hands-on practice, students will be able to write programs that iterate over ranges,
process repeated input, and perform calculations using loops.
Hardware/Software Tools
• Hardware: Desktop/Computer
• Software Tool: VSCODE/Anaconda
While Loops
We have already learned about for loops, which allow us to repeat things a specified number of times.
Sometimes, though, we need to repeat something, but we don't know ahead of time exactly how many
times it has to be repeated. For instance, a game of Tic-tac-toe keeps going until someone wins or
there are no more moves to be made, so the number of turns will vary from game to game. This is a
situation that would call for a while loop.
A while loop statement in Python programming language repeatedly executes a target statement as
long as a given condition is true.
Syntax
while expression:
statement(s)
Here, statement(s) may be a single statement or a block of statements with uniform indent. The
condition may be any expression, and true is any non-zero value. The loop iterates while the condition
is true. When the condition becomes false, program control passes to the line immediately following the
loop.
In Python, all the statements indented by the same number of character spaces after a programming
construct are considered to be part of a single block of code. Python uses indentation as its method of
grouping statements.
Flow Diagram
The while loop checks the condition first. If condition is true, the conditional code executes and the loop
repeats. If condition is false, execution moves past the loop.
A key point of the while loop is that the loop might not ever run. When the condition is tested and the
result is false, the loop body will be skipped and the first statement after the while loop will be executed.
Output:
1 2 3 4 5
Example 2: Sum using while loop
total = 0
num = 1
while num <= 5:
total += num
num += 1
print("Total:", total)
Output:
1 2 3 4
Output:
1 2 4 5
Practice Tasks
• Print numbers from 1 to 10 using a while loop.
• Print all even numbers between 1 and 20.
• Print a countdown from 10 to 1.
• Take n as input and calculate the sum from 1 to n.
• Print the table of a number (e.g., 5 x 1 to 5 x 10).
Reverse a Number
Input: 1234 -> Output: 4321
• Input a number and count how many digits it has.
• Calculate factorial of a number using a while loop.
Example: 121 -> palindrome, 123 -> not palindrome
Sum of Digits
Input: 456 -> Output: 15
LAB 8: Python – Conditional Structures
Objective
The objective of this lab will be to learn about conditional statements with the help of examples and
learning tasks.
Activity Outcomes
The activities provide hands-on practice with the following topics:
• Implement an if statement.
• Implement an if-else statement.
• Implement an if-elif statement.
• Nest if-else statements.
1) Useful Concepts
Condition statements allow us to write code that behaves differently in different scenarios.
37. The most basic conditional statement is an if statement. The code inside the if statement would
only execute if the condition is fulfilled i.e the condition inside the round brackets returns true.
if(<condition>):
// some code
38. We can have another scenario in which in one condition we want to do one thing but in another
condition, we want to do something else. This can be done by using if-else. The else statement
runs only when the condition corresponding to the if block returns false.
if(<condition>):
// some code
else:
// other code
39. When we have multiple conditions and we want to write different code for each of them, we can
use if elif else.
if(<condition_1>):
// some code
elif(<condition_2>):
// condition 2
elif(<condition_3>):
// condition 3
else:
// default code
40. The nested if statement can be used to implement multiple alternatives. For instance, assigns a
letter value to the variable grade according to the score, with multiple alternatives.
Lab Tasks
41. Write a program to check whether an integer is positive, negative, or zero.
42. Write a program to input marks of five subjects Physics, Chemistry, Biology, Mathematics, and
Computer. Calculate percentage and grade according to following: Percentage >= 90%:
Grade A Percentage >= 80%: Grade B Percentage >= 70%: Grade C Percentage >= 60%:
Grade D Percentage >= 40%: Grade E Percentage < 40%: Grade F
43. Write a program to check whether the triangle is equilateral, isosceles or scalene triangle.
44. Write a program to check whether a year is a leap year or not.
45. Write a dummy authentication system program in which you accept user inputs for email and
password. Let's say the correct email and password are abc@[Link] and abc respectively.
If the email and password entered are correct it should display "User is logged in". If the email is
correct, then prompt the user that the password is not correct. If the password is correct then
prompt the user to enter the correct email. If both are incorrect then display the corresponding
message.