Python For Engineers Lab Manual AY2023 24
Python For Engineers Lab Manual AY2023 24
Python For Engineers Lab Manual AY2023 24
CERTIFICATE
List of Experiments
Sr
Date Objective of Experiment Marks Sign
No
1 Installation and working with Python
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
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.
Experiment No.: 1
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.
print('Hello!')
print('I am Mukesh!')
print('Department of Electrical Engineering,', 'GCET!')
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.
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
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
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.
• 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.
• 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.
• 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".
• 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:
• 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.
"""
#%% 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()
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?
Experiment No.: 2
Aim: To understand control structure, data types, arithmetic operators and
strings in Python.
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.
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.
\n Newline
\t Horizontal Tab
\b Backspace
\\ The \ character
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.
Precedence Rules:
The precedence rules you learned in algebra apply during the evaluation of arithmetic
expressions in Python.
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.
Experiment No.: 3
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.
Following built-in functions can be used along with List as well as Tuple.
Examples:
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.
Examples:
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.
Experiment No.: 4
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.
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:
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>
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>
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?
Experiment No.: 5
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:
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.
Example_1:
Example_2:
Example_3:
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
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:
Example_7:
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)
Experiment No.: 6
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:
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:
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:
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?
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
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.
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.
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:
Plotting a Line:
Customization of Plots:
Bar Chart:
Scatter Plot:
Pie Chart:
Line Colors:
Line Styles:
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]
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:
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.
Keyword Arguments
You can also send arguments with the key = value syntax. This way the order of the arguments
does not matter.
Example:
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:
Experiment No.: 9
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:
Now enter the Python interpreter and import this module with the following command:
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:
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:
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).
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.
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.
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.
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
Experiment No.: 10
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
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.
Mode Description
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.
For example:
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.
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:
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 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.
Experiment No.: 11
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]
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
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.
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:
Example2:
try:
# do something
pass
except ValueError:
# handle ValueError exception
pass
except:
# handle all other exceptions
pass
Alternately, we can use a tuple of values to specify multiple exceptions in an except clause.
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.
Exercises:
Experiment No.: 12
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.
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.
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.
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)
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.
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:
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.