You are on page 1of 119

Python Notes

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.

Why to Learn Python?


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 a MUST for students and working professionals to become a great Software
Engineer specially when they are working in Web Development Domain. I will list down
some of the key advantages of learning Python:
 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.

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.

In Python, keywords are case sensitive.

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

None break except in raise

True class finally is return

and continue for lambda try

as def from nonlocal while

assert del global not with

Yield
async elif if or
Python Identifiers
An identifier is a name given to entities like class, functions, variables, etc. It helps to
differentiate one entity from another.

Rules for writing identifiers


1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase
(A to Z) or digits (0 to 9) or an underscore _. Names like myClass, var_1 and
print_this_to_screen, all are valid example.

2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is a


valid name.

3. Keywords cannot be used as identifiers.

E.g global = 1

Output File "<interactive input>", line 1 global = 1

^SyntaxError:

invalid syntax

4. We cannot use special symbols like !, @, #, $, % etc. in our identifier.a@ = 0

Output File "<interactive input>", line 1 a@ = 0 ^SyntaxError:

invalid syntax

5. An identifier can be of any length.

Things to Remember

Python is a case-sensitive language. This means, Variable and variable are not the
same. Always give the identifiers a name that makes sense. While c = 10 is a valid
name, writing count = 10 would make more sense, and it would be easier to figure out
what it represents when you look at your code after a long gap.

Multiple words can be separated using an underscore, like this_is_a_long_variable.


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)

Here, the surrounding parentheses ( ) do the line continuation implicitly. Same


is the case with [ ] and { }. For example:
colors = [‘red’, ‘blue’, ‘green’]
We can also put multiple statements in a single line using semicolons, as
follows: a = 1; b = 2; c = 3

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.

Incorrect indentation will result in IndentationError.


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.

In Python, we use the hash (#) symbol to start writing a comment.

It extends up to the newline character. Comments are for programmers to


better understand a program. Python Interpreter ignores comments.
#This is a comment

#print out Helloprint(‘Hello’)

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

#to multiple lines

Another way of doing this is to use triple quotes, either ‘’’ or “””.

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

also aperfect example


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.

Triple quotes are used while writing docstrings. For example:


def double(num):

“””Function to double the value”””

return 2*num

Docstrings appear right after the definition of a function, class, or a module.


This separates docstrings from multiline comments using triple quotes.

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):

“””Function to double the value”””

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:

Python abs() Function


The python abs() function is used to return the absolute value of a number. It
takes only one argument, a number whose absolute value is to be returned. The
argument can be an integer and floating-point number. If the argument is a
complex number, then, abs() returns its magnitude.

Python abs() Function Example

6. # integer number

7. integer = -20

8. print('Absolute value of -40 is:', abs(integer))

9.

10. # floating number

11. floating = -20.83

12. print('Absolute value of -40.83 is:', abs(floating))

Output:

Absolute value of -20 is: 20Absolute value of -20.83 is: 20.83

Python all() Function


The python all() function accepts an iterable object (such as list, dictionary, etc.).
It returns true if all items in passed iterable are true. Otherwise, it returns False. If
the iterable object is empty, the all() function returns True.

Python all() Function Example

13. # all values true

14. k = [1, 3, 4, 6]
15. print(all(k))

16.

17. # all values false

18. k = [0, False]

19. print(all(k))

20. # one false value

21. k = [1, 3, 7, 0]

22. print(all(k))

23. # one true value

24. k = [0, False, 5]

25. print(all(k))

26. # empty iterable

27. k = []

28. print(all(k))

Output:

TrueFalseFalseFalseTrue

Python bin() Function


The python bin() function is used to return the binary representation of a specified
integer. A result always starts with the prefix 0b.

Python bin() Function Example

29. x = 10

30. y = bin(x)

31. print (y)

Output:
0b1010

Python bool()
The python bool() converts a value to boolean(True or False) using the standard
truth testing procedure.

Python bool() Example

32. test1 = []

33. print(test1,'is',bool(test1))

34. test1 = [0]

35. print(test1,'is',bool(test1))

36. test1 = 0.0

37. print(test1,'is',bool(test1))

38. test1 = None

39. print(test1,'is',bool(test1))

40. test1 = True

41. print(test1,'is',bool(test1))

42. test1 = 'Easy string'

43. print(test1,'is',bool(test1))

Output:

[] is False[0] is True0.0 is FalseNone is FalseTrue is TrueEasy string is


True

Python bytes()
The python bytes() in Python is used for returning a bytes object. It is an
immutable version of the bytearray() function.

It can create empty bytes object of the specified size.

Python bytes() Example

44. string = "Hello World."

45. array = bytes(string, 'utf-8')


46. print(array)

Output:

b ' Hello World.'

Python callable() Function


A python callable() function in Python is something that can be called. This built-in
function checks and returns true if the object passed appears to be callable,
otherwise false.

Python callable() Function Example

47. x = 8

48. print(callable(x))

Output:

False

Python compile() Function


The python compile() function takes source code as input and returns a code
object which can later be executed by exec() function.

Python compile() Function Example

49. # compile string source to code

50. code_str = 'x=5\ny=10\nprint("sum =",x+y)'

51. code = compile(code_str, 'sum.py', 'exec')

52. print(type(code))

53. exec(code)

54. exec(x)

Output:

<class 'code'>sum = 15

Python exec() Function


The python exec() function is used for the dynamic execution of Python program
which can either be a string or object code and it accepts large blocks of code,
unlike the eval() function which only accepts a single expression.
Python exec() Function Example

55. x = 8

56. exec('print(x==8)')

57. exec('print(x+4)')

Output:

True12

Python sum() Function


As the name says, python sum() function is used to get the sum of numbers of an
it erable, i.e., list.

Python sum() Function Example

58. s = sum([1, 2,4 ])

59. print(s)

60. s = sum([1, 2, 4], 10)

61. print(s)

Output: 717

Python any() Function


The python any() function returns true if any item in an iterable is true. Otherwise,
it returns False.

Python any() Function Example

62. l = [4, 3, 2, 0]

63. print(any(l))

64. l = [0, False]

65. print(any(l))

66. l = [0, False, 5]

67. print(any(l))

68. l = []
69. print(any(l))

Output:

TrueFalseTrueFalse

Python ascii() Function


The python ascii() function returns a string containing a printable representation of
an object and escapes the non-ASCII characters in the string using \x, \u or \U
escapes.

Python ascii() Function Example

70. normalText = 'Python is interesting'

71. print(ascii(normalText))

72. otherText = 'Pythön is interesting'

73. print(ascii(otherText))

74. print('Pyth\xf6n is interesting')

Output:

'Python is interesting''Pyth\xf6n is interesting'Pythön is interesting

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.

Python bytearray() Example

75. string = "Python is a programming language."

76.

77. # string with encoding 'utf-8'

78. arr = bytearray(string, 'utf-8')

79. print(arr)
Output:

bytearray(b'Python is a programming language.')

Python eval() Function


The python eval() function parses the expression passed to it and runs python
expression(code) within the program.

Python eval() Function Example

80. x = 8

81. print(eval('x + 1'))

Output:

Python float()
The python float() function returns a floating-point number from a number or
string.

Python float() Example

82. # for integers

83. print(float(9))

84. # for floats

85. print(float(8.19))

86. # for string floats

87. print(float("-24.27"))

88. # for string floats with whitespaces

89. print(float(" -17.19\n"))

90. # string float error


91. print(float("xyz"))

Output:

9.08.19-24.27-17.19ValueError: could not convert string to float: 'xyz'

Python format() Function


The python format() function returns a formatted representation of the given
value.

Python format() Function Example

92. # d, f and b are a type

93. # integer

94. print(format(123, "d"))

95. # float arguments

96. print(format(123.4567898, "f"))

97. # binary format

98. print(format(12, "b"))

Output:

123123.4567901100

Python frozenset()
The python frozenset() function returns an immutable frozenset object initialized
with elements from the given iterable.

Python frozenset() Example

99. # tuple of letters

100. letters = ('m', 'r', 'o', 't', 's')

101. fSet = frozenset(letters)


102. print('Frozen set is:', fSet)

103. print('Empty frozen set is:', frozenset())

Output:

Frozen set is: frozenset({'o', 'm', 's', 'r', 't'})Empty frozen set is:
frozenset()

Python getattr() Function


The python getattr() function returns the value of a named attribute of an object.
If it is not found, it returns the default value.

Python getattr() Function Example

104. class Details:

105. age = 22

106. name = "Phill"

107. details = Details()

108. print('The age is:', getattr(details, "age"))

109. print('The age is:', details.age)

Output:

The age is: 22The age is: 22

Python globals() Function


The python globals() function returns the dictionary of the current global symbol
table.

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.

Python globals() Function Example

110. age = 22

111. globals()['age'] = 22

112. print('The age is:', age)


Output:

The age is: 22

Python hasattr() Function


The python any() function returns true if any item in an iterable is true, otherwise
it returns False.

