0% found this document useful (0 votes)
227 views107 pages

Final Lab Manual

Uploaded by

talha.nadeem9912
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)
227 views107 pages

Final Lab Manual

Uploaded by

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

IQRA University

CSC 333 Introduction to Python

Lab# 01
Python & its Programming Interfaces

Objective:
This experiment introduces the students to Python programming language
and one of its development environments. This lab will set the foundation
for the CSC-333 Introduction to Python course.

Name of Student:

Roll No:

Date of Experiment:

1
Lab 01: Introduction to Programming Fundamentals and
Python

Introduction to Programming

Background:

Communicating with a computer involves speaking the language that computer understands,
which immediately rules out English as the language of communication with computer. The
classical method of learning English is to first learn the alphabets used in the language, then
learn to combine these alphabets to form words. Instead of straight-away learning how to write
programs, we must first know what alphabets, numbers and special symbols are used in Python,
then how using them constants, variables and keywords are constructed, and finally how are
these combined to form an instruction. A group of instructions would be combined later on to
form a program. This is illustrated in the figure below.

Everyone can learn to code; it’s just like solving a puzzle or a riddle. You apply logic, try a
solution, experiment a little more, and then solve the problem.

Python Basics:

The Python programming language was developed in the late 1980s by Dutch programmer
Guido van Rossum while working at CWI (the Centrum voor Wiskunde en Informatica in
Amsterdam, Netherlands). The language was not named after the large snake species but rather
after the BBC comedy series Monty Python’s Flying Circus. Guido van Rossum happens to be
a fan. Just like the Linux OS, Python eventually became an open source software development
project. However, Guido van Rossum still has a central role in deciding how the language is
going to

2
evolve. To cement that role, he has been given the title of “Benevolent Dictator for Life” by the
Python community.
The Environment:

In your Start menu or Applications folder, find the IDLE program and run it. You’ll see a text-
based command window like the one shown in the figure below. This is called the Python shell.
A shell is a window or screen that lets the user enter commands or lines of code.

The >>> is called a prompt, and it means that the computer is ready to accept your first
command. The computer is asking you to tell it what to do. Type print("Hello,
world!") and press ENTER or RETURN on your keyboard. You should see the Python
shell respond by printing the text in quotes that you entered inside the parentheses: Hello,
world!. That’s it — you’ve written your first program!

Python supports two mode to the programmer to interact with it, namely Interactive mode and
Normal mode. The figure below provides the key features of both of these modes. The mode we
have been using so far is called the interactive mode.

3
Let us explore the Normal programming mode option. Select the New File option from the File
dropdown and write the same code into the editor.

Let’s write a new program in Python. In the new, blank window, type the following three lines
of code:

Save the file with some appropriate name. The first line is called a comment. Comments, which
begin with a hash mark (#), are programming notes or reminders that the computer ignores. In
this example, the comment is just a note to remind us of the program’s name. The second line
asks the user to input their name and remembers it as name. The third line prints "Hi, " followed
by the user’s name. Notice that there’s a comma (,) separating the quoted text "Hi, " from the
name.

4
Once done go the Run dropdown and select the Run Module option. This will execute your
whole program on a separate prompt. This way of programming is the normal development
mode for the Python IDLE where the program is written in a separate editor and then executed
after being saved.

Now let us explore the python interactive mode a bit more. The Python shell gives you direct
access to Python’s power without writing a whole program. The Python shell can be used as a
sandbox and comes very handy for quick developmental tasks. The interactive mode can also
be used as a calculator to answer some of your basic mathematical needs. It is sometimes called
the command line because you can type commands line by line and instantly see the result. You
can type a math problem (called an expression in programming) like 4 + 2 directly at the
command prompt (the >>> symbol with the flashing cursor) in the Python shell, and when you
press ENTER, you’ll see the result of the expression, or the answer to the math problem.

When we program computers, we call a mistake in a statement a syntax error; when we make a
mistake in a sentence in English, we might call it bad grammar. The difference is that, unlike
English speakers, computers cannot understand bad grammar at all. Python, like most
programming languages, is very good at performing calculations as long as we follow syntax
rules, but it cannot understand anything we are saying if we have the syntax wrong. Take a look
at the figure below to see some examples of syntax errors, followed by the expressions stated in
a way that Python can understand.

5
Introduction to Anaconda Framework
Anaconda is a complete, open source data science package with a community of over 6 million
users. It is easy to download and install, and it is supported on Linux, MacOS, and Windows.
The distribution comes with more than 1,000 data packages as well as the Conda package and
virtual environment manager. Anaconda Navigator, a desktop graphical user interface (GUI)
system, includes links to all the applications included with the distribution including RStudio,
iPython, Jupyter Notebook, JupyterLab, Spyder, Glue, and Orange. The documentation is
incredibly detailed and there is an excellent community of users for additional support.

To work in Anaconda Distribution Environment. Click on


Windows Icon -> Search for Anaconda3 -> Click on Anaconda Navigator.

After you click on the Anaconda Navigator it will take some time depending on your computer
configuration and then open the Anaconda Navigator Windows as shown in the figure below.

6
Here we can see that Anaconda Distribution is full of tools such as Jupyter Notebook, Orange 3
, rstudio, vscode, sypder etc. All these tools will be used later in your upcoming semesters. But
for you in current semester we will use Jupyter Notebook. So let's start with Jupyter Notebook.

Introduction Jupyter Notebook


The Jupyter Notebook is an incredibly powerful tool for interactively developing and
presenting python projects. A notebook integrates code and its output into a single document
that combines visualizations, narrative text, mathematical equations, and other rich media. The
intuitive workflow promotes iterative and rapid development, making notebooks an
increasingly popular choice. Best of all, as part of the open source Project Jupyter, they are
completely free.
The Jupyter project is the successor to the earlier IPython Notebook, which was first published
as a prototype in 2010. Although it is possible to use many different programming languages
within Jupyter Notebooks, this article will focus on Python as it is the most common use case.

Running Jupyter
On Windows, you can run Jupyter via the shortcut Anaconda adds to your start menu, which
will open a new tab in your default web browser that should look something like the following
screenshot.

Jupyter Control Panel

This isn't a notebook just yet, but don't panic! There's not much to it. This is the Notebook
Dashboard, specifically designed for managing your Jupyter Notebooks. Think of it as the

7
launchpad for exploring, editing and creating your notebooks.
Be aware that the dashboard will give you access only to the files and sub-folders contained
within Jupyter's start-up directory; however, the start-up directory can be changed. It is also
possible to start the dashboard on any system via the command prompt (or terminal on Unix
systems) by entering the command jupyter notebook; in this case, the current working directory
will be the start-up directory.
The astute reader may have noticed that the URL for the dashboard is something like
http://localhost:8888/tree. Localhost is not a website, but indicates that the content is being
served from your local machine: your own computer. Jupyter's Notebooks and dashboard are
web apps, and Jupyter starts up a local Python server to serve these apps to your web browser,
making it essentially platform independent and opening the door to easier sharing on the web.
The dashboard's interface is mostly self-explanatory — though we will come back to it briefly
later. So what are we waiting for? Browse to the folder in which you would like to create your
first notebook, click the "New" drop-down button in the top-right and select "Python 3" (or the
version of your choice).

8
New Notebook Menu

Your first Jupyter Notebook will open in new tab — each notebook uses its own tab because
you can open multiple notebooks simultaneously. If you switch back to the dashboard, you will
see the new file Untitled.ipynb and you should see some green text that tells you your notebook
is running.

What is an ipynb File?


It will be useful to understand what this file really is. Each .ipynb file is a text file that describes
the contents of your notebook in a format called JSON. Each cell and its contents, including
image attachments that have been converted into strings of text, is listed therein along with
some metadata. You can edit this yourself — if you know what you are doing! — by selecting
"Edit > Edit Notebook Metadata" from the menu bar in the notebook.
You can also view the contents of your notebook files by selecting "Edit" from the controls on
the dashboard, but the keyword here is "can"; there's no reason other than curiosity to do so
unless you really know what you are doing.

The Notebook Interface


Now that you have an open notebook in front of you, its interface will hopefully not look
entirely alien; after all, Jupyter is essentially just an advanced word processor. Why not take a
look around? Check out the menus to get a feel for it, especially take a few moments to scroll
down the list of commands in the command palette, which is the small button with the
keyboard icon (or Ctrl + Shift + P).

9
New Jupyter Notebook

There are two fairly prominent terms that you should notice, which are probably new to you:
cells and kernels are key both to understanding Jupyter and to what makes it more than just a
word processor. Fortunately, these concepts are not difficult to understand.

A kernel is a "computational engine" that executes the code contained in a notebook document.

A cell is a container for text to be displayed in the notebook or code to be executed by the
notebook's kernel.

Cells
We'll return to kernels a little later, but first let's come to grips with cells. Cells form the body
of a notebook. In the screenshot of a new notebook in the section above, that box with the green
outline is an empty cell. There are two main cell types that we will cover:

 A code cell contains code to be executed in the kernel and displays its output below.
 A Markdown cell contains text formatted using Markdown and displays its output in-
place when it is run.

The first cell in a new notebook is always a code cell. Let's test it out with a classic hello world
example. Type print('Hello World!') into the cell and click the run button Notebook Run Button
in the toolbar above or press Ctrl + Enter. The result should look like this:

When you ran the cell, its output will have been displayed below and the label to its left will
have changed from In [ ] to In [1]. The output of a code cell also forms part of the document,
which is why you can see it in this article. You can always tell the difference between code and
Markdown cells because code cells have that label on the left and Markdown cells do not. The
"In" part of the label is simply short for "Input," while the label number indicates when the cell
was executed on the kernel — in this case the cell was executed first. Run the cell again and the
label will change to In [2] because now the cell was the second to be run on the kernel. It will
become clearer why this is so useful later on when we take a closer look at kernels.

10
Keyboard Shortcuts
One final thing you may have observed when running your cells is that their border turned blue,
whereas it was green while you were editing. There is always one "active" cell highlighted with
a border whose color denotes its current mode, where green means "edit mode" and blue is
"command mode."
So far we have seen how to run a cell with Ctrl + Enter, but there are plenty more. Keyboard
shortcuts are a very popular aspect of the Jupyter environment because they facilitate a speedy
cell-based workflow. Many of these are actions you can carry out on the active cell when it's in
command mode.
Below, you'll find a list of some of Jupyter's keyboard shortcuts. You're not expected to
pick them up immediately, but the list should give you a good idea of what's possible.

Toggle between edit and command mode with Esc and Enter,

respectively. Once in command mode:

 Scroll up and down your cells with your Up and Down keys. Press A or B to insert a

new cell above or below the active cell.

 M will transform the active cell to a Markdown cell.

 Y will set the active cell to a code cell.

 D + D (D twice) will delete the active cell.

 Z will undo cell deletion.

 Hold Shift and press Up or Down to select multiple cells at once. With multple

cells selected:

o Shift + M will merge your selection.

 Ctrl + Shift + -, in edit mode, will split the active cell at the cursor.

 You can also click and Shift + Click in the margin to the left of your cells to select them.

Exercise:
1. Print your name on the python shell (Hint, the location with the >>> prompt). Also
perform some basic algebraic operations such as 2+3 and 4-5 on the shell. Take a screen
shot of your working and attach in your submission document.
2. Now rather than performing your working in the shell. Create a python program printing
you name on the console. The program should also print the results of 2+3 and 4-5 on

11
separate lines within the program. Save the program at an appropriate location
and execute it. Attach screenshots of both your program and its output in your
final submission file.
3. Replicate what you have achieved in Exercise 2 in a Jupyter Notebook this
time. All the three operations (i.e. Printing of name, an addition operation, and
a subtraction operation) should take place in separate “code” cells. Execute
each of these cells and take screenshots.

4. Finally, add “markdown” cells above each of the cells created during
Exercise 3. Each of these markdown cells should contain a heading and
some text discussing what is being done in the cell below. Again take
screenshots of your final notebook.

Submission Instructions: Your submission should include a word document having


screenshots of all your performance. Furthermore, all files created during the lab
(.py, ,ipynb, or any output files in the future) should also be attached as your
submission (not in zipped format).
IQRA University

CSC 333 Introduction to Python

Lab# 02
Python Variables and Data Types

Objective:
This experiment introduces the students to Python data types and the use of
variables in programming languages.

1
Lab 02: Python Data Types & Variables along with Flowcharts

Variables and Data Types in Python:


The most basic component of any programming language are "things," also called variables A
variable has a name and an associated value The most common types of variables in Python

are:

A variable of any specific data type can be declared using the initialization operation “ = “. It is
important that the name of the variable is on the left hand side of the = operator while declaring
a variable.

To determine what type of variable, use the type function

For any programming language, variable naming is a key aspect of making the code
programmer- friendly. Python is a case-sensitive programming language i.e. x ≠ X. The name
of the variable must start with a letter and contain letters, numbers, and underscores. Blank
spaces are not allowed in variable names. It is a good programming practice to use descriptive
variable names with reasonable length. There are a few names already reserved in Python
which cannot be used as variable names.

2
As for the data types a variable can acquire, Python supports a number of data types. Amongst
the most basic data type are integers, floating point numbers, strings, and Boolean values. The
following examples show how variables can be initiated as integers, floating point numbers, or
Boolean in the python programming environment.

String

Background
Earlier we introduced the string class str. Our goal then was to show that Python supported
values other than numbers. We showed how string operators make it possible to write
string expressions and process strings in a way that is as familiar as writing algebraic
expressions. We also used strings to introduce the indexing operator [ ]. In this section we
re-discover strings and what can be done with them in more depth. We show, in particular,
a more general version of the indexing operator and many of the commonly used string
methods that make Python a strong text-processing tool

String Representations

We already know that a string value is represented as a sequence of characters that is enclosed
:within quotes, whether single or double quotes

>>>"!Hello, World"
!Hello, World

3
>>>’hello'
hello

Python List
A list is a collection of items in a particular order. You can make a list that includes the letters
of the alphabet, the digits from 0–9, or the names of all the people in your family. You can put
anything you want into a list, and the items in your list don’t have to be related in any
particular way. Because a list usually contains more than one element, it’s a good idea to
make the name of your list plural, such as letters, digits, or names.
In Python, square brackets ([]) indicate a list, and individual elements in the list are separated
by commas. Here’s a simple example of a list that contains a few kinds of bicycles:

If you ask Python to print a list, Python returns its representation of the list, including the
square brackets:

Lists are ordered collections, so you can access any element in a list by telling Python the
position, or index, of the item desired. To access an element in a list, write the name of the list
followed by the index of the item enclosed in square brackets. Also, remember that Python
considers the first item in a list to be at position 0, not position 1.

For example, let’s pull out the first bicycle in the list bicycles:

Python has a special syntax for accessing the last element in a list. By asking for the item at
index -1, Python always returns the last item in the list:

4
Changing, Adding and Removing Elements from a List

The syntax for modifying an element is similar to the syntax for accessing an element in a list.
To change an element, use the name of the list followed by the index of the element you want
to change, and then provide the new value you want that item to have.

Adding Elements to a List


You might want to add a new element to a list for many reasons. For example, you might
want to make new aliens appear in a game, add new data to a visualization, or add new
registered users to a website you’ve built. Python provides several ways to add new data to
existing lists.
Appending Elements to a List:

Inserting Elements to a List:

A list is a container that holds comma-separated values (items or elements) between square
brackets where items or elements need not all have the same type. In general, we can define a
list as an object that contains multiple data items (elements). The contents of a list can be
changed during program execution. The size of a list can also change during execution, as

5
elements are added or removed from it.

List Operators and Functions:

Usa Explanation
ge
x in x is an item of lst
lst
x not x is not an item of lst
in lst
lst + Concatenation of lst and lstB
lstB
lst*n, Concatenation of n copies of lst
n*lst
lst[i] Item at index i of lst

len(ls Number of items in lst


t)
min(l Minimum item in lst
st)
max( Maximum item in lst
lst)
sum( Sum of items in lst
lst)

List Methods:

Usag Explanation
e
lst.app adds item to the end of lst
end(ite
m)
lst.cou returns the number of times item occurs in
nt(ite lst
m)
lst.ind Returns index of (first occurrence of) item
ex(ite in lst
m)
lst.pop Removes and returns the last item in lst
()

6
lst.rem Removes (the first occurrence of) item from
ove(ite lst
m)
lst.rev Reverses the order of items in lst
erse(it
em)
lst.sort Sorts the items of lst in increasing order
(item)

Student Exercise

1. Go through the Lab2_Numbers&Variables.ipynb file provided with the lab manual and
execute all its cells one by one while reading the text. Attach an executed copy of the
notebook and a PDF printout of your attempted notebook along with your lab
submission.

2. Attempt the exercise provided at the end of the notebook


Lab2_Numbers&Variables.ipynb. The exercises should be programmed within the same
notebook and should be included in the PDF printout submission.

3. Execute each of the examples provided to you in the notebook Lab2_Lists.ipynb attached
with this lab. Execute all its cells one by one while reading the text. Attach an executed
copy of the notebook and a PDF printout of your attempted notebook along with your lab
submission.

4. Declare a list of all the months in a year with the name months_year. Then attempt the
following.
i. Create a copy of the list with the name months_31. Once created, remove
all the months from this list not having 31 days.
ii. Create a copy of the months_31 list having the name months_30Plus and
apart from February, place the missing months in the list at appropriate
locations.

5. Create a shallow copy of list std_names, assign it to a new name, std_names2, and then
remove the string Ali Abid. Observe if the original list has also been altered or not.

std_names=['Kashif Ali', 'Rehan Ahmed', 'Ali Abid']


IQRA University

CSC 333 Introduction to Python

Lab# 03
Python Operations

Objective:
This experiment takes the students through the available operators in
python. This includes algebraic, comparison, Boolean and bit-wise type of
operators.

Name of Student:

Roll No:

Date of Experiment:

1
Lab 03: Operators in Python
Python Operators
Operators are used to perform operations on variables and values. Python divides the operators in
the following groups:

1. Arithmetic operators
2. Comparison operators
3. Bitwise operators
4. Assignment operators
5. Logical operators
6. Identity operators
7. Membership operators

Python Arithmetic Operators


Arithmetic operators are used with numeric values to perform common mathematical operations:

Operator Name Example


+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division or Integer x // y
division

In order of priority, ex-ponentiation gets done first, followed by multiplication and division
(including // and %), and addition and subtraction come last. The classic math class mnemonic,
PEMDAS (Please Excuse My Dear Aunt Sally), might be helpful.

Python Comparison Operators


Comparison operators are used to compare two values:

Operator Name Example


== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

2
Python Bitwise Operators
In Python, bitwise operators are used to performing bitwise calculations on integers. The integers
are first converted into binary and then operations are performed on bit by bit, hence the name
bitwise operators. Then the result is returned in decimal format.

Operator Name Purpose


& Bitwise AND Operators Perform binary AND
operation
| Bitwise OR Operation Perform binary OR
operation
~ Bitwise NOT Operation Perform
bitwise
inversion of the
numbers
^ Bitwise XOR Operation Exclusive-OR
operation
between two
numbers
>> Shift Right Operation Shift the number to
the right
<< Shift Left Operation Shift the number to
the left

Python Assignment Operators


Assignment operators are used to assign values to variables:

Operator Example Same As


= x=5 x=5
+= 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 //= 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 >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

3
Python Logical Operators
Logical operators are used to combine conditional statements:

Operator Description Example


And Returns True if both statements x < 5 and x <
are true 10
Or Returns True if one of the x < 5 or x < 4
statements is true
Not Reverse the result, returns False not(x < 5 and x
if the result is true < 10)

Python Identity Operators


Identity operators are used to compare the objects, not if they are equal, but if they are actually
the same object, with the same memory location:

Operator Description Example


Is Returns true if both variables are x is y
the same object
is not Returns true if both variables are x is not y
not the same object

Python Membership Operators


Membership operators are used to test if a sequence is presented in an object:

Operator Description Example


In Returns True if a sequence with x in y
the specified value is present in
the object
not in Returns True if a sequence with x not in y
the specified value is not present
in the object

4
Student Exercise
1. Thoroughly study and execute the notebook provided with this lab.

Create a new notebook and attempt each of the following within the same notebook
2. In what order are the operators in the following expressions evaluated?
a) 2 + 3 == 4 or a >= 5
b) lst[1] * -3 < -10 == 0
c) (lst[1] * -3 < -10) in [0, True]
d) 2 * 3**2
e) 4 / 2 in [1, 2, 3]
f) 14 * 15 / 3 // 2 % 13
First comment in a markdown cell regarding the execution then support your answer
through execution in a code cell

3. Write a sequence of python instructions that takes two numbers ‘x’and ‘y’ as inputs and
computes |𝑥−𝑦|
𝑥+𝑦

4. Write a sequence of steps which takes hours and minutes from the user in 24 hour clock
format. Then convert and display the 24 hour format time into 12 hour format. (Hint:
you might have to use different type of division operators (/, //, %))

5. Masking is the act of applying a mask to a value. This is accomplished by doing:


 Bitwise ANDing in order to extract a subset of the bits in the value
 Bitwise ORing in order to set a subset of the bits in the value
 Bitwise XORing in order to toggle a subset of the bits in the value

Below is an example of extracting a subset of the bits in the value:

5
Based on this concept, provide bitwise working of the following and support
through appropriate executions in your jupyter notebook.
a) Which of the bits will be masked out and which of them will be retained if:
 16 & 15
 4&7
b) Which of the bits will be overwritten and which ones will be retained if:
 24 | 15
 14 | 7
c) Which of the bits will be toggled (complemented) and which ones will
be retained if:
 24 ^ 15
 14 ^ 7
For all the 3 parts a, b, and c provide comments along with code discussing
the masking operation taking place.

6. Implement the following function and evaluate its value for the x = 2, and y = 5

7. Take an input number from the user and provide its multiplication by 2 and division by
2 as a response. You are not allowed to use the * and / operators. Use the bitwise
operations instead. Also provide the bitwise working of the operation you perform in
the space provided below:
 x divided by 2:
 x multiplied with 2:

6
IQRA University

CSC 333 Introduction to Python

Lab# 04
Tuples, Dictionaries and Sets

Objective:
This experiment introduces the students to the more advance data types
within Python. The explored datatypes include Tuples, Sets and
Dictionaries.

Name of Student:

Roll No:

Date of Experiment:

1
Lab 04: Advanced Python Datatypes
Tuples, Dictionaries, & Sets

Tuples in Python

In addition to lists, Python also supports tuples which, in many ways, behave like lists except
that tuples are immutable.A tuple object contains a sequence of values separated by commas
and enclosed in parentheses (( )) instead of brackets ([ ]):
>>> days = ('Mo', 'Tu', 'We')
>>> days ('Mo',
'Tu', 'We')
The parentheses are optional in simple expressions like this assignment:
>>> days = 'Mo', 'Tu', 'We', 'Th'
>>> days
('Mo', 'Tu', 'We', 'Th')

In particular, the indexing operator can be used to access tuple items using the item’s offset as
the index, just like in lists. So, as in lists, items in tuples are ordered and can be accessed using
an index (offset).

Unlike lists, tuples are immutable: once a tuple is created, it cannot be changed. To learn more
about operators that can be used on tuples, go through the tuple notebook provided along with
this lab manual. We’ll have to wait a bit to understand when one should use a tuple instead of
a list to store a sequence of data.

Let us now have a look at some Tuple operators and methods. The table below provides a
reference to a few tuple operators and functions.

Usage Explanation
x in tpl x is an item of tpl
x not in tpl x is not an item of tpl

tpl + tpl2 Concatenation of tpl and tpl2

