Python Report
Python Report
Python Report
Introduction to Python
Python was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde &
Informatica (CWI) in the Netherlands as a successor to the ABC language, capable of
exception handling and interfacing with the Amoeba operating system. Its implementation
began in December 1989 released in 1991. Python is now open source with more set of
libraries to automate things.
Python was designed for readability with some similarities to the English language. Also it
uses new lines to complete a command, as opposed to other programming languages which
often use semicolons or parentheses.
Python relies more on indentation, using whitespace, to define scope such as:
Scope of loops
Functions
Classes
Uses of Python
Used on a server to create web applications.
Used alongside software to create workflows.
Used to connect to database systems and can also modify files (Read/Write)
Used to handle big data.
Used perform complex mathematics computations
Used for rapid prototyping
Advantages of Python
It can works on different platforms such as Windows, Mac, Linux, Raspberry Pi, etc
It has simple syntax similar to the English language.
It has syntax in such way that developers can program with few lines of code than other
programming languages.
It runs on an interpreter system, means that code can be executed as soon as it is
developed which helps in quick prototyping.
It can be treated in a procedural way, an object-orientated way or a functional way.
Open your Python editor (IDLE), and enter the following code:
print("Hello World")
Save your program to a file called hello.py (python files needs to be saved in .py)
This is typically done using the editor's File > Save or similar. ...
Run your Program by Run > Run Module
Examples of variables:
X = 70 ; x is integer
y = "test" ; y is string
z = ‘ test ‘ ; z is string
a, b, c = "Test1", " Test2", " Test3" ; assigning values to multiple variables in single line
x = y = z = "Text" ; assigning values to same value to multiple variables in single line
Examples of variables:
var = 222
var_1 = "test"
var20 = "Feb"
4var = 222
Var-N = "test"
V ar = "Feb"
Output Variables:
Print statement is used as output variables.
Example:
x, y, z = "Red", "Green", "Yellow"
print(x)
print(y)
print(z)
Global Variables:
Variables that are created outside the function are known as global variables.
Global variables can be used in both inside and outside the functions.
Example:
a = "Super"
def myfunc():
print("EmbeddedFrU is " + a)
myfunc()
Consider the global and local variable with the same name outside and inside
a function respectively. The variable created inside will hold local property and
can be accessed inside the function only whereas variable which is created
outside the function (i.e., globally) will hold the global property and can be
accessed anywhere inside the file. Hence in order to create global variable
inside function “Global “keyword.
Example
If the global keyword is used, the variable will hold global property:
def myfunc():
global x
x = "fantastic"
myfunc()
print("EmbeddedFrU is " + x)
Data Type Defining variables with unspecific Defining variables with specific
data types data types
int x = 20 x = int(20)
Complex x = 1j x = complex(1j)
However, most commonly used sequence types are Strings, Lists and Tuples.
Note: Python has built-in functions for finding the length of a sequence and for finding its
largest and smallest elements.
Lists
The list is a most versatile data type available which can be written as a list of
comma-separated values (items) between square brackets.
Lists are like dynamic sized arrays
An list can contain DataTypes like Integers, Strings, as well as Objects
Lists are mutable, hence, lists can be altered even after their creation
List can be ordered and a definite count.
Elements in a list are indexed according to a definite sequence and the
indexing of a list is done with 0 being the first index
Example:
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
In order to access values in lists, use the square brackets for slicing along with the
index or indices to obtain value available at that specified index
Example:
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7 ]
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]
Updating Lists:
Example:
list = ['physics', 'chemistry', 1997, 2000]
print "Value available at index 2 : "
print list[2]
list[2] = 2001
print "New value available at index 2 : "
print list[2]
append():
Used to add its argument as a single element to the end of a list and length of the list
increases by one.
Example:
list = ['embedded', 'for']
list.append('U')
print list
extend():
Iterates over its argument and adding each element to the list and extending the list.
The length of the list increases by number of elements in it’s argument.
Example:
list = ['Embedded', 'for', 1, 2, 3, 4]
list.extend('you')
print list
Example:
list1 = ['physics', 'chemistry', 1997, 2000]
del list1[2];
“Remove()”: function is used to delete the first occurrence of number mentioned in its
arguments.
Example:
lis = [2, 1, 3, 5, 3, 8]
lis.remove(3)
List operations:
Example:
Sl No Results Description
1 cmp(list1, list2) Compares elements of both lists.
2 len(list) Gives the total length of the list.
3 max(list) Returns item from the list with max value.
4 min(list) Returns item from the list with min value.
5 list(seq) Converts a tuple into list.
Sl No Results Description
1 list.append(obj) Appends object obj to list
2 list.count(obj) Returns count of how many times obj occurs in list
3 list.extend(seq) Appends the contents of seq to list
4 list.index(obj) Returns the lowest index in list that obj appears
5 list.insert(index, obj) Inserts object obj into list at offset index
6 list.pop(obj=list[-1]) Removes and returns last object or obj from list
7 list.remove(obj) Removes object obj from list
8 list.reverse() Reverses objects of list in place
9 list.sort([func]) Sorts objects of list, use compare func if given
Basic Operators
Operators are basically a constructs which can manipulate the value of operands
Types of Operator
Arithmetic Operators
Comparison/Relational Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Arithmetic Operators:
A is initialised with 10 and B is initialised with 5
Relational Operators:
Assignment Operators:
A is initialised with 10 and B is initialised with 20
Bitwise Operators:
A is initialised with 01010101 and B is initialised with 10101010
~ (Binary NOT) It is unary and has the effect of 'flipping' ~a = 1010 1010
bits.
<< (Binary Left The left operands value is moved left by a << 2 = 1010 1000
shift) the number of bits specified by the right
operand.
>> (Binary Right The left operands value is moved right a >> 2 = 0010 1010
shift) by the number of bits specified by the
right operand.
Logical Operators:
A is initialised with TRUE and B is initialised with FALSE
Membership Operators:
Membership operators test for membership in a sequence, such as strings, lists, or
tuples
Identity Operators:
Identity operators compare the memory locations of two objects
String Formatting
One of the best feature of python is string format operator % which is unique to string.
Example:
print "My name is %s and weight is %d kg!" % ('ABC', 55)
Output:
My name is ABC and weight is 55 kg!
Symbol Conversion
%c character
%s string conversion via str() prior to formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase letters)
%X hexadecimal integer (UPPERcase letters)
%e exponential notation (with lowercase 'e')
%E exponential notation (with UPPERcase 'E')
%f floating point real number
%g the shorter of %f and %e
%G the shorter of %f and %E
Strings
Strings are the most popular types in Python. It can be created by enclosing characters
in quotes. Python treats single quotes same as double quotes. Creating strings is as
simple as assigning a value to a variable.
Example:
var = 'Hello World!'
var = "Python Programming"
e.g. -1 refers to the last character, -2 refers to the second last character and so on.
E m b e d d e d F r U
0 1 2 3 4 5 6 7 8 9 10
-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Example:
String1 = "EmbeddedFrU"
print(String1) EmbeddedFrU
E m b e d d e d F r U
0 1 2 3 4 5 6 7 8 9 10
-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Example:
String1 = "EmbeddedFrU"
print(String1) EmbeddedFrU
String1 = "EmbeddedFrUTeam”
print(String1) -> "EmbeddedFrUTeam”
Note: if it is attempted to print the string after deletion, which prone to error since String is
deleted and is unavailable to print.
Formatting of Strings:
Strings in Python can be formatted with the use of keyword format() method which is very
versatile and powerful tool for formatting of Strings.
Format method in String contains curly braces {} as placeholders which can hold arguments
according to position or keyword to specify the order.
Example:
Default order
String1 = "{} {} {}".format('Embedded', 'Fr', 'U')
print(String1) -> Embedded Fr U
Positional Formatting
String1 = "{1} {0} {2}".format('Embedded', 'Fr', 'U')
print(String1) -> Fr Embedded U
Keyword Formatting
String1 = "{u} {f} {e}".format(e = ' Embedded ', f = 'Fr', u = 'U')
print(String1) -> U Fr Embedded
String constants
IF statement:
An if statement consists of a boolean expression/conditional operator followed
by one or more statements
Syntax:
if expression:
statement(s)
if...else statements:
An if statement can be followed by an optional else statement, which executes
when the Boolean expression/conditional operator is FALSE.
Syntax:
if expression:
statement(s)
else:
statement(s)
nested if statements
You can use one if or else if statement inside another if or else if statement(s).
Syntax:
if expression:
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
elif expression4:
statement(s)
else:
statement(s)
else:
statement(s)
Loops
A loop statement allows us to execute a statement or group of statements
multiple times
Uses of Loops:
Loops are used for statements which needs to be executed sequentially like first
statement in a function is executed first, followed by the second, and so on.
Also, in the situation when it is needed to execute a block of code several number of
times.
for loop
Executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
Syntax:
for iterating_var in sequence:
statements(s)
nested loops
You can use one or more loop inside any another while, for or do..while loop.
Syntax:
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
break statement
Terminates the loop statement and transfers execution to the statement
immediately following the loop.
Syntax:
break
continue statement
Causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.
Syntax:
Continue
pass statement
The pass statement in Python is used when a statement is required syntactically
but you do not want any command or code to execute.
Syntax:
Pass
Functions
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.
Defining a Function
Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
The code block within every function starts with a colon (:) and is indented.
Syntax
Example
Function Arguments:
Function can be called 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.
Keyword arguments:
Keyword arguments are related to the function calls. When keyword arguments is used
in a function call, the caller identifies the arguments by the parameter name.
This allows to skip arguments or place them out of order since the Python interpreter is
able to use the keywords provided to match the values with parameters.
Keyword 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.
Variable-length arguments:
It is needed to process a function for more arguments than specified while defining the
function. These arguments are called variable-length arguments and are not named in
the function definition, unlike required and default arguments.
Return Statement
The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is the same as return
None.
Classes
A user-defined prototype for an object that defines a set of attributes that characterize
any object of the class. The attributes are data members (class variables and instance
variables) and methods, accessed via dot notation.
Creating Classes
The class statement creates a new class definition. The name of the class immediately
follows the keyword class followed by a colon as follows -
class ClassName:
'Optional class documentation string'
class_suite
The class has a documentation string, which can be accessed via ClassName.__doc__.
The class_suite consists of all the component statements defining class members, data
attributes and functions.
Example
Following is the example of a simple Python class -
class Employee:
empCount = 0
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
def displayEmployee(self):
The variable empCount is a class variable whose value is shared among all instances of
this class. This can be accessed as Employee.empCount from inside the class or
outside the class.
The first method __init__() is a special method, which is called class constructor or
initialization method that Python calls when you create a new instance of this class.
Declare other class methods like normal functions with the exception that the first
argument to each method is self. Python adds the self-argument to the list; it is not
needed to include, when it call the methods.
Accessing Attributes
Access the object's attributes using the dot operator with object. Class variable would be
accessed using class name as follows -
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
Class Employee:
'Common base class for all employees'
empCount = 0
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
Destroying Objects
Python deletes unneeded objects (built-in types or class instances) automatically to free
the memory space. The process by which Python periodically reclaims blocks of memory
that no longer are in use is termed Garbage Collection.
Python's garbage collector runs during program execution and is triggered when an
object's reference count reaches zero. An object's reference count changes as the
number of aliases that point to it changes.
__del__() destructor prints the class name of an instance that is about to be destroyed
Example:
class Point:
def __init__( self, x=0, y=0):
self.x = x
self.y = y
def __del__(self):
class_name = self.__class__.__name__
print class_name, "destroyed"
pt1 = Point()
pt2 = pt1
pt3 = pt1
print id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts
del pt1
del pt2
del pt3
Class variable - A variable that is shared by all instances of a class. Class variables are
defined within a class but outside any of the class's methods. Class variables are not
used as frequently as instance variables are.
Data member - A class variable or instance variable that holds data associated with a
class and its objects.
Instance variable - A variable that is defined inside a method and belongs only to the
current instance of a class.
Inheritance - The transfer of the characteristics of a class to other classes that are
derived from it.
Instance - An individual object of a certain class. An object obj that belongs to a class
Circle, for example, is an instance of the class Circle.
Object - A unique instance of a data structure that's defined by its class. An object
comprises both data members (class variables and instance variables) and methods.
Objects
A unique instance of a data structure that's defined by its class. An object
comprises both data members (class variables and instance variables) and methods
Example:
p1 = MyClass()
print(p1.x)
Object Methods:
Objects can also contain methods. Methods in objects are functions that belong to the
object.
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
Delete Objects:
Delete objects by using the ‘del’ keyword:
Example:
Delete the age property from the p1 object:
del p1
Dictionary
Each key is separated from its value by a colon (:), the items are separated by commas,
and the whole thing is enclosed in curly braces. An empty dictionary without any items is
written with just two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary
can be of any type, but the keys must be of an immutable data type such as strings,
numbers, or tuples.
dict['Name']: Zara
dict['Age']: 7
If we attempt to access a data item with a key, which is not part of the dictionary, we get
an error as follows -
dict['Alice']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice
Updating Dictionary
dictionary can be updating 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 -
dict['Age']: 8
dict['School']: DPS School
To explicitly remove an entire dictionary, just use the del statement. Following is a
simple example -
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
Note - del() method is discussed in subsequent section.
(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 -
dict['Name']: Manni
(b) Keys must be immutable. Which means you can use strings, numbers or tuples as
dictionary keys but something like ['key'] is not allowed. Following is a simple example -
Module
Module allows to organize logically in Python code. Grouping related code into a module
the code easier to understand and use. A module is a Python object with arbitrarily
named attributes that can be binded with 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 aname normally resides in a file named
aname.py. Here's an example of a simple module, support.py
Import Statement
Python source file as a module by executing an import statement in some other Python
source file. The import has the following syntax -
Hello : Zara
A module is loaded only once, regardless of the number of times it is imported. This
prevents the module execution from happening over and over again if multiple imports
occur.
From...import Statement
This statement allows to import specific attributes from a module into the current
namespace.
Syntax:
from modname import name1[, name2[, ... nameN]]
For example, to import the function fibonacci from the module fib, use the following
statement -
From...import * Statement
This allows 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 -
If the module isn't found, Python then searches each directory in the shell
variable PYTHONPATH.
If all else fails, Python checks the default path. On UNIX, this default path is
normally /usr/local/lib/python/.
The module search path is stored in the system module sys as the sys.path variable.
The sys.path variable contains the current directory, PYTHONPATH, and the
installation-dependent default.
PYTHONPATH Variable
The PYTHONPATH is an environment variable, consisting of a list of directories. The
syntax of PYTHONPATH is the same as that of the shell variable PATH.
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, in order to assign a value to a global variable within a function, you must first
use the global statement.
The statement global VarName tells Python that VarName 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
UnboundLocalError is the result. Uncommenting the global statement fixes the problem.
Example:
Money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1
print Money
AddMoney()
print Money
The list contains the names of all the modules, variables and functions that are defined
in a module. Following is a simple example -
content = dir(math)
print content
When the above code is executed, it produces the following result -
If locals() is called from within a function, it will return all the names that can be accessed
locally from that function.
If globals() 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.
Reload() Function
When the module is imported into a script, the code in the top-level portion of a module
is executed only once.
Therefore, re-execute the top-level code in a module and can use the reload() function.
The reload() function imports a previously imported module again
Syntax: reload(module_name);
Example: reload(hello)
Consider a file Pots.py available in Phone directory. This file has following line of source
code -
def Pots():
print "I'm Pots Phone"
Similar way, another two files having different functions with the same name as above -
To make all functions available when function of phone imported, it is needed to put
explicit import statements in __init__.py as follows -
Once these lines added to __init__.py, all of these classes available when the Phone
package imported .
Phone.Pots()
Phone.Isdn()
Phone.G3()
When the above code is executed, it produces the following result -
Programs
1.Creating a countdown timer in Python
Output:
Output:
Output: