0% found this document useful (0 votes)
2 views32 pages

Python Programming Lab Manual

The document is a lab manual for Python programming covering key topics such as variables, data types, tuples, operators, and expressions. It includes objectives, examples, and practice exercises for each topic to enhance students' understanding and skills in Python. The manual emphasizes the importance of data integrity, type checking, and the use of various operators in programming.

Uploaded by

holimsla
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)
2 views32 pages

Python Programming Lab Manual

The document is a lab manual for Python programming covering key topics such as variables, data types, tuples, operators, and expressions. It includes objectives, examples, and practice exercises for each topic to enhance students' understanding and skills in Python. The manual emphasizes the importance of data integrity, type checking, and the use of various operators in programming.

Uploaded by

holimsla
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

Python Programming

Complete Lab Manual

University of Chakwal, Punjab, Pakistan


Department of Engineering — Faculty of Engineering
PH: 0543-540625 Fax: 0543-541366

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.

Basic Data Types in Python


Data Type Description Example
int Integer numbers 10, -5
float Decimal numbers 3.14, -2.5
str Text/String "Hello"
bool Boolean (True/False) True

3. Declaring Variables
name = "Asmara"
age = 19
cgpa = 3.75
enrolled = True
print(name)
print(age)
print(cgpa)
print(enrolled)

Checking Data Types in Python


In Python, every value stored in a variable has a data type. Since Python is dynamically typed, the type
is automatically assigned at runtime.
To determine the type of a variable, we use the built-in function:
type(variable_name)
This function returns the class type of the object.

Example 1: Checking Basic Data Types


age = 21
cgpa = 3.8
name = "Ali"
is_active = True
print(type(age))
print(type(cgpa))
print(type(name))
print(type(is_active))

Expected Output:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>

4. Type Casting (Type Conversion)


Type casting converts one data type to another.

4.1 Integer to Float


x = 5
y = float(x)
print(y)
print(type(y))

4.2 Float to Integer


x = 5.8
y = int(x)
print(y) # Output: 5 (decimal removed)

4.3 String to Integer


num = "25"
converted = int(num)
print(converted + 5)

5. User Input in Python


Python uses input() to take input from the user.
Important: input() always returns a string.

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)

Boolean Data Type


Boolean values: True or False

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.).

2. Solved Examples (Methods & Operations)


Example 1: Basic Tuple Creation and Accessing
# Creating a tuple of colors
colors = ("Red", "Green", "Blue", "Yellow")
print(colors[1]) # Output: Green
print(colors[-1]) # Output: Yellow (Negative Indexing)

Example 2: The Singleton Rule (Single Element Tuple)


# A comma is required for a single-element tuple
single_val = (5,)
print(type(single_val)) # Output: <class 'tuple'>

Example 3: Tuple Concatenation


t1 = (1, 2, 3)
t2 = (4, 5, 6)
t3 = t1 + t2
print(t3) # Output: (1, 2, 3, 4, 5, 6)

Example 4: Using the count() Method


# Counts occurrences of a specific value
scores = (10, 20, 10, 40, 10, 50)
print([Link](10)) # Output: 3

Example 5: Using the index() Method


# Finds the index of the first occurrence
fruits = ("apple", "banana", "cherry")
print([Link]("banana")) # Output: 1

Example 6: Tuple Unpacking


coordinates = (4, 5, 12)
x, y, z = coordinates
print(f"X: {x}, Y: {y}, Z: {z}")
Example 7: Membership Testing
names = ("Ali", "Usama", "Khan")
print("Usama" in names) # Output: True

Example 8: Reversing via Slicing


data = (10, 20, 30, 40)
print(data[::-1]) # Output: (40, 30, 20, 10)

Example 9: Modifying via Conversion


# Tuples are immutable, so we convert to a list to change data
menu = ("Pizza", "Burger", "Pasta")
list_menu = list(menu)
list_menu[1] = "Steak"
menu = tuple(list_menu)
print(menu) # Output: ('Pizza', 'Steak', 'Pasta')

Example 10: Nested Tuples


nested = (1, 2, (3, 4), 5)
print(nested[2][0]) # Output: 3

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.

Task 2: Duplicate Analysis


Create a tuple with 10 numbers where some are repeated. Ask the user for a number and use the
count() method to tell them how many times that number exists in the tuple.

Task 3: Character Combiner


Given the tuple chars = ('U', 'n', 'i', 'v', 'e', 'r', 's', 'e'), write a script to join these characters into a single
string.

Task 4: Variable Swap


Demonstrate variable swapping for a = 100 and b = 200 using tuple unpacking in a single line.

Task 5: Tuple Reversal


Write a program that takes a tuple of 5 names from a user and prints them in reverse order using
slicing.
Task 6: List in a Tuple
Create a tuple t = (1, 2, [3, 4]). Change the value 3 to 99 within the nested list. Explain why this is
possible.

Task 7: Statistics Task


Create a tuple of 10 integers. Write a script to find and print the max(), min(), and sum() of these
numbers.

Task 8: Slicing Mastery


Given nums = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9), write three separate slices to print:
• The first 3 elements.
• The last 3 elements.
• The middle 4 elements.

Task 9: Database Search


Create a tuple of 10 city names. Ask the user to input a city name. Use the in keyword to check if it
exists and index() to show its position.

Task 10: Tuple to Dictionary


Create a list of tuples where each tuple is (Student_Name, Roll_No). Use a loop to convert this list of
tuples into a Python Dictionary.

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.

Skills You Will Gain


• Python operators in problem-solving.
• Understanding expressions and evaluating them step by step.
• Debugging and predicting the result of complex expressions.
• Using operators in conditional and arithmetic scenarios.
• Writing clean, well-structured programs with operators.

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.

Categories of Operators in Python


Operator Type Example Description
Arithmetic +, -, *, /, //, %, ** Basic math operations
Relational >, <, >=, <=, ==, != Compare values
Logical and, or, not Combine conditional statements
Assignment =, +=, -=, *=, /=, %= Assign values
Bitwise &, |, ^, ~, <<, >> Bit-level operations
Membership in, not in Check for existence in sequence
Identity is, is not Compare memory locations

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

Operator Precedence & Associativity in Expressions


Operators are executed in a specific order.

Order of precedence (highest to lowest):


1. ** (Exponentiation)
2. *, /, //, %
3. +, -
4. Relational operators (>, <, ==, etc.)
5. Logical operators (and, or, not)

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.

1.2. Learning Objectives


By the end of this lab, you will be able to:
• Create and define strings using different quoting methods.
• Access individual characters and substrings using indexing and slicing.
• Use common string methods for cleaning, transforming, and analyzing text
(e.g., .lower(), .upper(), .split(), .strip(), .find()).
• Understand and apply basic text processing concepts relevant to data science, such as
tokenization and acronym generation.
• Differentiate between strings and lists and convert between them.

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.

2.1. Creating Strings


You can create a string by enclosing characters in quotes. Python is flexible, allowing single, double, or
even triple quotes.
# Single quotes
string1 = 'Hello, World!'

# Double quotes
string2 = "Data Science is fun!"

# Triple quotes for multi-line strings


string3 = """This is a
multi-line string
in Python."""

print(string1)
print(string2)
print(string3)

2.2. Strings as Sequences


Because a string is a sequence, we can treat it like a list of characters. This means we can find out its
length, loop through it, and access specific positions.
my_string = "Python"
print(f"The string is: {my_string}")
print(f"Length of string: {len(my_string)}") # Output: 6
The len() function is one of the most common and important functions for strings, returning the number
of characters.

3. Accessing Characters: Indexing


Every character in a string has a position number, called an index. Python uses zero-based indexing,
meaning the first character is at index 0.
Character P y t h o n
Index 0 1 2 3 4 5
Negative Index -6 -5 -4 -3 -2 -1

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}")

# Using negative indexing to get the last character


last_char_negative = language[-1]
second_last = language[-2]
print(f"Last char (negative): {last_char_negative}") # 'n'
print(f"Second last: {second_last}") # 'o'

4. Extracting Substrings: Slicing


Slicing allows you to extract a portion (substring) of a string. The syntax is [start:end], which extracts
characters from index start up to, but not including, index end.
text = "Data Science"

# 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'

# Slice from beginning up to index 4


sub3 = text[:4]
print(f"text[:4] -> '{sub3}'") # Output: 'Data'

# Slice from index 5 to the end


sub4 = text[5:]
print(f"text[5:] -> '{sub4}'") # Output: 'Science'

# Get every other character (using a step)


sub5 = text[::2]
print(f"text[::2] -> '{sub5}'") # Output: 'Dt cec'

5. Essential String Methods for Data Cleaning


Data cleaning is a massive part of data science. These methods help you standardize and clean your
text data.
Method Description Example Result
.lower() Converts all characters to "DaTa".lower() "data"
lowercase.
.upper() Converts all characters to "DaTa".upper() "DATA"
uppercase.
.title() Converts the first character "data science".title() "Data
of each word to uppercase. Science"
.strip() Removes leading/trailing " text ".strip() "text"
whitespace.
.replace(a, b) Replaces all occurrences of "1,000".replace(",", "") "1000"
substring a with b.

6.1. Splitting with .split()


The .split() method breaks a string into a list of substrings. By default, it splits on whitespace.
sentence = "The quick brown fox jumps over the lazy dog"
words = [Link]()
print(words)
# Output: ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy',
'dog']

# Splitting on a specific character