tpl*n, n*tpl Concatenation of n copies of tpl

tpl[i] Item at index i of tpl

2
len(tpl) Number of items in tpl

min(tpl) Minimum item in tpl

max(tpl) Maximum item in tpl

sum(tpl) Sum of items in tpl

Let us now discuss the methods that can be used on tuples. We have said that tuples behave
like lists except that they are immutable. Compared to List Methods, you will note that all but
two list methods modify the list they are called on. The two methods are count( ) and index( )
and they happen to be the only two tuple methods.

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

Following are some basic information about dictionary data structures.


i. A dictionary in Python is an unordered set of key: value pairs.
ii. Unlike lists, dictionaries are inherently order less. The key: value pairs appear
to be in a certain order but it is irrelevant.
iii. Each KEY must be unique, but the VALUES may be the same for two or
more keys.
iv. If you assign a value to a key then later in the same dictionary have the
same key assigned to a new value, the previous value will be overwritten.
v. Instead of using a number to index the items (as you would in a list), you
must use the specific key, e.g., calling IQRA_Dict['Python'].

Dictionary Methods to Extract the Data

There are three dictionary methods for extracting certain data.

<dictionary>.keys( ) returns the keys in the dictionary as a list (sort of), and

<dictionary>.values( ) returns the dictionary values as a list (sort of).

<dictionary>.items( ) returns key, value pairs for the dictionary

Why "sort of"? Because the returned objects are not a list -- they are their own list-like types,
3
called dict_keys and dict_values.

Adding New Items Inside Existing Dictionary

Adding an item to the dictionary is done by using a new index key and assigning a
value to it. We can even change the value of exiting keys by reassign a new value.

Removing Items from the Dictionary


There are several methods to remove items from a dictionary, Such as pop(), del , etc.
Removing Items from the Dictionary using POP( )
The pop( ) method removes the item with the specified key name. Note: In versions
before 3.7, a random item is removed instead .

Removing Items from the Dictionary using DEL( )


The del keyword removes the item with the specified key name.
Removing Items from the Dictionary using popitem( )
The popitem( ) method removes the last inserted item (in versions before 3.7, a
random item is removed instead).

Nested Dictionary
We can use a dictionary inside a dictionary. This can be helpful when creating telephone
directories or records etc.

Example: A record set for the faculty members of Computer Science Department. Using the
concept of nested dictionary or nested dictionary.

4
Code:
faculty = {1: {'name': 'Syed Faisal Ali', 'experience': '22',
'gender': 'Male'},
2: {'name': 'Dr. M Wasim', 'experience': '23',
'gender': 'Male'},
3: {'name': 'Dr. Lubaid', 'experience': '23',
'gender': 'Male'},
4: {'name': 'Noor ul Huda', 'experience': '3',
'gender': 'Female'},
5: {'name': 'Parkash Lohana', 'experience': '19',
'gender': 'Male'},
6: {'name': 'Fauzan Saeed', 'experience': '15',
'gender': 'Male'}}

print(faculty)

Introduction to Set
1. A set is an unordered collection of items. Every element is unique (no duplicates) and
must be immutable.
2. However, the set itself is mutable. We can add or remove items from it.
3. Sets can be used to perform mathematical set operations like union, intersection,
symmetric difference etc.

Creating a Set
A set is created by placing all the items (elements) inside curly braces { }, separated by
comma or by using the built-in function set( ). It can have any number of items and they may
be of different types (integer, float, tuple, string etc.). But a set cannot have a mutable
element, like list, set or dictionary, as its element.

Initializing an Empty Set


Sets are a mutable collection of distinct (unique) immutable values that are unordered.
You can initialize an empty set by using the constructor function set( ).

Similarity between Dictionary and Sets


Keep in mind that curly braces can only be used to initialize a set containing values. The code below
shows that using curly braces without values is one of the ways to initialize a dictionary and not a set.

# initialize empty set


My_empty_set = set()

# initialize empty set


My_empty_dictionary1 = dict()

5
My_empty_dictionary2 = {}

Use Set Operations in SET data


We can use a variety of set operations on a set.

Adding and Removing Values from Set


To add or remove values from set, let us initialize some values inside the set. Then use the add
method, to add new elements in set.

Removing Items from the Set using .remove()


You can use the remove method to remove an element from a set.

6
Removing Items from the Set using discard ( )
You can also use the discard method to remove a value from a set.

Removing Items from the Set using POP( )


You can also use the pop( ), method to remove an item, but this method will remove the last
item. Remember that sets are unordered, so you will not know what item that gets removed. The
return value of the pop( ) method is the removed item.

Clearing Items from the Set using clear( )


The clear( ) methods removes all the elements from the sets.

Student Exercise
1. Thoroughly study and execute the notebook provided with this lab.

2. Write a function to design a personal phone directory of your parents and friends.
You must add 8 members.
(a) Then use a function to delete a member from a telephone directory using his/her key.
(b) Print total number of members in your personal phone directory.

3. Create the following tuple

my_tpl = (1,2,3,4,5,6)

Now perform all the list operations and methods discussed in Lab 2 “Python Variables
and Basic Data Types”. Report the reasons for all the errors prompted by Python on the
tuple.

4. You are provided with the grades of the students within a class through the following

list. grades = [95, 96, 100, 85, 95, 90, 95, 100, 100, 89, 93, 95, 85, 96, 90]

use Python sets to identify all the unique grades attained by the students.

5. You are provided with the following two grade lists for the two sections of Introduction
to Python class.

Grades_1 = [95, 96, 100, 85, 95, 90, 95, 100, 100, 89, 93, 95, 85, 96, 90]
7
Grades_2 = [89, 95, 100, 80, 79, 93, 92, 100, 86, 92, 85, 85, 86, 90]
Provide the following:
a. List of all the unique grades in Grades_1
b. List of all the unique grades in Grades_2
c. All the grades that are common in the both the classes
d. All the unique grades that are attained by the students of both the classes
combined
e. Unique grades that are attained by the students of class 1 (Grades_1) but not
by any student in class 2 (Grades_2)
IQRA University

CSC 333 Introduction to Python

Lab# 05
Flow-control Structures

Objective:
This experiment introduces the concept and implementation
of program flow control structures in programming.

Name of Student:

Roll No:

Date of Experiment:
Lab 05: Introduction to Flow Control Structures
1. Simple if Condition
Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome.
You need to determine which action to take and which statements to execute if outcome is TRUE
or FALSE otherwise.

Following is the general form of a typical decision making structure found in most of the
programming languages.

Figure 1: Shows the flow structure of if statement

Python programming language assumes any non-zero and non-null values as TRUE, and if it is
either zero or null, then it is assumed as FALSE value.

Python supports the usual logical conditions from mathematics:

Logics Logical Conditions


Equals a == b
Less than a<b
Greater than a>b
Not Equals a != b
Less than or equal to a <= b
Greater than or equal to a >= b

CS-112 | Introduction to Programming Fundamentals 3


2. If with else Condition:
An else statement can be combined with an if statement. An else statement contains the block of
code that executes if the conditional expression in the if statement resolves to 0 or a FALSE
value.

The else statement is an optional statement and there could be at most only one else statement
following if.

Figure 2: The flow structure of if with else


statement

3. Loops

In general, statements are executed sequentially: The first statement in a module is executed first,
followed by the second, and so on. There may be a situation when you need to execute a block of
code several number of times. Programming languages provide various control structures that
allow for more complicated execution paths. A loop statement allows us to execute a statement or
group of statements multiple times. The following diagram illustrates a loop statement −

CS-112 | Introduction to Programming Fundamentals 6


Fall 2021, CS 112
Programming Fundamentals Lab 05: Introduction to Flow-control Structures

Figure 2: A simple loop architecture

Python programming language provides following types of loops to handle looping requirements.
Sr.No. Loop Type & Description
1 while loop
Repeats a statement or group of statements while a given condition is TRUE. It
tests the condition before executing the loop body.
2 for loop
Executes a sequence of statements multiple times and abbreviates the code that manages
the loop variable.
3 nested loops
You can use one or more loop inside any another while, for or do..while loop.

Loop Control Statements


Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.

Python supports the following control statements.

CS-112 | Introduction to Programming Fundamentals 2


Fall 2021, CS 112
Programming Fundamentals Lab 05: Introduction to Flow-control Structures

Sr.No. Control Statement & Description


1 break statement
Terminates the loop statement and transfers execution to the statement
immediately following the loop.
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition
prior to reiterating.
3 pass statement
The pass statement in Python is used when a statement is required syntactically
but you do not want any command or code to execute.

4. Simple for Loop


A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set,
or a string). This is less like the for keyword in other programming language, and works
more like an iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
For Example:
for iterating_var in sequence:
statements(s)

5. Nesting with Condition and Loop


Python programming language allows the usage of one loop inside another loop. The following
section shows a few examples to illustrate the concept. The syntax for a nested for loop statement
with if condition in Python programming language is as follows –
For Example

for iterating_var in sequence:


if(test condition):
statement (s)
statements(s)
else:

statements(s)

statements(s)

A final note on loop nesting is that you can put any type of loop inside any other type of loop.
For example, a for loop can be inside another for loop or inside condition or condition may be
CS-112 | Introduction to Programming Fundamentals 3
Fall 2021, CS 112
Programming Fundamentals Lab 05: Introduction to Flow-control Structures

called inside a loop and vice versa.

Examples
Program 1: Practicing with simple if condition. Execute the following program with a = 400 and b
=
500. Then change the value of a =500 and b = 400.

Code:

Program 2: Practicing with simple if condition if any of the condition is true using OR and
AND operator. Run the program for another combination (values) of a, b, and c.

Code:

4
Fall 2021, CS 112
Programming Fundamentals Lab 05: Introduction to Flow-control Structures

Program 3: Write a program which takes the initial and final values from the user then
print the sum of all the number.

Code:

Program 4: Write a program to convert digital number from 0 to 16 into binary, octal and
hexa-decimal number system.

Code:

Program 5: Write a Python program to construct the following pattern, using a nested for loop.

*
**
***
****
*****
****
***
**
*

Code:

5
Fall 2021, CS 112
Programming Fundamentals Lab 05: Introduction to Flow-control Structures

Program 6: Write a program which calculates the vowels from the given string.

Code:

Student Exercise

1. Write a program that takes a year as input and determines whether it is a leap year. A leap year is the
one that is either divisible by 4, but not by 100 or it is divisible by 400.

2. Write a program that calculates the sum of the squares of numbers in a given range (e.g., 1 to 5).

3. Write a program which takes the lower limit and upper limit then find which of the number are
prime number.

4. Create a program that prints a multiplication table (from 1 to 10) using nested for loops.

5. Given a list of names, create a program that prints each name along with its index. Use enumerate
and tuple unpacking.

6. Calculate the arithmetic sequence of n numbers. The program will generate the nth term of the
sequence, whereas the user will enter the first term and the common difference.
Example: you have entered the first term as 3 and common difference 6 you are
interesting in 35th term. So it will calculate and generate the answer as 207.
6
Fall 2021, CS 112
Programming Fundamentals

Lab 05: Introduction to Flow-control Structures

𝑎𝑛 = 𝑎1 + (𝑛 − 1)𝑑

7. Write a program which will collect name, father’s name, roll number and marks of subjects (5) as a
tuple of tuple for 4 students. Then the program will generate a result with name, father’s name,
marks obtained with total marks, grade and percentage. Use tuple unpacking as demonstrated in
Example 6 of the Notebook to attempt this question. Your input tuple would appear similar to:

tpl = ((‘farhan’, ‘karim’, ‘12345’, 54, 67, 78, 65, 89),


(‘usman’, ‘arif’, ‘98765’, 67, 76, 78, 56, 76),
(‘furqan’, ‘ahmed’, ‘12378’, 78, 65, 89, 76, 78),
(‘adnan’, ‘wahid’, ‘45678’, 76, 78, 67, 76, 78))

7
IQRA University

CSC 333 Introduction to Python

Lab# 06
While Loop & User Defined Functions

Objective:
This lab introduces the students to the basics of while loop. The students
are also provided with the understanding of User Defined Functions
(UDFs) within the Python Programming Language.

Name of Student:

Roll No:

Date of Experiment:

2
Lab 05: Introduction to Flow Control Structures
1. Simple While Loop
A while loop statement in Python programming language repeatedly executes a target statement
as long as a given condition is true.
Syntax
The syntax of a while loop in Python programming language is –

while <expression>:
Block of while statement(s)
Normal program execution

Here, statement(s) may be a single statement or a block of statements with uniform


indent. The condition may be any expression. The loop iterates while the condition is true. When
the condition becomes false, program control passes to the line immediately following the loop.

Figure 1: A simple while loop architecture

3
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. As shown in figure 1, a simple structure of
while loop for understanding of logic behind the while 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.

Program 1: Practicing with simple while loop, using the final condition to terminate the loop

Program 2: Practicing with simple while loop with infinite iterations as the condition is always
true.

Program 3: Write a program which takes the limit for while loop condition and sum the total
amount.

2. Difference between for and while loop


For loop is used to iterate over elements of a sequence. It is often used when you have a piece of
4
code which you want to repeat "n" number of time.
While Loop is used to repeat a block of code. Instead of running the code block once, It executes
the code block multiple times until a certain condition is met.

3. else Statement with For and While Loops


An else statement can be combined with the a loop. The else statement contains the block of code
that executes if the loop terminates in a conventional format due to the conditions against the
while loop becoming false. If the loop is terminated un-conventionally then the else block is not
executed. The else statement is an optional statement and there could be at most only one else
statement following a for or a while loop.

Program 4: Practicing with simple while loop with else condition.

Program 5: Practicing with Simple for loop and else condition.

4. Functions in Python
Functions are an essential part of the Python programming language: you might have already
encountered and used some of the many fantastic functions that are built-in in the Python
language or that come with its library ecosystem. However, as a Computer Scientist, you’ll
constantly need to write your own functions to solve problems that your projects or problems
poses to you.

We will introduce you to functions in Python. We will learn the following parts under function:

5
i. Functions vs Methods
ii. Parameters vs Arguments
iii. How to define a function: User-Defined Functions (UDFs)

You use functions in programming to bundle a set of instructions that you want to use repeatedly
or that, because of their complexity, are better self-contained in a sub-program and called when
needed. That means that a function is a piece of code written to carry out a specified task. To
carry out that specific task, the function might or might not need multiple inputs. When the task is
carried out, the function can or cannot return one or more values.

There are three types of functions in Python:

1. Built-in-Function:
Built-in functions, such as help() to ask for help, min() to get the minimum value, print() to
print an object to the terminal.

2. User-Defined Functions:
User-Defined Functions (UDFs), which are functions that users create to help them out.

3. Anonymous Functions:
Anonymous functions, which are also called lambda functions because they are not declared
with the standard def keyword.

4 Functions vs Methods
A method refers to a function which is part of a class. You access it with an instance or
object of the class. A function doesn’t have this restriction: it just refers to a standalone
function. This means that all methods are functions but not all functions are methods.

5 Parameters vs Arguments
Parameters are the names used when defining a function or a method, and into which
arguments will be mapped. In other words, arguments are the things which are supplied to
any function or method call, while the function or method code refers to the arguments by
their parameter names. As shown in the following program where we will make a function f
which takes one argument name x.

Program 6: Write a function f which takes one argument x, it will square the value of x and add
1 in it then return the answer to user.

6
How to define a User-Defined Functions (UDFs)
User defined functions (UDFs) are normally defined by the keyword def followed by the following
format:
def <function name> (argument1, argument2,<multiple arguments>):
body of the function
return <value>
Keep in mind the indentation is very important in programming python code.

Program 7: Write a Python function which takes no argument and generate and print a list of first
and last 6 elements where the values are cube of numbers between 1 and 30 (both included).

Difference between Print and return statements within a function:


A common mistake is to use the print() function instead of the return statement inside a function.
Suppose we had defined our first function f() in this way:
def f(x):
print(x**2 + 1)
It would seem that such an implementation of function f() works fine:
>>> f(2)
5
However, when used in an expression, function f() will not work as expected:
>>> 3 * f(2) + 1
5
Traceback (most recent call last):
File '<pyshell#103>', line 1, in <module>
3 * f(2) + 1
TypeError: unsupported operand type(s) for *:
'int' and 'NoneType'
7
When evaluating f(2) in the expression 3 * f(2) + 1, the Python interpreter evaluates (i.e.,
executes) f(2), which prints the value 5. You can actually see this 5 in the line before the
“Traceback” error line.

So f( ) prints the computed value, but it does not return it. This means that f(2) returns nothing
and thus evaluates to nothing in an expression. Actually, Python has a name for the “nothing”
type: It is the 'NoneType' referred to in the error message shown. The error itself is caused by the
attempt to multiply an integer value with “nothing.” That said, it is perfectly OK to call print()
inside a function, as long as the intent is to print rather than return a value.

Student Exercise

1. Write a function interest( ) that takes one input, a floating-point interest rate (e.g. 0.06 which
corresponds to a 6% interest rate). Your function should compute and return how long (in
years) it will take an investment to double in value.
Note: The number of years it takes an investment to double does not depend upon the value of
the initial investment.

2. Implement a function mystery( ) that takes as input a positive integer n and answers this
question. How many times can n be halved (using integer division) before reaching 1?
The value should returned.

>>>mystery(4)
2
>>>mystery(11)
3
>>>mystery(25)
4
3. Write two functions which will take required arguments for calculating the Area and Volume of
a cylinder. Figure 1 provides some basic concepts for computing the area of a cylinder.

8
Figure 1 – Calculating the Area and Volume of Cylinder
Note: Use the following format to get the square on the answer:
print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimals))

4. Write a function that can calculate the arithmetic sequence of n numbers. The program will
generate the nth term of the sequence, whereas the user will enter the first term and the
common difference. The program will then ask either to continue or not, if the user will enter
yes it will ask the next nth term to calculate.

Example: you have entered the first term as 3 and common difference 6 you are interested in
35th term. So it will calculate and generate the answer as 207.

Now it will again ask for you to continue if you agree it will ask next term like 45th or 96th term
to calculate.

9
IQRA University

CSC 333 Introduction to Python

Lab# 07
Strings and Print Formatting in Python

Objective:
This lab explores the String datatype and its related features. The lab also
discusses the print function and the formatting operations that can be used
along with it.

Name of Student:

Roll No:

Date of Experiment:

2
Lab 07: Strings and Formatted outputs

1. String, Revisited

Background
Earlier we introduced the string class str. Our goal then was to show that Python supported
values other than numbers. We showed how string operators make it possible to write string
expressions and process strings in a way that is as familiar as writing algebraic expressions. We
also used strings to introduce the indexing operator [ ]. In this section we re-discover strings
and what can be done with them in more depth. We show, in particular, a more general version
of the indexing operator and many of the commonly used string methods that make Python a
strong text- processing tool

String Representations

We already know that a string value is represented as a sequence of characters that is enclosed
:within quotes, whether single or double quotes

>>>"!Hello, World"
!Hello, World
>>>’hello'
hello

The Indexing Operator, Revisited

We have already introduced the indexing operator [ ]:

>>> s = 'hello'
>>> s[0]
'h'

The indexing operator takes an index i and returns the single-character string consisting of the
character at index i. The indexing operator can also be used to obtain a slice of a string. For
example:

>>> s[0:2]
'he'

The expression s[0:2] evaluates to the slice of string s starting at index 0 and ending before index
2. In general, s[i : j] is the substring of string s that starts at index i and ends at index j-1. Here are

3
more examples.
>>> s[3:4]
'l'
>>> s[-3:-1]
'll'

The last example shows how to get a slice using negative indexes: The substring obtained starts
at index -3 and ends before index -1 (i.e., at index -2). If the slice we want starts at the first
character of a string, we can drop the first index:

>>> s[:2]
'he'

In order to obtain a slice that ends at the last character of a string, we must drop the second index:

>>> s[-3:]
'llo'

String Methods

The string class supports a large number of methods. These methods provide the developer with a
text-processing toolkit that simplifies the development of text-processing applications. Here we
cover some of the more commonly used methods

We start with the string method find( ). When it is invoked on string s with one string input
argument target, it checks whether target is a substring of s. If so, it returns the index (of the first
character) of the first occurrence of string target; otherwise, it returns -1 For example, here is how
method find( ) is invoked on string message using target string 'top secret'.

message = ''This message is top secret and should not be divulged to


anyone without top secret clearance”

>>>message.find('top secret')
16

Index 16 is output by method find( ) since string 'top secret' appears in string message starting at index
16. The method count( ), when called by string s with string input argument target, returns the
number of times target appears as a substring of s. For example
>>>message.count('top secret')
>>>2

The value 2 is returned because string 'top secret' appears twice in message The function
replace(),when invoked on string s, takes two string inputs, old and new, and outputs a copy of string

4
s with every occurrence of substring old replaced by :string new. For example

>>>message.replace('top', 'no')
This message is no secret and should not\n' 'be divulged to anyone
without no secret clearance

Has this changed the string message? Let’s check

>>>print(message)
This message is top secret and should not be divulged to anyone
without top secret clearance

So string message was not changed by the replace( ) method. Instead, a copy of message, with
appropriate substring replacements got returned. This string cannot be used later on because we have
not assigned it a variable name. Typically, the replace( ) method would be used in an assignment
statement like this

>>> public = message.replace('top', 'no')


>>> print(public)
This message is no secret and should not be divulged to anyone
without no secret clearance

Recall that strings are immutable (i.e., they cannot be modified). This is why string method replace( )
returns a (modified) copy of the string invoking the method rather than changing the string. In the
next example, we showcase a few other methods that return a modified copy of the string

>>> message = 'top secret’


>>> message.capitalize()
'Top secret'
>>> message.upper()
'TOP SECRET'

Method capitalize( ), when called by string s, makes the first character of s uppercase; method
upper() makes all the characters uppercase. The very useful string method split( ) can be called on a
string in order to obtain a list of words in the string

>>> this is the text.split(‘,’)


>>> ['this', 'is', 'the', 'text']

In this statement, the method split( ) uses the blank spaces in the string 'this is the text' to create word
substrings that are put into a list and returned. The method split( ) can also be called with a delimiter
string as input. The delimiter string is used in place of the blank space to break up the string. For
example, to break up the string
>>> x = '2;3;5;7;11;13’

into a list of number, you would use ';' as the delimiter


5
>>> x.split(';')
['13' ,'11' ,'7' ,'5' ,'3' ,'2']

Finally, another useful string method is translate( ). It is used to replace certain characters in a string
with others based on a mapping of characters to characters. Such a mapping is constructed using a
special type of string method that is called not by a string object using by the string class str itself

>>>table = str.maketrans('abcdef', 'uvwxyz')

The variable table refers to a mapping of characters a,b,c,d,e,f to characters u,v,w,x,y,z, respectively.
For our purposes here, it is enough to understand its use as an argument to the method translate()

>>> ‘fad'.translate(table)
>>> 'zux'

>>> ’desktop'.translate(table)'
>>> 'xysktop'

The string returned by translate( ) is obtained by replacing characters according to the mapping
described by table. In the last example, d and e are replaced by x and y, but the other characters
remain the same because mapping table does not include them
A partial list of string methods is shown in Table 6.1. Many more are available, and to :view them
all, use the help( ) tool

>>> help(str)
...

6
Formatted Output
The results of running a program are typically shown on the screen or written to a file. Either way,
the results should be presented in a way that is visually effective. The Python output formatting tools
help achieve that. In this section we learn how to format output using features of the print( ) function
and the string format( ) method. We also look at how strings containing a date and time are
interpreted and created.

Function print( )
The print() function is used to print values onto the screen. Its input is an object and it prints a string
representation of the object’s value.

>>> n = 5
>>> print(n)
5

Function print( ) can take an arbitrary number of input objects, not necessarily of the same type. The
values of the objects will be printed in the same line, and blank spaces (i.e., characters ' ') will be
inserted between them:

7
>>> r = 5/3
>>> print(n, r)
5 1.66666666667
>>> name = 'Ida'
>>> print(n, r, name)
5 1.66666666667 Ida

The blank space inserted between the values is just the default separator. If we want to insert
semicolons between values instead of blank spaces, we can do that too. The print( ) function takes an
optional separation argument sep, in addition to the objects to be printed:

>>> print(n, r, name, sep=';')


5;1.66666666667;Ida

The argument sep=';' specifies that semicolons should be inserted to separate the printed values of n,
r, and name. In general, when the argument sep=<some string> is added to the arguments of the
print( ) function, If we want to print the values in separate lines, the separator should be the new line
character, '\n'.

>>> print(n, r, name, sep='\n')


5
1.66666666667
Ida

The print( ) function supports another formatting argument end, in addition to sep. Normally each,
successive print( ) function call will print in a separate line:

>>> for name in ['Joe', 'Sam', 'Tim', 'Ann']:


print(name)
Joe
Sam
Tim
Ann

The reason for this behavior is that, by default, the print( ) statement appends a new line character (\
n) to the arguments to be printed. Suppose that the output we really want is:

Joe! Sam! Tim! Ann!

When the argument end=<some string> is added to the arguments to be printed, the string <some
string> is printed after all the arguments have been printed. If the argument end=<some string> is
missing, then the default string '\n', the new line character, is printed instead; this causes the current
line to end. So, to get the screen output in the format we want, we need to add the argument end = '!'
to our print( ) function call:

8
>>> for name in ['Joe', 'Sam', 'Tim', 'Ann']:
print(name, end='! ')
Joe! Sam! Tim! Ann!

String Method format( )


The sep argument can be added to the arguments of a print( ) function call to insert the same
string between the values printed. Inserting the same separator string is not always what we
want. Consider the problem of printing the day and time in the way we expect to see time, given
these variables:

>>> weekday = 'Wednesday'


>>> month = 'November'
>>> day = 10
>>> year = 2019
>>> hour = 11
>>> minute = 45
>>> second = 33

What we want is to call the print( ) function with the preceding variables as input arguments
and obtain something like:

Wednesday, November 10, 2010 at 11:45:33

It is clear that we cannot use a separator argument to obtain such an output. One way to achieve
this output would be to use string concatenation to construct a string in the right format:

Ooops, There is a mistake, a + before str(second). That fixes it (check it!) but we should not be
satisfied. The reason why I messed up is that the approach I used is very tedious and error prone.
There is an easier, and far more flexible, way to format the output. The string (str) class provides
a powerful class method, format( ), for example, in which we only want to print the time:

>>> '{0}:{1}:{2}'.format(hour, minute, second)


'11:45:33'
The objects to be printed (hour, minute, and second) are arguments of the format( ) method. The
string invoking the format( ) function—that is, the string '{0}:{1}:{2}'— is the format string: It
describes the output format. All the characters outside the curly braces—that is, the two colons
(':')—are going to be printed as is. The curly braces {0}, {1}, and {2} are placeholders where the
objects will be printed. The numbers 0, 1, and 2

9
Following Figure shows what happens when we move the indexes 0, 1, and 2 in the previous
example:

The default, when no explicit number is given inside the curly braces, is to assign the first
placeholder (from left to right) to the first argument of the format() function, the second placeholder
to the second argument, and so on, as shown in following Figure.

Let’s go back to our original goal of printing the date and time. The format string we need is ‘{},{},{},
{} at {}:{}:{}' assuming that the format( ) function is called on variables weekday, month, day, year,
hours, minutes, seconds in that order. We check this (see also following Figure for the illustration of
the mapping of variables to placeholders):

10
Lining Up Data in Columns

To illustrate the issues, let’s consider the problem of properly lining up values of functions i 2, i3
and 2i for i = 1; 2; 3; . . . Lining up the values properly is useful because it illustrates the very
different growth rates of these functions:

We can specify the (minimum) field width with a decimal integer defining the number of
character positions reserved for the value. If not specified or if the specified field width is
insufficient, then the field width will be determined by the number of digits/characters in the
displayed value. Here is an example:

>>> '{0:3},{1:5}'.format(12, 354)

' 12, 354'

In this example, we are printing integer values 12 and 354. The format string has a placeholder for
with '0:3' inside the braces. The 0 refers to the first argument of the format() function (12), as 12
we’ve seen before. Everything after the ':' specifies the formatting of the value. In this case, 3
indicates that the width of the placeholder should be 3. Since 12 is a two-digit number, an extra
blank space is added in front. The placeholder for 354 contains '1:5', so an extra two blank spaces
are added in front. When the field width is larger than the number of digits, the default is to right-
justify— that is, push the number value to the right. Strings are left-justified. In the next example,
a field of width 10 characters is reserved for each argument first and last. Note that extra blanks
are added after the string value.

>>> first = 'Bill'

>>> last = 'Gates'

>>> '{:10}{:10}'.format(first, last)

11
'Bill Gates '

The precision is a decimal number that specifies how many digits should be displayed before
and after the decimal point of a floating-point value. It follows the field width and a period
separates them. In the next example, the field width is 8 but only four digits of the floating-point
value are displayed. Where n = 1000 and d = 3.

The type determines how the value should be presented. The available integer presentation types are
listed in the table.

We illustrate the different integer type options on integer value 10.

Two of the presentation-type options for floating-point values are f and e. The type option f displays the
value as a fixed-point number (i.e., with a decimal point and fractional part)

12
>>>‘{6.2F}’.format(3/5)
>>>’1.67’

In this example, the format specification ':6.2f' reserves a minimum width of 6 with exactly two
digits past the decimal point for a floating-point value represented as a fixedpoint number. The
type option :e represents the value in scientific notation in which the exponent is shown after the
character e

>>> ‘{:e}‘.format(3 / 5)
'1.666667e+00'

This represents 1:666667 . 100

Now let’s go back to our original problem of presenting the values of functions i2, i3, and 2i for i
= up to at most 12.We specify a minimum width of 3 for i and 6 for the values of i2, i3, and 2i to
obtain the output in the desired format

Implement function roster( ) that takes a list containing student information and prints out a
roster, as shown below. The student information, consisting of the student’s last name, first
name, class, and average course grade, will be stored in that order in a list. Therefore, the input list
is a list of lists. Make sure the roster printed out has 10 slots for every string value and 8 for the
grade, including 2. slots for the decimal part

13
Getting and Formatting the Date and Time
Getting and Formatting the Date and Time Programs often need to interpret or produce strings
that contain a date and time. In addition, they may also need to obtain the current time. The
current date and time are obtained by asking the underlying operating system. In Python the term
module provides an API to the operating system time utilities as well as tools to format date and
time values. To see how to use it, we start by importing the time module:

>>> import time

Several functions in the time module return some version of the current time. The time( ) function
returns the time in seconds since the epoch:

>>> time.time()
1268762993.335

You can check the epoch for your computer system using another function that returns the time in a
format very different from time():

>>> time.gmtime(0)

time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0,


m_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)

>>> time.localtime()
time.struct_time(tm_year=2010, tm_mon=3, tm_mday=16, tm_hour= 13,
tm_min=50, tm_sec=46, tm_wday=1, tm_yday=75, tm_isdst=1)

The output format is not very readable (and is not designed to be). Module time provides a formatting
function strftime( ) that outputs time in the desired format. This function takes a format string and the
14
time returned by gmtime( ) or localtime( ) and outputs the time in a format described by the
format string. Here is an example, illustrated in Figure.

In

this example, strftime( ) prints the time returned by time.localtime( ) in the format specified by the
format string '%A %b/%d/%y %I:%M %p'. The format string includes directives %A, %b, %d, %y,
%I, %M, and %p that specify what date and time values to output at the directive’s location, using the
mapping shown in Table 4.3. All the other characters (/, :, and the blank spaces) of the format string
are copied to the output as is.

15
Student Exercise

1. Construct the strings by using the string time format function strftime ( )
a. (‘Monday, November 25 2019')
b. ('09:40 PM Central Daylight Time on 11/25/2019')
c. ('I will meet you on Thu July 13 at 09:40 PM.')

2. Assuming that variable forecast has been assigned string 'It will be a sunny day today'
Write Python function corresponding to these assignments:
a. To variable count, the number of occurrences of string 'day' in string forecast.
b. To variable weather, the index where substring 'sunny' starts.
c. To variable change, a copy of forecast in which every occurrence of substring 'sunny'
is replaced by 'cloudy'.

3. Write function even( ) that takes a positive integer n as input and prints on the screen all
numbers between, and including, 2 and n divisible by 2 or by 3, using this output format:
>>> even(17)
2, 3, 4, 6, 8, 9, 10, 12, 14, 15, 16,

4. Write a function month( ) that takes a number between 1 and 12 as input and returns the
three- character abbreviation of the corresponding month. Do this without using an if
statement, just string operations. Hint: Use a string to store the abbreviations in order.

>>>
month(1)
'Jan'
>>>
month(11)
'Nov'

5. Design an application in of small POS (Point of Sale) in which you generate burger type,
quantity, rate and amount line by line at the end it will print the total sum and 13 % GST.
Keep in mind that each receipt has username, and date of print. Create a function which can
solve your problem.

6. Create a function which will take a start point and end point from user and convert the
numbers in binary, octal, decimal, and hexa-decimal with proper formatting style. The first
line will be headings and the rest of the line with proper space between each type.

16
IQRA University

CSC 333 Introduction to Python

Lab# 08
File I/O Operations

Objective:
The lab introduces the students to external File Handling
in Python

Name of Student:

Roll No:

Date of Experiment:

2
Lab 08: Introduction to Files

Fil
es A file could be a text document or spreadsheet, an HTML file, or a Python module.
Such files are referred to as text files. Text files contain a sequence of characters that
are encoded using some encoding (ASCII, utf-8, etc.). A file also can be an
executable application (like python.exe), an image, or an audio file. These files are
referred to as binary files because they are just a sequence of bytes and there is no
encoding. All files are managed by the file system, which we introduce next.
File System
The file system is the component of a computer system that organizes files and
provides ways to create, access, and modify files. While files may be physically
stored on various secondary (hardware) memory devices, the file system provides a
uniform view of the files that hides the differences between how files are stored on
the different hardware devices. The effect is that reading or writing files is the
same, whether the file is on a hard drive, flash memory stick, or DVD-RW.
Files are grouped together into directories or folders. The top folder as identified in
the figure is called the root folder. A folder may contain other folders in addition to
(regular) files. The file system organizes files and folders into a tree structure as
demonstrated in the figure below. It is a convention in computer science to draw
hierarchical tree structures upside down with the root of the tree on top.

Opening and Closing Files:


Opening and Closing a File Processing a file consists of these three steps:
1. Opening a file for reading or writing
2. Reading from the file and/or writing to the file
3. Closing the file

3
The built-in function open( ) is used to open a file, whether the file is a text file or a
binary file. In order to read file example.txt, we must first open it:

>>> infile = open('example.txt', 'r')

The function open( ) takes three string arguments: a file name and, optionally, a
mode and an encoding; we will not discuss the encoding argument in this lab. The
file name is really the pathname (absolute or relative) of the file to be opened. In the
last example, the file relative pathname is example.txt. Python will look for a file
named example.txt in the current working directory (recall that this will be the folder
containing the module that was last imported); if no such file exists, an exception
occurs. For example:

>>> infile = open('sample.txt') Traceback


(most recent call last):
File "<pyshell#339>", line 1, in <module> infile =
open('sample.txt') IOError: [Errno 2] No such file or
directory: 'sample.txt'

The file name could also be the absolute path of the file such as, for example
/Users/lperkovic/example.txt on a UNIX box or

C:/Users/sfaisal/example.txt on a Windows machine

We have figured out that the first argument to the open function call is the file name,
absolute or relative. The second parameter passed is the mode of the file to be
opened. The mode is a string that specifies how we will interact with the opened file.
In function call open('example.txt', 'r'), the mode 'r' indicates that the opened file will
be read from; it also specifies that the file will be read from as a text file.
In general, the mode string may contain one of r, w, a, or r+ to indicate whether the
file should be opened for reading, writing, appending, or reading and writing,
respectively. If missing, the default is r. In addition, t or b could also appear in the
mode string: indicates that the file is a text file, while b indicates it is a binary file. If
neither is present, the file will be opened as a text file. So open('example.txt', 'r') is
equivalent to open('example.txt', 'rt'), which is equivalent to open('example.txt'). .
This is all summarized in Table below.

4
The difference between opening a file as a text or binary file is that binary files are
treated as a sequence of bytes and are not decoded when read or encoded when
written to. Text files, however, are treated as encoded files using some encoding.
The open ( ) function returns an object of an Input or Output Stream type that
supports methods to read and/or write characters. We refer to this object as a file
object. Different modes will give us file objects of different file types. Depending on
the mode, the file type will support all or some of the read/write methods specific to
the file objects. The separate read methods are used to read the content of the file in
different ways. We show the difference between the three on file example.txt whose
content is:

With every opened file, the file system will associate a cursor that points to a
character in the file. When the file is first opened, the cursor typically points to the
beginning of the file (i.e., the first character of the file). When reading the file,
characters that are read are the characters that start at the cursor; if we are writing to
the file, then anything we write will be written starting at the cursor position.

We now use the read( ) function to read just one character. The read( ) function will
return the first character in the file as a (one-character) string.
>>> infile.read(1)
'T'

After the character 'T' is read, the cursor will move and point to the next character,
which is 'h' (i.e., the first unread character). Let’s use the read( ) function again, but
now to read five characters at a time. What is returned is a string of the five
characters following the character 'T' we initially read:
>>> infile.read(5)
'he 3 '

5
The function readline( ) will read characters from the file up to the end of the line
(i.e., the new line character \n) or until the end of the file, whichever happens first.
Note that in our case the last character of the string returned by readline( ) is the new
line character:

>>> infile.readline()

'lines in this file end with the new line character.\n' The cursor now points to the
beginning of the second line. Finally, we use the read( ) function without arguments
to read the remainder of the file:

>>> infile.read( )

'\nThere is a blank line above this line.\n'


The cursor now points at the “End-Of-File” (EOF) character, which indicates the end
of the file

To close the opened file that infile refers to, you just do: infile.close( )
Closing a file releases the file system resources that keep track of information about
the opened file (i.e., the cursor position information).

Patterns for Reading a Text File

Depending on what you need to do with a file, there are several ways to access the
file content and prepare it for processing. We describe several patterns to open a file
for reading and read the content of the file. We will use the file example.txt again to
illustrate the patterns:

One way to access the text file content is to read the content of the file into a string
object. This pattern is useful when the file is not too large and string operations will be
used to process the

6
file content. For example, this pattern can be used to search the file content or to replace every
occurrence of a substring with another.

Program: 1
We illustrate this pattern by implementing function numChars( ), which takes the
name of a file as input and returns the number of characters in the file. We use the
read( ) function to read the file content into a string:

When we run this function on our example file, we obtain:


>>> numChars('example.txt')
98

Write function stringCount( ) that takes two string inputs—a file name and a target string
— and returns the number of occurrences of the target string in the file.

>>> stringCount('example.txt', 'line')


4

Program 2:
The file reading pattern we discuss next is useful when we need to process the words
of a file. To access the words of a file, we can read the file content into a string and use
the string split(
) function, in its default form, to split the content into a list of words. (So, our definition
of a word in this example is just a contiguous sequence of nonblank characters.)
We illustrate this pattern on the next function, which returns the number of words in a file. It
also prints the list of words, so we can see the list of words.

7
Sometimes a text file needs to be processed line by line. This is done, for example,
when searching a web server log file for records containing a suspicious IP address.
A log file is a file in which every line is a record of some transaction (e.g., the
processing of a web page request by a web server). In this third pattern, the readlines(
) function is used to obtain the content of the file as a list of lines. We illustrate the
pattern on a simple function that counts the number of lines in a file by returning the
length of this list. It also will print the list of lines so we can see what the list looks
like:

Let’s test the function on our example file. Note that the new line character \n in each line

All file processing patterns we have seen so far read the whole file content into a
string or a, list of strings (lines). This approach is OK if the file is not too large. If the
file is large better approach would be to process the file line by line; that way we
avoid having the whole file in main memory. Python supports iteration over lines of a
file object. We use this approach to print each line of the example file:

8
In every iteration of the for loop, the variable line will refer to the next line of the
file. In first iteration, variable line refers to the line 'The three lines in ...'; in the
second, it refers to .'... and in the final iteration, it refers to 'There is a blank ;'n\'
.Thus, at any point in time, only one line of the file needs to be kept in memory

Writing to a Text File


In order to write to a text file, the file must be opened for writing:

>>> outfile = open('test.txt', 'w')

If there is no file test.txt in the current working directory, the open( ) function will
create it. If a file text.txt exists, its content will be erased. In both cases, the cursor
will point to the beginning of the (empty) file. (If we wanted to add more content to
the (existing) file, we would use the mode 'a' instead of 'w'.)
Once a file is opened for writing, function write( ) is used to write strings to it. It will
write the string starting at the cursor position. Let’s start with a one-character string:

>>> outfile.write('T')
1

The value returned is the number of characters written to the file. The cursor now points
to the position after T, and the next write will be done starting at that point.

>>> outfile.write('his is the first line.')


22

In this write, 22 characters are written to the first line of the file, right after T. The
cursor will now point to the position after the period.

>>> outfile.write(' Still the first line...\n')


25

Everything written up until the new line character is written in the same line.With
the '\n' character written, what follows will go into the second line:
9
>>> outfile.write('Now we are in the second line.\n')
31

The \n escape sequence indicates that we are done with the second line and will write
the third line next. To write something other than a string, it needs to be converted to a
string first:

>>> outfile.write('Non string value like '+str(5)+' must be converted first.\n’)


49

Here is where the string format( ) function is helpful. To illustrate the benefit of
using string formatting, we print an exact copy of the previous line using string
formatting:

>>> outfile.write('Non string value like {} must be converted


first.\n'.format(5))
49

Just as for reading, we must close the file after we are done writing:
>>> outfile.close()
The file test.txt will be saved in the current working directory and will have this
content: This is the first line. Still the first line...
1 Now we are in the second line.

2 Non string value like 5 must be converted first.

3 Non string value like 5 must be converted first.

10
Student Exercise

1. Implement function distribution() that takes as input the name of a file (as a string). This
one-line file will contain letter grades separated by blanks. Your function should print the
distribution of grades, as shown.

>>> distribution('grades.txt')
6 students got A
2 students got A-
3 students got B+
2 students got B
2 students got B-
4 students got C
1student got C-
2students got F

2. Implement function duplicate() that takes as input the name (a string) of a file in the
current directory and returns True if the file contains duplicate words and False otherwise.

>>> duplicate('Duplicates.txt')
True
>>> duplicate('noDuplicates.txt')
False

3. The function abc() takes the name of a file (a string) as input. The function should
open the file, read it, and then write it into file abc.txt with this modification: Every
occurrence of a four-letter word in the file should be replaced with string 'xxxx'.
>>> abc('example.txt')
Note that this function produces no output, but it does create file abc.txt in
the current folder

4. Implement function myGrep( ) that takes as input two strings, a file name and a target string,
and prints every line of the file that contains the target string as a substring.

11
5. Write a function stats() that takes one input argument: the name of a text file. The function
should print, on the screen, the number of lines, words, and characters in the file; your function
should open the file only once.

>>> stats('example.txt')
line count: 3 word count:
20 character
count: 98

12
IQRA University

CSC 333 Introduction to Python

Lab# 09
Exception Handling, Debugging, and
Unit Testing
Objective:
The students are exposed to the concept of Exception Handling in Python.
Debugging within the PyCharm IDE is also explored. Finally, the students
are provided with a brief introduction of unit testing.

Name of Student:

Roll No:

Date of Experiment:

2
Lab 09: Exception Handling

Introduction to Exceptions

Exceptions in Python
Python has many built-in exceptions that are raised when your program encounters an error
(something in the program goes wrong).

When these exceptions occur, the Python interpreter stops the current process and passes it to the
calling process until it is handled. If not handled, the program will crash.

For example, let us consider a program where we have a function A that calls function B, which in
turn calls function C. If an exception occurs in function C but is not handled in C, the exception
passes to B and then to A.

If never handled, an error message is displayed and our program comes to a sudden unexpected halt.

3
Catching Exceptions in Python
In Python, exceptions can be handled using a try statement.

The critical operation which can raise an exception is placed inside the try clause. The code that
handles the exceptions is written in the except clause.

We can thus choose what operations to perform once we have caught the exception. Here is a
simple example.

# import module sys to get the type of


exception import sys

randomList = ['a', 0, 2]

for entry in
randomList: try:
print("The entry is",
entry) r = 1/int(entry)
brea
k
except:
print("Oops!", sys.exc_info()[0],
"occurred.") print("Next entry.")
print()
print("The reciprocal of", entry, "is", r)
Output

The entry is a
Oops! <class 'ValueError'>
occurred. Next entry.

The entry is 0
Oops! <class 'ZeroDivisionError'>
occured. Next entry.

The entry is 2
The reciprocal of 2 is 0.5

In this program, we loop through the values of the randomList list. As previously mentioned, the
portion that can cause an exception is placed inside the try block.

If no exception occurs, the except block is skipped and normal flow continues (for last value).
But if any exception occurs, it is caught by the except block (first and second values).

Here, we print the name of the exception using the exc_info() function inside sys module. We can
see that a causes ValueError and 0 causes ZeroDivisionError.

Since every exception in Python inherits from the base Exception class, we can also perform the
above task in the following way:

4
# import module sys to get the type of
exception import sys
randomList = ['a', 0, 2]

for entry in
randomList: try:
print("The entry is",
entry) r = 1/int(entry)
break
except Exception as e:
print("Oops!", e. class , "occurred.")
print("Next entry.")
print()
print("The reciprocal of", entry, "is", r)

This program has the same output as the above program.

Catching Specific Exceptions in Python

In the above example, we did not mention any specific exception in the except clause.

This is not a good programming practice as it will catch all exceptions and handle every case in the
same way. We can specify which exceptions an except clause should catch.

A try clause can have any number of except clauses to handle different exceptions, however, only
one will be executed in case an exception occurs.

We can use a tuple of values to specify multiple exceptions in an except clause. Here is an example
pseudo code.

try:
# do
something
pass

except ValueError:
# handle ValueError
exception pass

except (TypeError,
ZeroDivisionError): # handle
multiple exceptions
# TypeError and
ZeroDivisionError pass

except:
# handle all other
exceptions Pass

5
Raising Exceptions in Python

In Python programming, exceptions are raised when errors occur at runtime. We can also
manually raise exceptions using the raise keyword.

We can optionally pass values to the exception to clarify why that exception was raised.
>>> raise KeyboardInterrupt
Traceback (most recent call
last):
...
KeyboardInterrupt

>>> raise MemoryError("This is an


argument") Traceback (most recent call
last):
...
MemoryError: This is an argument

>>> try:
... a = int(input("Enter a positive integer: "))
... if a <= 0:
... raise ValueError("That is not a positive number!")
... except ValueError as ve:
... print(ve)
...
Enter a positive integer: -2
That is not a positive
number!

Python try with else clause


In some situations, you might want to run a certain block of code if the code block inside try ran
without any errors. For these cases, you can use the optional else keyword with the try statement.

Note: Exceptions in the else clause are not handled by the preceding except

clauses. Let's look at an example:

# program to print the reciprocal of even numbers

try:
num = int(input("Enter a number:
")) assert num % 2 == 0
except:
print("Not an even
number!") else:
reciprocal =
1/num
print(reciprocal)
Output

If we pass an odd number:

6
Enter a number: 1
Not an even
number!
If we pass an even number, the reciprocal is computed and displayed.

Enter a number:
4 0.25
However, if we pass 0, we get ZeroDivisionError as the code block inside else is not
handled by preceding except.

Enter a number: 0
Traceback (most recent call last):
File "<string>", line 7, in
<module> reciprocal = 1/num
ZeroDivisionError: division by zero

Python try...finally
The try statement in Python can have an optional finally clause. This clause is executed no matter
what, and is generally used to release external resources.

For example, we may be connected to a remote data center through the network or working with a
file or a Graphical User Interface (GUI).

In all these circumstances, we must clean up the resource before the program comes to a halt whether
it successfully ran or not. These actions (closing a file, GUI or disconnecting from network) are
performed in the finally clause to guarantee the execution.

Here is an example of file operations to illustrate


this. try:
f = open("test.txt",encoding =
'utf-8') # perform file operations
finally:
f.close()
This type of construct makes sure that the file is closed even if an exception occurs during the
program execution.

Built-in exceptions
A list of Python's Built-in Exceptions is shown below. This list shows the Exception and why it is
thrown (raised).

Exception Cause of Error


AssertionError if assert statement fails.
AttributeError if attribute assignment or reference
fails.
EOFError if the input() functions hits end-of-file
condition.
FloatingPointError if a floating point operation fails.
GeneratorExit Raise if a generator's close() method
is called.
ImportError if the imported module is not found.
IndexError if index of a sequence is out of range.
7
KeyError if a key is not found in a dictionary.
KeyboardInterrupt if the user hits interrupt key (Ctrl+c
or delete).
MemoryError if an operation runs out of memory.
NameError if a variable is not found in local or
global scope.
NotImplementedError by abstract methods.
OSError if system operation causes system
related error.
OverflowError if result of an arithmetic operation is
too large to be
represented.
ReferenceError if a weak reference proxy is used
to access a
garbage collected referent.
RuntimeError if an error does not fall under any
other category.
StopIteration by next() function to indicate that
there is no further
item to be returned by iterator.
SyntaxError by parser if syntax error is
encountered.
IndentationError if there is incorrect indentation.
TabError if indentation consists of
inconsistent tabs and
spaces.
SystemError if interpreter detects internal error.
SystemExit by sys.exit() function.
TypeError if a function or operation is applied to
an object of
incorrect type.
UnboundLocalError if a reference is made to a local variable in a
function or method, but no value has been bound
to
that variable.
UnicodeError if a Unicode-related encoding or
decoding error
occurs.
UnicodeEncodeError if a Unicode-related error occurs
during encoding.
UnicodeDecodeError if a Unicode-related error occurs
during decoding.
UnicodeTranslateError if a Unicode-related error occurs
during translating.
ValueError if a function gets argument of correct type
but improper value.
ZeroDivisionError if second operand of division or
modulo operation
is zero.

Raising Custom Exceptions


You can raise Exceptions yourself to indicate that something went wrong. It is good practice to
use Python's built-in Exception objects whenever this makes sense.
def factorial(n):
if n < 0:

raise ValueError('Factorial expects non-negative

integers') return 1 if n == 0 else n*factorial(n-1)

factorial(-1)

8
Output:

ValueError: Factorial expects non-negative

integers But you can also create custom

Exception objects.

class FactorialError(Exception):

pass def factorial(n):

if n < 0:

raise FactorialError('Factorial expects non-negative

integers') return 1 if n == 0 else n*factorial(n-1)

factorial(-1)

Output:

FactorialError: Factorial expects non-negative integers

Python - Assert Statement


In Python, the assert statement is a powerful tool that helps with debugging and handling errors
during development. It allows you to make assumptions about the code and catch potential issues
early on.
The assert statements can be useful when testing functions or methods, as it allows you to ensure that
the function is behaving as expected. Additionally, assert statements can be used to enforce certain
conditions on the inputs or outputs of a function, such as ensuring that a parameter is within a certain
range or that a return value meets certain criteria.

def division(x,y):

assert y!=0, "y cannot be zero"

print(x/y)

division(10,2) #5

division(10,0) #AssertionError: y cannot be zero

9
Student Exercise
1. Write a python program that prompts the user to enter two numbers and print its quotient. If the
denominator entered is 0, then a ZeroDivisionError is generated

2. Write a python program that opens a file and writes data to it. Handle exceptions that can be
generated during the I/O operations.

Output

Error Working With File

3. Write a python program that will ask a user for a donation amount, it should be a number. If user put
a string value it should generate the exception and handle it appropriately.

4. Write a python program to write an interactive calculator! User input is assumed to be a formula that
consist of a number, an operator (at least + and -), and another number, separated by white space
(e.g. 1 + 1). Split user input using str.split(), and check whether the resulting list is valid:

If the input does not consist of 3 elements, raise a FormulaError, which is a user defined
Exception (Custom Exception).

Try to convert the first and third input to a float (like so: float_value = float(str_value)).
Catch any ValueError that occurs, and instead raise a FormulaError

If the second input is not '+' or '-', again raise a

FormulaError An interaction could look like this:

>>> 1 + 1

2.0

>>> 3.2 - 1.5

1.7000000000000002

>>> quit

10
IQRA University

CSC 333 Introduction to Python

Lab# 10
Modules, Namespaces & Variable Scope

Objective:
This lab introduces the student to the concept of Namespaces and
variable scope. The students are also introduced to the concept of
Module handling within Python

Name of Student:

Roll No:

Date of Experiment:

1
1. Namespace and Scope
A namespace is a system to have a unique name for each and every object in Python. An
object might be a variable or a method. Python itself maintains a namespace in the form of a
Python dictionary. Let’s go through an example, a directory-file system structure in
computers. Needless to say, that one can have multiple directories having a file with the same
name inside of every directory. But one can get directed to the file, one wishes, just by
specifying the absolute path to the file.

Real-time example, the role of a namespace is like a surname. One might not find a single
“Alice” in the class there might be multiple “Alice” but when you particularly ask for “Alice
Lee” or “Alice Clark” (with a surname), there will be only one (time being don’t think of both
first name and surname are same for multiple students).

On the similar lines, Python interpreter understands what exact method or variable one is
trying to point to in the code, depending upon the namespace. So, the division of the word
itself gives little more information. Its Name (which means name, an unique identifier) +
Space(which talks something related to scope). Here, a name might be of any Python method

or variable and space depends upon the location from where is trying to access a variable or a
method.

Types of namespaces:

When Python interpreter runs solely without and user-defined modules, methods, classes, etc.
Some functions like print( ), id( ) are always present, these are built in namespaces. When a
user creates a module, a global namespace gets created, later creation of local functions creates
the local namespace. The built-in namespace encompasses global namespace and global
namespace encompasses local namespace.

Built-in Namespace: This encompasses names like print(), len(), and other functions
provided by Python out of the box. They are accessible globally without needing explicit
imports.

Global Namespace: This includes names defined at the top level of a module or script. They
are visible throughout the entire module.

2
Local Namespace: This is created when a function is called and is temporary, existing only
during the function's execution.

2. Lifetime of a namespace:
A lifetime of a namespace depends upon the scope of objects, if the scope of an object ends,
the lifetime of that namespace comes to an end. Hence, it is not possible to access inner
namespace’s objects from an outer namespace.

Program 1: Write a program to show different types of variables according to their scopes.

Code:
#iqra_1 is in the global namespace
iqra_1 = 5
def some_func():

# cs_2 is in the local namespace


cs_2 = 6
def some_inner_func():

# var3 is in the nested local


# namespace
var3 = 7

As shown in the following figure, same object name can be present in multiple namespaces
as isolation between the same name is maintained by their namespace.

3
But in some cases, one might be interested in updating or processing global variable only, as
shown in the following example, one should mark it explicitly as global and the update or
process.

Program 2: Write a program to show how global scope works and called inside the
function. Similarly, the function updating will affect the value of global variable.

Code:
count = 5
def some_method():
global count
count = count + 1
print(count)
some_method()

3. Importing Modules
A module in Python is essentially a file containing Python definitions, statements, and
functions. It allows for the organization of code into separate files, enhancing modularity
4
and
reusability. Importing a module into your script or module enables you to leverage its
functions and variables.

Importing Entire Module


Importing an entire module is straightforward using the import keyword. For example:

# Importing the math module


import math

# Using a function from the math module


result = math.sqrt(25)

Importing Specific Items


When only specific items are needed from a module, they can be imported directly:

# Importing only the sqrt function from the math module


from math import sqrt

# Using the sqrt function directly


result = sqrt(25)

Importing with an Alias


Aliases can be used to provide shorter names for modules:

# Importing the pandas module with an alias 'pd'


import pandas as pd

Working Between Two Modules


Working with multiple modules involves importing functions, variables, or classes from one
module into another. This promotes code reuse and facilitates a more organized project
structure. Consider two modules: module1.py and module2.py.

module1.py
# module1.py
def greet(name):
return f"Hello, {name}!"

5
module2.py
# module2.py
from module1 import greet

# Using the greet function from module1


message = greet("Alice")
print(message)

In this example, module2 imports the greet function from module1 and seamlessly utilizes it.

sys.path and Module Search Path


The sys.path variable is a list containing directory names where Python searches for
modules. When you import a module, Python scans these directories. Understanding sys.path
is crucial when dealing with modules and packages.

You can modify sys.path to include additional directories, giving you control over the
module search path:

import sys

# Adding a custom directory to sys.path


sys.path.append("/path/to/custom/module")

By managing the module search path, you can effectively organize your project structure
and ensure Python locates the modules you want to import.

6
Student Exercise
Task 1: Create a Python program that explores different types of namespaces and
demonstrates the concept of scope. Follow the steps below:

Global Namespace:
Declare a global variable in the main program scope.
Create a function that tries to access and print the global variable.
Execute the function to observe how the global namespace is accessed.

Local Namespace:
Inside the function created in step 1, declare a local
variable. Print the local variable within the function.
Attempt to access the local variable outside the function to highlight the concept of
local scope.

Nested Local Namespace:


Create a nested function within the function from step
1. Declare a variable in the nested function and print
it.
Attempt to access the nested variable outside both functions to emphasize the nested
local scope.

Updating Global Variable:


Declare a global variable outside any function.
Create a function that updates the global variable. Use the global keyword to indicate
that you are modifying the global variable.
Print the global variable before and after calling the function to demonstrate how
changes in the function affect the global scope.

Task 2: Create two separate Python modules, say module_a.py and module_b.py. In
module_a.py, define a variable var_a and a function func_a(). Print a message within the
function. In module_b.py, import var_a and func_a from module_a.py. Use the imported
variable and call the imported function in module_b.py and print the results.

Task 3: Create a directory named custom_modules. Inside custom_modules, create a


Python module named custom_module.py. In custom_module.py, define a variable or
function. Create another Python script outside of the custom_modules directory. Import
the variable or function from custom_module.py into the external script. Print or use the
imported element to verify that the import is successful. Experiment with modifying
sys.path to include the directory containing custom_module.py and observe the changes
in the import behavior.

7
IQRA University

CSC 333 Introduction to Python

Lab# 11
Object-Oriented Programming

Objective:
This lab introduces the student to the Object Oriented
Programming Paradigm within the Python programming
language

Name of Student:

Roll No:

Date of Experiment:

1
1. Introduction to Class and Class Diagram
 Class diagrams are visual representations of the static structure and composition of a
particular system using the conventions set by the Unified Modeling Language (UML).
 System designers use class diagrams as a way ofsimplifying how objects in a system
interact with each other.
 Using class diagrams, it is easier to describe all the classes, packages, and interfaces
that constitute a system and how these components are interrelated.
 Since class diagrams are used for many different purposes, such as making stakeholders
aware of requirements to highlighting your detailed design, you need to apply a
different style in each Circumstance.

Example

 Simple class diagram may be used to show how an organization such as a convenient
store chain is set up.
 Precisely detailed class diagrams can readily be used as the primary reference for
translating the designed system into a programming code.

2. Notation of Class Diagram

Class

 An object is any person, place, thing, concept, event, screen, or report applicable toyour
system.
 Objects both know things (they have attributes) and they do things (they have methods).
 A class is a representation of an object and, in many ways, it is simply a template from
which objects are created.
 Classes form the main building blocks of an object-oriented application.

Example
Although thousands of students attend the university, you would only model one class, called
Student, which would represent the entire collection of students.

Attributes
An attribute of a class represents a characteristic of a class that is of interest for the user.

The full format of the attribute text notation is:

2
Visibility name: type multiplicity = default [property-string]

Operations
A UML operation is a declaration, with a name, parameters, return type, exceptions list, and
possibly a set of constraints of pre and post conditions. But, it isn’t an implementation –
rather, methods are implementation.

Visibility:
Use visibility markers to signify who can access the information contained within a class.

 Public +
 Private -
 Protected #

3. Relationship
Dependency: class A uses class B Aggregation: class A has a class B Composition: class A
owns a class B
Inheritance: class B is a Class A (or class A is extended by class B)

1. Association
An association is a "using" relationship between two or more objects in which the objects have
their own life time and there is no owner.

For Example: A patient may visit one or many doctors and same way, a doctor can be
associated with multiple patients. If a patient dies, existence of doctor will not be vanished
and similarly if doctor dies patient will remain patient.

Association is represented as thin line connecting two classes. Association can be unidirectional

3
(shown by arrow at one end) or bidirectional (shown by arrow at both end) or without arrow.

Multiplicity defines how many instances can be associated at any given moment.

0..1 No instances or A flight seat can have no or one


one instance passenger
only
1 Exactly one A course can have only one
instance professor conducting it
0..* or * Zero or more A class can have zero or more
instances students.
1..* One or more A flight can have one or more
instances (at passenger
least one)

Example:

Association Wrote between Professor and Book with association ends author and textbook.

2. Aggregation

Aggregation is a special form of association. It is also a relationship between two classes like
association, however, it’s a directional association, which means it is strictly a one way association,
means unidirectional association. It represents a Has-A relationship.

For Example: Consider two classes Student class and Address class. Each student must have an
address so the relationship between student and address is a Has-A relationship. But if you consider
its vice versa then it would not make sense as an Address doesn’t need to have a Student necessarily.

NOTE: Unarguably, Address is an attribute of a student, but here in this example I am breaking
address into several fields i.e city, province and country. This is the reason for making address a class.

3. Composition
Composition is a special case of aggregation. In a more specific manner, a restricted
aggregation is called composition. When an object contains the other object, if the contained
object cannot exist without the existence of container object, then it is called composition.

4
For Example: Consider the same scenario with some modifications. In this scenario, a student
has address and each student has different address (Please keep sibling relationship argument
apart). So, when a student record is added his house number and street number will be
entered. And if I delete the record of a particular student, then his/her record will be of no use.

filled black diamond at the aggregate (whole) end.

Example:

1. Generalization
In object oriented programming, the concept of IS-A is a totally based on Inheritance, which
can be of two types Class Inheritance or Interface Inheritance. It is just like saying "A is a B
type of thing". For example, Apple is a Fruit, Car is a Vehicle etc. Inheritance is uni-
directional. For example House is a Building. But Building is not a House.

It is key point to note that you can easily identify the IS-A relationship. Wherever you see an
extends keyword or implements keyword in a class declaration, then this class is said to have
IS- A relationship.

Case Study1

Library Management System Problem Statement:

The case study titled Library Management System is library management software for the
purpose of monitoring and controlling the transactions in a library. This case study on the library
5
management system gives us the complete information about the library and the daily
transactions done in a Library. We need to maintain the record of new s and retrieve the
details of books available in the library which mainly focuses on basic operations in a library
like adding new member, new books, and up new information, searching books and members
and facility to borrow and return books. It features a familiar and well thought-out, an
attractive user interface, combined with strong searching, insertion and reporting capabilities.
The report generation facility of library system helps to get a good idea of which are borrowed
by the members, makes users possible to generate hard copy.

The following are the brief description on the functions achieved through this case study:

End-Users
• Librarian: To maintain and update the records and also to cater the needs of the users.

Reader: Need books to read and also places various requests to the librarian.
Vendor: To provide and meet the requirement of the prescribed books.

Class Diagram Classes identified: Library

Librarian Books Database User


Vendor

6
Use-case Diagram

Actors vs Use Cases:

Librarian
•Issue a book
•Update and maintain records
•Request the vendor for a book
•Track complaints

User
•Register
•Login
•Search a book
•Request for issue
•View history
•Request to the Librarian
•Unregister
Books
Database
•Update records
•Show books status

Vendors
•Provide books to the library
•Payment acknowledgement

2. The init ( ) Method

The init ( ) method is profound for two reasons. Initialization is the first big step in an
object's life; every object must be initialized properly to work properly. The second reason is
that the argument values for init ( ) can take on many forms.

Because there are so many ways to provide argument values to init ( ), there is a vast array
of use cases for object creation. We take a look at several of them. We want to maximize
clarity, so we need to define an initialization that properly characterizes the problem domain.

Before we can get to the init ( ) method, however, we need to take a look at the implicit

7
class hierarchy in Python, glancing, briefly, at the class named object. This will set the stage
for comparing default behavior with the different kinds of behavior we want from our own
classes.

In this example, we take a look at different forms of initialization for simple objects (for
example, playing cards). After this, we can take a look at more complex objects, such as
hands that involve collections and players that involve strategies and states.

Python is a multi-paradigm programming language. Meaning, it supports different


programming approach.

One of the popular approach to solve a programming problem is by creating objects. This is
known as Object-Oriented Programming (OOP).

An object has two characteristics:

 attributes
 behavior

Let's take an example:


Parrot is an object,

 name, age, color are attributes


 singing, dancing are behavior

The concept of OOP in Python focuses on creating reusable code. This concept is also known
as DRY (Don't Repeat Yourself).

In Python, the concept of OOP follows some basic principles:

1 A process of using details from a new class


Inheritanc
without modifying existing class.
e
2 Enca Hiding the private details of a class from other
psula objects.
t
ion
3 Polymorph A concept of using common operation in different ways
for different data input.
ism

Python Object Inheritance

Inheritance is the process by which one class takes on the attributes and methods of another.
Newly formed classes are called child classes, and the classes that child classes are derived
from are called parent classes.
8
It’s important to note that child classes override or extend the functionality (e.g., attributes
and behaviors) of parent classes. In other words, child classes inherit all of the parent’s
attributes and behaviors but can also specify different behavior to follow. The most basic type
of class is an object, which generally all other classes inherit as their parent.

When you define a new class, Python 3 it implicitly uses object as the parent class. So the
following two definitions are equivalent:

Exercise 1: Write a class of Dog, each dog must be of species type mammal. Each dog has its
name and age. The class can have method for description( ) and sound( ) which dog produces.
Create an object and perform some operations.
class Dog:

# Class Attribute
species = 'mammal'

# Initializer / Instance Attributes


def init (self, name, age): self.name = name
self.age = age
# instance method
def description(self):
return "{ } is { } years old".format(self.name, self.age)

# instance method
def speak(self, sound):
return "{ } says { }".format(self.name, sound)
# Instantiate the Dog object
razer = Dog("Razer", 6)

# call our instance methods


print(razer.description( ))
print(razer.speak("Woof Woof"))

Exercise 2: Write a class of Dog, each dog must be of species type mammal. Each dog has its
name and age. The class can have method for description () and sound () which dog produces.
Now this time you need to create two sub classes of Dogs one is Bull Dog and other is
Russell Terrier Create few objects and perform some operations including the inheritance.

# Parent class
class Dog:
# Class attribute
species = 'mammal'

9
# Initializer / Instance attributes
def init (self, name, age): self.name = name
self.age = age
# instance method
def description(self):
return "{ } is { } years old".format(self.name, self.age)

# instance method
def speak(self, sound):
return "{ } says { }".format(self.name, sound)

# Child class (inherits from Dog class)


class RussellTerrier(Dog):
def run(self, speed):
return "{ } runs { }".format(self.name, speed)

# Child class (inherits from Dog class)


class Bulldog(Dog):
def run(self, speed):
return "{ } runs { }".format(self.name, speed)

# Child classes inherit attributes and # behaviors from the parent class
thunder = Bulldog("Thunder", 9)
print(thunder.description())

# Child classes have specific attributes # and behaviors as well


print(thunder.run("slowly"))

spinter = Bulldog("Spinter", 12)


print(spinter.description( ))
print(spinter.run("fast"))

roger = RussellTerrier("Roger", 5)

print(roger.description( ))
print(roger.run("quickly"))

Exercise 3: Extending question number 2, now we need to check that either the different
dog classes and their objects link with each other or not. In this case we need to create a
method to find either it’s an instance of each other objects or not.

10
# Parent class
class Dog:
# Class attribute
species = 'mammal'

# Initializer / Instance attributes


def init (self, name, age): self.name = name
self.age = age

# instance method
def description(self):
return "{ } is { } years old".format(self.name, self.age)
# instance method
def speak(self, sound):
return "{ } says { }".format(self.name, sound)

# Child class (inherits from Dog() class)


class RussellTerrier(Dog):
def run(self, speed):
return "{ } runs { }".format(self.name, speed)

# Child class (inherits from Dog() class)


class Bulldog(Dog):
def run(self, speed):
return "{ } runs { }".format(self.name, speed)

# Child classes inherit attributes and # behaviors from the parent class
thunder = Bulldog("Thunder", 9)
print(thunder.description())

# Child classes have specific attributes # and behaviors as well


print(thunder.run("slowly"))

# Is thunder an instance of Dog()?


print(isinstance(thunder, Dog))

# Is thunder_kid an instance of Dog()?

11
thunder_kid = Dog("ThunderKid", 2)
print(isinstance(thunder, Dog))

# Is Kate an instance of Bulldog()


Kate = RussellTerrier("Kate", 4)
print(isinstance(Kate, Dog))

# Is thunder_kid and instance of kate?


print(isinstance(thunder_kid, Kate))
print("Thanks for understanding the concept of OOPs")

NOTE:

Make sense? Both thunder_kid and Kate are instances of the Dog() class, while Spinter is
not an instance of the Bulldog() class. Then as a sanity check, we tested if kate is an
instance of thunder_kid, which is impossible since thunder_kid is an instance of a class
rather than a class itself—hence the reason for the TypeError.

12
Student Exercise
Task 1: Create a directory named my_package. Inside my_package, create two Python
modules: ‘module_x.py’ and ‘module_y.py’. In module_x.py, define a class named
ClassX with a method. Also, define a variable var_x. In ‘module_y.py’, import ClassX
and var_x from ‘module_x.py’. Create an instance of ClassX and print the value of var_x
in ‘module_y.py’

Task 2: Design a class structure for a university management system. Create classes for
Students, Professors, Courses, and Departments. Implement methods for enrolling
students in courses, grading assignments, and managing course schedules. Consider
incorporating features like student transcripts and academic advising.

Task 3: Design a comprehensive class structure for an online shopping system. Create
classes for Customers, Products, and Orders. Implement methods for adding products to
the cart, processing orders, and calculating total costs. Consider incorporating concepts
like discounts, shipping fees, and order history.

Task 4: Design a class system for a university course registration system. Create classes
for Courses, Students, and Faculty Members. Implement methods for adding/removing
courses, registering for classes, and managing student schedules. Consider incorporating
features like prerequisite checks and course availability.

13
7
12

You might also like