Download as pdf or txt
Download as pdf or txt
You are on page 1of 82

Lab No.

1
Basics of computer programming and IDE Installation of Python

Learning Objectives:
• To understand the basics of computer programming
• Familiarization with IDE environment of Python
• Writing first program in Python from scratch

Pre-Lab Reading:
Program is a set of instructions used to solve a particular problem. A computer is a dumb
machine. It cannot do anything on its own. It can only act on the given instructions.

Programming:
Computer can only understand a sequence of 1s and 0s. The following looks strange to use but,
in fact is how computer reads and executes everything that it does:

101010001110010101010111100010101110

This is called Machine language. We can imagine how complicated programming would be if
we had to learn this complex language. That in fact, was how programming was done many
years ago; however today we are fortunate to have what are called high level languages such
as C, java and C++, python etc. These languages are more geared for human understanding
and thus make programming much easier. However, computer only understands machine
language, there must be a translation process to convert these high-level languages to
machine code. This is often done by a compiler. Compiler analyzes a program developed in a
particular computer (high level) language and then translates it into a form (machine
language) that is suitable for execution on your computer system. The program that is to be
compiled is first typed into a file on the computer system.

In the first step of the compilation process, the compiler examines each program statement
contained in the source program and checks it to ensure that it conforms to the syntax and
semantics of the language. If any mistakes are discovered by the compiler during this phase,
they are reported to the user and the compilation process ends right there. The errors then
have to be corrected in the source program (with the use of an editor) and the compilation
process must be restarted. Typical errors reported during this phase of compilation might be
due to an expression that has unbalanced parentheses (syntactic error), or due to the use of
a variable that is not “defined” (semantic error). Once we have executable code, the program
is ready to be run. Hopefully it will run, and everything will be fine, however that is not always
the case. During “run time”, we may encounter another kind of error called a run time error.
This error occurs when we ask computer to do something it cannot do. The computer cannot
violate the laws of mathematics and other binding restrictions.
Asking the computer to divide a number by zero is an example of a run time error. We get
executable code; however, when the program tries to execute the command to divide by
zero, the program will stop with a run time error. Run time errors, are usually more
challenging to find than syntax errors. Once we run our program and get neither syntax nor
run time errors, are we free to rejoice? Not exactly. Unfortunately, we may still encounter
the worst type of error: the dreaded Logic error. Whenever we ask the computer to do
something, but mean for it to do something else, we have a logic error. There must be precise
and clear instructions that generate our intentions to the computer. The computer only does
what we ask it to do.

Asking it to multiply by 3 when we want something doubled is an example of a logic error.


This type of error is difficult to identify as compiler cannot detect these errors, the only
possible way is to check that the output/result of your program matches with your
expectations or not.

Environment:
Variables An environment variable is a dynamic "object" on a computer that stores a value,
which in turn can be referenced by one or more software programs in Windows. Environment
variables help programs know what directory to install files in, where to store temporary files,
where to find user profile settings, and other things. It can be said that environment variables
help to create and shape the environment of where a program runs. Two types of
environment variables exist, user environment variables and system environment variables,
as following:

User environment variables:


As the name implies, are environment variables that are specific to each user account. This
means that the value of an environment variable when logged in as one user can be different
than the value of the same environment variable when logged in as a different user on the
same computer.

System environment variables:


Extend beyond just one user, applying to any user that might exist, or is created in the future.
Most system environment variables point to important locations like the Windows folder.

Python:
The Python programming language is useful for all kinds of scientific and engineering tasks.
You can use it to analyze and plot data. You can also use it to numerically solve science and
engineering problems that are difficult or even impossible to solve analytically.

While we want to Python’s powers to address scientific problems, you should know that
Python is a general-purpose computer language that is widely used to address all kinds of
computing tasks, from web applications to processing financial data on wall street and various
scripting tasks for computer system management. Over the past decade it has been
increasingly used by scientists and engineers for numerical computations, graphics, and as a
“wrapper” for numerical software originally written in other languages, like FORTRAN and C.

Python is like MATLAB and IDL, two other computer languages that are frequently used in
science and engineering applications. Like MATLAB and IDL, Python is an interpreted
language, meaning you can run your code without having to go through an extra step of
compiling, as required for the C and FORTRAN programming languages. It is also a dynamically
typed language, meaning you don’t have to declare variables and set aside memory before
using them. Don’t worry if you don’t know exactly what these terms mean.
Their primary significance for you is that you can write Python code, test, and use it quickly with
a minimum of fuss.

One advantage of Python over similar languages like MATLAB and IDL is that it is free. It can
be downloaded from the web and is available on all the standard computer platforms,
including Windows, MacOS, and Linux. This also means that you can use Python without being
tethered to the internet, as required for commercial software that is tied to a remote license
server. Another advantage is Python’s clean and simple syntax, including its implementation
of object-oriented programming (which we do not emphasize in this introduction).

A disadvantage is that Python programs can be slower than compiled languages like C. For
large scale simulations and other demanding applications, there can be a considerable speed
penalty in using Python. In these cases, C, C++, or FORTRAN is recommended, although
intelligent use of Python’s array processing tools contained in the NumPy module can greatly
speed up Python code. Another disadvantage is that compared to MATLAB and IDL, Python is
less well documented.

This stems from the fact that it is public open-source software and thus is dependent on
volunteers from the community of developers and users for documentation. The
documentation is freely available on the web but is scattered among several different sites
and can be terse. This manual will acquaint you with the most used web sites. Search engines
like Google can help you find others.

The Python interpreter and the extensive standard library are freely available in source or
binary form for all major platforms from the Python Web site, https://www.python.org/, and
may be freely distributed. The same site also contains distributions of and pointers to many
free third-party Python modules, programs and tools, and additional documentation. The
Python interpreter is easily extended with new functions and data types implemented in C or
C++ (or other languages callable from C). Python is also suitable as an extension language for
customizable applications.

Python Editor (PyCharm):


PyCharm editor is a powerful tool for creating and modifying source code. As any other IDE
editor, it supports basic features like bookmarks, breakpoints, syntax highlighting, code
completion, zooming, folding code blocks, etc. There are, however, plenty of advanced
features like macros, intelligent and fast navigation, and a lot more.

To configure your editing environment, use the editor settings page and its relevant pages.
There is also a quick switch scheme command that lets you change color schemes, themes,
keymaps, etc. with a couple of keystrokes. The editor is tab-based. All operations with the
editor tabs are available from the context menu of a tab. If you open your project for the very
first time, you see the Welcome Screen.

You can either open your project from the disk or download it from the version control
system. Further, you can configure Python interpreter (in particular, create a virtual
environment), and set up your project. Open your project from disk

• On the Welcome Screen, click the Open link.


• In the Open File or Project dialog that opens, find location of the desired project:
Python print command operators:
To print some sentence or string, you need to write print with single or double quotation
marks to get output besides numbers. Python can manipulate strings in several ways as
enclosed in single quotes ‘…’ or double quotes “…” with the same result. For example, print”
Introduction to computing Lab” print’ Introduction to computing Lab’

When you are using single or double quotes together, then it can be written as:

print “I’d much rather you ‘not’.” print’


I “said” do not touch this.’

When you are using single or double quotes, backslash (\) can be used to escape quotes as:

print’ “Ins, \’t”, she said. ‘ print” \” A sentence/word that


needs quotation marks\””

You can add multiple things of different characters in a single print statement as:

print” Hello”, 11, “you” print ‘Hello’, 11, ‘you’

For printing output on new line, we can use escape character as:

Print ‘Computer systems lab \n first floor, Electrical Engineering Department ‘


Comments in Python:
There are two ways to comment on your code. The first is to include comments that detail or
indicate what a section of code does. The second makes use of multi-line comments or
paragraphs that serve as documentation for others reading your code. So, the first type is
used to comment for yourself and the second as a comment for others.

Single line comments are created simply by beginning a line with the hash (#) character and they
are automatically terminated by the end of line. For example,

# This would be my first comment in Python

Multi line Comments are usually those comments that span multiple lines to explain things in
more detail. It can be created by adding a delimiter (“””) on each end of the comment. For
example,

“”” This would be my first multi-line.

Hello world program in PyCharm environment:

The output of the above program will be,


Lab No. 2
Data types, Arithmetic, logical and assignment operator Learning Objectives:
• To understand the data types and variables in Python language

Pre-Lab Reading:

Variables are nothing but reserved memory locations to store values. This means that when you
create a variable you reserve some space in memory.

Based on the data type of a variable, the interpreter allocates memory and decides what can
be stored in the reserved memory. Therefore, by assigning different data types to variables,
you can store integers, decimals, or characters in these variables.

Assigning Values to Variables:


Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to
assign values to variables. The operand to the left of the = operator is the name of the variable
and the operand to the right of the = operator is the value stored in the variable.

Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and name variables,
respectively. This produces the following result

100
1000.0
John
Multiple Assignment

Python allows you to assign a single value to several variables simultaneously. For example − a
=b=c=1

Here, an integer object is created with the value 1, and all three variables are assigned to the
same memory location. You can also assign multiple objects to multiple variables. For example
– a, b, c =
1,2,"john"

Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and
one string object with the value "john" is assigned to the variable c.

Standard Data Types:


The data stored in memory can be of many types. For example, a person's age is stored as a
numeric value and his or her address is stored as alphanumeric characters. Python has various
standard data types that are used to define the operations possible on them and the storage
method for each of them.

Python has five standard data types –

• Numbers

• String

• List

• Tuple

• Dictionary

Python Numbers

Number data types store numeric values. Number objects are created when you assign a
value to them. For example – var1 = 1 var2 = 10

You can also delete the reference to a number object by using the del statement. The syntax
of the del statement is – del var1[, var2[, var3[...., varN]]]]
You can delete a single object or multiple objects by using the del statement. For example −
del var del var_a, var_b

Python supports four different numerical types –

• int (signed integers)

• long (long integers, they can also be represented in octal and hexadecimal)

• float (floating point real values)

• complex (complex numbers)

Examples
Here are some examples of numbers −

• Python allows you to use a lowercase l with long, but it is recommended that you use
only an uppercase L to avoid confusion with the number 1. Python displays long
integers with an uppercase L.
• A complex number consists of an ordered pair of real floating-point numbers denoted
by x + yj, where x and y are the real numbers and j is the imaginary unit.

Types of Operators:
Python language supports the following types of operators.

• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators

Arithmetic Operators:
Assume variable a holds 10 and variable b holds 20, then –

Logical Operators:
In Python, logic operators are used to perform logical operations on Boolean values ( True or False). Python
provides several logic operators that allow you to combine or modify Boolean values. The main logic
operators in Python are:
1. and: The and operator returns True if both operands are True, and False otherwise. It represents the logical
conjunction operation.
2. or: The or operator returns True if at least one of the operands is True, and False otherwise. It represents
the logical disjunction operation.
3. not: The not operator returns the opposite of the operand's Boolean value. If the operand is True, it
returns False, and if the operand is False, it returns True. It represents the logical negation operation.

Here's an example that demonstrates the usage of logic operators in Python:


a = True
b = False

# Logical AND
result_and = a and b
print(result_and) # Output: False

# Logical OR
result_or = a or b
print(result_or) # Output: True