Python hasattr() Function Example

113. l = [4, 3, 2, 0]

114. print(any(l))

115.

116. l = [0, False]

117. print(any(l))

118.

119. l = [0, False, 5]

120. print(any(l))

121.

122. l = []

123. print(any(l))

Output:

TrueFalseTrueFalse

Python iter() Function


The python iter() function is used to return an iterator object. It creates an object
which can be iterated one element at a time.

Python iter() Function Example

124. # list of numbers

125. list = [1,2,3,4,5]


126.

127. listIter = iter(list)

128.

129. # prints '1'

130. print(next(listIter))

131.

132. # prints '2'

133. print(next(listIter))

134.

135. # prints '3'

136. print(next(listIter))

137.

138. # prints '4'

139. print(next(listIter))

140.

141. # prints '5'

142. print(next(listIter))

Output:

12345

Python len() Function


The python len() function is used to return the length (the number of items) of an
object.

Python len() Function Example

143. strA = 'Python'


144. print(len(strA))

Output:

Python list()
The python list() creates a list in python.

Python list() Example

145. # empty list

146. print(list())

147.

148. # string

149. String = 'abcde'

150. print(list(String))

151.

152. # tuple

153. Tuple = (1,2,3,4,5)

154. print(list(Tuple))

155. # list

156. List = [1,2,3,4,5]

157. print(list(List))

Output:

[]['a', 'b', 'c', 'd', 'e'][1,2,3,4,5][1,2,3,4,5]

Python locals() Function


The python locals() method updates and returns the dictionary of the current local
symbol table.
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.

Python locals() Function Example

158. def localsAbsent():

159. return locals()

160.

161. def localsPresent():

162. present = True

163. return locals()

164.

165. print('localsNotPresent:', localsAbsent())

166. print('localsPresent:', localsPresent())

Output:

localsAbsent: {}localsPresent: {'present': True}

Python map() Function


The python map() function is used to return a list of results after applying a given
function to each item of an iterable(list, tuple etc.).

Python map() Function Example

167. def calculateAddition(n):

168. return n+n

169.

170. numbers = (1, 2, 3, 4)

171. result = map(calculateAddition, numbers)

172. print(result)
173.

174. # converting map object to set

175. numbersAddition = set(result)

176. print(numbersAddition)

Output:

<map object at 0x7fb04a6bec18>{8, 2, 4, 6}

Python memoryview() Function


The python memoryview() function returns a memoryview object of the given
argument.

Python memoryview () Function Example

177. #A random bytearray

178. randomByteArray = bytearray('ABC', 'utf-8')

179.

180. mv = memoryview(randomByteArray)

181.

182. # access the memory view's zeroth index

183. print(mv[0])

184.

185. # It create byte from memory view

186. print(bytes(mv[0:2]))

187.

188. # It create list from memory view

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.

Python object() Example

190. python = object()

191.

192. print(type(python))

193. print(dir(python))

Output:

<class 'object'>['__class__', '__delattr__', '__dir__', '__doc__', '__eq__',


'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__',
'__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

Python open() Function


The python open() function opens the file and returns a corresponding file object.

Python open() Function Example

194. # opens python.text file of the current directory

195. f = open("python.txt")

196. # specifying full path

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.

Python chr() Function Example

198. # Calling function

199. result = chr(102) # It returns string representation of a char

200. result2 = chr(112)

201. # Displaying result

202. print(result)

203. print(result2)

204. # Verify, is it string type?

205. print("is it string type:", type(result) is str)

Output:

ValueError: chr() arg not in range(0x110000)

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.

Python complex() Example

206. # Python complex() function example

207. # Calling function

208. a = complex(1) # Passing single parameter

209. b = complex(1,2) # Passing both parameters

210. # Displaying result


211. print(a)

212. print(b)

Output:

(1.5+0j)(1.5+2.2j)

Python delattr() Function


Python delattr() function is used to delete an attribute from a class. It takes two
parameters, first is an object of the class and second is an attribute which we want
to delete. After deleting the attribute, it no longer available in the class and throws
an error if try to call it using the class object.

Python delattr() Function Example

213. class Student:

214. id = 101

215. name = "Pranshu"

216. email = "pranshu@abc.com"

217. # Declaring function

218. def getinfo(self):

219. print(self.id, self.name, self.email)

220. s = Student()

221. s.getinfo()

222. delattr(Student,'course') # Removing attribute which is not available

223. s.getinfo() # error: throws an error

Output:

101 Pranshu pranshu@abc.comAttributeError: course


Python dir() Function
Python dir() function returns the list of names in the current local scope. If the
object on which method is called has a method named __dir__(), this method will
be called and must return the list of attributes. It takes a single object type
argument.

Python dir() Function Example

224. # Calling function

225. att = dir()

226. # Displaying result

227. print(att)

Output:

['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__',


'__loader__', '__name__', '__package__', '__spec__']

Python divmod() Function


Python divmod() function is used to get remainder and quotient of two numbers.
This function takes two numeric arguments and returns a tuple. Both arguments
are required and numeric

Python divmod() Function Example

228. # Python divmod() function example

229. # Calling function

230. result = divmod(10,2)

231. # Displaying result

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.

Python enumerate() Function Example

233. # Calling function

234. result = enumerate([1,2,3])

235. # Displaying result

236. print(result)

237. print(list(result))

Output:

<enumerate object at 0x7ff641093d80>[(0, 1), (1, 2), (2, 3)]

Python dict()
Python dict() function is a constructor which creates a dictionary. Python dictionary
provides three different constructors to create a dictionary:

 If no argument is passed, it creates an empty dictionary.

 If a positional argument is given, a dictionary is created with the same key-


value pairs. Otherwise, pass an iterable object.

 If keyword arguments are given, the keyword arguments and their values
are added to the dictionary created from the positional argument.

Python dict() Example

238. # Calling function

239. result = dict() # returns an empty dictionary

240. result2 = dict(a=1,b=2)

241. # Displaying result


242. print(result)

243. print(result2)

Output:

{}{'a': 1, 'b': 2}

Python filter() Function


Python filter() function is used to get filtered elements. This function takes two
arguments, first is a function and the second is iterable. The filter function returns a
sequence of those elements of iterable object for which function returns true
value.

The first argument can be none, if the function is not available and returns only
elements that are true.

Python filter() Function Example

244. # Python filter() function example

245. def filterdata(x):

246. if x>5:

247. return x

248. # Calling function

249. result = filter(filterdata,(1,2,6))

250. # Displaying result

251. print(list(result))

Output:

[6]

Python hash() Function


Python hash() function is used to get the hash value of an object. Python
calculates the hash value by using the hash algorithm. The hash values are integers
and used to compare dictionary keys during a dictionary lookup. We can hash only
the types which are given below:

Hashable types: * bool * int * long * float * string * Unicode * tuple * code
object.

Python hash() Function Example

252. # Calling function

253. result = hash(21) # integer value

254. result2 = hash(22.2) # decimal value

255. # Displaying result

256. print(result)

257. print(result2)

Output:

21461168601842737174

Python help() Function


Python help() function is used to get help related to the object passed during the
call. It takes an optional parameter and returns help information. If no argument is
given, it shows the Python help console. It internally calls python's help function.

Python help() Function Example

258. # Calling function

259. info = help() # No argument

260. # Displaying result

261. print(info)

Output:

Welcome to Python 3.5's help utility!


Python min() Function
Python min() function is used to get the smallest element from the collection. This
function takes two arguments, first is a collection of elements and second is key,
and returns the smallest element from the collection.

Python min() Function Example

262. # Calling function

263. small = min(2225,325,2025) # returns smallest element

264. small2 = min(1000.25,2025.35,5625.36,10052.50)

265. # Displaying result

266. print(small)

267. print(small2)

Output:

3251000.25

Python set() Function


In python, a set is a built-in class, and this function is a constructor of this class. It
is used to create a new set using elements passed during the call. It takes an
iterable object as an argument and returns a new set object.

Python set() Function Example

268. # Calling function

269. result = set() # empty set

270. result2 = set('12')

271. result3 = set('javatpoint')

272. # Displaying result

273. print(result)

274. print(result2)
275. print(result3)

Output:

set(){'1', '2'}{'a', 'n', 'v', 't', 'j', 'p', 'i', 'o'}

Python hex() Function


Python hex() function is used to generate hex value of an integer argument. It
takes an integer argument and returns an integer converted into a hexadecimal
string. In case, we want to get a hexadecimal value of a float, then use float.hex()
function.

Python hex() Function Example

276. # Calling function

277. result = hex(1)

278. # integer value

279. result2 = hex(342)

280. # Displaying result

281. print(result)

282. print(result2)

Output:

0x10x156

Python id() Function


Python id() function returns the identity of an object. This is an integer which is
guaranteed to be unique. This function takes an argument as an object and returns
a unique integer number which represents identity. Two objects with non-
overlapping lifetimes may have the same id() value.

Python id() Function Example

283. # Calling function


284. val = id("Javatpoint") # string object

285. val2 = id(1200) # integer object

286. val3 = id([25,336,95,236,92,3225]) # List object

287. # Displaying result

288. print(val)

289. print(val2)

290. print(val3)

Output:

139963782059696139963805666864139963781994504

Python setattr() Function


Python setattr() function is used to set a value to the object's attribute. It takes
three arguments, i.e., an object, a string, and an arbitrary value, and returns none.
It is helpful when we want to add a new attribute to an object and set a value to it.

Python setattr() Function Example

291. class Student:

292. id = 0

293. name = ""

294.

295. def __init__(self, id, name):

296. self.id = id

297. self.name = name

298.

299. student = Student(102,"Sohan")

300. print(student.id)
301. print(student.name)

302. #print(student.email) product error

303. setattr(student, 'email','sohan@abc.com') # adding new attribute

304. print(student.email)

Output:

102Sohansohan@abc.com

Python slice() Function


Python slice() function is used to get a slice of elements from the collection of
elements. Python provides two overloaded slice functions. The first function takes a
single argument while the second function takes three arguments and returns a
slice object. This slice object can be used to get a subsection of the collection.

Python slice() Function Example

305. # Calling function

306. result = slice(5) # returns slice object

307. result2 = slice(0,5,3) # returns slice object

308. # Displaying result

309. print(result)

310. print(result2)

Output:

slice(None, 5, None)slice(0, 5, 3)

Python sorted() Function


Python sorted() function is used to sort elements. By default, it sorts elements in
an ascending order but can be sorted in descending also. It takes four arguments
and returns a collection in sorted order. In the case of a dictionary, it sorts only
keys, not values.
Python sorted() Function Example

311. str = "javatpoint" # declaring string

312. # Calling function

313. sorted1 = sorted(str) # sorting string

314. # Displaying result

315. print(sorted1)

Output:

['a', 'a', 'i', 'j', 'n', 'o', 'p', 't', 't', 'v']

Python next() Function


Python next() function is used to fetch next item from the collection. It takes two
arguments, i.e., an iterator and a default value, and returns an element.

This method calls on iterator and throws an error if no item is present. To avoid the
error, we can set a default value.

Python next() Function Example

316. number = iter([256, 32, 82]) # Creating iterator

317. # Calling function

318. item = next(number)

319. # Displaying result

320. print(item)

321. # second item

322. item = next(number)

323. print(item)

324. # third item

325. item = next(number)


326. print(item)

Output:

2563282

Python input() Function


Python input() function is used to get an input from the user. It prompts for the
user input and reads a line. After reading data, it converts it into a string and
returns it. It throws an error EOFError if EOF is read.

Python input() Function Example

327. # Calling function

328. val = input("Enter a value: ")

329. # Displaying result

330. print("You entered:",val)

Output:

Enter a value: 45You entered: 45

Python int() Function


Python int() function is used to get an integer value. It returns an expression
converted into an integer number. If the argument is a floating-point, the
conversion truncates the number. If the argument is outside the integer range,
then it converts the number into a long type.

If the number is not a number or if a base is given, the number must be a string.

Python int() Function Example

331. # Calling function

332. val = int(10) # integer value

333. val2 = int(10.52) # float value

334. val3 = int('10') # string value


335. # Displaying result

336. print("integer values :",val, val2, val3)

Output:

integer values : 10 10 10

Python isinstance() Function


Python isinstance() function is used to check whether the given object is an
instance of that class. If the object belongs to the class, it returns true. Otherwise
returns False. It also returns true if the class is a subclass.

The isinstance() function takes two arguments, i.e., object and classinfo, and then
it returns either True or False.

Python isinstance() function Example

337. class Student:

338. id = 101

339. name = "John"

340. def __init__(self, id, name):

341. self.id=id

342. self.name=name

343.

344. student = Student(1010,"John")

345. lst = [12,34,5,6,767]

346. # Calling function

347. print(isinstance(student, Student)) # isinstance of Student class

348. print(isinstance(lst, Student))

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.

Python oct() function Example

349. # Calling function

350. val = oct(10)

351. # Displaying result

352. print("Octal value of 10:",val)

Output:

Octal value of 10: 0o12

Python ord() Function


The python ord() function returns an integer representing Unicode code point for
the given Unicode character.

Python ord() function Example

353. # Code point of an integer

354. print(ord('8'))

355.

356. # Code point of an alphabet

357. print(ord('R'))

358.

359. # Code point of a character

360. print(ord('&'))

Output:
568238

Python pow() Function


The python pow() function is used to compute the power of a number. It returns x
to the power of y. If the third argument(z) is given, it returns x to the power of y
modulus z, i.e. (x, y) % z.

Python pow() function Example

361. # positive x, positive y (x**y)

362. print(pow(4, 2))

363.

364. # negative x, positive y

365. print(pow(-4, 2))

366.

367. # positive x, negative y (x**-y)

368. print(pow(4, -2))

369.

370. # negative x, negative y

371. print(pow(-4, -2))

Output:

16160.06250.0625

Python print() Function


The python print() function prints the given object to the screen or other standard
output devices.

Python print() function Example

372. print("Python is programming language.")


373.

374. x=7

375. # Two objects passed

376. print("x =", x)

377.

378. y=x

379. # Three objects passed

380. print('x =', x, '= y')

Output:

Python is programming language.x = 7x = 7 = y

Python range() Function


The python range() function returns an immutable sequence of numbers starting
from 0 by default, increments by 1 (by default) and ends at a specified number.

Python range() function Example

381. # empty range

382. print(list(range(0)))

383.

384. # using the range(stop)

385. print(list(range(4)))

386.

387. # using the range(start, stop)

388. print(list(range(1,7 )))

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.

Python reversed() function Example

389. # for string

390. String = 'Java'

391. print(list(reversed(String)))

392.

393. # for tuple

394. Tuple = ('J', 'a', 'v', 'a')

395. print(list(reversed(Tuple)))

396.

397. # for range

398. Range = range(8, 12)

399. print(list(reversed(Range)))

400.

401. # for list

402. List = [1, 2, 7, 5]

403. print(list(reversed(List)))

Output:

['a', 'v', 'a', 'J']['a', 'v', 'a', 'J'][11, 10, 9, 8][5, 7, 2, 1]


Python round() Function
The python round() function rounds off the digits of a number and returns the
floating point number.

Python round() Function Example

404. # for integers

405. print(round(10))

406.

407. # for floating point

408. print(round(10.8))

409.

410. # even choice

411. print(round(6.6))

Output:

10117

Python issubclass() Function


The python issubclass() function returns true if object argument(first argument) is
a subclass of second class(second argument).

Python issubclass() Function Example

412. class Rectangle:

413. def __init__(rectangleType):

414. print('Rectangle is a ', rectangleType)

415.

416. class Square(Rectangle):

417. def __init__(self):

418. Rectangle.__init__('square')
419.

420. print(issubclass(Square, Rectangle))

421. print(issubclass(Square, list))

422. print(issubclass(Square, (list, Rectangle)))

423. print(issubclass(Rectangle, (list, Rectangle)))

Output:

TrueFalseTrueTrue

Python str
The python str() converts a specified value into a string.

Python str() Function Example

424. str('4')

Output:

'4'

Python tuple() Function


The python tuple() function is used to create a tuple object.

Python tuple() Function Example

425. t1 = tuple()

426. print('t1=', t1)

427.

428. # creating a tuple from a list

429. t2 = tuple([1, 6, 9])

430. print('t2=', t2)

431.

432. # creating a tuple from a string


433. t1 = tuple('Java')

434. print('t1=',t1)

435.

436. # creating a tuple from a dictionary

437. t1 = tuple({4: 'four', 5: 'five'})

438. print('t1=',t1)

Output:

t1= ()t2= (1, 6, 9)t1= ('J', 'a', 'v', 'a')t1= (4, 5)

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.

Python type() Function Example

439. List = [4, 5]

440. print(type(List))

441.

442. Dict = {4: 'four', 5: 'five'}

443. print(type(Dict))

444.

445. class Python:

446. a=0

447.

448. InstanceOfPython = Python()

449. print(type(InstanceOfPython))
Output:

<class 'list'><class 'dict'><class '__main__.Python'>

Python vars() function


The python vars() function returns the __dict__ attribute of the given object.

Python vars() Function Example

450. class Python:

451. def __init__(self, x = 7, y = 9):

452. self.x = x

453. self.y = y

454.

455. InstanceOfPython = Python()

456. print(vars(InstanceOfPython))

Output:

{'y': 9, 'x': 7}

Python zip() Function


The python zip() Function returns a zip object, which maps a similar index of
multiple containers. It takes iterables (can be zero or more), makes it an iterator
that aggregates the elements based on iterables passed, and returns an iterator of
tuples.

Python zip() Function Example

457. numList = [4,5, 6]

458. strList = ['four', 'five', 'six']

459.

460. # No iterables are passed


461. result = zip()

462.

463. # Converting itertor to list

464. resultList = list(result)

465. print(resultList)

466.

467. # Two iterables are passed

468. result = zip(numList, strList)

469.

470. # Converting itertor to set

471. resultSet = set(result)

472. print(resultSet)

Output:

[]{(5, 'five'), (4, 'four'), (6, 'six')}


Chap.5
Loop and control structure
Python If-else statements
Decision making is the most important aspect of almost all the programming
languages. As the name implies, decision making allows us to run a particular block
of code for a particular decision. Here, the decisions are made on the validity of the
particular conditions. Condition checking is the backbone of decision making.

In python, decision making is performed by the following statements.

Statement Description

If Statement The if statement is used to test a


specific condition. If the condition is
true, a block of code (if-block) will be
executed.

If - else Statement The if-else statement is similar to if


statement except the fact that, it also
provides the block of the code for the
false case of the condition to be
checked. If the condition provided in
the if statement is false, then the else
statement will be executed.

Nested if Statement Nested if statements enable us to use if


? else statement inside an outer if
statement.

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.

The syntax of the if-statement is given below.

473. if expression:

474. statement
Example 1
475. num = int(input("enter the number?"))

476. if num%2 == 0:

477. print("Number is even")

Output:

enter the number?10Number is even

Example 2 : Program to print the largest of the three


numbers.
478. a = int(input("Enter a? "));

479. b = int(input("Enter b? "));

480. c = int(input("Enter c? "));

481. if a>b and a>c:

482. print("a is largest");

483. if b>a and b>c:

484. print("b is largest");

485. if c>a and c>b:

486. print("c is largest");

Output:

Enter a? 100Enter b? 120Enter c? 130c is largest

The if-else statement


The if-else statement provides an else block combined with the if statement which
is executed in the false case of the condition.

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

488. #block of statements

489. else:

490. #another block of statements (else-block)

Example 1 : Program to check whether a person is


eligible to vote or not.
491. age = int (input("Enter your age? "))

492. if age>=18:
493. print("You are eligible to vote !!");

494. else:

495. print("Sorry! you have to wait !!");

Output:

Enter your age? 90You are eligible to vote !!

Example 2: Program to check whether a number is


even or not.
496. num = int(input("enter the number?"))

497. if num%2 == 0:

498. print("Number is even...")

499. else:

500. print("Number is odd...")

Output:

enter the number?10Number is even

The elif statement


The elif statement enables us to check multiple conditions and execute the specific
block of statements depending upon the true condition among them. We can have
any number of elif statements in our program depending upon our need. However,
using elif is optional.

The elif statement works like an if-else-if ladder statement in C. It must be


succeeded by an if statement.

The syntax of the elif statement is given below.

501. if expression 1:

502. # block of statements

503.

504. elif expression 2:

505. # block of statements


506.

507. elif expression 3:

508. # block of statements

509.

510. else:

511. # block of statements

Example 1
512. number = int(input("Enter the number?"))

513. if number==10:

514. print("number is equals to 10")


515. elif number==50:

516. print("number is equal to 50");

517. elif number==100:

518. print("number is equal to 100");

519. else:

520. print("number is not equal to 10, 50 or 100");

Output:

Enter the number?15number is not equal to 10, 50 or 100

Example 2
521. marks = int(input("Enter the marks? "))

522. f marks > 85 and marks <= 100:

523. print("Congrats ! you scored grade A ...")

524. lif marks > 60 and marks <= 85:

525. print("You scored grade B + ...")

526. lif marks > 40 and marks <= 60:

527. print("You scored grade B ...")

528. lif (marks > 30 and marks <= 40):

529. print("You scored grade C ...")

530. lse:

531. print("Sorry you are fail ?")


Chap.6
Python Loops
The flow of the programs written in any programming language is sequential by
default. Sometimes we may need to alter the flow of the program. The execution of
a specific code may need to be repeated several numbers of times.

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.

Why we use loops in python?


The looping simplifies the complex problems into the easy ones. It enables us to
alter the flow of the program so that instead of writing the same code again and
again, we can repeat the same code for a finite number of times. For example, if we
need to print the first 10 natural numbers then, instead of using the print statement
10 times, we can print inside a loop which runs up to 10 iterations.

Advantages of loops
There are the following advantages of loops in Python

 It provides code re-usability.

 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).

There are the following loop statements in Python.

Loop Statement Description

for loop The for loop is used in the case where


we need to execute some part of the
code until the given condition is
satisfied. The for loop is also called as a
per-tested loop. It is better to use for
loop if the number of iteration is known
in advance.
while loop The while loop is to be used in the
scenario where we don't know the
number of iterations in advance. The
block of statements is executed in the
while loop until the condition specified
in the while loop is satisfied. It is also
called a pre-tested loop.

do-while loop The do-while loop continues until a


given condition satisfies. It is also
called post tested loop. It is used when
it is necessary to execute the loop at
least once (mostly menu driven
programs).

Python for loop


The for loop in Python is used to iterate the statements or a part of the program
several times. It is frequently used to traverse the data structures like list, tuple, or
dictionary.

The syntax of for loop in python is given below.

1. for iterating_var in sequence:

2. statement(s)
The for loop flowchart

For loop Using Sequence


Example-1: Iterating string using for loop

3. str = "Python"

4. for i in str:

5. print(i)

Output:

Python

Example- 2: Program to print the table of the given number .

6. list = [1,2,3,4,5,6,7,8,9,10]

7. n = 5
8. for i in list:

9. c = n*i

10. print(c)

Output:

5101520253035404550s

Example-4: Program to print the sum of the given list.

11. list = [10,30,23,43,65,12]

12. sum = 0

13. for i in list:

14. sum = sum+i

15. print("The sum is:",sum)

Output:

The sum is: 183

For loop Using range() function


The range() function

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:

16. range(start,stop,step size)

 The start represents the beginning of the iteration.

 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.

Consider the following examples:

Example-1: Program to print numbers in sequence.


17. for i in range(10):

18. print(i,end = ' ')

Output:

0 1 2 3 4 5 6 7 8 9

Example - 2: Program to print table of given number.

19. n = int(input("Enter the number "))

20. for i in range(1,11):

21. c = n*i

22. print(n,"*",i,"=",c)

Output:

Enter the number 1010 * 1 = 1010 * 2 = 2010 * 3 = 3010 * 4 = 4010 * 5 = 5010


* 6 = 6010 * 7 = 7010 * 8 = 8010 * 9 = 9010 * 10 = 100

Example-3: Program to print even number using step size in range().

23. n = int(input("Enter the number "))

24. for i in range(2,n,2):

25. print(i)

Output:

Enter the number 2024681012141618

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.

26. list = ['Peter','Joseph','Ricky','Devansh']

27. for i in range(len(list)):

28. print("Hello",list[i])

Output:

Hello PeterHello JosephHello RickyHello Devansh


Nested for loop in python
Python allows us to nest any number of for loops inside a for loop. The inner loop is
executed n number of times for every iteration of the outer loop. The syntax is
given below.

Syntax

29. for iterating_var1 in sequence: #outer loop

30. for iterating_var2 in sequence: #inner loop

31. #block of statements

32. #Other statements

Example- 1: Nested for loop


33. # User input for number of rows

34. rows = int(input("Enter the rows:"))

35. # Outer loop will print number of rows

36. for i in range(0,rows+1):

37. # Inner loop will print number of Astrisk

38. for j in range(i):

39. print("*",end = '')

40. print()

Output:

Enter the rows:5***************

Example-2: Program to number pyramid.


41. rows = int(input("Enter the rows"))

42. for i in range(0,rows+1):

43. for j in range(i):

44. print(i,end = '')

45. print()
Output:

122333444455555

Using else statement with for loop


Unlike other languages like C, C++, or Java, Python allows us to use the else
statement with the for loop which can be executed only when all the iterations are
exhausted. Here, we must notice that if the loop contains any of the break
statement then the else statement will not be executed.

Example 1
46. for i in range(0,5):

47. print(i)

48. else:

49. print("for loop completely exhausted, since there is no break.")

Output:

01234for loop completely exhausted, since there is no break.

The for loop completely exhausted, since there is no break.

Example 2
50. for i in range(0,5):

51. print(i)

52. break;

53. else:print("for loop is exhausted");

54. print("The loop is broken due to break statement...came out of the loop")

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;

# Now you can call printme function


printme("I'm first call to user defined function!")
printme("Again second call to the same function")

When the above code is executed, it produces the following result −


I'm first call to user defined function!
Again second call to the same 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
back in the calling function. For example −
#Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return

# Now you can call changeme function


mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

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.
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assig new reference in mylist
print "Values inside the function: ", mylist
return

# Now you can call changeme function


mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

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;

# Now you can call printme function


printme()

When the above code is executed, it produces the following result −


Traceback (most recent call last):
File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)
Keyword arguments
Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python
interpreter is able to use the keywords provided to match the values with parameters.
You can also make keyword calls to the printme() function in the following ways −
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme( str = "My string")

When the above code is executed, it produces the following result −


My string
The following example gives more clear picture. Note that the order of parameters
does not matter.
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )

When the above code is executed, it produces the following result −


Name: miki
Age 50
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 −
# Function definition is here
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )
printinfo( name="miki" )

When the above code is executed, it produces the following result −


Name: miki
Age 50
Name: miki
Age 35
Variable-length arguments
You may need to process a function for more arguments than you 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.
Syntax for a function with non-keyword variable arguments is this −
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all
nonkeyword variable arguments. This tuple remains empty if no additional arguments
are specified during the function call. Following is a simple example −
# Function definition is here
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;

# Now you can call printinfo function


printinfo( 10 )
printinfo( 70, 60, 50 )

When the above code is executed, it produces the following result −


Output is:
10
Output is:
70
60
50
The Anonymous Functions
These functions are called anonymous because they are not declared in the standard
manner by using the def keyword. You can use the lambda keyword to create small
anonymous functions.
 Lambda forms can take any number of arguments but return just one value in
the form of an expression. They cannot contain commands or multiple
expressions.
 An anonymous function cannot be a direct call to print because lambda requires
an expression
 Lambda functions have their own local namespace and cannot access variables
other than those in their parameter list and those in the global namespace.
 Although it appears that lambda's are a one-line version of a function, they are
not equivalent to inline statements in C or C++, whose purpose is by passing
function stack allocation during invocation for performance reasons.

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 −

# Function definition is here


sum = lambda arg1, arg2: arg1 + arg2;

# Now you can call sum as a function


print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )

When the above code is executed, it produces the following result −


Value of total : 30
Value of total : 40
The 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.
All the above examples are not returning any value. You can return a value from a
function as follows −
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print "Inside the function : ", total
return total;

# Now you can call sum function


total = sum( 10, 20 );
print "Outside the function : ", total

When the above code is executed, it produces the following result −


Inside the function : 30
Outside the function : 30
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

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 −

total = 0; # This is global variable.


# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print "Inside the function local total : ", total
return total;

# Now you can call sum function


sum( 10, 20 );
print "Outside the function global total : ", total

When the above code is executed, it produces the following result −


Inside the function local total : 30
Outside the function global total : 0
Chap.8
Python Arrays: Create, Reverse, Pop with Python Array Examples

What is Python Array?


A Python Array is a collection of common type of data structures having elements
with same data type. It is used to store collections of data. In Python programming, an
arrays are handled by the "array" module. If you create arrays using the array module,
elements of the array must be of the same numeric type.

Python Lists Vs Arrays

In Python, we can treat lists as arrays. However, we cannot constrain the type
of elements stored in a list. For example:

# elements of different types


a = [1, 3.5, "Hello"]

If you create arrays using the  array  module, all elements of the array must be
of the same numeric type.

import array as arr


# Error
a = arr.array('d', [1, 3.5, "Hello"])

Output

Traceback (most recent call last):


File "<string>", line 3, in <module>
a = arr.array('d', [1, 3.5, "Hello"])
TypeError: must be real number, not str
When to use arrays?

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:

import array as arr


a = arr.array('d', [1.1, 3.5, 4.5])
print(a)

Output

array('d', [1.1, 3.5, 4.5])

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:
import array as arr
a = arr.array('i', [2, 4, 6, 8])

print("First element:", a[0])


print("Second element:", a[1])
print("Last element:", a[-1])

Output

First element: 2
Second element: 4
Last element: 8

Note: The index starts from 0 (not 1) similar to lists.

Slicing Python Arrays


We can access a range of items in an array by using the slicing operator  : .

import array as arr

numbers_list = [2, 5, 62, 5, 42, 52, 48, 5]


numbers_array = arr.array('i', numbers_list)

print(numbers_array[2:5]) # 3rd to 5th


print(numbers_array[:-5]) # beginning to 4th
print(numbers_array[5:]) # 6th to end
print(numbers_array[:]) # beginning to end

Output

array('i', [62, 5, 42])


array('i', [2, 5, 62])
array('i', [52, 48, 5])
array('i', [2, 5, 62, 5, 42, 52, 48, 5])
Changing and Adding Elements
Arrays are mutable; their elements can be changed in a similar way as lists.

import array as arr

numbers = arr.array('i', [1, 2, 3, 5, 7, 10])

# changing first element


numbers[0] = 0
print(numbers) # Output: array('i', [0, 2, 3, 5, 7, 10])

# changing 3rd to 5th element


numbers[2:5] = arr.array('i', [4, 6, 8])
print(numbers) # Output: array('i', [0, 2, 4, 6, 8, 10])

Output

array('i', [0, 2, 3, 5, 7, 10])


array('i', [0, 2, 4, 6, 8, 10])

We can add one item to the array using the  append()  method, or add several
items using the  extend()  method.

import array as arr

numbers = arr.array('i', [1, 2, 3])

numbers.append(4)
print(numbers) # Output: array('i', [1, 2, 3, 4])

# extend() appends iterable to the end of the array


numbers.extend([5, 6, 7])
print(numbers) # Output: array('i', [1, 2, 3, 4, 5, 6, 7])

Output
array('i', [1, 2, 3, 4])
array('i', [1, 2, 3, 4, 5, 6, 7])

We can also concatenate two arrays using  +  operator.

import array as arr

odd = arr.array('i', [1, 3, 5])


even = arr.array('i', [2, 4, 6])

numbers = arr.array('i') # creating empty array of integer


numbers = odd + even

print(numbers)

Output

array('i', [1, 3, 5, 2, 4, 6])

Removing Python Array Elements


We can delete one or more items from an array using Python's del statement.

import array as arr

number = arr.array('i', [1, 2, 3, 3, 4])

del number[2] # removing third element


print(number) # Output: array('i', [1, 2, 3, 4])

del number # deleting entire array


print(number) # Error: array is not defined

Output

array('i', [1, 2, 3, 4])


Traceback (most recent call last):
File "<string>", line 9, in <module>
print(number) # Error: array is not defined
NameError: name 'number' is not defined
We can use the  remove()  method to remove the given item, and  pop()  method
to remove an item at the given index.

import array as arr

numbers = arr.array('i', [10, 11, 12, 12, 13])

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])

How to Search and get the index of a value in an Array


With this operation, you can search for an item in an array based on its value. This
method accepts only one argument, value. It is a non-destructive method, which
means it does not affect the array values.

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.

import array as myarray


number = myarray.array('b', [2, 3, 4, 5, 6])
print(number.index(3))

Output:

1
This operation will return the index of the first occurrence of the mentioned element.

How to Reverse an Array in Python


This operation will reverse the entire array.

Syntax: array.reverse()

import array as myarray


number = myarray.array('b', [1,2, 3])
number.reverse()
print(number)

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:

from array import array


p = array('u',[u'\u0050',u'\u0059',u'\u0054',u'\u0048',u'\u004F',u'\u004E'])
print(p)
q = p.tounicode()
print(q)

Output:

array('u', 'PYTHON')
PYTHON

Count the occurrence of a Value in Array


You can also count the occurrence of elements in the array using the array.count(x)
syntax.

Example:

import array as myarr


number = myarr.array('b', [2, 3, 5, 4,3,3,3])
print(number.count(3))

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)

Object: The instance of a class / it’s the working entity of a class


Class: This is the model or standard about the capability of what an object can do
Method: Can modify a class state that would apply across all the instances of the class
Instance: These are like Objects, however, let’s think about it in these terms: A
blueprint for a car design is the class description, all the cars manufactured from that
blueprint are objects of that class. Your car that has been made from that blueprint is an
instance of that class.
Now that we have covered these keywords, let’s jump into the four principles of
object-oriented-programming: Encapsulation, Abstraction, Inheritance, and
Polymorphism.

The Four Principles of Object-Oriented-Programming (OOP):


Encapsulation
Encapsulation is accomplished when each object maintains a private state, inside a
class. Other objects can not access this state directly, instead, they can only invoke a
list of public functions. The object manages its own state via these functions and no
other class can alter it unless explicitly allowed. In order to communicate with the object,
you will need to utilize the methods provided. One way I like to think of encapsulation is
by using the example of people and their dogs. If we want to apply encapsulation, we do
so by encapsulating all “dog” logic into a Dog class. The “state” of the dog is in the
private variables playful, hungry and energy and each of these variables has their
respective fields.
There is also a private method: bark(). The dog class can call this whenever it
wants, and the other classes can not tell the dog when to bark. There are also public
methods such as sleep(), play() and eat() that are available to other classes. Each of
these functions modifies the internal state of the Dog class and may invoke bark(), when
this happens the private state and public methods are bonded.

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
55. class derived-class(base class):

56. <class-suite>

A class can inherit multiple classes by mentioning all of them inside the bracket.
Consider the following syntax.

