Python Tutorial
Python Tutorial
Chap.1
Introduction
Python is a general-purpose interpreted, interactive, object-oriented, and high-
level programming language. It was created by Guido van Rossum during 1985- 1990.
Like Perl, Python source code is also available under the GNU General Public License
(GPL). This tutorial gives enough understanding on Python programming language.
Characteristics of Python
Following are important characteristics of Python Programming −
It supports functional and structured programming methods as well as OOP.
It can be used as a scripting language or can be compiled to byte-code for
building large applications.
It provides very high-level dynamic data types and supports dynamic type
checking.
It supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Applications of Python
As mentioned before, Python is one of the most widely used language over the web. I'm
going to list few of them here:
Easy-to-learn − Python has few keywords, simple structure, and a clearly
defined syntax. This allows the student to pick up the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
Easy-to-maintain − Python's source code is fairly easy-to-maintain.
A broad standard library − Python's bulk of the library is very portable and
cross-platform compatible on UNIX, Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
Extendable − You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more
efficient.
Databases − Python provides interfaces to all major commercial databases.
GUI Programming − Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows
MFC, Macintosh, and the X Window system of Unix.
Scalable − Python provides a better structure and support for large programs
than shell scripting.
Python is a high-level, interpreted, interactive and object-oriented scripting language.
Python is designed to be highly readable. It uses English keywords frequently where as
other languages use punctuation, and it has fewer syntactical constructions than other
languages.
Python is Interpreted − Python is processed at runtime by the interpreter. You
do not need to compile your program before executing it. This is similar to PERL
and PHP.
Python is Interactive − You can actually sit at a Python prompt and interact with
the interpreter directly to write your programs.
Python is Object-Oriented − Python supports Object-Oriented style or
technique of programming that encapsulates code within objects.
Python is a Beginner's Language − Python is a great language for the
beginner-level programmers and supports the development of a wide range of
applications from simple text processing to WWW browsers to games.
Chap.2
Python Keywords and Identifiers
Today will learn about keywords (reserved words in Python) and identifiers (names
given to variables, functions, etc.).
Python Keywords
Keywords are the reserved words in Python.
We cannot use a keyword as a variable name, function name or any other identifier.
They are used to define the syntax and structure of the Python language.
There are 33 keywords in Python 3.7. This number can vary slightly over the course
of time.
All the keywords except True, False and None are in lowercase and they must be
written as they are. The list of all the keywords is given below.
False await else import pass
Python Identifiers
An identifier is a name given to entities like class, functions, variables, etc. It helps to
differentiate one entity from another.
E.g global = 1
^SyntaxError:
invalid syntax
invalid syntax
Chap.3
Python Statement, Indentation and
Comments
In this tutorial, you will learn about Python statements, why indentation is
important and use of comments in programming.
Python Statement
Instructions that a Python interpreter can execute are called statements. For
example, a = 1 is an assignment statement. If statement, for statement, while
statement, etc. are other kinds of statements which will be discussed later.
Multi-line statement
In Python, the end of a statement is marked by a newline character. But we
can make a statement extend over multiple lines with the line continuation
character (\). For example:
a = 1 + 2 + 3 + \
4 + 5 + 6 + \
7 + 8 + 9
This is an explicit line continuation. In Python, line continuation is implied
inside parentheses ( ), brackets [ ], and braces { }. For instance, we can
implement the above multi-line statement as:
a = (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9)
Python Indentation
Most of the programming languages like C, C++, and Java use braces { } to
define a block of code. Python, however, uses indentation.
A code block (body of a function, loop, etc.) starts with indentation and ends
with the first unindented line. The amount of indentation is up to you, but it
must be consistent throughout that block.
Generally, four whitespaces are used for indentation and are preferred over
tabs. Here is an example.
For i in range(1,11):
print(i)
if i == 5: break
The enforcement of indentation in Python makes the code look neat and
clean. This results in Python programs that look similar and consistent.
Indentation can be ignored in line continuation, but it’s always a good idea to
indent. It makes the code more readable. For example:
if True:
print(‘Hello’)
a = 5
and
if True: print(‘Hello’); a = 5
both are valid and do the same thing, but the former style is clearer.
Python Comments
Comments are very important while writing a program. They describe what is
going on inside a program, so that a person looking at the source code does
not have a hard time figuring it out.
You might forget the key details of the program you just wrote in a month’s
time. So taking the time to explain these concepts in the form of comments is
always fruitful.
Multi-line comments
We can have comments that extend up to multiple lines. One way is to use
the hash(#) symbol at the beginning of each line. For example:
#This is a long comment
#and it extends
These triple quotes are generally used for multi-line strings. But they can be
used as a multi-line comment as well. Unless they are not docstrings, they do
not generate any extra code.
“””This is
ofmulti-line comments”””
Docstrings in Python
A docstring is short for documentation string.
Python docstrings (documentation strings) are the string literals that appear
right after the definition of a function, method, class, or module.
return 2*num
The docstrings are associated with the object as their __doc__ attribute.
So, we can access the docstrings of the above function with the following lines
of code:
def double(num):
return 2*numprint(double.__doc__)
Output
Function to double the value
Chap.4
Python Built-in Functions
The Python built-in functions are defined as the functions whose functionality is pre-
defined in Python. The python interpreter has several functions that are always
present for use. These functions are known as Built-in Functions. There are several
built-in functions in Python which are listed below:
6. # integer number
7. integer = -20
9.
Output:
14. k = [1, 3, 4, 6]
15. print(all(k))
16.
19. print(all(k))
21. k = [1, 3, 7, 0]
22. print(all(k))
25. print(all(k))
27. k = []
28. print(all(k))
Output:
TrueFalseFalseFalseTrue
29. x = 10
30. y = bin(x)
Output:
0b1010
Python bool()
The python bool() converts a value to boolean(True or False) using the standard
truth testing procedure.
32. test1 = []
33. print(test1,'is',bool(test1))
35. print(test1,'is',bool(test1))
37. print(test1,'is',bool(test1))
39. print(test1,'is',bool(test1))
41. print(test1,'is',bool(test1))
43. print(test1,'is',bool(test1))
Output:
Python bytes()
The python bytes() in Python is used for returning a bytes object. It is an
immutable version of the bytearray() function.
Output:
47. x = 8
48. print(callable(x))
Output:
False
52. print(type(code))
53. exec(code)
54. exec(x)
Output:
<class 'code'>sum = 15
55. x = 8
56. exec('print(x==8)')
57. exec('print(x+4)')
Output:
True12
59. print(s)
61. print(s)
Output: 717
62. l = [4, 3, 2, 0]
63. print(any(l))
65. print(any(l))
67. print(any(l))
68. l = []
69. print(any(l))
Output:
TrueFalseTrueFalse
71. print(ascii(normalText))
73. print(ascii(otherText))
Output:
Python bytearray()
The python bytearray() returns a bytearray object and can convert objects into
bytearray objects, or create an empty bytearray object of the specified size.
76.
79. print(arr)
Output:
80. x = 8
Output:
Python float()
The python float() function returns a floating-point number from a number or
string.
83. print(float(9))
85. print(float(8.19))
87. print(float("-24.27"))
Output:
93. # integer
Output:
123123.4567901100
Python frozenset()
The python frozenset() function returns an immutable frozenset object initialized
with elements from the given iterable.
Output:
Frozen set is: frozenset({'o', 'm', 's', 'r', 't'})Empty frozen set is:
frozenset()
105. age = 22
Output:
A Symbol table is defined as a data structure which contains all the necessary
information about the program. It includes variable names, methods, classes, etc.
110. age = 22
111. globals()['age'] = 22
113. l = [4, 3, 2, 0]
114. print(any(l))
115.
117. print(any(l))
118.
120. print(any(l))
121.
122. l = []
123. print(any(l))
Output:
TrueFalseTrueFalse
128.
130. print(next(listIter))
131.
133. print(next(listIter))
134.
136. print(next(listIter))
137.
139. print(next(listIter))
140.
142. print(next(listIter))
Output:
12345
Output:
Python list()
The python list() creates a list in python.
146. print(list())
147.
148. # string
150. print(list(String))
151.
152. # tuple
154. print(list(Tuple))
155. # list
157. print(list(List))
Output:
160.
164.
Output:
169.
172. print(result)
173.
176. print(numbersAddition)
Output:
179.
180. mv = memoryview(randomByteArray)
181.
183. print(mv[0])
184.
186. print(bytes(mv[0:2]))
187.
189. print(list(mv[0:3]))
Output:
65b'AB'[65, 66, 67]
Python object()
The python object() returns an empty object. It is a base for all the classes and
holds the built-in properties and methods which are default for all the classes.
191.
192. print(type(python))
193. print(dir(python))
Output:
195. f = open("python.txt")
197. f = open("C:/Python33/README.txt")
Output:
Since the mode is omitted, the file is opened in 'r' mode; opens for reading.
Python chr() Function
Python chr() function is used to get a string representing a character which points
to a Unicode code integer. For example, chr(97) returns the string 'a'. This function
takes an integer argument and throws an error if it exceeds the specified range.
The standard range of the argument is from 0 to 1,114,111.
202. print(result)
203. print(result2)
Output:
Python complex()
Python complex() function is used to convert numbers or string into a complex
number. This method takes two optional parameters and returns a complex
number. The first parameter is called a real and second as imaginary parts.
212. print(b)
Output:
(1.5+0j)(1.5+2.2j)
214. id = 101
220. s = Student()
221. s.getinfo()
Output:
227. print(att)
Output:
232. print(result)
Output:
(5, 0)
Python enumerate() Function
Python enumerate() function returns an enumerated object. It takes two
parameters, first is a sequence of elements and the second is the start index of the
sequence. We can get the elements in sequence either through a loop or next()
method.
236. print(result)
237. print(list(result))
Output:
Python dict()
Python dict() function is a constructor which creates a dictionary. Python dictionary
provides three different constructors to create a dictionary:
If keyword arguments are given, the keyword arguments and their values
are added to the dictionary created from the positional argument.
243. print(result2)
Output:
{}{'a': 1, 'b': 2}
The first argument can be none, if the function is not available and returns only
elements that are true.
246. if x>5:
247. return x
251. print(list(result))
Output:
[6]
Hashable types: * bool * int * long * float * string * Unicode * tuple * code
object.
256. print(result)
257. print(result2)
Output:
21461168601842737174
261. print(info)
Output:
266. print(small)
267. print(small2)
Output:
3251000.25
273. print(result)
274. print(result2)
275. print(result3)
Output:
281. print(result)
282. print(result2)
Output:
0x10x156
288. print(val)
289. print(val2)
290. print(val3)
Output:
139963782059696139963805666864139963781994504
292. id = 0
294.
296. self.id = id
298.
300. print(student.id)
301. print(student.name)
304. print(student.email)
Output:
102Sohansohan@abc.com
309. print(result)
310. print(result2)
Output:
slice(None, 5, None)slice(0, 5, 3)
315. print(sorted1)
Output:
['a', 'a', 'i', 'j', 'n', 'o', 'p', 't', 't', 'v']
This method calls on iterator and throws an error if no item is present. To avoid the
error, we can set a default value.
320. print(item)
323. print(item)
Output:
2563282
Output:
If the number is not a number or if a base is given, the number must be a string.
Output:
integer values : 10 10 10
The isinstance() function takes two arguments, i.e., object and classinfo, and then
it returns either True or False.
338. id = 101
341. self.id=id
342. self.name=name
343.
Output:
TrueFalse
Python oct() Function
Python oct() function is used to get an octal value of an integer number. This
method takes an argument and returns an integer converted into an octal string. It
throws an error TypeError, if argument type is other than an integer.
Output:
354. print(ord('8'))
355.
357. print(ord('R'))
358.
360. print(ord('&'))
Output:
568238
363.
366.
369.
Output:
16160.06250.0625
374. x=7
377.
378. y=x
Output:
382. print(list(range(0)))
383.
385. print(list(range(4)))
386.
Output:
[][0, 1, 2, 3][1, 2, 3, 4, 5, 6]
Python reversed() Function
The python reversed() function returns the reversed iterator of the given
sequence.
391. print(list(reversed(String)))
392.
395. print(list(reversed(Tuple)))
396.
399. print(list(reversed(Range)))
400.
403. print(list(reversed(List)))
Output:
405. print(round(10))
406.
408. print(round(10.8))
409.
411. print(round(6.6))
Output:
10117
415.
418. Rectangle.__init__('square')
419.
Output:
TrueFalseTrueTrue
Python str
The python str() converts a specified value into a string.
424. str('4')
Output:
'4'
425. t1 = tuple()
427.
431.
434. print('t1=',t1)
435.
438. print('t1=',t1)
Output:
Python type()
The python type() returns the type of the specified object if a single argument is
passed to the type() built in function. If three arguments are passed, then it returns
a new type object.
440. print(type(List))
441.
443. print(type(Dict))
444.
446. a=0
447.
449. print(type(InstanceOfPython))
Output:
452. self.x = x
453. self.y = y
454.
456. print(vars(InstanceOfPython))
Output:
{'y': 9, 'x': 7}
459.
462.
465. print(resultList)
466.
469.
472. print(resultSet)
Output:
Statement Description
Indentation in Python
For the ease of programming and to achieve simplicity, python doesn't allow the
use of parentheses for the block level code. In Python, indentation is used to
declare a block. If two statements are at the same indentation level, then they are
the part of the same block.
Generally, four spaces are given to indent the statements which are a typical
amount of indentation in python.
Indentation is the most used part of the python language since it declares the block
of code. All the statements of one block are intended at the same level indentation.
We will see how the actual indentation takes place in decision making and other
stuff in python.
The if statement
The if statement is used to test a particular condition and if the condition is true, it
executes a block of code known as if-block. The condition of if statement can be
any valid logical expression which can be either evaluated to true or false.
473. if expression:
474. statement
Example 1
475. num = int(input("enter the number?"))
476. if num%2 == 0:
Output:
Output:
If the condition is true, then the if-block is executed. Otherwise, the else-block is
executed.
The syntax of the if-else statement is given below.
487. if condition: yy
489. else:
492. if age>=18:
493. print("You are eligible to vote !!");
494. else:
Output:
497. if num%2 == 0:
499. else:
Output:
501. if expression 1:
503.
509.
510. else:
Example 1
512. number = int(input("Enter the number?"))
513. if number==10:
519. else:
Output:
Example 2
521. marks = int(input("Enter the marks? "))
530. lse:
For this purpose, The programming languages provide various types of loops which
are capable of repeating some specific code several numbers of times. Consider the
following diagram to understand the working of a loop statement.
Advantages of loops
There are the following advantages of loops in Python
Using loops, we do not need to write the same code again and again
Using loops, we can traverse over the elements of data structures (array or
linked lists).
533. statement(s)
536. print(i)
Output:
Python
538. n=5
540. c = n*i
541. print(c)
Output:
5101520253035404550s
543. sum = 0
Output:
The range() function is used to generate the sequence of the numbers. If we pass
the range(10), it will generate the numbers from 0 to 9. The syntax of the range()
function is given below.
Syntax:
The stop represents that the loop will iterate till stop-1. The range(1,5) will
generate numbers 1 to 4 iterations. It is optional.
The step size is used to skip the specific numbers from the iteration. It is
optional to use. By default, the step size is 1. It is optional.
Output:
0 1 2 3 4 5 6 7 8 9
552. c = n*i
553. print(n,"*",i,"=",c)
Output:
556. print(i)
Output:
We can also use the range() function with sequence of numbers. The len()
function is combined with range() function which iterate through a sequence using
indexing. Consider the following example.
Output:
Syntax
571. print()
Output:
576. print()
Output:
122333444455555
Example 1
577. for i in range(0,5):
578. print(i)
579. else:
Output:
Example 2
581. for i in range(0,5):
582. print(i)
583. break;
In the above example, the loop is broken due to the break statement; therefore,
the else statement will not be executed. The statement present immediate next to
else block will be executed.
Output:
The loop is broken due to the break statement...came out of the loop. We will learn
more about the break statement in next tutorial.
Chap.7
Python Function
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 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.
Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
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.
def printme( str ):
"This prints a passed string into this function"
print str
return
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
printme() function −
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
Here, we are maintaining reference of the passed object and appending values in the
same object. So, this would produce the following result −
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
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 −
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
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 −
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
Syntax
The syntax of lambda functions contains only a single statement, which is as follows −
lambda [arg1 [,arg2,.....argn]]:expression
Following is the example to show how lambda form of function works −
Global variables
Local variables
Global vs. Local variables
Variables that are defined inside a function body have a local scope, and those defined
outside have a global scope.
This means that local variables can be accessed only inside the function in which they
are declared, whereas global variables can be accessed throughout the program body
by all functions. When you call a function, the variables declared inside it are brought
into scope. Following is a simple example −
Chap.8
Python Arrays: Create, Reverse, Pop with Python Array Examples
In Python, we can treat lists as arrays. However, we cannot constrain the type
of elements stored in a list. For example:
If you create arrays using the array module, all elements of the array must be
of the same numeric type.
Output
Lists are much more flexible than arrays. They can store elements of different
data types including strings. And, if you need to do mathematical computation
on arrays and matrices, you are much better off using something like NumPy.
So, what are the uses of arrays created from the Python array module?
The array.array type is just a thin wrapper on C arrays which provides space-
efficient storage of basic C-style data types. If you need to allocate an array
that you know will not change, then arrays can be faster and use less memory
than lists.
Creating Python Arrays
To create an array of numeric values, we need to import the array module. For
example:
Output
Here, we created an array of float type. The letter d is a type code. This
determines the type of the array during creation.
Accessing Python Array Elements
We use indices to access elements of an array:
Output
First element: 2
Second element: 4
Last element: 8
Output
Output
We can add one item to the array using the append() method, or add several
items using the extend() method.
numbers.append(4)
print(numbers) # Output: array('i', [1, 2, 3, 4])
Output
print(numbers)
Output
Output
We can use the remove() method to remove the given item, and pop() method
to remove an item at the given index.
numbers.remove(12)
print(numbers) # Output: array('i', [10, 11, 12, 13])
print(numbers.pop(2)) # Output: 12
print(numbers) # Output: array('i', [10, 11, 13])
Output
array('i', [10, 11, 12, 13])
12
array('i', [10, 11, 13])
The syntax is
arrayName.index(value)
Example:
Let's find the value of "3" in the array. This method returns the index of the searched
value.
Output:
This operation will return the index of the first occurrence of the mentioned element.
Syntax: array.reverse()
Output:
array('b', [3, 2, 1])
Convert array to Unicode:
Python array can be converted to Unicode. To fulfill this need, the array must be a
type 'u'; otherwise, you will get "ValueError."
Example:
Output:
array('u', 'PYTHON')
PYTHON
Example:
Output:
Traverse an Array
You can traverse a Python array by using loops, like this one:
import array
balance = array.array('i', [300,200,100])
for x in balance:
print(x)
Output:
300
200
100
Chap.9
Principles of Object-Oriented-Programming (OOP)
Abstraction
Abstraction is an extension of encapsulation. It is the process of selecting data from
a larger pool to show only the relevant details to the object. Suppose you want to create
a dating application and you are asked to collect all the information about your users.
You might receive the following data from your user: Full name, address, phone
number, favorite food, favorite movie, hobbies, tax information, social security number,
credit score. This amount of data is great however not all of it is required to create a
dating profile. You only need to select the information that is pertinent to your dating
application from that pool. Data like Full name, favorite food, favorite movie, and
hobbies make sense for a dating application. The process of
fetching/removing/selecting the user information from a larger pool is referred to as
Abstraction. One of the advantages of Abstraction is being able to apply the same
information you used for the dating application to other applications with little or no
modification.
Inheritance
Inheritance is the ability of one object to acquire some/all properties of another
object. For example, a child inherits the traits of his/her parents. With inheritance,
reusability is a major advantage. You can reuse the fields and methods of the existing
class. In Java, there are various types of inheritances: single, multiple, multilevel,
hierarchical, and hybrid. For example, Apple is a fruit so assume that we have a class
Fruit and a subclass of it named Apple. Our Apple acquires the properties of the Fruit
class. Other classifications could be grape, pear, and mango, etc. Fruit defines a class
of foods that are mature ovaries of a plant, fleshy, contains a large seed within or
numerous tiny seeds. Apple the sub-class acquires these properties from Fruit and has
some unique properties, which are different from other sub-classes of Fruit such as red,
round, depression at the top.
Polymorphism
Polymorphism gives us a way to use a class exactly like its parent so there is no
confusion with mixing types. This being said, each child sub-class keeps its own
functions/methods as they are. If we had a superclass called Mammal that has a
method called mammalSound(). The sub-classes of Mammals could be Dogs, whales,
elephants, and horses. Each of these would have their own iteration of a mammal
sound (dog-barks, whale-clicks).
Python Inheritance
Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides
code reusability to the program because we can use an existing class to create a new
class instead of creating it from scratch.
In inheritance, the child class acquires the properties and can access all the data
members and functions defined in the parent class. A child class can also provide its
specific implementation to the functions of the parent class. In this section of the tutorial,
we will discuss inheritance in detail.
In python, a derived class can inherit base class by just mentioning the base in the
bracket after the derived class name. Consider the following syntax to inherit a base
class into the derived class.
Syntax
586. class derived-class(base class):
587. <class-suite>
A class can inherit multiple classes by mentioning all of them inside the bracket.
Consider the following syntax.
Syntax
588. class derive-class(<base class 1>, <base class 2>, ..... <base class
n>):
Example 1
590. class Animal:
597. d = Dog()
598. d.bark()
599. d.speak()
Output:
dog barkingAnimal Speaking
Syntax
600. class class1:
601. <class-suite>
606. .
607. .
Example
608. class Animal:
611. #The child class Dog inherits the base class Animal
615. #The child class Dogchild inherits another child class Dog
619. d = DogChild()
620. d.bark()
621. d.speak()
622. d.eat()
Output:
dog barkingAnimal SpeakingEating bread...
Python Multiple inheritance
Python provides us the flexibility to inherit multiple base classes in the child class.
Syntax
623. class Base1:
624. <class-suite>
625.
627. <class-suite>
628. .
629. .
630. .
632. <class-suite>
633.
635. <class-suite>
Example
636. class Calculation1:
645. d = Derived()
646. print(issubclass(Derived,Calculation2))
647. print(issubclass(Calculation1,Calculation2))
Output:
TrueFalse
Example
1. class Calculation1:
2. def Summation(self,a,b):
3. return a+b;
4. class Calculation2:
5. def Multiplication(self,a,b):
6. return a*b;
7. class Derived(Calculation1,Calculation2):
8. def Divide(self,a,b):
9. return a/b;
10. d = Derived()
11. print(d.Summation(10,20))
12. print(d.Multiplication(10,20))
13. print(d.Divide(10,20))
Output:
302000.5
Example
14. class Calculation1:
24. print(isinstance(d,Derived))
Output:
True
Method Overriding
We can provide some specific implementation of the parent class method in our child
class. When the parent class method is defined in the child class with some specific
implementation, then the concept is called method overriding. We may need to perform
method overriding in the scenario where the different definition of a parent class
method is needed in the child class.
Example
25. class Animal:
27. print("speaking")
30. print("Barking")
31. d = Dog()
32. d.speak()
Output:
Barking
38. return 7;
39.
42. return 8;
43. b1 = Bank()
44. b2 = SBI()
45. b3 = ICICI()
Output:
Bank Rate of interest: 10SBI Rate of interest: 7ICICI Rate of interest: 8
Example
49. class Employee:
50. __count = 0;
57. try:
58. print(emp.__count)
59. finally:
60. emp.display()
Output:
The number of employees 2AttributeError: 'Employee' object has no attribute
'__count'
Polymorphism in Python
What is Polymorphism : The word polymorphism means having many forms. In
programming, polymorphism means same function name (but different signatures)
being uses for different types.
Output:53
return x + y+z
# Driver code
print(add(2, 3))
print(add(2, 3, 4))
Output:
59
def capital(self):
def language(self):
def type(self):
class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")
def language(self):
def type(self):
obj_ind = India()
obj_usa = USA()
country.capital()
country.language()
country.type()
In Python, Polymorphism lets us define methods in the child class that have the same
name as the methods in the parent class. In inheritance, the child class inherits the
methods from the parent class. However, it is possible to modify a method in a child
class that it has inherited from the parent class. This is particularly useful in cases
where the method inherited from the parent class doesn’t quite fit the child class. In
such cases, we re-implement the method in the child class. This process of re-
implementing a method in the child class is known as Method Overriding.
class Bird:
def intro(self):
class sparrow(Bird):
def flight(self):
class ostrich(Bird):
def flight(self):
obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()
obj_bird.intro()
obj_bird.flight()
obj_spr.intro()
obj_spr.flight()
obj_ost.intro()
obj_ost.flight()
Output:There are many types of birds.Most of the birds can fly but
some cannot.There are many types of birds.Sparrows can fly.There are
many types of birds.Ostriches cannot fly.
obj.capital()
obj.language()
obj.type()
obj_ind = India()
obj_usa = USA()
func(obj_ind)
func(obj_usa)
def capital(self):
def language(self):
def type(self):
class USA():
def capital(self):
def language(self):
def type(self):
def func(obj):
obj.capital()
obj.language()
obj.type()
obj_ind = India()
obj_usa = USA()
func(obj_ind)
func(obj_usa)
Chap.10
Create UI in Python-Tkinter
Modern computer applications are user-friendly. User interaction is not restricted to
console-based I/O. They have a more ergonomic graphical user interface (GUI) thanks
to high speed processors and powerful graphics hardware. These applications can
receive inputs through mouse clicks and can enable the user to choose from
alternatives with the help of radio buttons, dropdown lists, and other GUI elements (or
widgets).
Such applications are developed using one of various graphics libraries available. A
graphics library is a software toolkit having a collection of classes that define a
functionality of various GUI elements. These graphics libraries are generally written in
C/C++. Many of them have been ported to Python in the form of importable modules.
Some of them are listed below:
Tkinter is the Python port for Tcl-Tk GUI toolkit developed by Fredrik Lundh. This
module is bundled with standard distributions of Python for all platforms.
PyQtis, the Python interface to Qt, is a very popular cross-platform GUI framework.
PyGTK is the module that ports Python to another popular GUI widget toolkit called
GTK.
WxPython is a Python wrapper around WxWidgets, another cross-platform graphics
library.
This tutorial explains the use of Tkinter in developing GUI-based Python programs.
Python-Tkinter Window
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.
Signature: Button(window, attributes)
You can set the following important properties to customize a button:
text : caption of the button
bg : background colour
fg : foreground colour
font : font name and size
image : to be displayed instead of text
command : function to be called when clicked
Example: Button
Copy
Label
A label can be created in the UI 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 adds a label in the window.
Example: Label
from tkinter import *
window=Tk()
lbl=Label(window, text="This is Label widget", fg='red',
font=("Helvetica", 16))
lbl.place(x=60,y=50)window.title('Hello Python')
window.geometry("300x200+10+10")
window.mainloop()
Here, the label's caption will be displayed in red colour using Helvetica
font of 16 point size.
Entry
This widget renders a single-line text box for accepting the user input. For multi-line text
input use the Text widget. Apart from the properties already mentioned, the Entry class
constructor accepts the following:
bd : border size of the text box; default is 2 pixels.
show : to convert the text box into a password field, set show property to "*".
The following code adds the text field.
txtfld=Entry(window, text="This is Entry Widget",
bg='black',fg='white', bd=5)
The following example creates a window with a button, label and entry
field.
Example: Create Widgets
Copy
Create UI in Python-Tkinter
Event Handling
An event is a notification received by the application object from various GUI widgets as
a result of user interaction. The Application object is always anticipating events as it
runs an event listening loop. User's actions include mouse button click or double click,
keyboard key pressed while control is inside the text box, certain element gains or goes
out of focus etc.
Events are expressed as strings in <modifier-type-qualifier> format.
Many events are represented just as qualifier. The type defines the class of the event.
The following table shows how the Tkinter recognizes different events:
Event Modifier Type Qualifier Action
<Button-1> Button 1 Left mouse button
click.
An event should be registered with one or more GUI widgets in the application. If it's
not, it will be ignored. In Tkinter, there are two ways to register an event with a widget.
First way is by using the bind() method and the second way is by using the command
parameter in the widget constructor.
Bind() Method
The bind() method associates an event to a callback function so that,
when the even occurs, the function is called.
Syntax:
Widget.bind(event, callback)
Command Parameter
Each widget primarily responds to a particular type. For example, Button is a source of
the Button event. So, it is by default bound to it. Constructor methods of many widget
classes have an optional parameter called command. This command parameter is set
to callback the function which will be invoked whenever its bound event occurs. This
method is more convenient than the bind() method.
btn = Button(window, text='OK', command=myEventHandlerFunction)
In the example given below, the application window has two text input fields and
another one to display the result. There are two button objects with the captions Add
and Subtract. The user is expected to enter the number in the two Entry widgets. Their
addition or subtraction is displayed in the third.
The first button (Add) is configured using the command parameter. Its value is the add()
method in the class. The second button uses the bind() method to register the left
button click with the sub() method. Both methods read the contents of the text fields by
the get() method of the Entry widget, parse to numbers, perform the addition/subtraction
and display the result in third text field using the insert() method.
Example:
Copy
UI in Python-Tkinter
Thus, you can create the UI using TKinter in Python.
Chap.11
Oracle Database Connection in Python
Sometimes as part of programming, we required to work with the databases because we
want to store a huge amount of information so we use databases, such as Oracle, MySQL,
etc. So In this article, we will discuss the connectivity of Oracle database using Python.
This can be done through the module name cx_Oracle.
Oracle Database
For communicating with any database through our Python program we require some
connector which is nothing but the cx_Oracle module.
con = cx_Oracle.connect('tiger/scott@localhost:1521/xe')
print(con.version)
except cx_Oracle.DatabaseError as e:
print("There is a problem with Oracle", e)
#con.autocommit = True
# Inserting a record into table employee
cursor.execute('insert into employee values(10001,\'Rahul\',50000.50)')
except cx_Oracle.DatabaseError as e:
print("There is a problem with Oracle", e)
# Load data from a csv file into Oracle table using executemany
try:
con = cx_Oracle.connect('tiger/scott@localhost:1521/xe')
else:
try:
cur = con.cursor()
data = [[10007, 'Vikram', 48000.0], [10008, 'Sunil', 65000.1], [10009,
'Sameer', 75000.0]]
cur = con.cursor()
# Inserting multiple records into employee table
# (:1,:2,:3) are place holders. They pick data from a list supplied as
argument
cur.executemany('insert into employee values(:1,:2,:3)', data)
else:
# To commit the transaction manually
con.commit()
print('Multiple records are inserted successfully')
finally:
if cur:
cur.close()
if con:
con.close()
Output:
Multiple records are inserted successfully
There might be times when it is required to execute a SQL statement multiple times
based on the different values supplied to it each time. This can be achieved using
executemany() method. We supply a list containing a list of values that will replace
placeholders in a SQL query to be executed.
From the above case
:1 is substituted by value 10007
:2 is substituted by value ‘Vikram’
:3 is substituted by value 48000.0
And so on(next list of values in a given list)
Similarly, you can supply a list of dictionaries. But instead of placeholder, we will use the
bind variable( discussed later).
View result set from a select query using fetchall(), fetchmany(int),
fetchone()
import cx_Oracle
try:
con = cx_Oracle.connect('tiger/scott@localhost:1521/xe')
else:
try:
cur = con.cursor()
rows = cur.fetchall()
print(rows)
# fetchmany(int) is used to fetch limited number of records from result set based on
integer argument passed in it
rows = cur.fetchmany(3)
print(rows)
# fetchone() is used fetch one record from top of the result set
rows = cur.fetchone()
print(rows)
print('Error:'+str(er))
finally:
if cur:
cur.close()
finally:
if con:
con.close()
Output:
[(10001, 'Rahul', 50000.5), (10002, 'Sanoj', 40000.75), (10003,
'Soumik', 30000.25), (10004, 'Sayan', 45000.0), (10005, 'Sobhan',
60000.1), (10006, 'Gururaj', 70000.0), (10007, 'Vikram', 48000.0),
(10008, 'Sunil', 65000.1), (10009, 'Sameer', 75000.0)]
[(10001, 'Rahul', 50000.5), (10002, 'Sanoj', 40000.75), (10003,
'Soumik', 30000.25)]
(10001, 'Rahul', 50000.5)
In the above program, we have used 3 methods
1. fetchall() : The fetchall() is used to fetch all records from the result set.
2. fetchmany(int) : The fetchmany(int) is used to fetch the limited number of
records from the result set based on the integer argument passed in it.
3. fetchone() : The fetchone() is used to fetch one record from the top of the
result set.
5. View result set from a select query using bind variable
import cx_Oracle
try:
con = cx_Oracle.connect('tiger/scott@localhost:1521/xe')
else:
try:
cur = con.cursor()
rows = cur.fetchall()
print(rows)
except cx_Oracle.DatabaseError as er:
print('Error:', er)
finally:
if cur:
cur.close()
finally:
if con:
con.close()
Output:
[(10001, 'Rahul', 50000.5), (10005, 'Sobhan', 60000.1), (10006,
'Gururaj', 70000.0),
(10008, 'Sunil', 65000.1), (10009, 'Sameer', 75000.0)]
In this case, I have passed a dictionary in execute() method. This dictionary contains the
name of the bind variable as a key, and it’s corresponding value. When the SQL query is
executed, value from the key is substituted in place of bind variable.