Python For Engineers Lab Manual AY2023 24

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

LAB MANUAL

Subject Code: 102040522


Subject Name: Python for Engineers
AY 2023-2024

Department of Electrical Engineering


G H Patel College of Engineering & Technology
Vallabh Vidyanagar -388 120
Gujarat, India
G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

CERTIFICATE

This is to certify that Mr./Ms. __________________________________ of

______________________ Department, En. No. ___________________ has

satisfactorily completed his/her term work in 102040522: Python for

Engineers for the term ending in Nov/Dec- 2023.

Date of submission: ________________

Faculty In-Charge Head of the Department

Lab Manual – 102040522: Python for Engineers Page 3


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

List of Experiments
Sr
Date Objective of Experiment Marks Sign
No
1 Installation and working with Python

2 Write Python programs to understand control


structures
3 Write Python programs to understand list and
tuples
4 Use conditional statements in Python programs

5 Use loops (for and while) in Python programs

6 Use List, Set and Dictionary Comprehensions

7 Write Python Programs to Plot Data Using Pyplot

8 Write Python programs to create functions and


use functions in the program
9 Import module and use it in Python programs

10 Write Python programs on File Handling

11 Write Python programs on Exception handling

12 Develop programs to learn GUI programming


using Tkinter

Lab Manual – 102040522: Python for Engineers Page 5


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Vision
To be a leader in educating, creating and graduating today's and tomorrow's finest engineers
through investment in the intellectual and human capital of each individual student, focusing
on both breadth and depth of knowledge, multidisciplinary and integrated education, meeting
and exceeding current and future challenges in Electrical Engineering.

Mission

To produce graduates with a strong foundation of scientific and engineering knowledge.


To foster acquired knowledge and develop technology through excellence in research, in
core as well as in the interdisciplinary fields related to Electrical Engineering.
To contribute to the sustainable development of the nation and the quality of life of the
people through leadership in professionalism, education, research and public services.

Programme Specific Outcomes (PSO)

An ability to acquire fundamental knowledge of electrical engineering and apply them to


electrical domains such as power system, electrical machines, power electronics,
automation and control etc.
An ability to solve complex engineering problems using various software and hardware
tools and develop analytical skills for economical and optimal solutions.
Able to create social and environmental awareness along with ethical responsibility and
enthusiasm for real world applications.

Programme Outcomes (POs)


PO1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.
PO2. Problem analysis: Identify, formulate, research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
PO3. Design/development of solutions: Design solutions for complex engineering problems
and design system components or processes that meet the specified needs with
appropriate consideration for the public health and safety, and the cultural, societal,
and environmental considerations.
Lab Manual – 102040522: Python for Engineers Page 7
G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

PO4. Conduct investigations of complex problems: Use research-based knowledge and


research methods including design of experiments, analysis and interpretation of data,
and synthesis of the information to provide valid conclusions.
PO5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
PO6. The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
PO7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of,
and need for sustainable development.
PO8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
PO9. Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
PO10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend
and write effective reports and design documentation, make effective presentations,
and give and receive clear instructions.
PO11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a
member and leader in a team, to manage projects and in multidisciplinary
environments.
PO12. Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.

Course Outcomes (COs)

After learning the course the students should be able to:


Able to write, test and debug code written in python
Develop python programs using conditional statements and loops
Define Python functions and use Python data structures–lists, tuples, dictionaries.
Perform file operations to read, write and append data in files
Create GUI applications in Python

Lab Manual – 102040522: Python for Engineers Page 8


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Laboratory Safety Information


Introduction
The danger of injury or death from electrical shock, fire, or explosion is present while
conducting experiments. To work safely, it is important that you understand the prudent
practices necessary to minimize the risks and what to do if there is an accident.

Electrical Shock
Avoid contact with conductors in energized electrical circuits. Electrocution has been reported
at dc voltages as low as 42 volts. Just 100ma of current passing through the chest is usually
fatal. Muscle contractions can prevent the person from moving away while being electrocuted.
• Do not touches someone who is being shocked while still in contact with the electrical
conductor or you may also be electrocuted. Instead, switch off the main supply, this
shuts off all power.
• Make sure your hands are dry. The resistance of dry, unbroken skin is relatively high and
thus reduces the risk of shock. Skin that is broken, wet or damp with sweat has a low
resistance.
• When working with an energized circuit, work with only your right hand, keeping your
left hand away from all conductive material. This reduces the likelihood of an accident
that results in current passing through your heart.
• Be cautious of rings, watches, and necklaces. Skin beneath a ring or watch is damp,
lowering the skin resistance. Shoes covering the feet are much safer than sandals.

Fire
Transistors and other components can become extremely hot and cause severe burns if
touched. If resistors or other components on your proto-board catch fire, turn off the power
supply and notify the instructor. If electronic instruments catch fire, switch off the main supply,
this shuts off all power. These small electrical fires extinguish quickly after the power is shut off.
Avoid using fire extinguishers on electronic instruments.

Explosion
When using electrolytic capacitors, be careful to observe proper polarity and do not exceed the
voltage rating. Electrolytic capacitors can explode and cause injury.

Lab Manual – 102040522: Python for Engineers Page 9


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Experiment No.: 1

Aim: Installation and working with Python

Introduction:
Python is an easy-to-learn programming language that has some really useful features for a
beginning programmer. The code is quite easy to read when compared to other programming
languages, and it has an interactive shell into which you can enter your programs and see them
run. Python is a general-purpose programming language that can be used effectively to build
almost any kind of program that does not need direct access to the computer’s hardware.
Because Python is designed to be interpreted, it can provide the kind of runtime feedback that
is especially helpful to novice programmers. There are also a large number of freely available
libraries that interface to Python and provide useful extended functionality.

Python has the following features:


Python has simple, conventional syntax. Python statements are very close to those of
pseudocode algorithms, and Python expressions use the conventional notation found in
algebra. Thus, students can spend less time learning the syntax of a programming language
and more time learning to solve interesting problems.
Python has safe semantics. Any expression or statement whose meaning violates the
definition of the language produces an error message.
Python scales well. It is very easy for beginners to write simple programs in Python. Python
also includes all of the advanced features of a modern programming language, such as
support for data structures and object-oriented software development, for use when they
become necessary.
Python is highly interactive. Expressions and statements can be entered at an interpreter’s
prompts to allow the programmer to try out experimental code and receive immediate
feedback. Longer code segments can then be composed and saved in script files to be
loaded and run as modules or standalone applications.
Python is general purpose. In today’s context, this means that the language includes
resources for contemporary applications, including media computing and networks.
Python is free and is in widespread use in industry. Students can download Python to run on
a variety of devices. There is a large Python user community, and expertise in Python
programming has great resume value.

Lab Manual – 102040522: Python for Engineers Page 11


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Basic Elements of Python:


A Python program, sometimes called a script, is a sequence of definitions and commands. These
definitions are evaluated and the commands are executed by the Python interpreter in
something called the shell. Typically, a new shell is created whenever execution of a program
begins. Usually a window is associated with the shell.
A command, often called a statement, instructs the interpreter to do something. For example,
the statement print('Hello!') instructs the interpreter to call the function print, which will
output the string Hello! to the window associated with the shell. The sequence of commands

print('Hello!')
print('I am Mukesh!')
print('Department of Electrical Engineering,', 'GCET!')

causes the interpreter to produce the output

Hello!
I am Mukesh!
Department of Electrical Engineering, GCET!

Notice that two values were passed to print in the third statement. The print function takes a
variable number of arguments separated by commas, and prints them, separated by a space
character, in the order in which they appear.

Terminology:
Python: A programming language, the language you write computer programs in.
Anaconda: A Python distribution: A single download that conveniently packages all of the
above and installs it on your computer.
IPython: A Python interpreter: A computer application that provides a convenient and
interactive mode for executing Python commands and programs.
Spyder: An integrated development environment (IDE)
Jupyter: A web application that allows to create and run IPython in the browser. A
computer application that includes IPython, a text editor for writing and debugging
programs, and more
NumPy: A standard library that provides numerical arrays and mathematical functions.
PyPlot: A module that provides visualization tools.

Lab Manual – 102040522: Python for Engineers Page 12


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Python IDE’s
Typing programs directly into the shell is highly inconvenient. Most programmers prefer to use
some sort of text editor that is part of an integrated development environment (IDE). One IDE,
IDLE comes as part of the standard Python installation package. As Python has grown in
popularity, other IDE’s have sprung up. These newer IDE’s often incorporate some of the more
popular Python libraries and provide facilities not provided by IDLE. Anaconda and Canopy are
among the more popular of these IDE’s.
All of the Python IDE’s provide
A text editor with syntax highlighting, auto completion, and smart indentation,
a shell with syntax highlighting, and
an integrated debugger

Installing Anaconda on Windows:


Anaconda is a free and open-source distribution of the Python programming language for
scientific computing (data science, machine learning applications, large-scale data processing,
predictive analytics, etc.), that aims to simplify package management and deployment.
It is developed and maintained by Anaconda, Inc., which was founded by Peter Wang and Travis
Oliphant in 2012. As an Anaconda, Inc. product, it is also known as Anaconda Distribution.

Follow the steps below to install the Anaconda distribution of Python on Windows.

Steps:
1. Visit Anaconda.com/downloads
2. Select Windows
3. Download the .exe installer
4. Open and run the .exe installer
5. Start Anaconda with Windows start menu

1. Visit the Anaconda downloads page


• Go to the following link: anaconda.com/downloads
• The Anaconda Downloads Page will look something like this:

Lab Manual – 102040522: Python for Engineers Page 13


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

2. Select Windows
• Select Windows where the three operating systems are listed.

3. Download
• Download the most recent Python 3 release. At the time of writing, the most recent
release was the Python 3.7 Version. If you are unsure if your computer is running a 64-
bit or 32-bit version of Windows, select 64-bit as 64-bit Windows is most common.

Lab Manual – 102040522: Python for Engineers Page 14


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

• You may be prompted to enter your email. You can still download Anaconda if you
click ‘No Thanks’ and don't enter your Work Email address.
• The download is quite large, so it may take a while to for Anaconda to download.

4. Open and run the installer


• Once the download completes, open and run the .exe installer
• Click Next.
• Read the licensing terms and click “I Agree”.
• Select an install for “Just Me” unless you’re installing for all users (which requires
Windows Administrator privileges) and click Next.

• Choose whether to add Anaconda to your PATH environment variable. We recommend


not adding Anaconda to the PATH environment variable, since this can interfere with
other software. Instead, use Anaconda software by opening Anaconda Navigator or the
Anaconda Prompt from the Start Menu.

Lab Manual – 102040522: Python for Engineers Page 15


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

• Choose whether to register Anaconda as your default Python. Unless you plan on
installing and running multiple versions of Anaconda or multiple versions of Python,
accept the default and leave this box checked.
• Click the Install button. If you want to watch the packages Anaconda is installing, click
Show Details.
• Click the Next button.

Lab Manual – 102040522: Python for Engineers Page 16


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

• After a successful installation you will see the “Thanks for installing Anaconda” dialog
box:
• Your Anaconda is ready for you to become the next programmer legend! Click "Finish".

5. Start Anaconda with Windows start menu


• Find the new Start menu item "Anaconda" (the exact location may depend on the
Windows version you're using) and click "Spyder". This is the editor that we shall be
using.

Lab Manual – 102040522: Python for Engineers Page 17


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

• Spyder is s a powerful IDE (interactive development environment) for the Python


language with advanced editing, interactive testing, debugging and introspection
features.
• The name SPyDER derives from "Scientific Python Development EnviRonment"
• Useful features include:
✓ An advanced editor with syntax highlighting and code completion help.
✓ A console to run and test the scripts.
✓ A debugger to find errors in the code running it line by line and checking the content of
the variables.

• Write a test program, for example:


p r i n t ( ” Hell o , World ! ” )

• Go to the ”Run” menu, then click on the ”Run” item (or just press F5).
• With the first run of the program, Spyder will ask about some basic options.
• In this window, select ”Execute in a new dedicated Python console”, which means that
each run of the program will go clean, without variable values from the previous runs
(which could cause weird errors).
• Your program runs in the bottom right part of the editor:

Lab Manual – 102040522: Python for Engineers Page 18


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

• If you need to fix your program settings from the first run, you can do so in menu ”Run”
by clicking ”Configure...” (Ctrl+F6).
• If your installation and “Hello world” test succeeded, then:
• Try to modify some parts of the code and see what happens when you run it.

Exercise: Run the following program and write your comments.


# 3151108 - Python Programming
# My First Program

"""
#%% starts a new cell. Use second green triangle to run just the cell that your mouse has last
clicked in (or Ctrl-Enter on a PC or Menu>Run>Run Cell)
"""
#%%
def hello():
print("Hello, world!")

#%%
def myName():
print("My name is (type your name here)")

#%%
def myEnno():
print("My Enrollment number is (type your enrollment here)")

#%%
def ourCollege():
print("GCET is our College")

#%%
hello()
myName()
myEnno()
ourCollege()

Lab Manual – 102040522: Python for Engineers Page 19


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Questions:
1. What is Python?
2. Name some of the features of Python.
3. Is python a case sensitive language?
4. What is an Interpreted language?
5. How to write single-line and multi-line comments in Python?

Lab Manual – 102040522: Python for Engineers Page 20


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Experiment No.: 2
Aim: To understand control structure, data types, arithmetic operators and
strings in Python.

Python control structures:


Any computer program can be written using the basic control structures. A control structure (or
flow of control) is a block of programming that analyses variables and chooses a direction in
which to go based on given parameters. In simple sentence, a control structure is just a decision
that the computer makes. So, it is the basic decision-making process in programming and flow
of control determines how a computer program will respond when given certain conditions and
parameters.

There are two basic aspects of computer programming: data and instructions. To work with
data, you need to understand variables and data types; to work with instructions; you need to
understand control structures and statements. Flow of control through any given program is
implemented with three basic types of control structures: Sequential, Selection and
Repetition.

Data types in Python:


The way bytes in memory are interpreted is determined by the type of the value or object and
the operations we apply to these values. Each value in Python is called an object. Each object is
of a particular type. There are various data types in Python. Some of the important types are
listed below.

Lab Manual – 102040522: Python for Engineers Page 21


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Numeric Types: int, float, complex


Text Type: str (string)
Boolean Type: bool
Sequence Types: list, tuple, range
Mapping Type: dict (dictionary )
Set Types: set

In Python, the data type is set when you assign a value to a variable:

x1 = 10 int
x2= 10.5 float
x3 = 2+1j complex
x4= "Hi from GCET!" str

If you want to specify the data type, you can use the following constructor functions.

x1 = int(10)
x2 = float(10.5)
x3 = complex(2+1j)
x4 = str(" Hi from GCET!" )

Integers can be of any length, it is only limited by the memory available. A floating-point
number is accurate up to 15 decimal places. Integer and floating points are separated by
decimal points. 1 is an integer, 1.0 is a floating-point number.
Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary
part. Here are some examples. String is sequence of Unicode characters. We can use single
quotes or double quotes to represent strings. Multi-line strings can be denoted using triple
quotes, ''' or """.

Escape Sequences:
Escape sequences are the way Python expresses special characters, such as the tab, the
newline, and the backspace (delete key), as literals. The newline character \n is called an escape
sequence. Because the backslash is used for escape sequences, it must be escaped to appear as
a literal character in a string. Thus, print(“\\”) would display a single \ character. Table lists
some escape sequences in Python.

Lab Manual – 102040522: Python for Engineers Page 22


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Escape sequence Meaning

\n Newline

\t Horizontal Tab

\b Backspace

\\ The \ character

\' Single quotation mark

\" Double quotation mark

Arithmetic Operators:
An arithmetic expression consists of operands and operators combined in a manner that is
already familiar to you from learning algebra. Table shows several arithmetic operators and
gives examples of how you might use them in Python code.

Operator Name Expression Meaning


+ Addition x+y Sum of x and y
Subtraction or x-y or Difference of x and y
-
Negation -x Negation of x
* Multiplication x*y Product of x and y
/ Division x/y Division of x and y
% Modulus x%y Remainder of x divided by y
** Exponent x**y x to the power y
Quotient of x divided by y, decimal
// Floor Division x//y
point are removed

Precedence Rules:
The precedence rules you learned in algebra apply during the evaluation of arithmetic
expressions in Python.

Lab Manual – 102040522: Python for Engineers Page 23


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

o Exponentiation has the highest precedence and is evaluated first.


o Unary negation is evaluated next, before multiplication, division, and remainder.
o Multiplication, both types of division, and remainder are evaluated before addition and
subtraction.
o Addition and subtraction are evaluated before assignment.
o With two exceptions, operations of equal precedence are left associative, so they are
evaluated from left to right. Exponentiation and assignment operations are right
associative, so consecutive instances of these are evaluated from right to left.
o You can use parentheses to change the order of evaluation.

Parenthesis
Power
Multiplication
Addition
Left to Right
Exercise:
1. The type function: The type() function returns the type of the specified object. Execute
the following code and write the output.

Lab Manual – 102040522: Python for Engineers Page 24


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

2. Evaluate following expressions in Python.


a) 5+2*3, b) (5+2)*3, c) 6%2, d) 2*3**2, e) 4-5+2*4/2
f) -2**3, g) (-2)**3, h) 2**3**2, i) (2**3)**2 j) 6/2*3+4%2-2
3. Write a Python program to solve Quadratic Equation.
4. Write a Python program to find simple interest for given principal amount, time and rate
of interest.
5. Write a Python program to convert Celsius into Fahrenheit temperature.
6. Write a Python program to find perimeter of rectangle.
7. Write a Python program which accepts the radius of a circle from the user and compute
the area.
8. Write a Python program to compute distance between two points taking input from the
user (Pythagorean Theorem).
9. Write a Python program to compute area of triangle with three sides (Heron’s Formula).
Take input from user.
10. Write a Python command to display the following message.
Hello!, Welcome to
the world of 'Python'.

Lab Manual – 102040522: Python for Engineers Page 25


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Experiment No.: 3

Aim: Write Python programs to understand list and tuples.

Lists:
A list is a sequence of data values called items or elements. The items or elements can be of
any types. The len function returns the number of elements in its list argument. Here are some
real-world examples of lists:
o A shopping list for the grocery store
o A to-do list
o A roster for an athletic team
o A guest list for a wedding
o A recipe, which is a list of instructions
o A text document, which is a list of lines
o The words in a dictionary
o The names in a phone book

The logical structure of a list is similar to the structure of a string. Each of the items in a list is
ordered by position. Like a character in a string, each item in a list has a unique index that
specifies its position. The index of the first item is 0, and the index of the last item is the length
of the list minus 1. As sequences, lists and strings share many of the same operators, but
include different sets of methods.

Tuples:
A tuple is a type of sequence that is similar to a list, except that, unlike a list, a tuple is
immutable. You indicate a tuple literal in Python by enclosing its elements in parentheses
instead of square brackets. You can use most of the operators and functions used with lists in a
similar fashion with tuples. For the most part, anytime you foresee using a list whose structure
will not change, you can, and should, use a tuple instead. For example, the set of vowels and
the set of punctuation marks in a text-processing application could be represented as tuples of
strings.

List/Tuple concatenation is done using + operator which returns a new list consisting of the
elements of the two operands. Comparison operators are used to compares the elements at
the corresponding positions in the operand lists/tuples. It returns True if all the results are true,
or False otherwise.

Lab Manual – 102040522: Python for Engineers Page 27


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Following built-in functions can be used along with List as well as Tuple.

Built-in function Meaning

len() Returns number of elements in list/tuple

max() If list/tuple contains numbers, largest number will be returned. If


list/tuple contains strings, one that comes last in alphabetical order
will be returned.
min() If list/tuple contains numbers, smallest number will be returned. If
list/tuple contains strings, one that comes first in alphabetical order
will be returned.
sum() Returns addition of all elements in list/tuple

sorted() sorts the elements in list/tuple

Examples:

Lab Manual – 102040522: Python for Engineers Page 28


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

If items in list/tuple are strings, min() and max() functions returns string that comes first/last
in alphabetical order. If list/tuple is made up of numeric and nonnumeric values, TypeError
exception is raised as comparison of dissimilar objects is not possible.

Examples:

The built-in list class has following methods to perform various operations on list object.

Built-in type Meaning

append() appends an object to end of list

copy() makes a shallow copy of list

count() return number of occurrences of value in list

extend() extends the list by appending elements from another list/tuple

insert() inserts object in the list before given index

Lab Manual – 102040522: Python for Engineers Page 29


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

removes and returns item at given index . Raises IndexError if list is


pop()
empty or index is out of range.
removes first occurrence of value in the list. Raises ValueError if the
remove()
value is not present.

clear() remove all items from the list

reverse() reverses the list in place

sort() sorts the list in place

Examples:

Lab Manual – 102040522: Python for Engineers Page 30


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Examples:

Exercise:
1. Write a Python program to find following for the given list/tuple.
a) length b) sum c) min d) max
2. Write a Python program to sort the elements in a list/tuple in descending order.
3. Write a Python program to interchange first and last elements in a list.
4. Write a Python program to swap two elements in a list.
5. Write a Python program to print all the common elements of two lists.
6. Write a Python program to remove the first occurrence of a specified element from a
list.
7. Write a Python program which takes a list and returns a list with the elements shifted
left by one position. Example: [1, 2, 3] → [2, 3, 1].
8. Create a list of your five friends. Write a Python program to find max, min and sort the
names in alphabetical order.

Lab Manual – 102040522: Python for Engineers Page 31


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Experiment No.: 4

Aim: Use conditional statements in Python programs

Selection:
We have seen that computers can work through long sequences of instructions and that they
can do so repeatedly. However, not all problems can be solved in this manner. In some cases,
instead of moving straight ahead to execute the next instruction, the computer might be faced
with two alternative courses of action. The computer must pause to examine or test a
condition, which expresses a hypothesis about the state of its world at that point in time. If the
condition is true, the computer executes the first alternative action and skips the second
alternative. If the condition is false, the computer skips the first alternative action and executes
the second alternative. In other words, instead of moving blindly ahead, the computer exercises
some intelligence by responding to conditions in its environment. Hence, we explore several
types of selection statements, or control statements, that allow a computer to make choices.

The Boolean Type and Comparisons:


Before you can test conditions in a Python program, you need to understand the Boolean data
type, which is named for the nineteenth century British mathematician George Boole. The
Boolean data type consists of only two data values—True and False. In Python, Boolean literals
can be written in several ways, but most programmers prefer the use of the standard values
True and False. The condition in a selection statement often takes the form of a comparison.
For example, you might compare value A to value B to see which one is greater. The result of
the comparison is a Boolean value. It is either true or false that value A is greater than value B.
To write expressions that make comparisons, you have to be familiar with Python’s comparison
operators, which are listed in Table.

Operator Name Expression Meaning


== Equal x==y True if x is equal to y
!= Not equal x!=y True if x is not equal to y
> Greater than x>y True if x is greater than y
< Less than x<y True if x is less than y
>= Greater than or equal to x>=y True if x is greater than or equal to y
<= Less than or equal to x<=y True if x is less than or equal to y

Lab Manual – 102040522: Python for Engineers Page 33


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Logical Operators and Compound Boolean Expressions:


Often a course of action must be taken if either of two conditions is true. For example, valid
inputs to a program often lie within a given range of values. Any input above this range should
be rejected with an error message, and any input below this range should be dealt with in a
similar fashion. The two conditions can be combined in a Boolean expression that uses the
logical operator. The resulting compound Boolean expression simplifies the code somewhat. To
write compound Boolean expression, you have to be familiar with Python’s logical operators,
which are listed in Table.

Operator Expression Meaning


and x and y True if both x and y are True, returns False otherwise
or x or y True if either x or y is True, returns False otherwise
The not operator expects a single operand and returns its
not not x
logical negation, True, if it’s false, and False if it’s true.

if statement:
if statement is the most simple decision making statement. It is used to decide whether a
certain statement or block of statements will be executed or not i.e if a certain condition is true
then a block of statement is executed otherwise not.

Syntax:

In the form shown above:


<expr> is an expression evaluated in Boolean context, as discussed in the section on Logical
Operators.
<statement> is a valid Python statement, which must be indented.

Lab Manual – 102040522: Python for Engineers Page 34


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

if-else Statement:
The if-else statement is the most common type of selection statement. It is also called a two-
way selection statement, because it directs the computer to make a choice between two
alternative courses of action. The if-else statement is often used to check inputs for errors and
to respond with error messages if necessary. The alternative is to go ahead and perform the
computation if the inputs are valid. For example, suppose a program inputs the area of a circle
and computes and outputs its radius. Legitimate inputs for this program would be positive
numbers. But, by mistake, the user could still enter a zero or a negative number. Because the
program has no choice but to use this value to compute the radius, it might crash (stop running)
or produce a meaningless output.

Syntax:
if <expr>:
<statement(s)>
else:
<statement(s)>
<following statements>

In the form shown above:


<expr> is an expression evaluated in Boolean context, as discussed in the section on Logical
Operators.
<statement> is a valid Python statement, which must be indented.

Lab Manual – 102040522: Python for Engineers Page 35


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

if-elif-else Statement:
Using if-elif-else user can decide among multiple options. This is also called multi-way if
statement. The if statements are executed from the top down. As soon as one of the conditions
controlling the if is true, the statement associated with that if is executed, and the rest of the
ladder is bypassed. If none of the conditions is true, then the final else statement will be
executed.

Syntax:
if <expr>:
<statement(s)>
elif <expr>:
<statement(s)>
elif <expr>:
<statement(s)>
...
else:
<statement(s)>
<following statements>

Lab Manual – 102040522: Python for Engineers Page 36


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Compound Boolean expression:


The two conditions can be combined in a Boolean expression that uses the logical operator
or/and. The resulting compound Boolean expression simplifies the code somewhat, as follows:

Lab Manual – 102040522: Python for Engineers Page 37


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Exercise:
1. Assume that x is 3 and y is 5. Write the values of the following expressions:
a) x == y b) x > y – 3 c) x <= y – 2 d) x == y or x > 2
e) x != 6 and y > 10 f) x > 0 and x < 100
2. Write a program that prints “number is Even” if the input value is even and “number is
Odd” otherwise.
3. Write a program that accepts two numbers and prints large and small number.
4. Write a program that accepts the lengths of three sides of a triangle as inputs. Check
whether a triangle is equilateral, isosceles or scalene.
5. Write a program that accepts the lengths of three sides of a triangle as inputs. The
program output should indicate whether or not the triangle is a right triangle.
6. Write a program that accepts input number and check whether input number exists in
the given list or not.
7. Write a program to determine and print the letter grade corresponding to an input
numeric grade. (Consider GTU letter grade and numeric grad relation).
8. Create an if statement that checks whether the amount of money contained in the
variable money is between 100 and 500 or between 1,000 and 5,000.
9. Explain how to check for an invalid input number and prevent it being used in a
program. You may assume that the user enters a number.
10. Does the Boolean expression count >0 and total // count > 0 contain a potential error?
If not, why not?

Lab Manual – 102040522: Python for Engineers Page 38


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Experiment No.: 5

Aim: Use loops (for and while) in Python programs

Loops:
All the programs you have studied so far have consisted of short sequences of instructions or
selections that are executed one after the other. Even if we allowed the sequence of
instructions to be quite long, this type of program would not be very useful. Like human beings,
computers must be able to repeat a set of actions. Repetition statements, also known as loops,
repeat an action. Each repetition of the action is known as a pass or iteration. There are two
types of loops: those that repeat an action a predefined number of times (definite iteration)
and those that perform the action until the program determines that it needs to stop (indefinite
iteration). First we will examine Python’s for loop, the control statement that most easily
supports definite iteration.

for Loops:
It has the ability to iterate over the items of any sequence, such as a list or a string. The Python
for loop starts with the keyword "for" followed by an arbitrary variable name, which will hold
the values of the following sequence object, which is stepped through. The general syntax looks
like this:

Syntax of for Loop:

for val in sequence:


Body of for

Here, val is the variable that takes the value of the item inside the sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is separated
from the rest of the code using indentation.

Lab Manual – 102040522: Python for Engineers Page 39


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Example_1:

Example_2:

Example_3:

Lab Manual – 102040522: Python for Engineers Page 40


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

range() function:
To loop through a set of code a specified number of times, we can use the range() function. The
range() function returns a sequence of numbers, starting from 0 by default, and increments by
1 (by default), and ends at a specified number. However it is possible to specify the increment
value by adding a third parameter: range(begin, end, step), Ex: range(2, 20, 3).

Example_4:

Example_5:

while Loop:
Earlier we examined the for loop, which executes a set of statements a definite number of
times specified by the programmer. In many situations, however, the number of iterations in a
loop is unpredictable. The loop eventually completes its work, but only when a condition
changes. For example, the user might be asked for a set of input values. In that case, only the
user knows the number he will enter. The program’s input loop accepts these values until the

Lab Manual – 102040522: Python for Engineers Page 41


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

user enters a special value that terminates the input. This type of process is called conditional
iteration. Conditional iteration requires that a condition be tested within the loop to determine
whether the loop should continue. Such a condition is called the loop’s continuation condition.
If the continuation condition is false, the loop ends. If the continuation condition is true, the
statements within the loop are executed again.

Syntax:

while <expr>:
<statement(s)>

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.

The form of while statement is almost identical to that of the one-way selection statement.
However, the use of the reserved word while instead of if indicates that the sequence of
statements might be executed many times, as long as the condition remains true. Clearly,
something eventually has to happen within the body of the loop to make the loop’s
continuation condition become false. Otherwise, the loop will continue forever, an error known
as an infinite loop. At least one statement in the body of the loop must update a variable that
affects the value of the condition. The while loop is also called an entry-control loop, because
its condition is tested at the top of the loop.

Example_6:

Lab Manual – 102040522: Python for Engineers Page 42


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

break and continue Statement:


In Python, break and continue statements can alter the flow of a normal loop. Loops iterate
over a block of code until the test expression is false, but sometimes we wish to terminate the
current iteration or even the whole loop without checking test expression. So, break and
continue statements are used.

Example_7:

Lab Manual – 102040522: Python for Engineers Page 43


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Example_8:

Exercise:
1. Write a program to find the factors of a number.
2. Write a program to display only odd numbers from the given list.
3. Write a program to find the factorial of a number. (The factorial of a number is the
product of all the integers from 1 to that number. Factorial is not defined for negative
numbers, and the factorial of zero is one.)
4. Write a program to display the multiplication table for user input number.
5. Write a program to check whether an integer is a prime number or not. (A positive
integer greater than 1 which has no other factors except 1 and the number itself is
called a prime number.)
6. Write a program to print all prime numbers in an interval.
7. Write a program to print the fibonacci sequence. (A Fibonacci sequence is the integer
sequence of 0, 1, 1, 2, 3, 5, 8.... The first two terms are 0 and 1. All other terms are
obtained by adding the preceding two terms. This means to say the nth term is the sum
of (n-1)th and (n-2)th term.)
8. Write a program to count the number of vowel from the string.
9. What is the output of the following program?
x = ['ab', 'cd']
for i in x:
i.upper()
print(x)

Lab Manual – 102040522: Python for Engineers Page 44


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

10. What is the output of the following program?


i=1
while True:
if i%3 == 0:
break
print(i)
i += 1

11. What is the output of the following program?


True = False
while False:
print(True)
break

Lab Manual – 102040522: Python for Engineers Page 45


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Experiment No.: 6

Aim: Use List, Set and Dictionary Comprehensions

Comprehensions:
Python is a language of expressiveness in concise code, which is very elegant and easy to
comprehend. Comprehensions in Python provide us with a short and concise way to construct
new sequences (such as lists, set, dictionary etc.) using sequences which have been already
defined. They allow you to express complicated looping logic in a tiny amount of space.

List Comprehensions:
List Comprehensions provide an elegant way to create new lists. The following is the basic
structure of a list comprehension:

output_list = [output_exp for var in input_list if (var satisfies this condition)]

Note that list comprehension may or may not contain an if condition. List comprehensions can
contain multiple for (nested list comprehensions). It consists of brackets containing an
expression followed by a for clause, then zero or more for or if clauses. The expressions can be
anything, meaning you can put in all kinds of objects in lists. The result will be a new list
resulting from evaluating the expression in the context of the for and if clauses which follow it.
The list comprehension always returns a result list. For example, assume we want to create a
list of squares, like:

Equivalently, more concise and readable code using List Comprehensions:

Lab Manual – 102040522: Python for Engineers Page 47


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Nested List Comprehensions:


For example, this list comprehension combines the elements of two lists if they are not equal:

Which is equivalent to:

Examples of List Comprehensions:

Lab Manual – 102040522: Python for Engineers Page 48


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Dictionary Comprehensions:
Extending the idea of list comprehensions, we can also create a dictionary using dictionary
comprehensions. The basic structure of a dictionary comprehension looks like below.

output_dict = {key:value for (key, value) in iterable if (key, value satisfy this condition)}

In contrast to list comprehensions, they need two expressions separated with a colon followed
by for and if (optional) clauses. When a dictionary comprehension is run, the resulting key-
value pairs are inserted into a new dictionary in the same order in which they were produced. .
For example, assume we want to create a new dictionary by urning Keys Into Values and Vice
Versa:

Ex: Filtering Items:


To filter the items in a dictionary with a comprehension, you just need to add an if clause that
defines the condition you want to meet.

Ex: Doing Some Calculations:

Lab Manual – 102040522: Python for Engineers Page 49


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Set Comprehensions:
Set comprehensions are pretty similar to list comprehensions. The only difference between
them is that set comprehensions use curly brackets { }. Let’s look at the following example to
understand set comprehensions.

Exercise:
1. What is the output of the following program?

2. What is the output of the following program?

3. Write a program to create an output list which contains only the even numbers which
are present in the input list.
4. Write a program to create an output list which contains squares of all the numbers from
1 to 9.
5. Write a program to create an output dictionary which contains only the odd numbers
that are present in the input list as keys and their cubes as values.
6. Given two lists containing the names of states and their corresponding capitals,
construct a dictionary which maps the states with their respective capitals
(key:value pair).
7. Write a program to create an output set which contains only the positive numbers that
are present in the input list. Note that set will discard all the duplicate values.
Lab Manual – 102040522: Python for Engineers Page 50
G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Experiment No.: 7

Aim: Write Python Programs to Plot Data Using Pyplot

Matplotlib:
Matplotlib is a plotting library for the Python programming language and its numerical
mathematics extension NumPy. In this experiment you will learn about plotting different types
of graphs such as line chart, bar chart, pie-chart, and scatter plot using Matplotlib, which is
arguably the most popular graphing and data visualization library for Python. Graphs are
mathematical structures that represent pairwise relationships between objects. Matplotlib
uses an object oriented approach to plotting. This means that plots can be built step-by-step
by adding new elements to the plot.

There are two primary objects associated with a matplotlib plot:


o figure object: the overall figure space that can contain one or more plots.
o axis objects: the individual plots that are rendered within the figure.

You can think of the figure object as your plot canvas. You can think about the axis object as an
individual plot. A figure can hold one or more axis objects. This structure allows you to create
figures with one or more plots on them.

Lab Manual – 102040522: Python for Engineers Page 51


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Pyplot:
While Matplotlib contains many modules that provide different plotting functionality, the most
commonly used module is pyplot. Pyplot provides methods that can be used to add different
components to figure objects, including creating the individual plots as axis objects, also
known as subplots. The pyplot module is typically imported using the alias plt as demonstrated
below.

# Import pyplot
import matplotlib.pyplot as plt:

Steps involved in plotting a graph:


o Define the x-axis and corresponding y-axis values as lists.
o Plot them on canvas using .plot() function.
o Give a name to x-axis and y-axis using .xlabel() and .ylabel() functions.
o Give a title to your plot using .title() function.
o Finally, to view your plot, we use .show() function.

The pseudocode looks like this:


o import the library
o define the x-axis list
o define the y-axis list
o plot function(plt.plot(), plt.scatter(), plt.bar(), plt.pie(), plt.histi())
o xlabel
o ylabel
o legend
o show function

Lab Manual – 102040522: Python for Engineers Page 52


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Plotting a Line:

Plotting two or more lines on same plot:

Lab Manual – 102040522: Python for Engineers Page 53


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Customization of Plots:

Bar Chart:

Lab Manual – 102040522: Python for Engineers Page 54


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Scatter Plot:

Plotting Curves of given Equation:

Lab Manual – 102040522: Python for Engineers Page 55


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Pie Chart:

Create Multiple Plots:

Lab Manual – 102040522: Python for Engineers Page 56


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Line Colors:

Line Styles:

Lab Manual – 102040522: Python for Engineers Page 57


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Exercise:
1. Write a Python program to draw a line with suitable label in the x-axis, y-axis and a title.
2. Write a Python program to plot two or more lines with legends, different widths and
colors.
3. Write a Python program to plot two or more lines with different styles.
4. Write a Python program to draw a line and set the line markers.
5. Write a Python program to create multiple plots.
6. Write a Python programming to display a bar chart of the popularity of programming
Languages.
Sample data:
Programming languages: Java, Python, PHP, JavaScript, C#, C++
Popularity: 22.2, 17.6, 8.8, 8, 7.7, 6.7
7. Write a Python programming to display a horizontal bar chart of the popularity of
programming Languages with above sample data.
8. Write a Python programming to create a pie chart of the popularity of programming
Languages with above sample data.
9. Write a Python program to draw a scatter plot comparing two subject marks of
Mathematics and Science. Use marks of 10 students.
Test Data:
math_marks = [88, 92, 80, 89, 100, 80, 60, 100, 80, 34]
science_marks = [35, 79, 79, 48, 100, 88, 32, 45, 20, 30]
marks_range = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Lab Manual – 102040522: Python for Engineers Page 58


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Experiment No.: 8

Aim: Write Python programs to create functions and use functions in the
program

Using Functions:
Thus far, our programs have consisted of short code segments or scripts. Some of these have
used built-in functions to do useful work. Functions are a handy way to isolate a particular part
of your program’s functionality and make it reusable. The ability for programmers to define and
then use their own functions, as if they were built-in, is a qualitative leap forward in
convenience. Moreover, defining our own functions allows us to organize our code in existing
scripts more effectively. We’ve already been using functions extensively in our programs.
Whenever you’ve typed something like len(x) or type(y), you’ve been using functions. It’s just
that these functions come pre-defined by Python. Python also includes many useful functions,
which are organized in libraries of code called modules. In this lab, we examine the use of
functions.

A function is a chunk of code that can be called by name to perform a task. Functions often
require arguments, that is, specific data values, to perform their tasks. Arguments are also
known as parameters. When a function completes its task (which is usually some kind of
computation), the function may send a result back to the part of the program that called that
function in the first place. The process of sending a result back to another part of a program is
known as returning a value. For example, the argument in the function call round(6.5) is the
value 6.5, and the value returned is 7. Some functions have only optional arguments, some
have required arguments, and some have both required and optional arguments. For example,
the round function has one required argument, the number to be rounded.

Function Definitions:
In Python each function definition is of the form:

def name of function (parameters):


statements
return expression

Lab Manual – 102040522: Python for Engineers Page 59


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

That is to say, a function definition consists of:


o The keyword def (which is short for “define”), followed by the name of your function.
The name of your function can be any valid Python identifier.
o A pair of parentheses after the function name, which is a list of parameters to the
function.
o A colon after the parentheses.
o Potentially some Python statements. (These statements will be executed when your
function is called.)
o The keyword return, followed by an expression. This expression is what the function will
evaluate to when it’s called.

Creating a Function:

Number of Arguments
By default, a function must be called with the correct number of arguments. Meaning that if
your function expects 2 arguments, you have to call the function with 2 arguments, not more,
and not less.

Lab Manual – 102040522: Python for Engineers Page 60


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Example: This function expects 2 arguments, and gets 2 arguments:

Arbitrary Arguments, *args


If you do not know how many arguments that will be passed into your function, add a * before
the parameter name in the function definition. This way the function will receive a tuple of
arguments, and can access the items accordingly:

Lab Manual – 102040522: Python for Engineers Page 61


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Keyword Arguments
You can also send arguments with the key = value syntax. This way the order of the arguments
does not matter.
Example:

Arbitrary Keyword Arguments, **kwargs


If you do not know how many keyword arguments that will be passed into your function, add
two asterisk: ** before the parameter name in the function definition. This way the function
will receive a dictionary of arguments, and can access the items accordingly:
Example:

Passing a List as an Argument


You can send any data types of argument to a function (string, number, list, dictionary etc.), and
it will be treated as the same data type inside the function. E.g. if you send a List as an
argument, it will still be a List when it reaches the function:

Lab Manual – 102040522: Python for Engineers Page 62


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Example:

Exercise:
1. Write a Python function to find the Max of three numbers.
2. Write a Python function to multiply all the numbers in a list.
3. Write a Python function that accepts a string and calculate the number of uppercase,
lowercase, special characters and numeric values.
Sample String : "G. H. Patel College of Engineering & Technology"
Expected Output :
Upper case letters: 6
Lower case letters: 31
Number: 0
Special characters: 10
4. Write a Python function SumOfSquares that calls the function Square which returns the
square of the number.
5. Write a Python function that counts the number of occurrences of the character in the
given string. Provide two implementations: recursive and iterative.
6. Write a Python function that determines the factorial of given number. Provide two
implementations: recursive and iterative.
7. Write a Python function for recursive implementation of Fibonacci sequence.
8. Explain what happens when the following functions are called:

(a) (b) (c)


def sum(lower, upper): def example(aString, index): def example(n):
result = 0 if index < len(aString): if n > 0:
while lower <= upper: example(aString, index + 1) print(n)
result += lower print(aString[index], end="") example(n)
lower += 1 else:
return result example(n – 1)

Lab Manual – 102040522: Python for Engineers Page 63


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Experiment No.: 9

Aim: Import module and use it in Python programs

Modules:
If you quit from the Python interpreter and enter it again, the definitions you have made
(functions and variables) are lost. Therefore, if you want to write a somewhat longer program,
you are better off using a text editor to prepare the input for the interpreter and running it with
that file as input instead. This is known as creating a script. As your program gets longer, you
may want to split it into several files for easier maintenance. You may also want to use a handy
function that you’ve written in several programs without copying its definition into each
program.

To support this, Python has a way to put definitions in a file and use them in a script or in an
interactive instance of the interpreter. Such a file is called a module; definitions from a
module can be imported into other modules or into the main module.

A module is a file containing Python definitions and statements. The file name is the module
name with the suffix .py appended. Within a module, the module’s name (as a string) is
available as the value of the global variable __name__. For instance, use your favorite text
editor to create a file called fibo.py in the current directory with the following contents:

# Fibonacci numbers module


def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()

def fib2(n): # return Fibonacci series up to n


result = []
a, b = 0, 1
while a < n:
result.append(a)
a, b = b, a+b
return result

Lab Manual – 102040522: Python for Engineers Page 65


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Now enter the Python interpreter and import this module with the following command:

>>> import fibo

This does not enter the names of the functions defined in fibo directly in the current symbol
table; it only enters the module name fibo there. Using the module name you can access the
functions:

>>> fibo.fib(1000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
'fibo'

If you intend to use a function often you can assign it to a local name:

>>> fib = fibo.fib


>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

A module can contain executable statements as well as function definitions. These statements
are intended to initialize the module. They are executed only the first time the module name is
encountered in an import statement. (They are also run if the file is executed as a script.)

Each module has its own private symbol table, which is used as the global symbol table by all
functions defined in the module. Thus, the author of a module can use global variables in the
module without worrying about accidental clashes with a user’s global variables. On the other
hand, if you know what you are doing you can touch a module’s global variables with the same
notation used to refer to its functions.

Modules can import other modules. It is customary but not required to place
all import statements at the beginning of a module (or script, for that matter). The imported
module names are placed in the importing module’s global symbol table.

There is a variant of the import statement that imports names from a module directly into the
importing module’s symbol table. For example:

Lab Manual – 102040522: Python for Engineers Page 66


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

>>> from fibo import fib, fib2


>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

This does not introduce the module name from which the imports are taken in the local symbol
table (so in the example, fibo is not defined).

There is even a variant to import all names that a module defines:

>>> from fibo import *


>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

This imports all names except those beginning with an underscore (_). In most cases Python
programmers do not use this facility since it introduces an unknown set of names into the
interpreter, possibly hiding some things you have already defined.

Note that in general the practice of importing * from a module or package is frowned upon,
since it often causes poorly readable code. However, it is okay to use it to save typing in
interactive sessions.

If the module name is followed by as, then the name following as is bound directly to the
imported module.

>>> import fibo as fib


>>> fib.fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

This is effectively importing the module in the same way that import fibo will do, with the only
difference of it being available as fib.

It can also be used when utilising from with similar effects:

>>> from fibo import fib as fibonacci


>>> fibonacci(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Lab Manual – 102040522: Python for Engineers Page 67


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Module Search Path:

When a module named spam is imported, the interpreter first searches for a built-in module
with that name. If not found, it then searches for a file named spam.py in a list of directories
given by the variable sys.path. sys.path is initialized from these locations:

• The directory containing the input script (or the current directory when no file is
specified).
• PYTHONPATH (a list of directory names, with the same syntax as the shell
variable PATH).
• The installation-dependent list of directories configured at the time Python is installed.

After initialization, Python programs can modify sys.path. The directory containing the script
being run is placed at the beginning of the search path, ahead of the standard library path. This
means that scripts in that directory will be loaded instead of modules of the same name in the
library directory. This is an error unless the replacement is intended. See section Standard
Modules for more information.

Lab Manual – 102040522: Python for Engineers Page 68


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Exercise:

1. Create a module named as file.py which contains a function displayMsg that contains a
code to print some message on the console.
2. Create a module named as calculation.py which contains three functions as summation,
multiplication, and divide.
3. Write a Python code to demonstrate matrix operations add(), subtract() and divide().
4. Write a Python code to find rank, determinant, Matrix power and inverse of matrix using
the Linear Algebra module of NumPy.
5. Write a Python code for the mesh analysis of circuit using the Linear Algebra module of
NumPy

Electronic Circuit is

┌─ R1 ┬ R2 ─┐
V1 R3 V2
└─────┴─────┘
with following values:
V1 = 5 V
V2 = 2 V
R1 = 2000 # 2k Ohm
R2 = 2000 # 2k Ohm
R3 = 1000 # 1k Ohm

6. Write a Python code for the nodal analysis of circuit using the Linear Algebra module of
NumPy

Electronic Circuit is
+┌─ R1 ┬─────┬────┐
V R2 R3 I ↑
-└─────┴─────┴────┘
with following values:
V = 140 V
I = 18 V
R1 = 20 Ohm
R2 = 6 Ohm
R3 = 5 Ohm

Lab Manual – 102040522: Python for Engineers Page 69


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Experiment No.: 10

Aim: Write Python programs on File Handling

Introduction:
Files are named locations on disk to store related information. They are used to permanently
store data in a non-volatile memory (e.g. hard disk). Since Random Access Memory (RAM) is
volatile (which loses its data when the computer is turned off), we use files for future use of the
data by permanently storing them. When we want to read from or write to a file, we need to
open it first. When we are done, it needs to be closed so that the resources that are tied with
the file are freed. Hence, in Python, a file operation takes place in the following order:
• Open a file
• Read or write (perform operation)
• Close the file

Working of open() function


Python has a built-in open() function to open a file. This function returns a file object, also called
a handle, as it is used to read or modify the file accordingly. We use open () function in Python to
open a file in read or write mode. To return a file object we use open() function along with two
arguments, that accepts file name and the mode, whether to read or write.

So, the syntax being: open(filename, mode).

One must keep in mind that the mode argument is not mandatory. If not passed, then Python
will assume it to be “ r ” by default. The default is reading in text mode. In this mode, we get
strings when reading from the file. On the other hand, binary mode returns bytes and this is the
mode to be used when dealing with non-text files like images or executable files.

>>> f = open("test.txt") # open file in current directory


>>> f = open("C:/MMB/test.txt") # specifying full path

Lab Manual – 102040522: Python for Engineers Page 71


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

We can specify the following mode while opening a file.

Mode Description

r Opens a file for reading. (default)

Opens a file for writing. Creates a new file if it does not exist or truncates the file
w
if it exists.

x Opens a file for exclusive creation. If the file already exists, the operation fails.

Opens a file for appending at the end of the file without truncating it. Creates a
a
new file if it does not exist.

t Opens in text mode. (default)

b Opens in binary mode.

+ Opens a file for updating (reading and writing)

Text Files and Their Format:


Using a text editor such as Notepad or TextEdit, you can create, view, and save data in a text file.
Your Python programs can output data to a text file, a procedure explained later in this section.
The data in a text file can be viewed as characters, words, numbers, or lines of text, depending
on the text file’s format and on the purposes for which the data are used. When the data are
treated as numbers (either integers or floating-points), they must be separated by whitespace
characters—spaces, tabs, and newlines.

For example:

Lab Manual – 102040522: Python for Engineers Page 72


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Output:

A text file containing six floating-point numbers in previous example might look like

Note that this format includes a space or a newline as a separator of items in the text. All data
output to or input from a text file must be strings. Thus, numbers must be converted to strings
before output, and these strings must be converted back to numbers after input.

Working of read() mode:


There is more than one way to read a file in Python. If you need to extract a string that contains
all characters in the file then we can use file.read(). The full code would work like this:

Another way to read a file is to call a certain number of characters like in the following code the
interpreter will read the first 11 characters of stored data and return it as a string:

Lab Manual – 102040522: Python for Engineers Page 73


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

We can read the text.txt file as we wrote in the above section as follow:

We can see that once the end of the file is reached, we get an empty string on further reading.
We can change our current file cursor (position) using the seek() method.
Similarly, the tell() method returns our current position (in number of bytes).

We can see that the read() method returns a newline as '\n‘.

Lab Manual – 102040522: Python for Engineers Page 74


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

We have seen that we can read a file line-by-line using a for loop. Alternatively, we can use
the readline() method to read individual lines of a file. This method reads a file till the newline,
including the newline character.

Lastly, the readlines() method returns a list of remaining lines of the entire file. All these reading
methods return empty values when the end of file (EOF) is reached.

Exercises:
1. Write a Python program to read an entire text file.
2. Write a Python program to read a file line-by-line using for loop.
3. Write a Python program to read a file line-by-line using a while loop.
4. Write a Python program to read first n characters of a file.
5. Write a Python program to read all lines in a file at once.
6. Write a Python program to read specific lines of a file.
7. Write a Python program to count the number of words in a file.
8. Write a Python program to count the frequency of words in a file.
9. Write a Python program to count the number of lines in a text file.
10. Write a Python program to append text to a file and display the text.

Lab Manual – 102040522: Python for Engineers Page 75


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Lab Manual – 102040522: Python for Engineers Page 76


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Experiment No.: 11

Aim: Write Python programs on Exception handling

Exception:
An “exception” is usually defined as “something that does not conform to the norm,” and is
therefore somewhat rare. Virtually every module in the standard Python library uses them, and
Python itself will raise them in many different circumstances. You've already seen some of
them. Open a Python shell and enter

test = [1,2,3]
test[3]

and the interpreter will respond with something like

IndexError: list index out of range

IndexError is the type of exception that Python raises when a program tries to access an
element that is outside the bounds of an indexable type. The string following IndexError
provides additional information about what caused the exception to occur

Common built-in Exceptions:

Exception Cause of Error

ImportError Raised when the imported module is not found.

IndexError Raised when the index of a sequence is out of range.

KeyError Raised when a key is not found in a dictionary.

SyntaxError Raised when syntax error is encountered.

IndentationError Raised when there is incorrect indentation.

TypeError Raised when a function or operation is applied to an object of incorrect type.


Raised when a function gets an argument of correct type but improper
ValueError
value.
ZeroDivisionError Raised when the second operand of division or modulo operation is zero.

Lab Manual – 102040522: Python for Engineers Page 77


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Handle Exception:
Up to now, we have treated exceptions as fatal events. When an exception is raised, the
program terminates (crashes might be a more appropriate word in this case), and we go back to
our code and attempt to figure out what went wrong. When an exception is raised that causes
the program to terminate, we say that an unhandled exception has been raised.

An exception does not need to lead to program termination. Exceptions, when raised, can and
should be handled by the program. Sometimes an exception is raised because there is a bug in
the program (like accessing a variable that doesn't exist), but many times, an exception is
something the programmer can and should anticipate.

A program might try to open a file that does not exist. If an interactive program asks a user for
input, the user might enter something inappropriate. If you know that a line of code might raise
an exception when executed, you should handle the exception.

Handle Exception: try and except Block:


The try and except block in Python is used to catch and handle exceptions. Python executes
code following the try statement as a “normal” part of the program. The code that follows the
except statement is the program’s response to any exceptions in the preceding try clause.

As you saw earlier, when syntactically correct code runs into an error, Python will throw an
exception error. This exception error will crash the program if it is unhandled. The except clause
determines how your program responds to exceptions.
As you saw earlier, when syntactically correct code runs into an error, Python will throw an
exception error. This exception error will crash the program if it is unhandled. The except clause
determines how your program responds to exceptions.

Example1:

Lab Manual – 102040522: Python for Engineers Page 78


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Example2:

Handle Multiple Exceptions:


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.

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

Consider following code:

Lab Manual – 102040522: Python for Engineers Page 79


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Alternately, we can use a tuple of values to specify multiple exceptions in an except clause.

else and finally:


In Python, keywords else and finally can also be used along with the try and except clauses.
While the except block is executed if the exception occurs inside the try block, the else block
gets processed if the try block is found to be exception free.

The finally block consists of statements which should be processed regardless of an exception
occurring in the try block or not. As a consequence, the error-free try block skips the except
clause and enters the finally block before going on to execute the rest of the code. If, however,
there's an exception in the try block, the appropriate except block will be processed, and the
statements in the finally block will be processed before proceeding to the rest of the code.

The example below accepts two numbers from the user and performs their division. It
demonstrates the uses of else and finally blocks.

Lab Manual – 102040522: Python for Engineers Page 80


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Exercises:

1. Write a Python program to handle single exception (e.g. ZeroDivisionError).


2. Write a Python program to handle multiple exception (e.g. TypeError,
ZeroDivisionError).
3. Write a Python program to open a file, writes content in the file and comes out
gracefully because there is no problem. Now try to open a file where you do not have
write permission and raise an exception.
4. Write a Python program for exception handling with try, except, else, and finally.

Lab Manual – 102040522: Python for Engineers Page 81


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Lab Manual – 102040522: Python for Engineers Page 82


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Experiment No.: 12

Aim: Develop programs to learn GUI programming using Tkinter

Introduction about GUI:


We generally write a code and run it in a command-line terminal or an IDE (Integrated
Development Environment), and the code produces an output based on what you expect out of
it either on the terminal or on the IDE itself.

However, what if you want your system to have a fancy looking user-interface or maybe your
application requires you to have a GUI. GUI is nothing but a desktop app that provides you with
an interface that helps you to interact with the computers and enriches your experience of
giving a command (command-line input) to your code.

They are used to perform different tasks in desktops, laptops, and other electronic devices.
An interesting use-case would be - A GUI for controlling a Drone from your laptop, and the GUI
would probably have buttons to maneuver the Drone along with a screen that would show the
camera feed captured by the Drone in a real-time.

Some of the applications where the power of GUI is utilized are:


o Creating a Calculator which would have a user-interface and functionalities that persists
in a calculator.
o Text-Editors, IDE's for coding are on a GUI app.
o Sudoku, Chess, Solitaire, etc.., are games that you can play are GUI apps.
o Chrome, Firefox, Microsoft Edge, etc. used to surf the internet are the GUI app.

There are various frameworks such as PyGUI, PyQT, Tkinter etc. that Python provides to
develop a GUI. Tkinter commonly comes bundled with Python, using Tk and is Python's
standard GUI framework. It is famous for its simplicity and graphical user interface. It is open-
source and available under the Python License. Tkinter comes pre-installed with Python3, and
you need not bother about installing it.

Basic GUI Application with Tkinter:


GUI elements and their functionality are defined in the Tkinter module. The following code
demonstrates the steps in creating a GUI.

Lab Manual – 102040522: Python for Engineers Page 83


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

First of all, import the TKinter module. After importing, setup the application object by calling
the Tk() function. This will create a top-level window (root) having a frame with a title bar,
control box with the minimize and close buttons, and a client area to hold other widgets. The
geometry() method defines the width, height and coordinates of the top left corner of the
frame as below (all values are in pixels): window.geometry("widthxheight+XPOS+YPOS").

The application object then enters an event listening loop by calling the mainloop() method.
The application is now constantly waiting for any event generated on the elements in it. The
event could be text entered in a text field, a selection made from the dropdown or radio
button, single/double click actions of mouse, etc.

The application's functionality involves executing appropriate callback functions in response to


a particular type of event. The event loop will terminate as and when the close button on the
title bar is clicked. The above code will create the following window:

Tkinter Events:
The event is the mouse operation by the user or we can say that the “handler” function is called
with an event object. It can handle all the functions related to them. Assigning a function to an
event of a widget is called event binding. When the event occurs, the assigned function is
invoked automatically.
Lab Manual – 102040522: Python for Engineers Page 84
G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

When an event occurs in the widget, Tkinter will invoke the handler automatically with the
event detail. All Tkinter widget classes are inherited from the Widget class. Let's add the most
commonly used widgets.

Button:
The button can be created using the Button class. The Button class constructor requires a
reference to the main window and to the options.

Button(window, attributes)

You can set the following important properties to customize a button:


text : caption of the button
bg : background colour
fg : foreground colour
font : font name and size
image : to be displayed instead of text
command : function to be called when clicked

Label:
A label can be created in the GUI in Python using the Label class. The Label constructor requires
the top-level window object and options parameters. Option parameters are similar to the
Button object. The following code adds a label in the window.

Lab Manual – 102040522: Python for Engineers Page 85


G H Patel College of Engineering & Technology
(A Constituent College of CVM University)
Department of Electrical Engineering

Entry:
This widget renders a single-line text box for accepting the user input. For multi-line text input
use the Text widget. Apart from the properties already mentioned, the Entry class constructor
accepts the following:

bd : border size of the text box; default is 2 pixels.


show : to convert the text box into a password field, set show property to "*".

The following code adds the text field.

txtfld=Entry(window, text="This is Entry Widget", bg='black',fg='white', bd=5)

Selection Widgets
Radiobutton:
This widget displays a toggle button having an ON/OFF state. There may be more than one
button, but only one of them will be ON at a given time.

Checkbutton:
This is also a toggle button. A rectangular check box appears before its caption. Its ON state is
displayed by the tick mark in the box which disappears when it is clicked to OFF.

Combobox:
This class is defined in the ttk module of tkinterpackage. It populates drop down data from a
collection data type, such as a tuple or a list as values parameter.

Listbox:
Unlike Combobox, this widget displays the entire collection of string items. The user can select
one or multiple items.

Exercise:
Create a GUI (Graphical User Interface) for basic calculator using Tkinter.

Lab Manual – 102040522: Python for Engineers Page 86

You might also like