NAVEEEED
NAVEEEED
NAVEEEED
1
Basics of computer programming and IDE Installation of Python
Learning Objectives:
• To understand the basics of computer programming
• Familiarization with IDE environment of Python
• Writing first program in Python from scratch
Pre-Lab Reading:
Program is a set of instructions used to solve a particular problem. A computer is a dumb
machine. It cannot do anything on its own. It can only act on the given instructions.
Programming:
Computer can only understand a sequence of 1s and 0s. The following looks strange to use but,
in fact is how computer reads and executes everything that it does:
101010001110010101010111100010101110
This is called Machine language. We can imagine how complicated programming would be if
we had to learn this complex language. That in fact, was how programming was done many
years ago; however today we are fortunate to have what are called high level languages such
as C, java and C++, python etc. These languages are more geared for human understanding
and thus make programming much easier. However, computer only understands machine
language, there must be a translation process to convert these high-level languages to
machine code. This is often done by a compiler. Compiler analyzes a program developed in a
particular computer (high level) language and then translates it into a form (machine
language) that is suitable for execution on your computer system. The program that is to be
compiled is first typed into a file on the computer system.
In the first step of the compilation process, the compiler examines each program statement
contained in the source program and checks it to ensure that it conforms to the syntax and
semantics of the language. If any mistakes are discovered by the compiler during this phase,
they are reported to the user and the compilation process ends right there. The errors then
have to be corrected in the source program (with the use of an editor) and the compilation
process must be restarted. Typical errors reported during this phase of compilation might be
due to an expression that has unbalanced parentheses (syntactic error), or due to the use of
a variable that is not “defined” (semantic error). Once we have executable code, the program
is ready to be run. Hopefully it will run, and everything will be fine, however that is not always
the case. During “run time”, we may encounter another kind of error called a run time error.
This error occurs when we ask computer to do something it cannot do. The computer cannot
violate the laws of mathematics and other binding restrictions.
Asking the computer to divide a number by zero is an example of a run time error. We get
executable code; however, when the program tries to execute the command to divide by
zero, the program will stop with a run time error. Run time errors, are usually more
challenging to find than syntax errors. Once we run our program and get neither syntax nor
run time errors, are we free to rejoice? Not exactly. Unfortunately, we may still encounter
the worst type of error: the dreaded Logic error. Whenever we ask the computer to do
something, but mean for it to do something else, we have a logic error. There must be precise
and clear instructions that generate our intentions to the computer. The computer only does
what we ask it to do.
Environment:
Variables An environment variable is a dynamic "object" on a computer that stores a value,
which in turn can be referenced by one or more software programs in Windows. Environment
variables help programs know what directory to install files in, where to store temporary files,
where to find user profile settings, and other things. It can be said that environment variables
help to create and shape the environment of where a program runs. Two types of
environment variables exist, user environment variables and system environment variables,
as following:
Python:
The Python programming language is useful for all kinds of scientific and engineering tasks.
You can use it to analyze and plot data. You can also use it to numerically solve science and
engineering problems that are difficult or even impossible to solve analytically.
While we want to Python’s powers to address scientific problems, you should know that
Python is a general-purpose computer language that is widely used to address all kinds of
computing tasks, from web applications to processing financial data on wall street and various
scripting tasks for computer system management. Over the past decade it has been
increasingly used by scientists and engineers for numerical computations, graphics, and as a
“wrapper” for numerical software originally written in other languages, like FORTRAN and C.
Python is like MATLAB and IDL, two other computer languages that are frequently used in
science and engineering applications. Like MATLAB and IDL, Python is an interpreted
language, meaning you can run your code without having to go through an extra step of
compiling, as required for the C and FORTRAN programming languages. It is also a dynamically
typed language, meaning you don’t have to declare variables and set aside memory before
using them. Don’t worry if you don’t know exactly what these terms mean.
Their primary significance for you is that you can write Python code, test, and use it quickly with
a minimum of fuss.
One advantage of Python over similar languages like MATLAB and IDL is that it is free. It can
be downloaded from the web and is available on all the standard computer platforms,
including Windows, MacOS, and Linux. This also means that you can use Python without being
tethered to the internet, as required for commercial software that is tied to a remote license
server. Another advantage is Python’s clean and simple syntax, including its implementation
of object-oriented programming (which we do not emphasize in this introduction).
A disadvantage is that Python programs can be slower than compiled languages like C. For
large scale simulations and other demanding applications, there can be a considerable speed
penalty in using Python. In these cases, C, C++, or FORTRAN is recommended, although
intelligent use of Python’s array processing tools contained in the NumPy module can greatly
speed up Python code. Another disadvantage is that compared to MATLAB and IDL, Python is
less well documented.
This stems from the fact that it is public open-source software and thus is dependent on
volunteers from the community of developers and users for documentation. The
documentation is freely available on the web but is scattered among several different sites
and can be terse. This manual will acquaint you with the most used web sites. Search engines
like Google can help you find others.
The Python interpreter and the extensive standard library are freely available in source or
binary form for all major platforms from the Python Web site, https://www.python.org/, and
may be freely distributed. The same site also contains distributions of and pointers to many
free third-party Python modules, programs and tools, and additional documentation. The
Python interpreter is easily extended with new functions and data types implemented in C or
C++ (or other languages callable from C). Python is also suitable as an extension language for
customizable applications.
To configure your editing environment, use the editor settings page and its relevant pages.
There is also a quick switch scheme command that lets you change color schemes, themes,
keymaps, etc. with a couple of keystrokes. The editor is tab-based. All operations with the
editor tabs are available from the context menu of a tab. If you open your project for the very
first time, you see the Welcome Screen.
You can either open your project from the disk or download it from the version control
system. Further, you can configure Python interpreter (in particular, create a virtual
environment), and set up your project. Open your project from disk
When you are using single or double quotes together, then it can be written as:
When you are using single or double quotes, backslash (\) can be used to escape quotes as:
You can add multiple things of different characters in a single print statement as:
For printing output on new line, we can use escape character as:
Single line comments are created simply by beginning a line with the hash (#) character and they
are automatically terminated by the end of line. For example,
Multi line Comments are usually those comments that span multiple lines to explain things in
more detail. It can be created by adding a delimiter (“””) on each end of the comment. For
example,
Pre-Lab Reading:
Variables are nothing but reserved memory locations to store values. This means that when you
create a variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can
be stored in the reserved memory. Therefore, by assigning different data types to variables,
you can store integers, decimals, or characters in these variables.
Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and name variables,
respectively. This produces the following result
100
1000.0
John
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously. For example − a
=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the
same memory location. You can also assign multiple objects to multiple variables. For example
– a, b, c =
1,2,"john"
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and
one string object with the value "john" is assigned to the variable c.
• Numbers
• String
• List
• Tuple
• Dictionary
Python Numbers
Number data types store numeric values. Number objects are created when you assign a
value to them. For example – var1 = 1 var2 = 10
You can also delete the reference to a number object by using the del statement. The syntax
of the del statement is – del var1[, var2[, var3[...., varN]]]]
You can delete a single object or multiple objects by using the del statement. For example −
del var del var_a, var_b
• long (long integers, they can also be represented in octal and hexadecimal)
Examples
Here are some examples of numbers −
• Python allows you to use a lowercase l with long, but it is recommended that you use
only an uppercase L to avoid confusion with the number 1. Python displays long
integers with an uppercase L.
• A complex number consists of an ordered pair of real floating-point numbers denoted
by x + yj, where x and y are the real numbers and j is the imaginary unit.
Types of Operators:
Python language supports the following types of operators.
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
Arithmetic Operators:
Assume variable a holds 10 and variable b holds 20, then –
Logical Operators:
In Python, logic operators are used to perform logical operations on Boolean values ( True or False). Python
provides several logic operators that allow you to combine or modify Boolean values. The main logic
operators in Python are:
1. and: The and operator returns True if both operands are True, and False otherwise. It represents the logical
conjunction operation.
2. or: The or operator returns True if at least one of the operands is True, and False otherwise. It represents
the logical disjunction operation.
3. not: The not operator returns the opposite of the operand's Boolean value. If the operand is True, it
returns False, and if the operand is False, it returns True. It represents the logical negation operation.
# Logical AND
result_and = a and b
print(result_and) # Output: False
# Logical OR
result_or = a or b
print(result_or) # Output: True
# Logical NOT
result_not = not a
print(result_not) # Output: False
x = 10
y=5
Assignment Operators:
In Python, assignment operators are used to assign values to variables. They allow you to
store a value in a variable, update the value of a variable, or modify it based on some
operation. Here are the different assignment operators available in Python:
1. =: The assignment operator ( =) is the most basic assignment operator in Python. It assigns
the value on the right-hand side to the variable on the left-hand side. For example:
2. +=: The += operator is a shorthand assignment operator that adds the value on the right-
hand side to the variable on the left-hand side and assigns the result back to the variable. It
is equivalent to x = x + 3. For example:
3. -=, *=, /=, //=, %=, **=: Similar to +=, these are shorthand assignment operators for
subtraction (-=), multiplication (*=), division (/=), floor division (//=), modulus (%=), and
exponentiation (**=) respectively. They perform the respective operation between the
variable on the left-hand side and the value on the right-hand side, and assign the result
back to the variable.
4. <<=, >>=, &=, |=, ^=: These are shorthand assignment operators for bit shifting ( <<= and >>=),
bitwise AND (&=), bitwise OR ( |=), and bitwise XOR (^=). They perform the respective
operation between the variable on the left-hand side and the value on the right-hand side,
and assign the result back to the variable.
Lab No. 3
String operation
Learning Objectives:
• To understand about input command in Python
• To practice different operations using input command
• To Familiarize with the concept of String in Python Pre-Lab Readings:
Theory
The following line of the program displays the prompt, the statement saying, “Press the enter key
to exit”, and waits for the user to act –
Here, "\n\n" is used to create two new lines before displaying the actual line. Once the user
presses the key, the program ends. This is a nice trick to keep a console window open until
the user is done with an application.
Python Strings:
Strings in Python are identified as a contiguous set of characters represented in the quotation
marks. Python allows for either pairs of single or double quotes. Subsets of strings can be
taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the
string and working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator. For example –
str = 'Hello World!'
Hello World! H
llo llo
World!
Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, if the
same type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines. For example, all the following
are legal –
comment
Hello, Python!
You can type a comment on the same line after a statement or expression –
# This is a comment.
Lab No. 4
Conditional statement and control structure
Learning Objectives:
• To understand decision making statements in Python
• To understand how to perform if-else checks in Python
Pre-Lab Readings:
Decision making is anticipation of conditions occurring while execution of the program and
specifying actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome.
You need to determine which action to take and which statements to execute if outcome is
TRUE or FALSE otherwise.
Following is the general form of a typical decision-making structure found in most of the
programming languages –
Python programming language assumes any non-zero and non-null values as TRUE, and if it is
either zero or null, then it is assumed as FALSE value.
Python programming language provides following types of decision-making statements. Click the
following links to check their detail.
Let us go through each decision making briefly − Single Statement Suites If the suite of an if
clause consists only of a single line, it may go on the same line as the header statement. Here
is an example of a one-line if clause –
Thus, in Python all the continuous lines indented with same number of spaces would form a block
These operators compare the values on either side of them and decide the relation among them.
They are also called Relational operators.
These laws apply on every kind of loops in different programming languages like Python, C, C++,
C#, Java, Basic, Assembly etc.
“Loop is a number generating system that generates numbers in a sequence between limits
given by user. Every time when a number is generated by loop it is saved in a variable for
example x. Loop contain three parts initial limit, boundary limit and rule for sequence. For
example, if we want to generate a sequence of 1,2,3,4, 5,.10 in this sequence
“Every time a number is generated and saved in x. Loop will execute code written inside its block.
This block may or may not use number generated by loop”
Syntax
The syntax of a while loop in Python programming language is −
Here, statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is any non-zero value. The loop iterates while the condition is true .
When the condition becomes false, program control passes to the line immediately following
the loop.
In Python, all the statements indented by the same number of character spaces after a
programming construct are part of a single block of code. Python uses indentation as its
method of grouping statements.
Flow Diagram:
Here, key point of the while loop is that the loop might not ever run. When the condition is
tested and the result is false, the loop body will be skipped and the first statement after the
while loop will be executed.
Example
The block here, consisting of the print and increment statements, is executed repeatedly until
count is no longer less than 9. With each iteration, the current value of the index count is
displayed and then increased by 1.
The Infinite Loop
A loop becomes infinite loop if a condition never becomes FALSE. You must use caution when
using while loops because of the possibility that this condition never resolves to a FALSE value.
This results in a loop that never ends. Such a loop is called an infinite loop.
An infinite loop might be useful in client/server programming where the server needs to run
continuously so that client programs can communicate with it as and when required.
Above example goes in an infinite loop and you need to use CTRL+C to exit the program.
• If the else statement is used with a for loop, the else statement is executed when
the loop has exhausted iterating the list.
• If the else statement is used with a while loop, the else statement is executed when
the condition becomes false.
The following example illustrates the combination of an else statement with a while statement
that prints a number if it is less than 5, otherwise else statement gets executed .
When the above code is executed, it produces the following result –
It is better not tried above example because it goes into infinite loop, and you need to press
CTRL+C keys to exit.
Pre-Lab Readings:
It can iterate over the items of any sequence, such as a list or a string.
Syntax
If a sequence contains an expression list, it is evaluated first. Then, the first item in the
sequence is assigned to the iterating variable iterating Var. Next, the statements block is
executed. Each item in the list is assigned to iterating Var, and the statement(s) block is
executed until the entire sequence is exhausted.
Flow Diagram:
Example:
Here [] is used for lists it will be described in later experiments. When the above code is
executed, it produces the following result −
Prime numbers using for loops
A prime number is a number which is only divisible by 1 and itself following is the program to
check if number entered by user is prime or not−
Here, we check if any number between 2 and one minus the number is divisible by the number
if yes, we flag it as composite by writing 0 in prime.
• If the else statement is used with a for loop, the else statement is executed when the
loop has exhausted iterating the list.
• If the else statement is used with a while loop, the else statement is executed when the
condition becomes false.
The following example illustrates the combination of an else statement with a for statement that
searches for prime numbers from 10 through 20.
Here break is used to break the loop when some special condition encounters. When the above
code is executed, it produces the following result –
Lab No. 6
Implementation of Lists, Tuples and Dictionary in Python
Learning Objectives:
• To understand the concept of Tuples and Lists in Python
• To understand the difference between Tuple and Lists
• Usage of loops for accessing lists
• Use of Tuples and Lists in functions
• To understand the concept of Dictionaries in Python
• To understand the nature of dictionaries as collection of keys and values
Pre-lab Reading:
The most basic data structure in Python is the sequence. Each element of a sequence is
assigned a number - its position or index. The first index is zero, the second index is one, and
so forth.
Python has six built-in types of sequences, but the most common ones are lists and tuples, which
we would see in this tutorial.
There are certain things you can do with all sequence types. These operations include indexing,
slicing, adding, multiplying, and checking for membership. In addition, Python has built-in
functions for finding the length of a sequence and for finding its largest and smallest elements.
Python Lists
The list is a most versatile datatype available in Python which can be written as a list of
commas separated values (items) between square brackets. Important thing about a list is
that items in a list need not be of the same type.
Creating a list is as simple as putting different comma-separated values between square brackets.
For example –
Like string indices, list indices start at 0, and lists can be sliced, concatenated and so on .
Accessing Values in Lists
To access values in lists, use the square brackets for slicing along with the index or indices to
obtain value available at that index. For example –
Updating Lists
You can update single or multiple elements of lists by giving the slice on the left-hand side of
the assignment operator, and you can add to elements in a list with the append () method.
For example –
Note − append () method is discussed in subsequent sec on.
In fact, lists respond to all the general sequence operations we used on strings in the prior
chapter.
Creating a tuple is as simple as putting different comma-separated values. Optionally you can put
these comma-separated values between parentheses also. For example –
To write a tuple containing a single value you must include a comma, even though there is only
one value –
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.
Updating Tuples
Tuples are immutable which means you cannot update or change the values of tuple
elements. You can take portions of existing tuples to create new tuples as the following
example demonstrates –
To explicitly remove an entire tuple, just use the del statement. For example−
This produces the following result. Note an exception raised, this is because after del tup tuple
does not exist anymore –
In fact, tuples respond to all the general sequence operations we used on strings
Indexing, Slicing, and Matrixes Because tuples are sequences, indexing and slicing work the same
way for tuples as they do for strings. Assuming following input −
No Enclosing Delimiters
Any set of multiple objects, comma-separated, written without identifying symbols, i.e.,
brackets for lists, parentheses for tuples, etc., default to tuples, as indicated in these short
examples –
Keys are unique within a dictionary while values may not be. The values of a dictionary can be
of any type, but the keys must be of an immutable data type such as strings, numbers, or
tuples.
Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry,
or deleting an existing entry as shown below in the simple example –
Delete Dictionary
Elements You can either remove individual dictionary elements or clear the entire contents
of a dictionary. You can also delete entire dictionary in a single operation. To explicitly
remove an entire dictionary, just use the del statement. Following is a simple example −
This produces the following result. Note that an exception is raised because after del dictionary
does not exist anymore –
(a) More than one entry per key not allowed. Which means no duplicate key is allowed.
When duplicate keys encountered during assignment, the last assignment wins. For example −
Built-in Dictionary
Functions & Methods Python includes the following dictionary functions –
Python includes following dictionary methods –
Lab No. 7
Implementation of Functions and formal parameter in Python
Learning Objectives:
• To understand the concept of functions in Python
• To learn how to define a function and how to call it
• Formal parameter
Pre-Lab Readings:
A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reusing.
As you already know, Python gives you many built-in functions like print (), etc. but you can also
create your own functions. These functions are called user-defined functions.
Defining a Function
You can define functions to provide the required functionality. Here are simple rules to define
a function in Python.
• Function blocks begin with the keyword def followed by the function name and
parentheses (()).
• Any input parameters or arguments should be placed within these parentheses. You
can also define parameters inside these parentheses.
• The first statement of a function can be an optional statement - the documentation
string of the function or docstring.
• The code block within every function starts with a colon (:) and is indented.
• The statement returns [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return
None.
Syntax
By default, parameters have a positional behavior, and you need to inform them in the same
order that they were defined.
Example
The following function takes a string as input parameter and prints it on standard screen.
Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be included in the
function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from another
function or directly from the Python prompt. Following is the example to call print me ()
function –
Pass by reference vs value All parameters (arguments) in the Python language are passed by
reference. It means if you change what a parameter refers to within a function, the change
also reflects in the calling function. For example −
Here, we are maintaining reference of the passed object and appending values in the same
object. So, this would produce the following result −
There is one more example where argument is being passed by reference and the reference is
being overwritten inside the called function.
The parameter mylist is local to the function changeme. Changing mylist within the function
does not affect mylist. The function accomplishes nothing and finally this would produce the
following result −
Function Arguments
You can call a function by using the following types of formal arguments –
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here,
the number of arguments in the function call should match exactly with the function definition.
To call the function printme(), you definitely need to pass one argument, otherwise it gives a
syntax error as follows –
This allows you to skip arguments or place them out of order because the Python interpreter
can use the keywords provided to match the values with parameters. You can also make
keyword calls to the printme() function in the following ways –
The following example gives clearer picture. Note that the order of parameters does not matter.
When the above code is executed, it produces the following result –
Default arguments
A default argument is an argument that assumes a default value if a value is not provided in
the function call for that argument. The following example gives an idea on default
arguments, it prints default age if it is not passed −
An asterisk (*) is placed before the variable name that holds the values of all nonkeyboard
variable arguments. This tuple remains empty if no additional arguments are specified during
the function call. Following is a simple example −
All the above examples are not returning any value. You can return a value from a function as
follows –
Scope of Variables
All variables in a program may not be accessible at all locations in that program. This depends
on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a particular
identifier. There are two basic scopes of variables in Python –
• Global variables
• Local variables
This means that local variables can be accessed only inside the function in which they are
declared, whereas global variables can be accessed throughout the program body by all
functions. When you call a function, the variables declared inside it are brought into scope.
Following is a simple example –
Formal Parameter:
In Python, formal parameters, also known as function parameters or arguments, are the
variables declared in the function definition. They act as placeholders for the values that
will be passed into the function when it is called. The values passed into the function are
called actual parameters or arguments.
Formal parameters are defined within the parentheses following the function name in the
function definition. Here's an example of a function definition with formal parameters:
In this example, a and b are the formal parameters of the add_numbers function. They define
the variables that will hold the values passed into the function. When the function is called,
the values for a and b are provided as actual arguments.
Here's an example of calling the add_numbers function and passing actual arguments:
In this case, 3 and 5 are the actual arguments that are passed to the add_numbers function.
The value 3 is assigned to the formal parameter a, and the value 5 is assigned to the formal
parameter b. The function then performs the addition and returns the result.
Formal parameters can also have default values assigned to them, making them optional
arguments. Here's an example:
def greet ( name, greeting="Hello" ): message = greeting + ", " + name + "!" return message
In this example, the greeting parameter has a default value of "Hello". If no value is provided
for greeting when calling the greet function, it will use the default value. However, you can
still pass a different value if desired:
print (greet( "John" )) # Output: "Hello, John!" print (greet( "John" , "Hi" )) # Output: "Hi, John!"
In the first call to greet , only the name argument is provided, so the default value of "Hello" is
used. In the second call, both name and greeting arguments are provided, so the value "Hi" is
used instead of the default value.
Lab No. 8
Class and objects
Objectives:
• To understand the use of objects
• To understand how to define objects in Python and its uses with classes
• To understand error handling
Class definitions can appear anywhere in a program, but they are usually near the beginning.
The syntax rules for a class definition are the same as for other control structures. There is a
header which begins with the keyword, class, followed by the name of the class, and ending
with a colon. In most cases, the statements inside a class definition should be function
definitions. Functions defined inside a class have a special name, they are called methods of
the class. The initmethod is a special method that is called just after a variable of the class
type is constructed or instantiated. Variables of the class type are also called instances or
objects of that type.
We are now ready to create our own user-defined type: the Point. Consider the concept of a
mathematical point. In two dimensions, a point is two numbers (coordinates) that are treated
collectively as a single object. In mathematical notation, points are often written in
parentheses with a comma separating the coordinates. For example, (0,0) represents the
origin, and (x,y) represents the point x units to the right and y units up from the origin. A
natural way to represent a point in NFC IEFR, FAISALABAD Electrical Introduction to
Computing Lab Python is with two numeric values.
To define a new user-defined compound type, also called a class to group these two values
into a compound object is as follows:
The function Point () is called the class constructor . The variable p is assigned a reference to
a new Point object. When calling the function Point (), Python performs some magic behind
the scenes and calls the __init__ method. The __init__ method has a parameter called self.
Every class method must have one parameter and that parameter should be called self. The
self-parameter is a reference to the object on which the method is being called.
Attributes:
The __init__ method above contains the definition of two object variables x and y. Object
variables are also called attributes of the object. Once a Point object has been instantiated, it
is now valid to refer to its attributes:
In this case, the attribute we are selecting is a data item from an instance. Here, the variable
p refers to a Point object, which contains two attributes. Each attribute refers to a number.
The expression p.x means, go to the object p refers to and get the value of x. The purpose of
dot notation is to identify which variable you are referring.
Methods:
__init__ is an example of a class function or method. We can add as many methods as we like
to a class, and this is one of the reasons OOP is so powerful. It’s quite a different way of
thinking about programming. Rather than having functions that act on any old data, in OOP,
the data carries the required functionality around with it. Let’s add a few methods to our
Point class:
Lab No. 10
Inheritance
Learning Objectives:
• To understand the modules in Python
• Concepts of inheritances in OOP
Reading Material:
A module allows you to logically organize your Python code. Grouping related code into a
module makes the code easier to understand and use. A module is a Python object with
arbitrarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions, classes, and
variables. A module can also include runnable code.
Example
The Python code for a module named a name normally resides in a file named aname.py. Here's
an example of a simple module, support.py
When the interpreter encounters an import statement, it imports the module if the module
is present in the search path. A search path is a list of directories that the interpreter searches
before importing a module. For example, to import the module support.py, you need to put
the following command at the top of the script –
When the above code is executed, it produces the following result –
A module is loaded only once, regardless of the number of times it is imported. This prevents the
module execution from happening repeatedly if multiple imports occur.
Pythons from statement lets you import specific attributes from a module into the current
namespace. The from...import has the following syntax –
For example, to import the function Fibonacci from the module fib, use the following statement
–
This statement does not import the entire module fib into the current namespace; it just
introduces the item Fibonacci from the module fib into the global symbol table of the
importing module.
It is also possible to import all names from a module into the current namespace by using the
following import statement –
This provides an easy way to import all the items from a module into the current namespace;
however, this statement should be used sparingly.
Locating Modules
When you import a module, the Python interpreter searches for the module in the following
sequences –
The module search path is stored in the system module sys as the sys.pathvariable. The
sys.path variable contains the current directory, PYTHONPATH, and the installation-
dependent default.
A Python statement can access variables in a local namespace and in the global namespace. If
a local and a global variable have the same name, the local variable shadows the global
variable.
Each function has its own local namespace. Class methods follow the same scoping rule as
ordinary functions.
Python makes educated guesses on whether variables are local or global. It assumes that any
variable assigned a value in a function is local.
Therefore, to assign a value to a global variable within a function, you must first use the global
statement.
The statement global Var Name tells Python that Var Name is a global variable. Python stops
searching the local namespace for the variable.
For example, we define a variable Money in the global namespace. Within the function Money,
we assign Money a value, therefore Python assumes Money as a local variable. However, we
accessed the value of the local variable Money before setting it, so an Unbound Local Error is
the result. Uncommenting the global statement fixes the problem.
The list contains the names of all the modules, variables and functions that are defined in a
module. Following is a simple example−
The global () and locals () functions can be used to return the names in the global and local
namespaces depending on the location from where they are called.
If locals () are called from within a function, it will return all the names that can be accessed locally
from that function.
If global () is called from within a function, it will return all the names that can be accessed globally
from that function.
The return type of both these functions is dictionary. Therefore, names can be extracted using
the keys () function.
When the module is imported into a script, the code in the top-level portion of a module is
executed only once.
Therefore, if you want to execute the top-level code in a module, you can use the reload ()
function. The reload () function imports a previously imported module again. The syntax of
the reload () function is this –
Lab No 11
Polymorphism:
Function Polymorphism:
An example of a Python function that can be used on different objects is the len() function.
String:
For strings len() returns the number of characters:
Input:
x = "Hello World!"
print(len(x))
Output:
12
Tuple:
Input:
print(len(mytuple))
Output:
Dictionary:
For dictionaries len() returns the number of key/value pairs in the dictionary:
Input:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
print(len(thisdict))
Output:
Class Polymorphism:
Polymorphism is often used in Class methods, where we can have multiple classes with the
same method name.
For example, say we have three classes: Car, Boat, and Plane, and they all have a method
called move():
Input:
class Car:
self.brand = brand
self.model = model
def move(self):
print("Drive!")
class Boat:
self.model = model
def move(self):
print("Sail!")
class Plane:
self.brand = brand
self.model = model
def move(self):
print("Fly!")
x.move()
Output:
Drive!
Sail!
Fly!
What about classes with child classes with the same name? Can we use polymorphism there?
Yes. If we use the example above and make a parent class called Vehicle, and
make Car, Boat, Plane child classes of Vehicle, the child classes inherits the Vehicle methods, but
can override them:
Input:
class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Move!")
class Car(Vehicle):
pass
class Boat(Vehicle):
def move(self):
print("Sail!")
class Plane(Vehicle):
def move(self):
print("Fly!")
print(x.brand)
print(x.model)
x.move()
Output:
Ford
Mustang
Move!
Ibiza
Touring 20
Sail!
Boeing
747
Fly!
The Boat and Plane classes also inherit brand, model, and move() from Vehicle, but they both
override the move() method.
Because of polymorphism we can execute the same method for all classes .
Lab No 12
Graphs (Show Sine, Cosine, Exponential, Polynomial Curves):
Now let’s plot the sine curve using the sine function that is inbuilt into the NumPy library
and plot it using Matplotlib.
Input:
import numpy as np
import matplotlib.pyplot as plt
# Creating x axis with range and y axis with Sine
# Function for Plotting Sine Graph
x = np.arange(0, 5*np.pi, 0.1)
y = np.sin(x)
# Plotting Sine Graph
plt.plot(x, y, color='green')
plt.show()
Output:
Plotting Cosine Graph using Matplotlib in Python:
Now let’s plot the cosine curve using the cosine function that is inbuilt into the NumPy
library and plot it using Matplotlib.
Input:
# Importing required library
import numpy as np
import matplotlib.pyplot as plt
# Creating x axis with range and y axis with Sine
# Function for Plotting Cosine Graph
x = np.arange(0, 5*np.pi, 0.1)
y = np.cos(x)
# Plotting coine Graph
plt.plot(x, y, color='green')
plt.show()
Output:
Input:
Module Needed:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Change the Size of Graph using
# Figsize
fig = plt.figure(figsize=(10, 10))
# Generating a 3D sine wave
ax = plt.axes(projection='3d')
# Creating array points using
# numpy
x = np.arange(0, 20, 0.1)
y = np.sin(x)
z = y*np.sin(x)
c=x+y
# To create a scatter graph
ax.scatter(x, y, z, c=c)
# turn off/on axis
plt.axis('off')
# show the graph
plt.show()
Output:
Example No 2:
In this example, we are selecting the 3D axis of the dimension X =5, Y=5, Z=5, and
in np.ones() we are passing the dimensions of the cube. The np.ones () function returns a
new array of given shape and type, with ones.
Input:
Input:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#Change the Size of Graph using Figsize
fig = plt.figure(figsize=(10,10))
#Generating a 3D sine wave
ax = plt.axes(projection='3d')
# assigning coordinates
x = np.linspace(-1, 5, 10)
y = np.linspace(-1, 5, 10)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X ** 2 + Y ** 2))
# creating the visualization
ax.plot_wireframe(X, Y, Z, color ='green')
# turn off/on axis
plt.axis('off')
Output: