Task 01
Task 01
BS (CS) _SP_2024
Lab_01 Manual
Learning Objectives:
1. Variables
2. Control Statements
3. List, Sets, Tuples, Dictionaries
4. Classes and Objects
5. Local and Global Variables
Lab Manual
Basis of Python
Variables
In Python, variables are used to store and manage data. Each variable has a name and a value, and the
type of the variable indicates what kind of data it can hold.
Syntax:
a = 10
name = “John”
is_student = True
#Taking input from a user
name = input (“Enter student name: ”)
Operators
Python language supports the following types of operators.
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Membership Operators
Arithmetic Operators:
Operator Example
Addition a + b = 30
Subtraction a - b =10
Multiplication a*b
Division a/b
Modulus b%a
Exponent a ** b
Comparison Operators:
Operator Description Example
== If the values of two operands are equal, then the condition a == b
becomes true
!= If values of two operands are not equal, then condition becomes true. a != b
<> If values of two operands are not equal, then condition becomes true. a<>b
> If the value of left operand is greater than the value of right operand, then a>b
condition becomes true.
< If the value of left operand is less than the value of right operand, then a<b
condition becomes true.
>= If the value of left operand is greater than or equal to the value of right a >= b
operand, then condition becomes true.
<= If the value of left operand is less than or equal to the value of right a <= b
operand, then condition becomes true.
Logical Operators:
Operator Description Example
and If both the operands are true, then condition becomes true. a and b
or If any of the two operands are non-zero, then condition becomes true. a or b
not Used to reverse the logical state of its operand a not b
Membership Operators:
Operator Description Example
in Evaluates to true if it finds a variable in the specified sequence and if a in b then:
false otherwise. statement
not in Evaluates to true if it does not find a variable in the specified if a not in b then:
sequence and false otherwise. statements;
Control Statements
In Python, control statements are used to guide the program's flow of operations. Depending on
specific conditions, they choose which statements to perform first or repeatedly go through a list
of statements.
If-else Statement:
if condition:
# Statements
elif another_condition:
# Statements
else:
#Statemets
For Statement
item_list = []
for variable in item_list:
#Statements
While Statement
while condition:
# Code to be executed as long as the condition is true
else:
List
List are ordered collection of data. They are mutable (changeable) and allow duplicate elements.
They are created using square brackets []. Data can be different types. Lists are versatile and can
be used to store and manipulate sequences of items.
Syntax
list_A = [‘a’,’b’,’c’,’d’,’BS_CS’, 0343]
print(list_A)
print(list_A[1:4]) or print(list_A[:4]) #Slicing
Different operations can be performed on list
Operation Description Syntax
Append Add an element at the end list_A.append(1)
Insert Inserts an element at a specific index list_A.insert(1, ‘Python’)
Extend Adds more than one element at the end of the list_A.extend([‘Python’, ‘Java’ ,
list ‘Perl’])
Remove Removes the first item with the specified value list_A.remove( ‘Perl’)
Pop Removes last element or removes the list_A.pop();
element at the specified position. list_A.pop(2); #Remove?
Index Returns the index of the first element with the list_A.index(0343);
specified value
Sorting Sorts the list. And reverse() reverses the list_A.sort();
order of the list list_A.reverse();
Built-in Functions:
Function Description
cmp (list1, list2) Compares elements of both lists.
len (list1) Gives the total length of the list.
max (list1) Returns item from the list with max value.
min (list1) Returns item from the list with min value.
list (seq) Converts a tuple into list.
Set
Set is unordered collection of data. They are mutable and don’t allow duplicate elements (Unique
elements). They are created using curly braces {} or the set() constructor. Sets are useful for
mathematical operations like union, intersection, and difference.
basket = {‘Apple’, ‘Orange’, ’pearl’, ‘Banana’, 1, 2, 57}
Example:
Set1 = {values} Set2 = {values}
Dictionary
A dictionary is a collection which is unordered, changeable, and indexed. In Python dictionaries
are written with curly brackets, and they have keys and values.
Syntax:
data = { key : value }
Example:
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964}
print(thisdict)
# Accessing Items
x = thisdict["model"] or x = thisdict.get("model")
Classes
A class is a blueprint for creating objects. It serves as a template that defines the attributes and
behaviors of an object.
It encapsulates data (attributes) and methods (functions) that operate on that data.
Also, promote code reusability and maintainability.
Syntax:
class ClassName:
#class attributes and methods
def functionName:
Objects
Objects are instances of a class, created using the class name followed by parentheses.
Objects encapsulate the attributes and methods defined in the class.
Syntax:
object_name = ClassName()
my_car = Car("Toyota", "Camry", 2022)
class ClassName:
def __init__(self, variable1, variable2):
self.variable1 = variable1
self.variable2 = variable2
def display():
print(f" Variable 1: {variable1},\nVariable 2: {variable2}”)
Lab Task
1. Write a Python script that defines a dictionary representing the inventory of a store. Implement
control statements to check if a user-provided product key exists in the dictionary and display its
corresponding details.
2. Write a Python program for a sports league that manages a tuple of player information.
Implement control statements to sort the players based on their performance metrics, such as
goals scored, assists, and playing time.
3. Design and implement a python class for simulating a transportation network. Create a class
representing "Transport" with associated functions to model various aspects of the network,
including vehicles, routes, and schedules. Ensure that the implementation adheres to the
fundamental principles of programming. (Hint: multiple vehicles have both shared and distinct
routes and schedules.)
4. Write a python code that perform following tasks:
data_points = [(2, 5), (1, 3), (4, 8), (3, 6), (2, 7)]
a. Sort the tuples based on the sum of their elements in descending order.
b. Filter the tuples to include only those where both elements are prime numbers.
c. Create a new tuple by extracting the second element from each tuple.
d. Calculate the product of all elements in the new tuple.