data = "apple,banana,grape,orange"
fruits = [Link](',')
print(fruits)
# Output: ['apple', 'banana', 'grape', 'orange']

6.2. Joining with .join()


words = ['Python', 'is', 'awesome']
sentence = ' '.join(words)
print(sentence) # Output: Python is awesome

# Joining with a comma


csv_line = ','.join(words)
print(csv_line) # Output: Python,is,awesome

7. Searching and Finding


Often, you need to know if a piece of text contains a specific word or pattern.
7.1. The in Operator
The simplest way to check for a substring is the in operator, which returns True or False.
text = "The quick brown fox"
if "fox" in text:
print("Found it!")
if "cat" not in text:
print("No cat here.")

7.2. The .find() Method


To get the location of a substring, use .find(). It returns the starting index of the first occurrence, or -1 if
not found.
email = "user@[Link]"
at_index = [Link]('@')
print(f"The '@' symbol is at index: {at_index}") # Output: 4
username = email[:at_index]
domain = email[at_index+1:]
print(f"Username: {username}, Domain: {domain}")
# Output: Username: user, Domain: [Link]

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).

Exercise 2: The Acronym Generator


Acronyms are often used in data science. Write a program that takes a phrase from the user and
generates its acronym.
Your program should:
11. Ask the user for a phrase (e.g., "Artificial Intelligence").
12. Split the phrase into individual words.
13. Extract the first letter of each word.
14. Convert those first letters to uppercase.
15. Join them together to form the acronym and print it.

Exercise 3 (Challenge): Data Cleaner


You are given a messy dataset in the form of a list. The list data contains strings with extra spaces and
inconsistent casing.
data = [" apple ", " BANANA ", "Cherry", " date "]
Write a program that:
16. Cleans the list by stripping whitespace and converting all fruit names to lowercase.
17. Prints the new cleaned list.
18. Then, join all the cleaned fruit names into a single string, separated by a comma and a space
(,), and print the result.
LAB 5: Lists in Python
Lab Objectives
Objective:
The objective of this lab session is to provide students with the skills they need to work with lists in
Python.
Duration: 3 Hours

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.

For example: Print the second item of the list:


thislist = ["apple", "banana", "cherry"]
print(thislist[1])

Negative Indexing
Negative indexing means start from the end. -1 refers to the last item, -2 refers to the second last item,
etc.

For Example: Print the last item of the list:


thislist = ["apple", "banana", "cherry"]
print(thislist[-1])

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: Return the third, fourth, and fifth item:


thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])

Change List Items


To change the value of a specific item, refer to the index number.

For example: Change the second item:


thislist = ["apple", "banana", "cherry"]
thislist[1] = "coffee"
print(thislist)

Add List Items


To add an item to the end of the list, use the append() method.

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.

For example: Insert an item as the second position:


thislist = ["apple", "banana", "cherry"]
[Link](1, "orange")
print(thislist)
Similarly, try to find the use of extend() and remove() functions.

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

# Access the third item of the list


third_item = my_list[2]
print(third_item) # the output will be 6

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.

Example using del statement:


my_list = [1, 2, 3, 4, 5]
# Delete the fourth element
del my_list[3]
print(my_list) # output will be [1, 2, 3, 5]

Example using remove() method:


my_list = [1, 2, 3, 4, 5]
# Remove the fourth item
my_list.remove(4)
print(my_list) # output will be [1, 2, 3, 5]

Sorting
One can use either the built-in sorted() function or the .sort() method to sort a list.

Example using the sorted function:


my_list = [3, 5, 2, 8, 1]
sorted_list = sorted(my_list)
print(sorted_list) # output will be [1, 2, 3, 5, 8]
Note that by default, sorting is done in ascending manner. If you want to have sorting in descending
order, you should use reverse = True as an input argument.
sorted_list = sorted(my_list, reverse=True)
print(sorted_list) # output will be [8, 5, 3, 2, 1]
The .sort() method is used to sort a list in place. This means that the list is sorted in the same object
instead of creating a new sorted 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]

# Remove the first item


my_list.pop(0)
print(my_list) # output will be [2, 3]
Exercises
23. Write a Python program to sum all the items in a list.
24. Write a Python program to get the smallest number from a list.
25. Write a Python program to get the largest number from a list.
26. Write a Python program to get a list, sorted in ascending order.
27. Write a Python program to get a list, sorted in descending order.
28. Write a Python program to copy the list items of one list to another.
29. Write a Python program to print a specified list. Sample List: ["Red", "Green", "White", "Black",
"Pink", "Yellow"]. Expected Output: ["Green", "White", "Black"]
30. Write a Python program to print a specified list. Sample List: ["Red", "Green", "White", "Black",
"Pink", "Yellow"]. Expected Output: ["Red", "White", "Pink"]
31. Find the index value of "White" in the given list. Sample List: ["Red", "Green", "White", "Black",
"Pink", "Yellow"]
32. Consider the following list: a = ["MUET", "SINDH", "LUMHS"]. Delete "LUMHS" by using pop(),
remove(), and del methods.
LAB 6: For Loop in Python
Lab Objective
In this lab, students will explore the fundamental concept of loops and understand why repetition is
essential in programming. They will learn how to use both for loops 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

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

Task 2: Loop with break (stop at 5)


for i in range(1, 11):
if i == 5:
break
print(i)

Output:
1 2 3 4

Task 3: Loop with continue (skip 5)


for i in range(1, 11):
if i == 5:
continue
print(i)

Output:
1 2 3 4 6 7 8 9 10

Task 4: Countdown from user input


n = int(input("Enter a number: "))
for number in range(n, 0, -1):
print(number)

Output (for input 15):


15 14 13 12 11 10 9 8 7 6 5 4 3 2 1

Task 5: Multiplication table of 7


for i in range(1, 11):
print("7 x", i, "=", 7 * i)

Output:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21 ... up to 7 x 10 = 70

Task 6: Sum using while loop (1 to 100)


sum = 0
i = 1
while i <= 100:
sum = sum + i
i = i + 1
print("Sum =", sum)

Output:
Sum = 5050

Task 7: Print squares of 1 to 10


for i in range(1, 11):
print("Square of", i, "is", i * i)

Output:
Square of 1 is 1
Square of 2 is 4 ... up to Square of 10 is 100

Task 8: Factorial of a number


num = int(input("Enter a number: "))
factorial = 1
for i in range(1, num + 1):
factorial = factorial * i
print("Factorial of", num, "is", factorial)

Task 9: Student data collection


students = {}
n = int(input("How many students are in the class?"))
for i in range(n):
name = input("Enter student's name: ")
marks = int(input("Enter marks(out of 100): "))
students[name] = marks
print("Student data: ", students)

Task 10: Star pattern


for i in range(1, 6):
print(i * "*")

Output:
*
**
***
****
*****

Task 11: For-else loop


for i in range(3):
print(i)
else:
print("Loop finished")

Task 12: Loop with Break


for i in range(5):
if i == 3:
break
print(i)

Task 13: Loop with Continue


for i in range(5):
if i == 2:
continue
print(i)

Task 14: Loop with index (enumerate)


fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)

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.

Example 1: Basic while loop


i = 1
while i <= 5:
print(i)
i += 1

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)

Loop with Break


i = 1
while i <= 10:
if i == 5:
break
print(i)

Output:
1 2 3 4

Loop with Continue


i = 0
while i < 5:
i += 1
if i == 3:
continue
print(i)

Output:
1 2 4 5

Loop with pass


In Python, the pass statement is a placeholder — it does nothing, but it allows you to write syntactically
valid code where a statement is required.
i = 0
while i < 5:
pass # will add logic later
i += 1

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.

Activity 1: Python program to illustrate an if statement


grade = 85
if grade >= 60:
print("You are passed")

Activity 2: Python program to illustrate an if else statement


grade = 85
if grade >= 60:
print("Pass")
else:
print("Fail")

Activity 3: Python program to illustrate an elif statement


x = 2
if (x == 3):
print('Lions are the king of the jungle')
elif (x == 4):
print('Canberra is the capital of Australia')
else:
print("Bears eat honey")

Activity 4: Python program to illustrate nested if else statements


x = 2
y = 6
if (x <= 2 and y < 20):
print('The numbers x and y fall under the criteria')
sum = x + y
if (sum < 50):
print('The sum of x and y is:', sum)
else:
print('The numbers x and y dont fall under the criteria')

Activity 5: Chinese Zodiac Sign Program


Write a program to find out the Chinese zodiac sign for a given year. The Chinese zodiac sign is based
on a 12-year cycle, and each year in this cycle is represented by an animal — monkey, rooster, dog,
pig, rat, ox, tiger, rabbit, dragon, snake, horse, and sheep.
year = eval(input("Enter a year: "))
zodiacYear = year % 12
if zodiacYear == 0:
print("monkey")
elif zodiacYear == 1:
print("rooster")
elif zodiacYear == 2:
print("dog")
elif zodiacYear == 3:
print("pig")
elif zodiacYear == 4:
print("rat")
elif zodiacYear == 5:
print("ox")
elif zodiacYear == 6:
print("tiger")
elif zodiacYear == 7:
print("rabbit")
elif zodiacYear == 8:
print("dragon")
elif zodiacYear == 9:
print("snake")
elif zodiacYear == 10:
print("horse")
else:
print("sheep")

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.

— End of Lab Manual —


University of Chakwal, Faculty of Engineering

You might also like