Syntax
57. class derive-class(<base class 1>, <base class 2>, ..... <base class n>):

58. <class - suite>

Example 1
59. class Animal:

60. def speak(self):

61. print("Animal Speaking")

62. #child class Dog inherits the base class Animal

63. class Dog(Animal):

64. def bark(self):

65. print("dog barking")

66. d = Dog()

67. d.bark()
68. d.speak()

Output:
dog barkingAnimal Speaking

Python Multi-Level inheritance


Multi-Level inheritance is possible in python like other object-oriented languages. Multi-
level inheritance is archived when a derived class inherits another derived class. There
is no limit on the number of levels up to which, the multi-level inheritance is archived in
python.

The syntax of multi-level inheritance is given below.

Syntax
69. class class1:

70. <class-suite>

71. class class2(class1):

72. <class suite>

73. class class3(class2):


74. <class suite>

75. .

76. .

Example
77. class Animal:

78. def speak(self):

79. print("Animal Speaking")

80. #The child class Dog inherits the base class Animal

81. class Dog(Animal):

82. def bark(self):

83. print("dog barking")

84. #The child class Dogchild inherits another child class Dog

85. class DogChild(Dog):

86. def eat(self):

87. print("Eating bread...")

88. d = DogChild()

89. d.bark()

90. d.speak()

91. d.eat()

Output:
dog barkingAnimal SpeakingEating bread...

Python Multiple inheritance


Python provides us the flexibility to inherit multiple base classes in the child class.
The syntax to perform multiple inheritance is given below.

Syntax
92. class Base1:

93. <class-suite>

94.

95. class Base2:

96. <class-suite>

97. .

98. .

99. .

100. class BaseN:

101. <class-suite>

102.

103. class Derived(Base1, Base2, ...... BaseN):

104. <class-suite>

The issubclass(sub,sup) method


The issubclass(sub, sup) method is used to check the relationships between the
specified classes. It returns true if the first class is the subclass of the second class, and
false otherwise.

Consider the following example.


Example
105. class Calculation1:

106. def Summation(self,a,b):

107. return a+b;

108. class Calculation2:

109. def Multiplication(self,a,b):

110. return a*b;

111. class Derived(Calculation1,Calculation2):

112. def Divide(self,a,b):

113. return a/b;

114. d = Derived()

115. print(issubclass(Derived,Calculation2))

116. 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

The isinstance (obj, class) method


The isinstance() method is used to check the relationship between the objects and
classes. It returns true if the first parameter, i.e., obj is the instance of the second
parameter, i.e., class.

Consider the following example.

Example
14. class Calculation1:

15. def Summation(self,a,b):

16. return a+b;

17. class Calculation2:

18. def Multiplication(self,a,b):

19. return a*b;

20. class Derived(Calculation1,Calculation2):

21. def Divide(self,a,b):

22. return a/b;

23. d = Derived()
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.

Consider the following example to perform method overriding in python.

Example
25. class Animal:

26. def speak(self):

27. print("speaking")

28. class Dog(Animal):

29. def speak(self):

30. print("Barking")

31. d = Dog()

32. d.speak()

Output:
Barking

Real Life Example of method overriding


33. class Bank:

34. def getroi(self):

35. return 10;

36. class SBI(Bank):


37. def getroi(self):

38. return 7;

39.

40. class ICICI(Bank):

41. def getroi(self):

42. return 8;

43. b1 = Bank()

44. b2 = SBI()

45. b3 = ICICI()

46. print("Bank Rate of interest:",b1.getroi());

47. print("SBI Rate of interest:",b2.getroi());

48. print("ICICI Rate of interest:",b3.getroi());

Output:
Bank Rate of interest: 10SBI Rate of interest: 7ICICI Rate of interest: 8

Data abstraction in python


Abstraction is an important aspect of object-oriented programming. In python, we can
also perform data hiding by adding the double underscore (___) as a prefix to the
attribute which is to be hidden. After this, the attribute will not be visible outside of the
class through the object.

Consider the following example.

Example
49. class Employee:

50. __count = 0;

51. def __init__(self):

52. Employee.__count = Employee.__count+1


53. def display(self):

54. print("The number of employees",Employee.__count)

55. emp = Employee()

56. emp2 = Employee()

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.

Example of inbuilt polymorphic functions :


# Python program to demonstrate in-built poly-
# morphic functions

# len() being used for a string


print(len("geeks"))

# len() being used for a list


print(len([10, 20, 30]))

Output:53

Examples of used defined polymorphic functions :


# A simple Python function to demonstrate
# Polymorphism

def add(x, y, z = 0):

return x + y+z

# Driver code
print(add(2, 3))
print(add(2, 3, 4))

Output:

59

Polymorphism with class methods:


Below code shows how python can use two different class types, in the same way. We
create a for loop that iterates through a tuple of objects. Then call the methods without
being concerned about which class type each object is. We assume that these methods
actually exist in each class.
class India():

def capital(self):

print("New Delhi is the capital of India.")

def language(self):

print("Hindi is the most widely spoken language of India.")

def type(self):

print("India is a developing country.")

class USA():

def capital(self):
print("Washington, D.C. is the capital of USA.")

def language(self):

print("English is the primary language of USA.")

def type(self):

print("USA is a developed country.")

obj_ind = India()

obj_usa = USA()

for country in (obj_ind, obj_usa):

country.capital()
country.language()
country.type()

Output:New Delhi is the capital of India.Hindi is the most widely


spoken language of India.India is a developing country.Washington,
D.C. is the capital of USA.English is the primary language of USA.USA
is a developed country.

Polymorphism with Inheritance:

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):

print("There are many types of birds.")


def flight(self):

print("Most of the birds can fly but some cannot.")

class sparrow(Bird):

def flight(self):

print("Sparrows can fly.")

class ostrich(Bird):

def flight(self):

print("Ostriches cannot fly.")

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.

Polymorphism with a Function and objects:


It is also possible to create a function that can take any object, allowing for
polymorphism. In this example, let’s create a function called “func()” which will take an
object which we will name “obj”. Though we are using the name ‘obj’, any instantiated
object will be able to be called into this function. Next, lets give the function something
to do that uses the ‘obj’ object we passed to it. In this case lets call the three methods,
viz., capital(), language() and type(), each of which is defined in the two classes ‘India’
and ‘USA’.
e.g Next, let’s create instantiations of both the ‘India’ and ‘USA’ classes if we don’t have
them already. With those, we can call their action using the same func() function:
def func(obj):

obj.capital()
obj.language()
obj.type()

obj_ind = India()

obj_usa = USA()

func(obj_ind)
func(obj_usa)

Code : Implementing Polymorphism with a Function


class India():

def capital(self):

print("New Delhi is the capital of India.")

def language(self):

print("Hindi is the most widely spoken language of India.")

def type(self):

print("India is a developing country.")

class USA():
def capital(self):

print("Washington, D.C. is the capital of USA.")

def language(self):

print("English is the primary language of USA.")

def type(self):

print("USA is a developed country.")

def func(obj):

obj.capital()
obj.language()
obj.type()

obj_ind = India()

obj_usa = USA()

func(obj_ind)
func(obj_usa)

Output:New Delhi is the capital of India.Hindi is the most widely


spoken language of India.India is a developing country.Washington,
D.C. is the capital of USA.English is the primary language of USA.USA
is a developed country.
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.

Basic GUI Application


GUI elements and their functionality are defined in the Tkinter module. The following
code demonstrates the steps in creating a UI.
from tkinter import *
window=Tk()# add widgets here
window.title('Hello Python')
window.geometry("300x200+10+20")
window.mainloop()
First of all, import the TKinter module. After importing, setup the application object by
calling the Tk() function. This will create a top-level window (root) having a frame with a
title bar, control box with the minimize and close buttons, and a client area to hold other
widgets. The geometry() method defines the width, height and coordinates of the top left
corner of the frame as below (all values are in pixels):
window.geometry("widthxheight+XPOS+YPOS") The application object then enters an
event listening loop by calling the mainloop() method. The application is now constantly
waiting for any event generated on the elements in it. The event could be text entered in
a text field, a selection made from the dropdown or radio button, single/double click
actions of mouse, etc. The application's functionality involves executing appropriate
callback functions in response to a particular type of event. We shall discuss event
handling later in this tutorial. The event loop will terminate as and when the close button
on the title bar is clicked. The above code will create the following window:

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

from tkinter import *


window=Tk()
btn=Button(window,text="This is Button widget",fg='blue')
btn.place(x=80,y=100)
window.title('HelloPython')
window.geometry("300x200+10+10")
window.mainloop()

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

from tkinter import *


window=Tk()
btn=Button(window, text="This is Button widget", fg='blue')
btn.place(x=80, y=100)
lbl=Label(window, text="This is Label widget", fg='red',
font=("Helvetica", 16))
lbl.place(x=60, y=50)
txtfld=Entry(window, text="This is Entry Widget", bd=5)
txtfld.place(x=80, y=150)
window.title('Hello Python')
window.geometry("300x200+10+10")
window.mainloop()
The above example will create the following window.
Create UI Widgets in Python-Tkinter

Selection Widgets
Radiobutton: This widget displays a toggle button having an ON/OFF state. There may
be more than one button, but only one of them will be ON at a given time.
Checkbutton: This is also a toggle button. A rectangular check box appears before its
caption. Its ON state is displayed by the tick mark in the box which disappears when it is
clicked to OFF.
Combobox: This class is defined in the ttk module of tkinterpackage. It populates drop
down data from a collection data type, such as a tuple or a list as values parameter.
Listbox: Unlike Combobox, this widget displays the entire collection of string items. The
user can select one or multiple items.
The following example demonstrates the window with the selection widgets:
Radiobutton, Checkbutton, Listbox and Combobox:
Example: Selection Widgets
Copy

from tkinter import *


from tkinter.ttk import
Comboboxwindow=Tk()
var = StringVar()
var.set("one")
data=("one", "two", "three", "four")
cb=Combobox(window, values=data)
cb.place(x=60, y=150)
lb=Listbox(window, height=5, selectmode='multiple')
for num in data:
lb.insert(END,num)
lb.place(x=250, y=150)
v0=IntVar()
v0.set(1)
r1=Radiobutton(window, text="male", variable=v0,value=1)
r2=Radiobutton(window, text="female", variable=v0,value=2)
r1.place(x=100,y=50)
r2.place(x=180, y=50)
v1 = IntVar()
v2 = IntVar()
C1 = Checkbutton(window, text = "Cricket", variable = v1)
C2 = Checkbutton(window, text = "Tennis", variable = v2)
C1.place(x=100, y=100)
C2.place(x=180, y=100)
window.title('Hello Python')
window.geometry("400x300+10+10")window.mainloop()
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.

<Button-2> Button 2 Middle mouse


button click.

<Destroy> Destroy Window is being


destroyed.

<Double-Button-1> Double Button 1 Double-click first


mouse button 1.
<Enter> Enter Cursor enters
window.

<Expose> Expose Window fully or


partially exposed.

<KeyPress-a> KeyPress a Any key has been


pressed.

<KeyRelease> KeyRelease Any key has been


released.

<Leave> Leave Cursor leaves


window.

<Print> Print PRINT key has


been pressed.

<FocusIn> FocusIn Widget gains


focus.

<FocusOut> FocusOut widget loses focus.

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)

For example, to invoke the MyButtonClicked() function on left button


click, use the following code:
Example: Even Binding
Copy

from tkinter import *


window=Tk()
btn = Button(window, text='OK')
btn.bind('<Button-1>',
MyButtonClicked)
The event object is characterized by many properties such as source
widget, position coordinates, mouse button number and event type.
These can be passed to the callback function if required.

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

from tkinter import *


class MyWindow:
def __init__(self, win):
self.lbl1=Label(win, text='First number')
self.lbl2=Label(win, text='Second number')
self.lbl3=Label(win, text='Result')
self.t1=Entry(bd=3)
self.t2=Entry()
self.t3=Entry()
self.btn1 = Button(win, text='Add')
self.btn2=Button(win, text='Subtract')
self.lbl1.place(x=100, y=50)
self.t1.place(x=200, y=50)
self.lbl2.place(x=100, y=100)
self.t2.place(x=200, y=100)
self.b1=Button(win,text='Add',command=self.add)
self.b2=Button(win, text='Subtract')
self.b2.bind('<Button-1>', self.sub)
self.b1.place(x=100, y=150)
self.b2.place(x=200, y=150)
self.lbl3.place(x=100, y=200)
self.t3.place(x=200, y=200)
def add(self):
self.t3.delete(0, 'end')
num1=int(self.t1.get())
num2=int(self.t2.get())
result=num1+num2
self.t3.insert(END, str(result))
def sub(self, event):
self.t3.delete(0, 'end')
num1=int(self.t1.get())
num2=int(self.t2.get())
result=num1-num2
self.t3.insert(END, str(result))
window=Tk()
mywin=MyWindow(window)
window.title('Hello Python')
window.geometry("400x300+10+10")
window.mainloop()
The above example creates the following UI.

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.

For installing cx-Oracle : 


If you are using Python >= 3.6 use the below command in Linux: –
pip install cx-Oracle
If you are using Python >= 3.6 use the below command in Windows: –
py -m pip install cx-Oracle
By this command, you can install cx-Oracle package but it is required to install Oracle
database first on your PC.
 
 Import database specific module 
Ex. import cx_Oracle
 connect(): Now Establish a connection between the Python program and
Oracle database by using connect() function. 
 
con = cx_Oracle.connect('username/password@localhost')
 cursor(): To execute a SQL query and to provide results some special object is
required that is nothing but cursor() object.
 
cursor = cx_Oracle.cursor()
 execute/executemany method :
 
cursor.execute(sqlquery) – – – -> to execute a single query. 
cursor.executemany(sqlqueries) – – – -> to execute a single query with multiple bind
variables/place holders.
 “Perform Basic CRUD Operations Using CX_ORACLE, Part 1.”
Additional Setup
Before you run the update examples with cx_Oracle, create a reset script and a template
that will handle all the example updates.

Reset template. To keep the examples clean and precise, you’ll want to reset the
data at times. Create a new file called reset_data.py with the following code, and then run
it whenever you would like to reset the data. (Note that this version adds pet data not
included in other articles in this series.)

import cx_Oracle
import os
connectString = os.getenv('db_connect')
con = cx_Oracle.connect(connectString)
cur = con.cursor()

# Delete rows
statement = 'delete from cx_pets'
cur.execute(statement)
# Reset Identity Column
statement = 'alter table cx_pets modify id generated
BY DEFAULT as identity (START WITH 8)'
cur.execute(statement)

# Delete rows
statement = 'delete from cx_people'
cur.execute(statement)

# Reset Identity Column


statement = 'alter table cx_people modify id
generated
BY DEFAULT as identity (START WITH 3)'
cur.execute(statement)

# Insert default rows


rows = [(1, 'Bob', 35, 'I like dogs'),
(2, 'Kim', 27, 'I like birds')]
cur.bindarraysize = 2
cur.setinputsizes(int, 20, int, 100)
cur.executemany("insert into cx_people(id, name,
age, notes)
values (:1, :2, :3, :4)", rows)
con.commit()

# Insert default rows


rows = [(1, 'Duke', 1, 'dog'),
(2, 'Pepe', 2, 'bird'),
(3, 'Princess', 1, 'snake'),
(4, 'Polly', 1, 'bird'),
(5, 'Rollo', 1, 'horse'),
(6, 'Buster', 1, 'dog'),
(7, 'Fido', 1, 'cat')]
cur.bindarraysize = 2
cur.setinputsizes(int, 20, int, 100)
cur.executemany("insert into cx_pets (id, name,
owner, type)
values (:1, :2, :3, :4)", rows)
con.commit()

cur.close()
Update template. To run the update examples in this article, create a new file called
update.py with the following code

import cx_Oracle
import os
connectString = os.getenv('db_connect')
con = cx_Oracle.connect(connectString)

def get_all_rows(label, data_type='people'):


# Query all rows
cur = con.cursor()
if (data_type == 'pets'):
statement = 'select id, name, owner, type
from cx_pets order by owner, id'
else:
statement = 'select id, name, age, notes
from cx_people order by id'
cur.execute(statement)
res = cur.fetchall()
print(label + ': ')
print (res)
print(' ')
cur.close()

get_all_rows('Original Data')

# Your code here

get_all_rows('New Data')
And for each example exercise, replace the # Your code here line with the specific
example code. The update.py template includes the helper function get_all_rows(), which
encapsulates a SELECT statement to verify that the updates worked. The SELECT
functionality is covered in Part 2 of this series.

Note: Please review all example code in this article, and run it only if you are sure it will
not cause any problems with your system.

Simple Update
Now perform a simple update that modifies a single record in the cx_people table.
Replace the # Your code here line in update.py with the following code snippet, and run
update.py in your Python session:

cur = con.cursor()
statement = 'update cx_people set age = :1 where id
= :2'
cur.execute(statement, (31, 1))
con.commit()
When I run this code in my Python session, I see
Original Data:
[(1, 'Bob', 35, 'I like dogs'), (2, 'Kim', 27, 'I
like birds')]

New Data:
[(1, 'Bob', 31, 'I like dogs'), (2, 'Kim', 27, 'I
like birds')]
Here’s what the update.py code does:

Gets a cursor object from the connection. You will use this cursor to perform your
database operations.

Prepares a SQL UPDATE statement, changing the age to 31 for the record whose id is 1.

Executes the statement, using bind variables. (See Part 2 of this series for an explanation
of bind variables.)

Commits the transaction.

Deeper Dive
Now update Bob’s notes to 'I like cats'.

When you’re done, the results should be


Original Data:
[(1, 'Bob', 31, 'I like dogs'), (2, 'Kim', 27, 'I
like birds')]

New Data:
[(1, 'Bob', 31, 'I like cats'), (2, 'Kim', 27, 'I
like birds')]
What does the successful code look like? Like this:
cur = con.cursor()
statement = 'update cx_people set notes = :1 where
id = :2'
cur.execute(statement, ("I like cats", 1))
con.commit()
Reset the data. Now is a good time to run reset_data.py.
Boilerplate change. Now change the
boilerplate get_all_rows statements in update.py to get pet data.
Replace the last three code lines of update.py with
get_all_rows('Original Data', 'pets')
# Your code here

get_all_rows('New Data', 'pets')


Make Sure Your WHERE Clause Is Specific
Note that the previous example used the id column in the WHERE
clause. For this data set, id is the primary key. You do not always
need to use a primary key, but make sure you update only the rows
you intend to.
Now let’s look at updating multiple rows. Let’s have Bob give his dog,
Duke, to Kim. Replace the # Your code here line in update.py with the
following code snippet, and run update.py in your Python session:
cur = con.cursor()
statement = 'update cx_pets set owner = :1
where owner = :2 and type = :3'
cur.execute(statement, (2, 1, 'dog'))
con.commit()
When I run this code in my Python session, I see
Original Data:
[(1, 'Duke', 1, 'dog'), (3, 'Princess', 1, 'snake'),
(4, 'Polly', 1, 'bird'), (5, 'Rollo', 1, 'horse'),
(6, 'Buster', 1, 'dog'), (7, 'Fido', 1, 'cat'),
(2, 'Pepe', 2, 'bird')]

New Data:
[(3, 'Princess', 1, 'snake'), (4, 'Polly', 1,
'bird'),
(5, 'Rollo', 1, 'horse'), (7, 'Fido', 1, 'cat'),
(1, 'Duke', 2, 'dog'), (2, 'Pepe', 2, 'bird'),
(6, 'Buster', 2, 'dog')]
Here’s what the update.py code does:

 Gets a cursor object from the connection


 Prepares a SQL UPDATE statement, changing the owner value
to 2 (Kim) for the records with an owner value of 1 (Bob) and a
type value of 'dog'
 Executes the statement, using bind variables
 Commits the transaction

This example uses only owner and type values, and it assumes that
Bob has only one dog, Duke, as in the original data. But the new reset
data function added a second dog, Buster. This example
demonstrates what can happen when multiple users are working with
the same data set.
In the data, the only unique identifier for cx_pets is id. Bob may have
two dogs—or even two dogs named Duke. If you intend to change a
specific row, make sure to use a unique identifier.
It also helps to . . .
Verify the Number of Affected Rows
Now let’s give Buster back to Bob. This time, use the unique id column
and print out the number of rows affected, using Cursor.rowcount.
Replace the # Your code here line in update.py with the following code
snippet, and run update.py in your Python session:
cur = con.cursor()
statement = 'update cx_pets set owner = :1 where id
= :2'
cur.execute(statement, (1, 6))
con.commit()
print('Number of rows updated: ' +
str(cur.rowcount))
print(' ')
When I run this code in my Python session, I see
Original Data:
[(3, 'Princess', 1, 'snake'), (4, 'Polly', 1,
'bird'),
(5, 'Rollo', 1, 'horse'), (7, 'Fido', 1, 'cat'),
(1, 'Duke', 2, 'dog'), (2, 'Pepe', 2, 'bird'),
(6, 'Buster', 2, 'dog')]

Number of rows updated: 1

New Data:
[(3, 'Princess', 1, 'snake'), (4, 'Polly', 1,
'bird'),
(5, 'Rollo', 1, 'horse'), (6, 'Buster', 1, 'dog'),
(7, 'Fido', 1, 'cat'), (1, 'Duke', 2, 'dog'),
(2, 'Pepe', 2, 'bird')]
Here’s what the update.py code does:

 Gets a cursor object from the connection


 Prepares a SQL UPDATE statement, changing the owner value
to 1 (Bob) for the records with an id value of 6 (Buster)
 Executes the statement, using bind variables
 Commits the transaction

Cursor.rowcount shows the number of rows affected for INSERT,


UPDATE, and DELETE statements and the number of rows returned
in a SELECT statement.
Another Deeper Dive
Now let’s give all birds to Kim—all the birds she doesn’t already have
—and print the number of affected rows.
When you’re done, the results should be
Original Data:
[(3, 'Princess', 1, 'snake'), (4, 'Polly', 1,
'bird'),
(5, 'Rollo', 1, 'horse'), (6, 'Buster', 1, 'dog'),
(7, 'Fido', 1, 'cat'), (1, 'Duke', 2, 'dog'),
(2, 'Pepe', 2, 'bird')]

Number of rows updated: 1


New Data:
[(3, 'Princess', 1, 'snake'), (5, 'Rollo', 1,
'horse'),
(6, 'Buster', 1, 'dog'), (7, 'Fido', 1, 'cat'),
(1, 'Duke', 2, 'dog'), (2, 'Pepe', 2, 'bird'),
(4, 'Polly', 2, 'bird')]
What does the successful code look like? Like this:
cur = con.cursor()
statement = 'update cx_pets set owner = :1
where type = :2 and owner != :3'
cur.execute(statement, (2, 'bird', 2))
con.commit()
print('Number of rows updated: ' +
str(cur.rowcount))
print(' ')

 commit(): For DML(Data Manipulation Language) queries that comprise


operations like update, insert, delete. We need to commit() then only the result
reflects in the database.
 fetchone(), fetchmany(int), fetchall():
1. fetchone() : This method is used to fetch one single row from the top
of the result set.
2. fetchmany(int): This method is used to fetch a limited number of
rows based on the argument passed in it.
3. fetchall() : This method is used to fetch all rows from the result set.
 close(): After all done it is mandatory to close all operations.
 
cursor.close()
con.close()
1. Creation of table
# importing module
import cx_Oracle

# Create a table in Oracle database


try:

con = cx_Oracle.connect('tiger/scott@localhost:1521/xe')
print(con.version)

# Now execute the sqlquery


cursor = con.cursor()

# Creating a table employee


cursor.execute("create table employee(empid integer primary key, name
varchar2(30), salary number(10, 2))")

print("Table Created successfully")

except cx_Oracle.DatabaseError as e:
print("There is a problem with Oracle", e)

# by writing finally if any error occurs


# then also we can close the all database operation
finally:
if cursor:
cursor.close()
if con:
con.close()
DDL statements don’t require to be committed. They are automatically committed. In the
above program, I have used execute() method to execute an SQL statement.
2. Inserting a record into table using execute() method
# importing module
import cx_Oracle
# Inserting a record into a table in Oracle database
try:
con = cx_Oracle.connect('tiger/scott@localhost:1521/xe')
cursor = con.cursor()

#con.autocommit = True
# Inserting a record into table employee
cursor.execute('insert into employee values(10001,\'Rahul\',50000.50)')

# commit() to make changes reflect in the database


con.commit()
print('Record inserted successfully')

except cx_Oracle.DatabaseError as e:
print("There is a problem with Oracle", e)

# by writing finally if any error occurs


# then also we can close the all database operation
finally:
if cursor:
cursor.close()
if con:
con.close()
Output: 
Record inserted successfully
Once we execute any DML statement it is required to commit the transaction. You can
commit a transaction in 2 ways: –

1. con.commit(). This is used to commit a transaction manually.


2. con.autocommit = True. This is used to commit a transaction automatically.
3. Inserting multiple records into a table using executemany() method
import cx_Oracle

# Load data from a csv file into Oracle table using executemany
try:
con = cx_Oracle.connect('tiger/scott@localhost:1521/xe')

except cx_Oracle.DatabaseError as er:


print('There is an error in Oracle database:', er)

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)

except cx_Oracle.DatabaseError as er:


print('There is an error in Oracle database:', er)

except Exception as er:


print(er)

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')

except cx_Oracle.DatabaseError as er:

print('There is an error in the Oracle database:', er)

else:

try:

cur = con.cursor()

# fetchall() is used to fetch all records from result set

cur.execute('select * from employee')

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

cur.execute('select * from employee')

rows = cur.fetchmany(3)

print(rows)

# fetchone() is used fetch one record from top of the result set

cur.execute('select * from employee')

rows = cur.fetchone()

print(rows)

except cx_Oracle.DatabaseError as er:

print('There is an error in the Oracle database:', er)

except Exception as er:

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')

 except cx_Oracle.DatabaseError as er:

    print('There is error in the Oracle database:', er)

 else:

    try:

        cur = con.cursor()

         cur.execute('select * from employee where salary > :sal', {'sal': 50000})

        rows = cur.fetchall()

        print(rows)

 
    except cx_Oracle.DatabaseError as er:

        print('There is error in the Oracle database:', er)

     except Exception 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.

You might also like