# Logical NOT
result_not = not a
print(result_not) # Output: False

x = 10
y=5

# Complex logical expression


result = (x > y) and (x % 2 == 0) or (y < 0)
print(result) # Output: True

Assignment Operators:

In Python, assignment operators are used to assign values to variables. They allow you to
store a value in a variable, update the value of a variable, or modify it based on some
operation. Here are the different assignment operators available in Python:
1. =: The assignment operator ( =) is the most basic assignment operator in Python. It assigns
the value on the right-hand side to the variable on the left-hand side. For example:
2. +=: The += operator is a shorthand assignment operator that adds the value on the right-
hand side to the variable on the left-hand side and assigns the result back to the variable. It
is equivalent to x = x + 3. For example:
3. -=, *=, /=, //=, %=, **=: Similar to +=, these are shorthand assignment operators for
subtraction (-=), multiplication (*=), division (/=), floor division (//=), modulus (%=), and
exponentiation (**=) respectively. They perform the respective operation between the
variable on the left-hand side and the value on the right-hand side, and assign the result
back to the variable.
4. <<=, >>=, &=, |=, ^=: These are shorthand assignment operators for bit shifting ( <<= and >>=),
bitwise AND (&=), bitwise OR ( |=), and bitwise XOR (^=). They perform the respective
operation between the variable on the left-hand side and the value on the right-hand side,
and assign the result back to the variable.
Lab No. 3

String operation
Learning Objectives:
• To understand about input command in Python
• To practice different operations using input command
• To Familiarize with the concept of String in Python Pre-Lab Readings:

Theory
The following line of the program displays the prompt, the statement saying, “Press the enter key
to exit”, and waits for the user to act –

raw_input ("\n\nPress the enter key to exit.")

Here, "\n\n" is used to create two new lines before displaying the actual line. Once the user
presses the key, the program ends. This is a nice trick to keep a console window open until
the user is done with an application.

Converting input to integers

Int x = int (input ("\n Plz enter value of x"))

Converting input to floats

float x = float (input ("\n Plz enter value of x"))

Python Strings:
Strings in Python are identified as a contiguous set of characters represented in the quotation
marks. Python allows for either pairs of single or double quotes. Subsets of strings can be
taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the
string and working their way from -1 at the end.

The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator. For example –
str = 'Hello World!'

print str # Prints complete string

print str[0] # Prints first character of the string

print str[2:5] # Prints characters starting from 3rd to 5th

print str[2:] # Prints string starting from 3rd character

print str * 2 # Prints string two times

print str + "TEST" # Prints concatenated string

This will produce the following result –

Hello World! H

llo llo
World!

Hello World! Hello World!

Hello World! TEST

Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, if the
same type of quote starts and ends the string.

The triple quotes are used to span the string across multiple lines. For example, all the following
are legal –

word = 'word' sentence = "This is a


sentence." paragraph = """This is a
paragraph. It is made up of multiple lines
and sentences."""
Comments in Python
A hash sign (#) that is not inside a string literal begins a comment. All characters after the #
and up to the end of the physical line are part of the comment and the Python interpreter
ignores them.

# First comment print "Hello, Python!" # second

comment

This produces the following result –

Hello, Python!

You can type a comment on the same line after a statement or expression –

name = "NFC IEFR" # This is again comment

You can comment multiple lines as follows –

# This is a comment.

# This is a comment, too.

# This is a comment, too.

# I said that already.

Using Blank Lines


A line containing only whitespace, possibly with a comment, is known as a blank line and Python
totally ignores it.
In an interactive interpreter session, you must enter an empty physical line to terminate a
multiline statement.

Lab No. 4
Conditional statement and control structure

Learning Objectives:
• To understand decision making statements in Python
• To understand how to perform if-else checks in Python

• To understand the use of while loop

• To understand the use decision statements with while


loops

• To understand the use of for loop

• To understand the use conditional statements with for


loops

Pre-Lab Readings:

Decision making is anticipation of conditions occurring while execution of the program and
specifying actions taken according to the conditions.

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 –

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 programming language provides following types of decision-making statements. Click the
following links to check their detail.
Let us go through each decision making briefly − Single Statement Suites If the suite of an if
clause consists only of a single line, it may go on the same line as the header statement. Here
is an example of a one-line if clause –

When the above code is executed, it produces the following result –


Lines and Indentation Python provides no braces to indicate blocks of code for class and
function definitions or flow control. Blocks of code are denoted by line indentation, which is
rigidly enforced. The number of spaces in the indentation is variable, but all statements within
the block must be indented the same amount. For example –

However, the following block generates an error –

Thus, in Python all the continuous lines indented with same number of spaces would form a block

Python Comparison Operators

These operators compare the values on either side of them and decide the relation among them.
They are also called Relational operators.

Assume variable a holds 10 and variable b holds 20, then –


Python Assignment Operators
Assume variable a holds 10 and variable b holds 20, then –
Pre-Lab Readings:
A while loop statement in Python programming language repeatedly executes a target statement
if a given condition is true.

Engr. Awais Laws for loops

These laws apply on every kind of loops in different programming languages like Python, C, C++,
C#, Java, Basic, Assembly etc.

Awais Law for loops No. 1

“Loop is a number generating system that generates numbers in a sequence between limits
given by user. Every time when a number is generated by loop it is saved in a variable for
example x. Loop contain three parts initial limit, boundary limit and rule for sequence. For
example, if we want to generate a sequence of 1,2,3,4, 5,.10 in this sequence

Initial limit is x=1, boundary condition is x<=10

Rule to generate next number is x = x + 1”

Awais Law for loops No. 2

“Every time a number is generated and saved in x. Loop will execute code written inside its block.
This block may or may not use number generated by loop”

Syntax
The syntax of a while loop in Python programming language is −

Here, statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is any non-zero value. The loop iterates while the condition is true .

When the condition becomes false, program control passes to the line immediately following
the loop.

In Python, all the statements indented by the same number of character spaces after a
programming construct are part of a single block of code. Python uses indentation as its
method of grouping statements.
Flow Diagram:
Here, key point of the while loop is that the loop might not ever run. When the condition is
tested and the result is false, the loop body will be skipped and the first statement after the
while loop will be executed.

Example

When the above code is executed, it produces the following result –

The block here, consisting of the print and increment statements, is executed repeatedly until
count is no longer less than 9. With each iteration, the current value of the index count is
displayed and then increased by 1.
The Infinite Loop
A loop becomes infinite loop if a condition never becomes FALSE. You must use caution when
using while loops because of the possibility that this condition never resolves to a FALSE value.
This results in a loop that never ends. Such a loop is called an infinite loop.

An infinite loop might be useful in client/server programming where the server needs to run
continuously so that client programs can communicate with it as and when required.

When the above code is executed, it produces the following result−

Above example goes in an infinite loop and you need to use CTRL+C to exit the program.

Using else Statement with Loops

Python supports to have an else statement associated with a loop statement.

• If the else statement is used with a for loop, the else statement is executed when
the loop has exhausted iterating the list.
• If the else statement is used with a while loop, the else statement is executed when
the condition becomes false.

The following example illustrates the combination of an else statement with a while statement
that prints a number if it is less than 5, otherwise else statement gets executed .
When the above code is executed, it produces the following result –

Single Statement Suites


Like the if statement syntax, if your while clause consists only of a single statement, it may
be placed on the same line as the while header. Here is the syntax and example of a one-line
while clause −

It is better not tried above example because it goes into infinite loop, and you need to press
CTRL+C keys to exit.

Pre-Lab Readings:
It can iterate over the items of any sequence, such as a list or a string.

Syntax

If a sequence contains an expression list, it is evaluated first. Then, the first item in the
sequence is assigned to the iterating variable iterating Var. Next, the statements block is
executed. Each item in the list is assigned to iterating Var, and the statement(s) block is
executed until the entire sequence is exhausted.
Flow Diagram:

Example:

Here [] is used for lists it will be described in later experiments. When the above code is
executed, it produces the following result −
Prime numbers using for loops
A prime number is a number which is only divisible by 1 and itself following is the program to
check if number entered by user is prime or not−

When the above code is executed, it produces the following result–

Here, we check if any number between 2 and one minus the number is divisible by the number
if yes, we flag it as composite by writing 0 in prime.

Using else Statement with Loops


Python supports to have an else statement associated with a loop statement

• If the else statement is used with a for loop, the else statement is executed when the
loop has exhausted iterating the list.

• If the else statement is used with a while loop, the else statement is executed when the
condition becomes false.

The following example illustrates the combination of an else statement with a for statement that
searches for prime numbers from 10 through 20.
Here break is used to break the loop when some special condition encounters. When the above
code is executed, it produces the following result –
Lab No. 6
Implementation of Lists, Tuples and Dictionary in Python

Learning Objectives:
• To understand the concept of Tuples and Lists in Python
• To understand the difference between Tuple and Lists
• Usage of loops for accessing lists
• Use of Tuples and Lists in functions
• To understand the concept of Dictionaries in Python
• To understand the nature of dictionaries as collection of keys and values

Pre-lab Reading:
The most basic data structure in Python is the sequence. Each element of a sequence is
assigned a number - its position or index. The first index is zero, the second index is one, and
so forth.

Python has six built-in types of sequences, but the most common ones are lists and tuples, which
we would see in this tutorial.

There are certain things you can do with all sequence types. These operations include indexing,
slicing, adding, multiplying, and checking for membership. In addition, Python has built-in
functions for finding the length of a sequence and for finding its largest and smallest elements.

Python Lists
The list is a most versatile datatype available in Python which can be written as a list of
commas separated values (items) between square brackets. Important thing about a list is
that items in a list need not be of the same type.

Creating a list is as simple as putting different comma-separated values between square brackets.
For example –

Like string indices, list indices start at 0, and lists can be sliced, concatenated and so on .
Accessing Values in Lists
To access values in lists, use the square brackets for slicing along with the index or indices to
obtain value available at that index. For example –

When the above code is executed, it produces the following result –

Updating Lists
You can update single or multiple elements of lists by giving the slice on the left-hand side of
the assignment operator, and you can add to elements in a list with the append () method.
For example –
Note − append () method is discussed in subsequent sec on.

When the above code is executed, it produces the following result –

Delete List Elements


To remove a list element, you can use either the del statement if you know exactly which
element(s) you are deleting or the remove () method if you do not know. For example –

When the above code is executed, it produces following result –


Note − remove () method is discussed in subsequent section.

Basic List Operations


Lists respond to the + and * operators much like strings; they mean concatenation and repetition
here too, except that the result is a new list, not a string.

In fact, lists respond to all the general sequence operations we used on strings in the prior
chapter.

Indexing, Slicing, and Matrixes


Because lists are sequences, indexing and slicing work the same way for lists as they do for strings.
Assuming following input –

Built-in List Functions & Methods


Python includes the following list functions –
Tuple:
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The
differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples
use parentheses, whereas lists use square brackets.

Creating a tuple is as simple as putting different comma-separated values. Optionally you can put
these comma-separated values between parentheses also. For example –

The empty tuple is written as two parentheses containing nothing−

To write a tuple containing a single value you must include a comma, even though there is only
one value –

Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.

Accessing Values in Tuples


To access values in tuple, use the square brackets for slicing along with the index or indices to
obtain value available at that index. For example –

When the above code is executed, it produces the following result –

Updating Tuples
Tuples are immutable which means you cannot update or change the values of tuple
elements. You can take portions of existing tuples to create new tuples as the following
example demonstrates –

When the above code is executed, it produces the following result−

Delete Tuple Elements


Removing individual tuple elements is not possible. There is, of course, nothing wrong with
putting together another tuple with the undesired elements discarded.

To explicitly remove an entire tuple, just use the del statement. For example−

This produces the following result. Note an exception raised, this is because after del tup tuple
does not exist anymore –

Basic Tuples Operations


Tuples respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new tuple, not a string.

In fact, tuples respond to all the general sequence operations we used on strings

Indexing, Slicing, and Matrixes Because tuples are sequences, indexing and slicing work the same
way for tuples as they do for strings. Assuming following input −
No Enclosing Delimiters
Any set of multiple objects, comma-separated, written without identifying symbols, i.e.,
brackets for lists, parentheses for tuples, etc., default to tuples, as indicated in these short
examples –

When the above code is executed, it produces the following result −

Built-in Tuple Functions


Python includes the following tuple functions –
Dictionary:
Each key is separated from its value by a colon (:), the items are separated by commas, and
the whole thing is enclosed in curly braces. An empty dictionary without any items is written
with just two curly braces, like this: {}.

Keys are unique within a dictionary while values may not be. The values of a dictionary can be
of any type, but the keys must be of an immutable data type such as strings, numbers, or
tuples.

Accessing Values in Dictionary


To access dictionary elements, you can use the familiar square brackets along with the key to
obtain its value. Following is a simple example−

When the above code is executed, it produces the following result −


If we attempt to access a data item with a key, which is not part of the dictionary, we get an
error as follows −

When the above code is executed, it produces the following result

Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry,
or deleting an existing entry as shown below in the simple example –

When the above code is executed, it produces the following result –

Delete Dictionary
Elements You can either remove individual dictionary elements or clear the entire contents
of a dictionary. You can also delete entire dictionary in a single operation. To explicitly
remove an entire dictionary, just use the del statement. Following is a simple example −

This produces the following result. Note that an exception is raised because after del dictionary
does not exist anymore –

Note − del () method is discussed in subsequent section.

Properties of Dictionary Keys


Dictionary values have no restrictions. They can be any arbitrary Python object, either standard
objects or user-defined objects. However, same is not true for the keys.

There are two important points to remember about dictionary keys –

(a) More than one entry per key not allowed. Which means no duplicate key is allowed.
When duplicate keys encountered during assignment, the last assignment wins. For example −

When the above code is executed, it produces the following result –


(b) Keys must be immutable. Which means you can use strings, numbers, or tuples as
dictionary keys but something like ['key'] is not allowed. Following is a simple example −

When the above code is executed, it produces the following result−

Built-in Dictionary
Functions & Methods Python includes the following dictionary functions –
Python includes following dictionary methods –
Lab No. 7
Implementation of Functions and formal parameter in Python
Learning Objectives:
• To understand the concept of functions in Python
• To learn how to define a function and how to call it
• Formal parameter

Pre-Lab Readings:
A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reusing.

As you already know, Python gives you many built-in functions like print (), etc. but you can also
create your own functions. These functions are called user-defined functions.

Defining a Function
You can define functions to provide the required functionality. Here are simple rules to define
a function in Python.

• Function blocks begin with the keyword def followed by the function name and
parentheses (()).
• Any input parameters or arguments should be placed within these parentheses. You
can also define parameters inside these parentheses.
• The first statement of a function can be an optional statement - the documentation
string of the function or docstring.
• The code block within every function starts with a colon (:) and is indented.
• The statement returns [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return
None.

Syntax
By default, parameters have a positional behavior, and you need to inform them in the same
order that they were defined.

Example
The following function takes a string as input parameter and prints it on standard screen.

Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be included in the
function and structures the blocks of code.

Once the basic structure of a function is finalized, you can execute it by calling it from another
function or directly from the Python prompt. Following is the example to call print me ()
function –

When the above code is executed, it produces the following result –

Pass by reference vs value All parameters (arguments) in the Python language are passed by
reference. It means if you change what a parameter refers to within a function, the change
also reflects in the calling function. For example −
Here, we are maintaining reference of the passed object and appending values in the same
object. So, this would produce the following result −

There is one more example where argument is being passed by reference and the reference is
being overwritten inside the called function.

The parameter mylist is local to the function changeme. Changing mylist within the function
does not affect mylist. The function accomplishes nothing and finally this would produce the
following result −
Function Arguments
You can call a function by using the following types of formal arguments –

• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments

Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here,
the number of arguments in the function call should match exactly with the function definition.

To call the function printme(), you definitely need to pass one argument, otherwise it gives a
syntax error as follows –

When the above code is executed, it produces the following result –


Keyword arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a
function call, the caller identifies the arguments by the parameter name.

This allows you to skip arguments or place them out of order because the Python interpreter
can use the keywords provided to match the values with parameters. You can also make
keyword calls to the printme() function in the following ways –

When the above code is executed, it produces the following result −

The following example gives clearer picture. Note that the order of parameters does not matter.
When the above code is executed, it produces the following result –

Default arguments
A default argument is an argument that assumes a default value if a value is not provided in
the function call for that argument. The following example gives an idea on default
arguments, it prints default age if it is not passed −

When the above code is executed, it produces the following result –


Variable-length arguments
You may need to process a function for more arguments than you specified while defining the
function. These arguments are called variable-length arguments and are not named in the
function definition, unlike required and default arguments. Syntax for a function with non-
keyword variable arguments is this –

An asterisk (*) is placed before the variable name that holds the values of all nonkeyboard
variable arguments. This tuple remains empty if no additional arguments are specified during
the function call. Following is a simple example −

When the above code is executed, it produces the following result –


The return Statement
The statement returns [expression] exits a function, optionally passing back an expression to
the caller. A return statement with no arguments is the same as return None.

All the above examples are not returning any value. You can return a value from a function as
follows –

When the above code is executed, it produces the following result–

Scope of Variables
All variables in a program may not be accessible at all locations in that program. This depends
on where you have declared a variable.

The scope of a variable determines the portion of the program where you can access a particular
identifier. There are two basic scopes of variables in Python –
• Global variables
• Local variables

Global vs. Local variables


Variables that are defined inside a function body have a local scope, and those defined outside
have a global scope.

This means that local variables can be accessed only inside the function in which they are
declared, whereas global variables can be accessed throughout the program body by all
functions. When you call a function, the variables declared inside it are brought into scope.
Following is a simple example –

When the above code is executed, it produces the following result −

 Formal Parameter:
In Python, formal parameters, also known as function parameters or arguments, are the
variables declared in the function definition. They act as placeholders for the values that
will be passed into the function when it is called. The values passed into the function are
called actual parameters or arguments.
Formal parameters are defined within the parentheses following the function name in the
function definition. Here's an example of a function definition with formal parameters:

def add_numbers ( a, b ): sum = a + b return sum

In this example, a and b are the formal parameters of the add_numbers function. They define
the variables that will hold the values passed into the function. When the function is called,
the values for a and b are provided as actual arguments.

Here's an example of calling the add_numbers function and passing actual arguments:

result = add_numbers( 3 , 5 ) print (result) # Output: 8

In this case, 3 and 5 are the actual arguments that are passed to the add_numbers function.
The value 3 is assigned to the formal parameter a, and the value 5 is assigned to the formal
parameter b. The function then performs the addition and returns the result.

Formal parameters can also have default values assigned to them, making them optional
arguments. Here's an example:

def greet ( name, greeting="Hello" ): message = greeting + ", " + name + "!" return message

In this example, the greeting parameter has a default value of "Hello". If no value is provided
for greeting when calling the greet function, it will use the default value. However, you can
still pass a different value if desired:

print (greet( "John" )) # Output: "Hello, John!" print (greet( "John" , "Hi" )) # Output: "Hi, John!"

In the first call to greet , only the name argument is provided, so the default value of "Hello" is
used. In the second call, both name and greeting arguments are provided, so the value "Hi" is
used instead of the default value.
Lab No. 8
Class and objects
Objectives:
• To understand the use of objects
• To understand how to define objects in Python and its uses with classes
• To understand error handling

Object Oriented Programming:


Python is an object-oriented programming language, which means that it provides features
that support object-oriented programming (OOP). Object-oriented programming has its roots
in the 1960s, but it wasn’t until the mid-1990s that it became the main programming
paradigm used in the creation of new software. It was developed to handle the rapidly
increasing size and complexity of software systems, and to make it easier to modify these
large and complex systems over time. Up to this point we have been writing programs using
a procedural programming paradigm. In procedural programming the focus is on writing
functions or procedures which operate on data. In object-oriented programming the focus is
on the creation of objects which contain both data and functionality together.

User-defined data types:


A class in essence defines a new data type. We have been using several of Python’s built-in
types throughout this course (Integers, Strings, Lists, and Dictionarists) but we can also define
new types if we wish to. Defining a new type in Python is very easy:

Class definitions can appear anywhere in a program, but they are usually near the beginning.
The syntax rules for a class definition are the same as for other control structures. There is a
header which begins with the keyword, class, followed by the name of the class, and ending
with a colon. In most cases, the statements inside a class definition should be function
definitions. Functions defined inside a class have a special name, they are called methods of
the class. The initmethod is a special method that is called just after a variable of the class
type is constructed or instantiated. Variables of the class type are also called instances or
objects of that type.

We are now ready to create our own user-defined type: the Point. Consider the concept of a
mathematical point. In two dimensions, a point is two numbers (coordinates) that are treated
collectively as a single object. In mathematical notation, points are often written in
parentheses with a comma separating the coordinates. For example, (0,0) represents the
origin, and (x,y) represents the point x units to the right and y units up from the origin. A
natural way to represent a point in NFC IEFR, FAISALABAD Electrical Introduction to
Computing Lab Python is with two numeric values.
To define a new user-defined compound type, also called a class to group these two values
into a compound object is as follows:

The __init__ Method and self:


From the class definition, as we seen above, the special method called __init__. This method
is called when a Point object is instantiated. To instantiate a Point object, we call a function
named Point:

The function Point () is called the class constructor . The variable p is assigned a reference to
a new Point object. When calling the function Point (), Python performs some magic behind
the scenes and calls the __init__ method. The __init__ method has a parameter called self.
Every class method must have one parameter and that parameter should be called self. The
self-parameter is a reference to the object on which the method is being called.

Attributes:
The __init__ method above contains the definition of two object variables x and y. Object
variables are also called attributes of the object. Once a Point object has been instantiated, it
is now valid to refer to its attributes:
In this case, the attribute we are selecting is a data item from an instance. Here, the variable
p refers to a Point object, which contains two attributes. Each attribute refers to a number.
The expression p.x means, go to the object p refers to and get the value of x. The purpose of
dot notation is to identify which variable you are referring.

Methods:
__init__ is an example of a class function or method. We can add as many methods as we like
to a class, and this is one of the reasons OOP is so powerful. It’s quite a different way of
thinking about programming. Rather than having functions that act on any old data, in OOP,
the data carries the required functionality around with it. Let’s add a few methods to our
Point class:
Lab No. 10
Inheritance
Learning Objectives:
• To understand the modules in Python
• Concepts of inheritances in OOP

Reading Material:
A module allows you to logically organize your Python code. Grouping related code into a
module makes the code easier to understand and use. A module is a Python object with
arbitrarily named attributes that you can bind and reference.

Simply, a module is a file consisting of Python code. A module can define functions, classes, and
variables. A module can also include runnable code.

Example

The Python code for a module named a name normally resides in a file named aname.py. Here's
an example of a simple module, support.py

The import Statement


You can use any Python source file as a module by executing an import statement in some other
Python source file. The import has the following syntax −

When the interpreter encounters an import statement, it imports the module if the module
is present in the search path. A search path is a list of directories that the interpreter searches
before importing a module. For example, to import the module support.py, you need to put
the following command at the top of the script –
When the above code is executed, it produces the following result –

A module is loaded only once, regardless of the number of times it is imported. This prevents the
module execution from happening repeatedly if multiple imports occur.

The from...import Statement

Pythons from statement lets you import specific attributes from a module into the current
namespace. The from...import has the following syntax –

For example, to import the function Fibonacci from the module fib, use the following statement

This statement does not import the entire module fib into the current namespace; it just
introduces the item Fibonacci from the module fib into the global symbol table of the
importing module.

The from...import * Statement

It is also possible to import all names from a module into the current namespace by using the
following import statement –

This provides an easy way to import all the items from a module into the current namespace;
however, this statement should be used sparingly.
Locating Modules
When you import a module, the Python interpreter searches for the module in the following
sequences –

• The current directory.


• If the module isn't found, Python then searches each directory in the shell variable
PYTHONPATH.
• If all else fails, Python checks the default path. On UNIX, this default path is normally
/user/local/lib/python/.

The module search path is stored in the system module sys as the sys.pathvariable. The
sys.path variable contains the current directory, PYTHONPATH, and the installation-
dependent default.

The PYTHONPATH Variable


The PYTHONPATH is an environment variable, consisting of a list of directories. The syntax of
PYTHONPATH is the same as that of the shell variable PATH.

Here is a typical PYTHONPATH from a Windows system –

And here is a typical PYTHONPATH from a UNIX system –

Namespaces and Scoping


Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable
names (keys) and their corresponding objects (values).

A Python statement can access variables in a local namespace and in the global namespace. If
a local and a global variable have the same name, the local variable shadows the global
variable.

Each function has its own local namespace. Class methods follow the same scoping rule as
ordinary functions.
Python makes educated guesses on whether variables are local or global. It assumes that any
variable assigned a value in a function is local.

Therefore, to assign a value to a global variable within a function, you must first use the global
statement.

The statement global Var Name tells Python that Var Name is a global variable. Python stops
searching the local namespace for the variable.

For example, we define a variable Money in the global namespace. Within the function Money,
we assign Money a value, therefore Python assumes Money as a local variable. However, we
accessed the value of the local variable Money before setting it, so an Unbound Local Error is
the result. Uncommenting the global statement fixes the problem.

The dir () Function T


he dir () built-in function returns a sorted list of strings containing the names defined by a module.

The list contains the names of all the modules, variables and functions that are defined in a
module. Following is a simple example−

When the above code is executed, it produces the following result −


Here, the special string variable __name__ is the module's name, and __file__is the filename
from which the module was loaded.

The global () and locals () Functions

The global () and locals () functions can be used to return the names in the global and local
namespaces depending on the location from where they are called.

If locals () are called from within a function, it will return all the names that can be accessed locally
from that function.

If global () is called from within a function, it will return all the names that can be accessed globally
from that function.

The return type of both these functions is dictionary. Therefore, names can be extracted using
the keys () function.

The reload () Function

When the module is imported into a script, the code in the top-level portion of a module is
executed only once.

Therefore, if you want to execute the top-level code in a module, you can use the reload ()
function. The reload () function imports a previously imported module again. The syntax of
the reload () function is this –
Lab No 11
Polymorphism:

The word "polymorphism" means "many forms", and in programming it refers to


methods/functions/operators with the same name that can be executed on many objects or
classes.

Function Polymorphism:

An example of a Python function that can be used on different objects is the len() function.

String:
For strings len() returns the number of characters:
Input:

x = "Hello World!"

print(len(x))
Output:

12

Tuple:

For tuples len() returns the number of items in the tuple:

Input:

mytuple = ("apple", "banana", "cherry")

print(len(mytuple))

Output:

Dictionary:
For dictionaries len() returns the number of key/value pairs in the dictionary:

Input:

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

print(len(thisdict))

Output:

Class Polymorphism:

Polymorphism is often used in Class methods, where we can have multiple classes with the
same method name.

For example, say we have three classes: Car, Boat, and Plane, and they all have a method
called move():

Input:

class Car:

def __init__(self, brand, model):

self.brand = brand

self.model = model

def move(self):

print("Drive!")

class Boat:

def __init__(self, brand, model):


self.brand = brand

self.model = model

def move(self):

print("Sail!")

class Plane:

def __init__(self, brand, model):

self.brand = brand

self.model = model

def move(self):

print("Fly!")

car1 = Car("Ford", "Mustang")

boat1 = Boat("Ibiza", "Touring 20")

plane1 = Plane("Boeing", "747") for x in (car1, boat1, plane1):

x.move()

Output:

Drive!
Sail!
Fly!

Inheritance Class Polymorphism:

What about classes with child classes with the same name? Can we use polymorphism there?

Yes. If we use the example above and make a parent class called Vehicle, and
make Car, Boat, Plane child classes of Vehicle, the child classes inherits the Vehicle methods, but
can override them:

Input:

class Vehicle:
def __init__(self, brand, model):

self.brand = brand

self.model = model

def move(self):

print("Move!")

class Car(Vehicle):

pass

class Boat(Vehicle):

def move(self):

print("Sail!")

class Plane(Vehicle):

def move(self):

print("Fly!")

car1 = Car("Ford", "Mustang")

boat1 = Boat("Ibiza", "Touring 20")

plane1 = Plane("Boeing", "747")

for x in (car1, boat1, plane1):

print(x.brand)

print(x.model)

x.move()

Output:

Ford
Mustang
Move!
Ibiza
Touring 20
Sail!
Boeing
747
Fly!

The Boat and Plane classes also inherit brand, model, and move() from Vehicle, but they both
override the move() method.

Because of polymorphism we can execute the same method for all classes .
Lab No 12
Graphs (Show Sine, Cosine, Exponential, Polynomial Curves):

Plotting Sine Graph using Matplotlib in Python

Now let’s plot the sine curve using the sine function that is inbuilt into the NumPy library
and plot it using Matplotlib.
Input:
import numpy as np
import matplotlib.pyplot as plt
# Creating x axis with range and y axis with Sine
# Function for Plotting Sine Graph
x = np.arange(0, 5*np.pi, 0.1)
y = np.sin(x)
# Plotting Sine Graph
plt.plot(x, y, color='green')
plt.show()
Output:
Plotting Cosine Graph using Matplotlib in Python:

Now let’s plot the cosine curve using the cosine function that is inbuilt into the NumPy
library and plot it using Matplotlib.
Input:
# Importing required library
import numpy as np
import matplotlib.pyplot as plt
# Creating x axis with range and y axis with Sine
# Function for Plotting Cosine Graph
x = np.arange(0, 5*np.pi, 0.1)
y = np.cos(x)
# Plotting coine Graph
plt.plot(x, y, color='green')
plt.show()
Output:

Plotting Both Combined Sine and Cosine Graph:


From the above two curves, one must think that both of them seem pretty similar. Let’s
look at both of these curves on the same graph then we will be able to detect the
difference between the graph of the two curves.

Input:

# Importing required library


import numpy as np
import matplotlib.pyplot as plt
# Creating x axis with range and y axis
# Function for Plotting Sine and Cosine Graph
x = np.arange(0, 5*np.pi, 0.1)
y1 = np.sin(x)
y2 = np.cos(x)
# Plotting Sine Graph
plt.plot(x, y1, color='green')
plt.plot(x, y2, color='darkblue')
plt.show()
Output:
Lab No 13.
Displaying 3D images in Python:
In this article, we will discuss how to display 3D images using different methods

Module Needed:

 Matplotlib: It is a plotting library for Python programming it serves as a visualization


utility library, Matplotlib is built on NumPy arrays, and designed to work with the
broader SciPy stack.
 Numpy: It is a general-purpose array-processing package. It provides a high-
performance multidimensional array and matrices along with a large collection of
high-level mathematical functions.
 mpl_toolkits: It provides some basic 3d plotting (scatter, surf, line, mesh) tools.
Example No 1:
Input:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Change the Size of Graph using
# Figsize
fig = plt.figure(figsize=(10, 10))
# Generating a 3D sine wave
ax = plt.axes(projection='3d')
# Creating array points using
# numpy
x = np.arange(0, 20, 0.1)
y = np.sin(x)
z = y*np.sin(x)
c=x+y
# To create a scatter graph
ax.scatter(x, y, z, c=c)
# turn off/on axis
plt.axis('off')
# show the graph
plt.show()
Output:

Example No 2:
In this example, we are selecting the 3D axis of the dimension X =5, Y=5, Z=5, and
in np.ones() we are passing the dimensions of the cube. The np.ones () function returns a
new array of given shape and type, with ones.

Input:

import matplotlib.pyplot as plt


from mpl_toolkits.mplot3d import Axes3D
import numpy as np
# Change the Size of Graph using
# Figsize
fig = plt.figure(figsize=(10, 10))
# Generating a 3D sine wave
ax = plt.axes(projection='3d')
# Create axis
axes = [5, 5, 5]
# Create Data
data = np.ones(axes)
# Control Tranperency
alpha = 0.9
# Control colour
colors = np.empty(axes + [4])
colors[0] = [1, 0, 0, alpha] # red
colors[1] = [0, 1, 0, alpha] # green
colors[2] = [0, 0, 1, alpha] # blue
colors[3] = [1, 1, 0, alpha] # yellow
colors[4] = [1, 1, 1, alpha] # grey
# turn off/on axis
plt.axis('off')
# Voxels is used to customizations of
# the sizes, positions and colors.
ax.voxels(data, facecolors=colors, edgecolors='grey')
Output:
Example No3:

In this example, we use numpy.linspace() that creates an array of 10 linearly placed


elements between -1 and 5, both inclusive after that the mesh grid function returns two 2-
dimensional arrays, After that in order to visualize an image of 3D wireframe we require
passing coordinates of X, Y, Z, color(optional).

Input:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#Change the Size of Graph using Figsize
fig = plt.figure(figsize=(10,10))
#Generating a 3D sine wave
ax = plt.axes(projection='3d')
# assigning coordinates
x = np.linspace(-1, 5, 10)
y = np.linspace(-1, 5, 10)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X ** 2 + Y ** 2))
# creating the visualization
ax.plot_wireframe(X, Y, Z, color ='green')
# turn off/on axis
plt.axis('off')
Output:

You might also like