100% found this document useful (1 vote)
399 views1,098 pages

Python Tutorial Final

This Python tutorial is designed for beginners to understand both basic and advanced concepts of Python programming, emphasizing its popularity and versatility in various applications such as Machine Learning and web development. The tutorial covers the latest Python version 3.11.2 and provides practical examples, an online compiler, and career guidance for aspiring Python developers. It highlights the demand for Python skills in the job market and the advantages of learning Python, making it a valuable resource for anyone looking to enhance their programming skills.

Uploaded by

amma srinivas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
399 views1,098 pages

Python Tutorial Final

This Python tutorial is designed for beginners to understand both basic and advanced concepts of Python programming, emphasizing its popularity and versatility in various applications such as Machine Learning and web development. The tutorial covers the latest Python version 3.11.2 and provides practical examples, an online compiler, and career guidance for aspiring Python developers. It highlights the demand for Python skills in the job market and the advantages of learning Python, making it a valuable resource for anyone looking to enhance their programming skills.

Uploaded by

amma srinivas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1098

Python Tutorial

About the Tutorial


Today, Python is one of the most popular programming languages. Although it is a general-
purpose language, it is used in various areas of applications such as Machine Learning,
Artificial Intelligence, web development, IoT, and more.
This Python tutorial has been written for the beginners to help them understand the basic
to advanced concepts of Python Programming Language. After completing this tutorial,
you will find yourself at a great level of expertise in Python, from where you can take
yourself to the next levels to become a world class Software Engineer.

This Python tutorial is based on the latest Python 3.11.2 version.

What is Python?
Python is a very popular general-purpose interpreted, interactive, object-oriented, and
high-level programming language. Python is dynamically-typed and garbage-collected
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).

Python supports multiple programming paradigms, including Procedural, Object


Oriented and Functional programming language. Python design philosophy
emphasizes code readability with the use of significant indentation.

This tutorial gives a complete understanding of Python programming language, starting


from basic concepts to advanced concepts. This tutorial will take you through simple and
practical approaches while learning Python Programming language.

Python Jobs
Today, Python is very high in demand, and all the major companies are looking for great
Python programmers to develop websites, software components, and applications or to
work with data science, AI, and ML technologies. When we were developing this tutorial in
2022, there was a high shortage of Python programmers, where the market demanded a
greater number of Python programmers due to its applications in machine learning,
artificial intelligence, etc.
Today, a Python programmer with 3-5 years of experience is asking for around $150,000
in an annual package, and this is the most demanding programming language in America.
Though it can vary depending on the location of the job. It's impossible to list all of the
companies using Python, to name a few big companies are:
 Google
 Intel
 NASA
 PayPal
 Facebook
 IBM
 Amazon
 Netflix
 Pinterest
 Uber
 Many more...

i
Python Tutorial

So, you could be the next potential employee for any of these major companies. We have
developed great learning material for you to learn Python programming, which will help
you prepare for the technical interviews and certification exams based on Python. So, start
learning Python using this simple and effective tutorial from anywhere and anytime,
absolutely at your pace.

Why to Learn Python?


Python is consistently rated as one of the world's most popular programming languages.
Python is fairly easy to learn, so if you are starting to learn any programming language,
then Python could be your great choice. Today, various schools, colleges, and universities
are teaching Python as their primary programming language. There are many other good
reasons that make Python the top choice of any programmer:
 Python is open source, which means it's available free of cost.
 Python is simple and easy to learn.
 Python is versatile and can be used to create different kinds of applications.
 Python has powerful development libraries, including AI, ML, etc.
 Python is much in demand and ensures a high salary.
Python is a MUST for students and working professionals to become great software
engineers, especially when they are working in the 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.

Python "Hello, World!"


To start with Python programming, the very basic program is to print "Hello, World!" You
can use the print() function. Below is an example of Python code to print "Hello, World!"

# Python code to print "Hello, World!"


print ("Hello, World!")

Python Online Compiler


Our Python programming tutorial provides various examples to explain different concepts.
We have provided Online Python Compiler/Interpreter. You can Edit and Execute almost
all the examples directly from your browser without the need to set up your development
environment.

Try to click the icon to run the following Python code to print conventional "Hello,
World!".

ii
Python Tutorial

Below code box allows you to change the value of the code. Try to change the
value inside print() and run it again to verify the result.

# This is my first Python program.


# This will print 'Hello, World!' as the output

print ("Hello, World!");

Careers with Python


If you know Python nicely, then you have a great career ahead. Here are just a few of the
career options where Python is a key skill:
 Game developer
 Web designer
 Python developer
 Full-stack developer
 Machine learning engineer
 Data scientist
 Data analyst
 Data engineer
 DevOps engineer
 Software engineer
 Many more other roles

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 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
Python is a general purpose programming language known for its readability. It is widely
applied in various fields.
 In Data Science, Python libraries like Numpy, Pandas, and Matplotlib are used for
data analysis and visualization.
 Python frameworks like Django, and Pyramid, make the development and
deployment of Web Applications easy.
 This programming language also extends its applications to computer vision and
image processing.
 It is also favored in many tasks like Automation, Job Scheduling, GUI development,
etc.

iii
Python Tutorial

Features of Python
The latest release of Python is 3.x. As mentioned before, Python is one of the most widely
used languages on the web. I'm going to list a 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 has a bulk of portable and cross-platform
libraries and they are compatible with UNIX, Windows, and Macintosh.
 Interactive Mode − Python has support for an interactive mode that 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 operating 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 Reference
The complete function and method references −
 Python Complete Reference
 Python Built-in Functions Reference
 Python Modules Reference
 Python Keywords Reference
 Python Cheatsheet

Python Practice
Practice Python from the below-given links:
 Python Quick Guide
 Python Online Quiz
 Python Interview Questions & Answers

Download Python
You can download Python from its official website: https://www.python.org/downloads/

Target Audience
This tutorial has been prepared for the beginners to help them understand the basics to
advanced concepts of Python programming language. After completing this tutorial, you
will find yourself at a great level of expertise in Python programming, from where you can
take yourself to the next levels.

iv
Python Tutorial

Prerequisites
Although it is a beginner’s tutorial, we assume that the readers have a reasonable
exposure to any programming environment and knowledge of basic concepts such as
variables, commands, syntax, etc.

Python Questions & Answers


You can explore a set of Python Questions and Answers at Python Questions & Answers

Copyright & Disclaimer


 Copyright 2025 by Tutorials Point (I) Pvt. Ltd.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at [email protected]

v
Python Tutorial

Table of Contents
About the Tutorial .......................................................................................................................................... i

What is Python?.............................................................................................................................................. i

Python Reference ......................................................................................................................................... iv

Python Practice ............................................................................................................................................. iv

Download Python ......................................................................................................................................... iv

Target Audience ............................................................................................................................................ iv

Prerequisites .................................................................................................................................................. v

Python Questions & Answers ........................................................................................................................ v

Table of Contents.......................................................................................................................................... vi

PYTHON BASICS .......................................................................................................................... 1

1. Python – Overview .................................................................................................................................. 2

2. Python - History and Versions ................................................................................................................. 4

3. Python - Features .................................................................................................................................... 7

4. Python vs C++ ........................................................................................................................................ 11

5. Python - Hello World Program .............................................................................................................. 17

6. Python - Application Areas .................................................................................................................... 20

7. Python Interpreter and Its Modes ......................................................................................................... 23

8. Python - Environment Setup ................................................................................................................. 28

9. Python - Virtual Environment ................................................................................................................ 37

10. Python - Syntax ..................................................................................................................................... 40

11. Python - Variables ................................................................................................................................. 47

12. Python - Data Types .............................................................................................................................. 57

13. Python - Type Casting ............................................................................................................................ 75

14. Python - Unicode System ...................................................................................................................... 85

15. Python - Literals .................................................................................................................................... 88

16. Python - Operators ................................................................................................................................ 94

vi
Python Tutorial

17. Python - Arithmetic Operators ............................................................................................................ 104

18. Python - Comparison Operators .......................................................................................................... 115

19. Python - Assignment Operators .......................................................................................................... 121

20. Python - Logical Operators .................................................................................................................. 128

21. Python - Bitwise Operators ................................................................................................................. 132

22. Python - Membership Operators ......................................................................................................... 137

23. Python - Identity Operators ................................................................................................................ 141

24. Python Operator Precedence .............................................................................................................. 144

25. Python - Comments ............................................................................................................................. 147

26. Python - User Input ............................................................................................................................. 151

27. Python - Numbers ............................................................................................................................... 157

28. Python - Booleans ............................................................................................................................... 174

PYTHON CONTROL STATEMENTS ............................................................................................ 176

29. Python - Control Flow.......................................................................................................................... 177

30. Python - Decision Making .................................................................................................................... 183

31. Python - if Statement .......................................................................................................................... 186

32. Python if-else Statement ..................................................................................................................... 189

33. Python - Nested if Statement .............................................................................................................. 195

34. Python - Match-Case Statement .......................................................................................................... 198

35. Python - Loops .................................................................................................................................... 201

36. Python - For Loops .............................................................................................................................. 203

37. Python for-else Loops.......................................................................................................................... 209

38. Python - While Loops .......................................................................................................................... 213

39. Python - break Statement ................................................................................................................... 218

40. Python - Continue Statement .............................................................................................................. 221

41. Python - pass Statement ..................................................................................................................... 224

42. Python - Nested Loops ........................................................................................................................ 226

vii
Python Tutorial

PYTHON FUNCTIONS & MODULES .......................................................................................... 229

43. Python - Functions .............................................................................................................................. 230

44. Python - Default Arguments ................................................................................................................ 243

45. Python - Keyword Arguments ............................................................................................................. 246

46. Python - Keyword-Only Arguments ..................................................................................................... 249

47. Python - Positional Arguments ............................................................................................................ 251

48. Python - Positional-Only Arguments ................................................................................................... 254

49. Python - Arbitrary or, Variable-length Arguments ............................................................................... 256

50. Python Variable Scope ........................................................................................................................ 259

51. Python - Function Annotations ............................................................................................................ 266

52. Python - Modules ................................................................................................................................ 270

53. Python - Built-in Functions .................................................................................................................. 281

PYTHON STRINGS .................................................................................................................... 287

54. Python - Strings ................................................................................................................................... 288

55. Python Slicing Strings .......................................................................................................................... 298

56. Python - Modify Strings ....................................................................................................................... 304

57. Python - String Concatenation ............................................................................................................. 307

58. Python - String Formatting .................................................................................................................. 310

59. Python - Escape Characters ................................................................................................................. 312

60. Python - String Methods ..................................................................................................................... 316

61. Python - String Exercises ..................................................................................................................... 321

PYTHON LISTS ......................................................................................................................... 323

62. Python - Lists ....................................................................................................................................... 324

63. Python - Access List Items ................................................................................................................... 328

64. Python - Change List Items .................................................................................................................. 331

65. Python - Add List Items ....................................................................................................................... 333

66. Python - Remove List Items ................................................................................................................. 335

viii
Python Tutorial

67. Python - Loop Lists .............................................................................................................................. 338

68. Python - List Comprehension .............................................................................................................. 342

69. Python - Sort Lists ............................................................................................................................... 346

70. Python - Copy Lists .............................................................................................................................. 349

71. Python - Join Lists ................................................................................................................................ 353

72. Python - List Methods ......................................................................................................................... 356

73. Python - List Exercises ......................................................................................................................... 359

PYTHON TUPLES...................................................................................................................... 361

74. Python - Tuples ................................................................................................................................... 362

75. Python - Access Tuple Items ................................................................................................................ 366

76. Python - Update Tuples ....................................................................................................................... 370

77. Python - Unpack Tuple Items .............................................................................................................. 374

78. Python - Loop Tuples ........................................................................................................................... 376

79. Python - Join Tuples ............................................................................................................................ 379

80. Python - Tuple Methods ...................................................................................................................... 383

81. Python Tuple Exercises ........................................................................................................................ 386

PYTHON SETS .......................................................................................................................... 388

82. Python - Sets ....................................................................................................................................... 389

83. Python - Access Set Items .................................................................................................................... 394

84. Python - Add Set Items ........................................................................................................................ 397

85. Python - Remove Set Items ................................................................................................................. 401

86. Python - Loop Sets............................................................................................................................... 408

87. Python - Join Sets ................................................................................................................................ 412

88. Python - Copy Sets .............................................................................................................................. 416

89. Python - Set Operators ........................................................................................................................ 419

90. Python - Set Methods.......................................................................................................................... 424

91. Python - Set Exercises ......................................................................................................................... 426

ix
Python Tutorial

PYTHON DICTIONARIES ........................................................................................................... 427

92. Python - Dictionaries ........................................................................................................................... 428

93. Python - Access Dictionary Items ........................................................................................................ 436

94. Python - Change Dictionary Items ....................................................................................................... 442

95. Python - Add Dictionary Items ............................................................................................................ 446

96. Python - Remove Dictionary Items ...................................................................................................... 451

97. Python - Dictionary View Objects ........................................................................................................ 455

98. Python - Loop Dictionaries .................................................................................................................. 458

99. Python - Copy Dictionaries .................................................................................................................. 461

100. Python - Nested Dictionaries ............................................................................................................... 465

101. Python - Dictionary Methods .............................................................................................................. 470

102. Python - Dictionary Exercises .............................................................................................................. 471

PYTHON ARRAYS ..................................................................................................................... 473

103. Python - Arrays ................................................................................................................................... 474

104. Python - Access Array Items ................................................................................................................ 479

105. Python - Add Array Items .................................................................................................................... 482

106. Python - Remove Array Items.............................................................................................................. 484

107. Python - Loop Arrays ........................................................................................................................... 486

108. Python - Copy Arrays ........................................................................................................................... 488

109. Python - Reverse Arrays ...................................................................................................................... 490

110. Python - Sort Arrays ............................................................................................................................ 493

111. Python - Join Arrays ............................................................................................................................ 496

112. Python - Array Methods ...................................................................................................................... 498

113. Python - Array Exercises ...................................................................................................................... 501

PYTHON FILE HANDLING ......................................................................................................... 503

114. Python - File Handling ......................................................................................................................... 504

115. Python - Write to File .......................................................................................................................... 510

x
Python Tutorial

116. Python - Read Files .............................................................................................................................. 515

117. Python - Renaming and Deleting Files ................................................................................................. 523

118. Python - Directories ............................................................................................................................ 525

119. Python - File Methods ......................................................................................................................... 529

120. Python OS File/Directory Methods ...................................................................................................... 531

121. Python OS.Path Methods .................................................................................................................... 535

OBJECT ORIENTED PROGRAMMING ........................................................................................ 538

122. Python - OOP Concepts ....................................................................................................................... 539

123. Python - Classes and Objects ............................................................................................................... 547

124. Python - Class Attributes ..................................................................................................................... 555

125. Python - Class Methods ....................................................................................................................... 559

126. Python - Static Methods ...................................................................................................................... 563

127. Python - Constructors.......................................................................................................................... 566

128. Python - Access Modifiers ................................................................................................................... 571

129. Python - Inheritance ............................................................................................................................ 576

130. Python - Polymorphism ....................................................................................................................... 584

131. Python - Method Overriding ............................................................................................................... 588

132. Python - Method Overloading ............................................................................................................. 591

133. Python - Dynamic Binding ................................................................................................................... 594

134. Python - Dynamic Typing ..................................................................................................................... 597

135. Python - Abstraction ........................................................................................................................... 599

136. Python - Encapsulation ........................................................................................................................ 601

137. Python - Interfaces .............................................................................................................................. 604

138. Python - Packages ............................................................................................................................... 607

139. Python - Inner Classes ......................................................................................................................... 611

140. Python - Anonymous Class and Objects............................................................................................... 615

141. Python - Singleton Class ...................................................................................................................... 617

142. Python - Wrapper Classes.................................................................................................................... 619

xi
Python Tutorial

143. Python - Enums ................................................................................................................................... 620

144. Python - Reflection .............................................................................................................................. 624

PYTHON ERRORS & EXCEPTIONS ............................................................................................. 631

145. Python - Syntax Errors ......................................................................................................................... 632

146. Python - Exceptions Handling .............................................................................................................. 635

147. Python - The try-except Block ............................................................................................................. 644

148. Python - The try-finally Block .............................................................................................................. 648

149. Python - Raising Exceptions ................................................................................................................. 651

150. Python - Exception Chaining ................................................................................................................ 655

151. Python - Nested try Block .................................................................................................................... 658

152. Python - User-Defined Exceptions ....................................................................................................... 661

153. Python - Logging .................................................................................................................................. 665

154. Python - Assertions ............................................................................................................................. 669

155. Python - Built-in Exceptions ................................................................................................................ 671

PYTHON MULTITHREADING .................................................................................................... 679

156. Python - Multithreading ...................................................................................................................... 680

157. Python - Thread Lifecycle .................................................................................................................... 688

158. Python - Creating a Thread .................................................................................................................. 692

159. Python - Starting a Thread................................................................................................................... 697

160. Python - Joining the Threads ............................................................................................................... 700

161. Python - Naming the Threads .............................................................................................................. 703

162. Python - Thread Scheduling ................................................................................................................. 707

163. Python - Thread Pools ......................................................................................................................... 711

164. Python - Main Thread.......................................................................................................................... 715

165. Python - Thread Priority ...................................................................................................................... 719

166. Python - Daemon Threads ................................................................................................................... 725

167. Python - Synchronizing Threads .......................................................................................................... 729

xii
Python Tutorial

PYTHON SYNCHRONIZATION................................................................................................... 734

168. Python - Inter-Thread Communication ................................................................................................ 735

169. Python - Thread Deadlock ................................................................................................................... 741

170. Python - Interrupting a Thread ............................................................................................................ 746

PYTHON NETWORKING ........................................................................................................... 749

171. Python - Network Programming .......................................................................................................... 750

172. Python - Socket Programming ............................................................................................................. 751

173. Python - URL Processing ...................................................................................................................... 760

174. Python - Generics ................................................................................................................................ 766

PYTHON LIBRARIES.................................................................................................................. 768

175. NumPy Tutorial ................................................................................................................................... 769

176. Python Pandas Tutorial ....................................................................................................................... 772

177. SciPy Tutorial ...................................................................................................................................... 777

178. Matplotlib Tutorial .............................................................................................................................. 778

179. Django Tutorial ................................................................................................................................... 784

180. OpenCV Python Tutorial ...................................................................................................................... 787

PYTHON MISCELLANEOUS....................................................................................................... 788

181. Python - Date and Time ....................................................................................................................... 789

182. Python - math Module ........................................................................................................................ 807

183. Python - Iterators ................................................................................................................................ 813

184. Python - Generators ............................................................................................................................ 819

185. Python - Closures ................................................................................................................................ 825

186. Python - Decorators ............................................................................................................................ 829

187. Python - Recursion .............................................................................................................................. 835

188. Python - Regular Expressions .............................................................................................................. 839

189. Python - PIP......................................................................................................................................... 854

190. Python - Database Access .................................................................................................................... 859

xiii
Python Tutorial

191. Python - Weak References .................................................................................................................. 869

192. Python - Serialization .......................................................................................................................... 875

193. Python - Templating ............................................................................................................................ 882

194. Python - Output Formatting ................................................................................................................ 888

195. Python - Performance Measurement .................................................................................................. 897

196. Python - Data Compression ................................................................................................................. 900

197. Python - CGI Programming .................................................................................................................. 901

198. Python - XML Processing ..................................................................................................................... 916

199. Python - GUI Programming.................................................................................................................. 927

200. Python - Command-Line Arguments .................................................................................................... 945

201. Python - Docstrings ............................................................................................................................. 952

202. Python - JSON...................................................................................................................................... 960

203. Python - Sending Email........................................................................................................................ 965

204. Python - Further Extensions ................................................................................................................ 974

205. Python - Tools/Utilities ....................................................................................................................... 983

206. Python - GUIs ...................................................................................................................................... 987

PYTHON ADVANCED CONCEPTS .............................................................................................. 994

207. Python - Abstract Base Classes ............................................................................................................ 995

208. Python - Custom Exceptions .............................................................................................................. 1000

209. Python - Higher Order Functions ....................................................................................................... 1003

210. Python - Object Internals .................................................................................................................. 1007

211. Python - Memory Management ........................................................................................................ 1010

212. Python - Metaclasses ........................................................................................................................ 1014

213. Python - Metaprogramming with Metaclasses .................................................................................. 1018

214. Python - Mocking and Stubbing ........................................................................................................ 1021

215. Python - Monkey Patching ................................................................................................................ 1024

216. Python - Signal Handling ................................................................................................................... 1026

217. Python - Type Hints ........................................................................................................................... 1030

xiv
Python Tutorial

218. Python - Automation Tutorial ........................................................................................................... 1040

219. Python - Humanize Package .............................................................................................................. 1046

220. Python - Context Managers ............................................................................................................... 1052

221. Python - Coroutines .......................................................................................................................... 1057

222. Python - Descriptors .......................................................................................................................... 1063

223. Python - Diagnosing and Fixing Memory Leaks .................................................................................. 1071

224. Python - Immutable Data Structures ................................................................................................. 1076

xv
Python Tutorial

Python Basics

1
1. Python – Overview Python Tutorial

Python is a high-level, interpreted, interactive and object-oriented scripting language.


Python is designed to be highly readable. It uses English keywords frequently whereas
other languages use punctuation. 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.
Python is an open-source and cross-platform programming language. It is available for
use under Python Software Foundation License (compatible to GNU General Public
License) on all the major operating system platforms such as Linux, Windows and Mac OS.
To facilitate new features and to maintain that readability, the Python Enhancement
Proposal (PEP) process was developed. This process allows anyone to submit a PEP for a
new feature, library, or other addition.
The design philosophy of Python emphasizes on simplicity, readability and unambiguity.
Python is known for its batteries included approach as Python software is distributed with
a comprehensive standard library of functions and modules.
Python's design philosophy is documented in the Zen of Python. It consists of nineteen
aphorisms such as −
 Beautiful is better than ugly
 Explicit is better than implicit
 Simple is better than complex
 Complex is better than complicated
To obtain the complete Zen of Python document, type import this in the Python Shell −

>>>import this

This will produce following 19 aphorisms -

Beautiful is better than ugly.


Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.

2
Python Tutorial

Special cases aren't special enough to break the rules.


Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Python supports imperative, structured as well as object-oriented programming


methodology. It provides features of functional programming as well.

Pythonic Code Style


Python leaves you free to choose to program in an object-oriented, procedural, functional,
aspect-oriented, or even logic-oriented way. These freedoms make Python a great
language to write clean and beautiful code.
Pythonic Code Style is actually more of a design philosophy and suggests to write a code
which is:
 Clean
 Simple
 Beautiful
 Explicit
 Readable

The Zen of Python


The Zen of Python is about code that not only works, but is Pythonic. Pythonic code is
readable, concise, and maintainable.

3
2. Python - History and VersionsPython Tutorial

History of Python
Python was developed by Guido van Rossum (a Dutch programmer) in the late 1980s and
early nineties at the National Research Institute for Mathematics and Computer Science in
the Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-
68, SmallTalk, and Unix shell and other scripting languages. Guido van Rossum wanted
Python to be a high-level language that was powerful yet readable and easy to use.
Python is copyrighted. Like Perl, Python source code is now available under the GNU
General Public License (GPL).
Being the principal architect of Python, the developer community conferred upon him the
title of Benevolent Dictator for Life (BDFL). However, in 2018, Rossum relinquished the
title. Thereafter, the development and distribution of the reference implementation of
Python is handled by a nonprofit organization Python Software Foundation.

Who Invented Python?


Python was invented by a Dutch Programmer Guido Van Rossum in the late 1980s. He
began working on Python in December 1989 as a hobby project while working at the
Centrum Wiskunde & Informatica (CWI) in the Netherlands. Python's first version (0.9.0)
was released in 1991.

Evolution of Python – The Major Python Versions


Following are the important stages in the history of Python −

Python 0.9.0
Python's first published version is 0.9. It was released in February 1991. It consisted of
features such as classes with inheritance, exception handling, and core data types like lists
and dictionaries.

Python 1.0
In January 1994, version 1.0 was released, armed with functional programming tools,
features like support for complex numbers etc. and module system which allows a better
code organization and reuse.

Python 2.0
Next major version − Python 2.0 was launched in October 2000. Many new features such
as list comprehension, garbage collection and Unicode support were included with it.
Throughout the 2000s, Python 2.x became the dominant version, gaining traction in
industries ranging from web development to scientific research. Various useful libraries
like NumPy, SciPy, and Django were also developed.

4
Python Tutorial

Python 3.0
Python 3.0, a completely revamped version of Python was released in December 2008.
The primary objective of this revamp was to remove a lot of discrepancies that had crept
in Python 2.x versions. Python 3 was backported to Python 2.6. It also included a utility
named as python2to3 to facilitate automatic translation of Python 2 code to Python 3.
Python 3 provided new syntax, Unicode support and improved integer division.

EOL for Python 2.x


Even after the release of Python 3, Python Software Foundation continued to support the
Python 2 branch with incremental micro versions till 2019. However, it decided to
discontinue the support by the end of year 2020, at which time Python 2.7.17 was the last
version in the branch.

Current Version of Python


Meanwhile, more and more features have been incorporated into Python's 3.x branch. As
of date, Python 3.11.2 is the current stable version, released in February 2023.

What's New in Python 3.11?


One of the most important features of Python's version 3.11 is the significant improvement
in speed. According to Python's official documentation, this version is faster than the
previous version (3.10) by up to 60%. It also states that the standard benchmark suite
shows a 25% faster execution rate.
 Python 3.11 has a better exception messaging. Instead of generating a long
traceback on the occurrence of an exception, we now get the exact expression
causing the error.
 As per the recommendations of PEP 678, the add_note() method is added to the
BaseException class. You can call this method inside the except clause and pass a
custom error message.
 It also adds the cbroot() function in the maths module. It returns the cube root of
a given number.
 A new module tomllib is added in the standard library. TOML (Tom's Obvious
Minimal Language) can be parsed with tomllib module function.

Python in the Future


Python is evolving every day and Python 3.x is receiving regular updates. Python's
developer community is focusing on performance improvements making it more efficient
while retaining its ease of use.
Python is being heavily used for machine learning, AI, and data science, so for sure its
future remains bright. It's role in these rapidly growing fields ensures that Python will stay
relevant for years.
Python is also increasingly becoming the first programming language taught in schools
and universities worldwide, solidifying its place in the tech landscape.

5
Python Tutorial

Frequently Asked Questions About Python History

1. Who created Python?


Python created by Guido Van Rossum, a Dutch Programmer.

2. Why Python is called Python?


Python does not have any relation to Snake. The name of the Python programming
language was inspired by a British Comedy Group Monty Python.

3. When was Python's first version released?


Python's first version was released in February 1991.

4. What was the first version of Python?


Python's first version was Python 0.9.0

5. When was Python 3.0 version released?


Python 3.0 version was released in December 2008.

6
3. Python - Features Python Tutorial

Python is a feature-rich, high-level, interpreted, interactive, and object-oriented scripting


language. Python is a versatile and very popular programming language due to its features
such as readability, simplicity, extensive libraries, and many more. In this tutorial, we will
learn about the various features of Python that make it a powerful and versatile
programming language.

Features of Python
Python's most important features are as follows:
 Easy to Learn
 Dynamically Typed
 Interpreter Based
 Interactive
 Multi-paradigm
 Standard Library
 Open Source and Cross Platform
 GUI Applications
 Database Connectivity
 Extensible
 Active Developer Community

Easy to Learn
This is one of the most important reasons for the popularity of Python. Python has a limited
set of keywords. Its features such as simple syntax, usage of indentation to avoid clutter
of curly brackets, and dynamic typing that doesn't necessitate prior declaration of variable
help a beginner to learn Python quickly and easily.

7
Python Tutorial

Dynamically Typed
Python is a dynamically typed programming language. In Python, you don't need to specify
the variable at the time of the declaration. The types are specified at the runtime based
on the assigned value due to its dynamically typed feature.

Interpreter Based
Instructions in any programming languages must be translated into machine code for the
processor to execute them. Programming languages are either compiler based or
interpreter based.
In case of a compiler, a machine language version of the entire source program is
generated. The conversion fails even if there is a single erroneous statement. Hence, the
development process is tedious for the beginners. The C family languages (including C,
C++, Java, C# etc.) are compiler based.
Python is an interpreter based language. The interpreter takes one instruction from the
source code at a time, translates it into machine code and executes it. Instructions before
the first occurrence of error are executed. With this feature, it is easier to debug the
program and thus proves useful for the beginner level programmer to gain confidence
gradually. Python therefore is a beginner-friendly language.

Interactive
Standard Python distribution comes with an interactive shell that works on the principle of
REPL (Read – Evaluate – Print – Loop). The shell presents a Python prompt >>>. You can
type any valid Python expression and press Enter. Python interpreter immediately returns
the response and the prompt comes back to read the next expression.

>>> 2*3+1
7
>>> print ("Hello World")
Hello World

The interactive mode is especially useful to get familiar with a library and test out its
functionality. You can try out small code snippets in interactive mode before writing a
program.

Multi-paradigm
Python is a completely object-oriented language. Everything in a Python program is an
object. However, Python conveniently encapsulates its object orientation to be used as an
imperative or procedural language – such as C. Python also provides certain functionalities
that resemble functional programming. Moreover, certain third-party tools have been
developed to support other programming paradigms such as aspect-oriented and logic
programming.

Standard Library
Even though it has a very few keywords (only Thirty-Five), Python software is distributed
with a standard library made of large number of modules and packages. Thus Python has
out of box support for programming needs such as serialization, data compression,

8
Python Tutorial

internet data handling, and many more. Python is known for its batteries included
approach.
Some of the Python's popular modules are:
 NumPy
 Pandas
 Matplotlib
 Tkinter
 Math

Open Source and Cross Platform


Python's standard distribution can be downloaded from
https://www.python.org/downloads/https://www.python.org/downloads/ without any
restrictions. You can download pre-compiled binaries for various operating systems. In
addition, the source code is also freely available, which is why it comes under open source
category.
Python software (along with the documentation) is distributed under Python Software
Foundation License. It is a BSD style permissive software license and compatible to GNU
GPL (General Public License).
Python is a cross-platform language. Pre-compiled binaries are available for use on various
operating systems such as Windows, Linux, Mac OS, Android OS. The reference
implementation of Python is called CPython and is written in C. You can download the
source code and compile it for your OS platform.
A Python program is first compiled to an intermediate platform independent byte code.
The virtual machine inside the interpreter then executes the byte code. This behavior
makes Python a cross-platform language, and thus a Python program can be easily ported
from one OS platform to other.

GUI Applications
Python's standard distribution has an excellent graphics library called TKinter. It is a
Python port for the vastly popular GUI toolkit called TCL/Tk. You can build attractive user-
friendly GUI applications in Python. GUI toolkits are generally written in C/C++. Many of
them have been ported to Python. Examples are PyQt, WxWidgets, PySimpleGUI etc.

Database Connectivity
Almost any type of database can be used as a backend with the Python application. DB-
API is a set of specifications for database driver software to let Python communicate with
a relational database. With many third party libraries, Python can also work with NoSQL
databases such as MongoDB.

Extensible
The term extensibility implies the ability to add new features or modify existing features.
As stated earlier, CPython (which is Python's reference implementation) is written in C.
Hence one can easily write modules/libraries in C and incorporate them in the standard
library. There are other implementations of Python such as Jython (written in Java) and
IPython (written in C#). Hence, it is possible to write and merge new functionality in these
implementations with Java and C# respectively.

9
Python Tutorial

Active Developer Community


As a result of Python's popularity and open-source nature, a large number of Python
developers often interact with online forums and conferences. Python Software Foundation
also has a significant member base, involved in the organization's mission to "Promote,
Protect, and Advance the Python Programming Language"
Python also enjoys a significant institutional support. Major IT companies Google,
Microsoft, and Meta contribute immensely by preparing documentation and other
resources.
Apart from the above-mentioned features, Python has another big list of good features,
few are listed below −
 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.

10
4. Python vs C++ Python Tutorial

Python is a general-purpose, high-level programming language. Python is used for web


development, Machine Learning, and other cutting-edge software development
technologies. Python is suitable for both new and seasoned C++ and Java programmers.
Guido Van Rossum has created Python in 1989 at Netherlands' National Research
Institute. Python was released in 1991.
C++ is a middle-level, case-sensitive, object-oriented programming language. Bjarne
Stroustrup created C++ at Bell Labs. C++ is a platform-independent programming
language that works on Windows, Mac OS, and Linux. C++ is near to hardware, allowing
low-level programming. This provides a developer control over memory, improved
performance, and dependable software.
Read through this article to get an overview of C++ and Python and how these two
programming languages are different from each other.

What is Python?
Python is currently one of the most widely used programming languages. It is an
interpreted programming language that operates at a high level. When compared to other
languages, the learning curve for Python is much lower, and it is also quite straightforward
to use.
Python is the programming language of choice for professionals working in fields such as
Artificial Intelligence, Machine Learning (ML), Data Science, the Internet of Things (IoT),
etc., because it excels at both scripting applications and as standalone programmers.
In addition to this, Python is the language of choice because it is easy to learn. Because
of its excellent syntax and readability, the amount of money spent on maintenance is
decreased. The modularity of the program and the reusability of the code both contribute
to its support for a variety of packages and modules.
Using Python, we can perform −
 Web development
 Data analysis and machine learning
 Automation and scripting
 Software testing and many more

Features
Here is a list of some of the important features of Python −
 Easy to learn − Python has a simple structure, few keywords, and a clear syntax.
This makes it easy for the student to learn quickly. Code written in Python is easier
to read and understand.
 Easy to maintain − The source code for Python is pretty easy to keep up with.
 A large standard library − Most of Python's libraries are easy to move around
and work on UNIX, Windows, Mac.
 Portable − Python can run on a wide range of hardware platforms, and all of them
have the same interface.
Python Example

11
Python Tutorial

Take a look at the following simple Python program −

a = int(input("Enter value for a"))


b = int(input("Enter value for b"))

print("The number you have entered for a is ", a)


print("The number you have entered for b is ", b)

In our example, we have taken two variables "a" and "b" and assigning some value to
those variables. Note that in Python, we don’t need to declare datatype for variables
explicitly, as the PVM will assign datatype as per the user’s input.
 The input() function is used to take input from the user through keyboard.
 In Python, the return type of input() is string only, so we have to convert it
explicitly to the type of data which we require. In our example, we have converted
to int type explicitly through int( ) function.
 print() is used to display the output.
Output
On execution, this Python code will produce the following output −

Enter value for a 10


Enter value for b 20

The number you have entered for a is 10


The number you have entered for b is 20

What is C++?
C++ is a statically typed, compiled, multi-paradigm, general-purpose programming
language with a steep learning curve. Video games, desktop apps, and embedded systems
use it extensively. C++ is so compatible with C that it can build practically all C source
code without any changes. Object-oriented programming makes C++ a better-structured
and safer language than C.

Features
Let’s see some features of C++ and the reason of its popularity.
 Middle-level language − It's a middle-level language since it can be used for
both system development and large-scale consumer applications like Media
Players, Photoshop, Game Engines, etc.

 Execution Speed − C++ code runs quickly because it's compiled and uses
procedures extensively. Garbage collection, dynamic typing, and other modern
features impede program execution.

 Object-oriented language − Object-oriented programming is flexible and


manageable. Large apps can also be developed through this language.
 Extensive Library Support − C++ has a vast library. Third-party libraries are
supported for fast development.

12
Python Tutorial

C++ Example
Let’s understand the syntax of C++ through an example written below.

#include
using namespace std;

int main() {
int a, b;
cout << "Enter The value for variable a \n";
cin >> a;
cout << "Enter The value for variable b";
cin >> b;
cout << "The value of a is "<< a << "and" << b;
return 0;
}

In our example, we are taking input for two variables "a" and "b" from the user through
the keyboard and displaying the data on the console.
Output
On execution, it will produce the following output −

Enter The value for variable a


10
Enter The value for variable b
20
The value of a is 10 and 20

Comparison Between Python and C++ across Various Aspects


Both Python and C++ are among the most popular programming languages. Both of them
have their advantages and disadvantages. In this tutorial, we shall take a look at their
features which differentiate one from another.

Compiled vs Interpreted
Like C, C++ is also a compiler-based language. A compiler translates the entire code in a
machine language code specific to the operating system in use and processor architecture.
Python is interpreter-based language. The interpreter executes the source code line by
line.

Cross platform
When a C++ source code such as hello.cpp is compiled on Linux, it can be only run on any
other computer with Linux operating system. If required to run on other OS, it needs to
be recompiled.
13
Python Tutorial

Python interpreter doesn't produce compiled code. Source code is converted to byte code
every time it is run on any operating system without any changes or additional steps.

Portability
Python code is easily portable from one OS to other. C++ code is not portable as it must
be recompiled if the OS changes.

Speed of Development
C++ program is compiled to the machine code. Hence, its execution is faster than
interpreter based language.
Python interpreter doesn't generate the machine code. Conversion of intermediate byte
code to machine language is done on each execution of program.
If a program is to be used frequently, C++ is more efficient than Python.

Easy to Learn
Compared to C++, Python has a simpler syntax. Its code is more readable. Writing C++
code seems daunting in the beginning because of complicated syntax rules such as use of
curly braces and semicolon for sentence termination.
Python doesn't use curly brackets for marking a block of statements. Instead, it uses
indents. Statements of similar indent level mark a block. This makes a Python program
more readable.

Static vs Dynamic Typing


C++ is a statically typed language. The type of variables for storing data need to be
declared in the beginning. Undeclared variables can't be used. Once a variable is declared
to be of a certain type, value of only that type can be stored in it.
Python is a dynamically typed language. It doesn't require a variable to be declared before
assigning it a value. Since, a variable may store any type of data, it is called dynamically
typed.

OOP Concepts
Both C++ and Python implement object oriented programming concepts. C++ is closer to
the theory of OOP than Python. C++ supports the concept of data encapsulation as the
visibility of the variables can be defined as public, private and protected.
Python doesn't have the provision of defining the visibility. Unlike C++, Python doesn't
support method overloading. Because it is dynamically typed, all the methods are
polymorphic in nature by default.
C++ is in fact an extension of C. One can say that additional keywords are added in C so
that it supports OOP. Hence, we can write a C type procedure oriented program in C++.
Python is completely object oriented language. Python's data model is such that, even if
you can adapt a procedure oriented approach, Python internally uses object-oriented
methodology.

Garbage Collection

14
Python Tutorial

C++ uses the concept of pointers. Unused memory in a C++ program is not cleared
automatically. In C++, the process of garbage collection is manual. Hence, a C++ program
is likely to face memory related exceptional behavior.
Python has a mechanism of automatic garbage collection. Hence, Python program is more
robust and less prone to memory related issues.

Application Areas
Because C++ program compiles directly to machine code, it is more suitable for system
programming, writing device drivers, embedded systems and operating system utilities.
Python program is suitable for application programming. Its main area of application today
is data science, machine learning, API development etc.

Difference Between Python and C++


The following table summarizes the differences between Python and C++ −

Criteria Python C++

Python is an interpreted-based C++ is a compiler-based


programming language. Python programming language. C++
Execution
programs are interpreted by an programs are compiled by a
interpreter. compiler.

Python is a dynamic-typed
Typing C++ is a static-typed language.
language.

Python is a highly portable C++ is not a portable language,


language, code written and code written and executed on a
Portability
executed on a system can be system cannot be run on another
easily run on another system. system without making changes.

Python provides a garbage


C++ does not provide garbage
collection feature. You do not
Garbage collection. You have to take care
need to worry about the memory
collection of freeing memories. It is
management. It is automatic in
manual in C++.
Python.

Python's syntaxes are very easy


Syntax C++'s syntaxes are tedious.
to read, write, and understand.

The speed of the execution of


Python's execution performance is
Performance C++ codes is faster than Python
slower than C++'s.
codes.

15
Python Tutorial

Python's application areas are C++'s application areas are


Application
machine learning, web embedded systems, device
areas
applications, and more. drivers, and more.

16
5. Python - Hello World ProgramPython Tutorial

This tutorial will teach you how to write a simple Hello World program using Python
Programming language. This program will make use of Python built-in print() function to
print the output.

Hello World Program in Python


Printing "Hello World" is the first program in Python. This program will not take any user
input. It will just print text on the output screen. It is used to test if the software needed
to compile and run the program has been installed correctly.

Steps
The following are the steps to write a Python program to print Hello World –
 Step 1: Install Python. Make sure that Python is installed on your system. If Python
is not installed, then install it from here:
https://www.python.org/downloads/https://www.python.org/downloads/
 Step 2: Choose Text Editor or IDE to write the code.
 Step 3: Open Text Editor or IDE, create a new file, and write the code to print Hello
World.
 Step 4: Save the file with a file name and extension ".py".
 Step 5: Compile/Run the program.

Python Program to Print Hello World


# Python code to print "Hello World"
print ("Hello World")

In the above code, we wrote two lines. The first line is the Python comment that will be
ignored by the Python interpreter, and the second line is the print() statement that will
print the given message ("Hello World") on the output screen.
Output

Hello World

Different Ways to Write and Execute Hello World Program

Using Python Interpreter Command Prompt Mode


It is very easy to display the Hello World message using the Python interpreter. Launch
the Python interpreter from a command terminal of your Windows Operating System and
issue the print statement from the Python prompt as follows −
Example

PS C:\> python

17
Python Tutorial

Python 3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934 64 bit


(AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

>>> print ("Hello World")


Hello World

Similarly, Hello World message is printed on Linux System.


Example

$ python3
Python 3.10.6 (main, Mar 10 2023, 10:55:28) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> print ("Hello World")


Hello World

Using Python Interpreter Script Mode


Python interpreter also works in scripted mode. Open any text editor, enter the following
text and save as Hello.py

print ("Hello World")

For Windows OS, open the command prompt terminal (CMD) and run the program as
shown below −

C:\>python hello.py

This will display the following output

Hello World

To run the program from Linux terminal

$ python3 hello.py

This will display the following output:

Hello World

Using Shebang #! in Linux Scripts


In Linux, you can convert a Python program into a self-executable script. The first
statement in the code should be a shebang #!. It must contain the path to Python
executable. In Linux, Python is installed in /usr/bin directory, and the name of the
executable is python3. Hence, we add this statement to hello.py file

#!/usr/bin/python3

18
Python Tutorial

print ("Hello World")

You also need to give the file executable permission by using the chmod +x command

$ chmod +x hello.py

Then, you can run the program with following command line −

$ ./hello.py

This will display the following output

Hello World

FAQs

1. Why the first program is called Hello World?


It is just a simple program to test the basic syntax and compiler/interpreter configuration
of Python programming language.

2. Is installation of Python required to run Hello World program?


Yes. Python installation is required to run Hello World program.

3. How do I run a Python program without installing it?


TutorialsPoint developed an online environment where you can run your codes. You can
use the Python online compiler to run your Python programs.

4. Which method is used to print Hello World or any message?


You can use the following methods –
 print() method
 sys.stdout.write() method by importing the sys module
 Using python-f string

19
6. Python - Application Areas Python Tutorial

Python is a general-purpose programming language. It is suitable for the development of


a wide range of software applications. Over the last few years Python has been the
preferred language of choice for developers in the following application areas −
 Data Science
 Machine Learning
 Web Development
 Computer Vision and Image processing
 Embedded Systems and IoT
 Job Scheduling and Automation
 Desktop GUI Applications
 Console-based Applications
 CAD Applications
 Game Development
Let's look into these application areas in more detail:

Data Science
Python's recent meteoric rise in the popularity charts is largely due to its Data science
libraries. Python has become an essential skill for data scientists. Today, real time web
applications, mobile applications and other devices generate huge amount of data.
Python's data science libraries help companies generate business insights from this data.
Libraries like NumPy, Pandas, and Matplotlib are extensively used to apply mathematical
algorithms to the data and generate visualizations. Commercial and community Python
distributions like Anaconda and ActiveState bundle all the essential libraries required for
data science.

Machine Learning
Python libraries such as Scikit-learn and TensorFlow help in building models for prediction
of trends like customer satisfaction, projected values of stocks etc. based upon the past
data. Machine learning applications include (but not restricted to) medical diagnosis,
statistical arbitrage, basket analysis, sales prediction etc.

Web Development
Python's web frameworks facilitate rapid web application development. Django, Pyramid,
Flask are very popular among the web developer community. etc. make it very easy to
develop and deploy simple as well as complex web applications.
Latest versions of Python provide asynchronous programming support. Modern web
frameworks leverage this feature to develop fast and high performance web apps and
APIs.

20
Python Tutorial

Computer Vision and Image processing


OpenCV is a widely popular library for capturing and processing images. Image processing
algorithms extract information from images, reconstruct image and video data. Computer
Vision uses image processing for face detection and pattern recognition. OpenCV is a C++
library. Its Python port is extensively used because of its rapid development feature.
Some of the application areas of computer vision are robotics, industrial surveillance,
automation, and biometrics etc.

Embedded Systems and IoT


Micropython (https://micropython.org/) is a lightweight version especially developed for
microcontrollers like Arduino. Many automation products, robotics, IoT, and kiosk
applications are built around Arduino and programmed with Micropython. Raspberry Pi is
also very popular and a low cost single board computer can be used for these types of
applications.

Job Scheduling and Automation


Python found one of its first applications in automating CRON (Command Run ON) jobs.
Certain tasks, like periodic data backups, can be written in Python scripts and can be
scheduled to be invoked automatically by operating system scheduler.
Many software products like Maya embed Python API for writing automation scripts
(something similar to Excel micros).

Desktop GUI Applications


Python is a great option for building ergonomic, attractive, and user-friendly desktop GUI
applications. Several graphics libraries, though built in C/C++, have been ported to
Python. The popular Qt graphics toolkit is available as a PyQt package in Python. Similarly,
WxWidgets has been ported to Python as WxPython. Python's built-in GUI package, TKinter
is a Python interface to the Tk Graphics toolkit.
Here is a select list of Python GUI libraries:
 Tkinter − Tkinter is the Python interface to the Tk GUI toolkit shipped with
Python's standard library.
 wxPython − This is the Python interface for the wxWidgets GUI toolkit. BitTorrent
Client application has been built with wxPython functionality.
 PyQt – Qt is one of the most popular GUI toolkits. It has been ported to Python as
a PyQt5 package. Notable desktop GUI apps that use PyQt include QGIS, Spyder
IDE, Calibre Ebook Manager, etc.
 PyGTK − PyGTK is a set of wrappers written in Python and C for GTK + GUI library.
The complete PyGTK tutorial is available here.
 PySimpleGUI − PySimpleGui is an open-source, cross-platform GUI library for
Python. It aims to provide a uniform API for creating desktop GUIs based on
Python's Tkinter, PySide, and WxPython toolkits.
 Jython − Jython is a Python port for Java, which gives Python scripts seamless
access to the Java GUI libraries on the local machine.

21
Python Tutorial

Console-based Applications
Python is often employed to build CLI (command-line interface) applications. Such scripts
can be used to run scheduled CRON jobs such as taking database backups etc. There are
many Python libraries that parse the command line arguments. The argparse library comes
bundled with Python’s standard library. You can use Click (part of Flask framework) and
Typer (included in FastAPI framework) to build console interfaces to the web-based
applications built by the respective frameworks. Textual is a rapid development framework
to build apps that run inside a terminal as well as browsers.

CAD Applications
CAD engineers can take advantage of Python's versatility to automate repetitive tasks
such as drawing shapes and generating reports.
Autodesk Fusion 360 is a popular CAD software, which has a Python API that allows
users to automate tasks and create custom tools. Similarly, SolidWorks has a built-in
Python shell that allows users to run Python scripts inside the software.
CATIA is another very popular CAD software. Along with a VBScript, certain third-party
Python libraries can be used to control CATIA.

Game Development
Some popular gaming apps have been built with Python. Examples include BattleField2,
The Sims 4, World of Tanks, Pirates of the Caribbean, and more. These apps are built with
one of the following Python libraries.
Pygame is one of the most popular Python libraries used to build engaging computer
games. Pygame is an open-source Python library for making multimedia applications like
games built on top of the excellent SDL library. It is a cross-platform library, which means
you can build a game that can run on any operating system.
Another library Kivy is also widely used to build desktop as well as mobile-based games.
Kivy has a multi-touch interface. It is an open-source and cross-platform Python library
for rapid development of game applications. Kivy runs on Linux, Windows, OS X, Android,
iOS, and Raspberry Pi.
PyKyra library is based on both SDL (Software and Documentation Localisation) and the
Kyra engine. It is one of the fastest game development frameworks. PyKyra supports
MPEG , MP3, Ogg Vorbis, Wav, etc., multimedia formats.

22
7. Python Interpreter and Its Modes
Python Tutorial

Python Interpreter
Python is an interpreter-based language. In a Linux system, Python's executable is
installed in /usr/bin/ directory. For Windows, the executable (python.exe) is found in the
installation folder (for example C:\python311).
This tutorial will teach you How Python Interpreter Works in interactive and scripted
mode. Python code is executed by one statement at a time method. Python interpreter
has two components. The translator checks the statement for syntax. If found correct, it
generates an intermediate byte code. There is a Python virtual machine which then
converts the byte code in native binary and executes it. The following diagram illustrates
the mechanism:

Python interpreter has an interactive mode and a scripted mode.

Python Interpreter - Interactive Mode


When launched from a command line terminal without any additional options, a Python
prompt >>> appears and the Python interpreter works on the principle of REPL (Read,
Evaluate, Print, Loop). Each command entered in front of the Python prompt is read,
translated and executed. A typical interactive session is as follows.

>>> price = 100


>>> qty = 5
>>> total = price*qty
>>> total
500
>>> print ("Total = ", total)
Total = 500

To close the interactive session, enter the end-of-line character (ctrl+D for Linux and
ctrl+Z for Windows). You may also type quit() in front of the Python prompt and press
Enter to return to the OS prompt.

>>> quit()
$

23
Python Tutorial

The interactive shell available with standard Python distribution is not equipped with
features like line editing, history search, auto-completion etc. You can use other advanced
interactive interpreter software such as IPython and bpython to have additional
functionalities.

Python Interpreter - Scripting Mode


Instead of entering and obtaining the result of one instruction at a time as in the interactive
environment, it is possible to save a set of instructions in a text file, make sure that it has
.py extension, and use the name as the command line parameter for Python command.
Save the following lines as prog.py, with the use of any text editor such as vim on Linux
or Notepad on Windows.

print ("My first program")


price = 100
qty = 5
total = price*qty
print ("Total = ", total)

When we execute above program on a Windows machine, it will produce following result:

C:\Users\Acer>python prog.py
My first program
Total = 500

Note that even though Python executes the entire script in one go, but internally it is still
executed in line by line fashion.
In case of any compiler-based language such as Java, the source code is not converted in
byte code unless the entire code is error-free. In Python, on the other hand, statements
are executed until first occurrence of error is encountered.
Let us introduce an error purposefully in the above code.

print ("My first program")


price = 100
qty = 5
total = prive*qty #Error in this statement
print ("Total = ", total)

Note the misspelt variable prive instead of price. Try to execute the script again as before

C:\Users\Acer>python prog.py
My first program
Traceback (most recent call last):
File "C:\Python311\prog.py", line 4, in <module>
total = prive*qty

24
Python Tutorial

^^^^^
NameError: name 'prive' is not defined. Did you mean: 'price'?

Note that the statements before the erroneous statement are executed and then the error
message appears. Thus it is now clear that Python script is executed in interpreted manner.

Python Interpreter - Using Shebang #!


In addition to executing the Python script as above, the script itself can be a self-
executable in Linux, like a shell script. You have to add a shebang line on top of the script.
The shebang indicates which executable is used to interpret Python statements in the
script. Very first line of the script starts with #! And followed by the path to Python
executable.
Modify the prog.py script as follows −

#! /usr/bin/python3.11

print ("My first program")


price = 100
qty = 5
total = price*qty
print ("Total = ", total)

To mark the script as self-executable, use the chmod command

$ chmod +x prog.py

You can now execute the script directly, without using it as a command-line argument.

$ ./hello.py

Interactive Python - IPython


IPython (stands for Interactive Python) is an enhanced and powerful interactive
environment for Python with many functionalities compared to the standard Python shell.
IPython was originally developed by Fernando Perez in 2001.
IPython has the following important features −
 IPython's object introspection ability to check properties of an object during
runtime.
 Its syntax highlighting proves to be useful in identifying the language elements
such as keywords, variables etc.
 The history of interactions is internally stored and can be reproduced.
 Tab completion of keywords, variables and function names is one of the most
important features.
 IPython's Magic command system is useful for controlling Python environment and
performing OS tasks.
 It is the main kernel for Jupyter notebook and other front-end tools of Project
Jupyter.

25
Python Tutorial

Install IPython with PIP installer utility.

pip3 install ipython

Launch IPython from command-line

C:\Users\Acer>ipython
Python 3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934
64 bit (AMD64)] on win32
Type 'copyright', 'credits' or 'license' for more information
IPython 8.4.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]:

Instead of the regular >>> prompt as in standard interpreter, you will notice two major
IPython prompts as explained below −
 In[1] appears before any input expression.
 Out[1] appears before the Output appears.

In [1]: price = 100


In [2]: quantity = 5
In [3]: total = price*quantity
In [4]: total
Out[4]: 500
In [5]:

Tab completion is one of the most useful enhancements provided by IPython. IPython pops
up appropriate list of methods as you press tab key after dot in front of object.
IPython provides information (introspection) of any object by putting ? in front of it. It
includes docstring, function definitions and constructor details of class. For example, to
explore the string object var defined above, in the input prompt enter var?.

In [5]: var = "Hello World"


In [6]: var?
Type: str
String form: Hello World
Length: 11
Docstring:
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)

26
Python Tutorial

or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.

IPython's magic functions are extremely powerful. Line magics let you run DOS commands
inside IPython. Let us run the dir command from within IPython console

In [8]: !dir *.exe


Volume in drive F has no label.
Volume Serial Number is E20D-C4B9

Directory of F:\Python311

07-02-2023 16:55 103,192 python.exe


07-02-2023 16:55 101,656 pythonw.exe
2 File(s) 204,848 bytes
0 Dir(s) 105,260,306,432 bytes free

Jupyter notebook is a web-based interface to programming environments of Python, Julia,


R and many others. For Python, it uses IPython as its main kernel.

27
8. Python - Environment SetupPython Tutorial

First step in the journey of learning Python is to install it on your machine. Today most
computer machines, especially having Linux OS, have Python pre-installed. However, it
may not be the latest version.
Python is available on a wide variety of platforms including Linux and Mac OS X. The
operating systems on which Python can be installed are listed below:
 Unix (Solaris, Linux, FreeBSD, AIX, HP/UX, SunOS, IRIX, etc.)
 Win 9x/NT/2000
 Macintosh (Intel, PPC, 68K)
 OS/2
 DOS (multiple versions)
 PalmOS
 Nokia mobile phones
 Windows CE
 Acorn/RISC OS
 BeOS
 Amiga
 VMS/OpenVMS
 QNX
 VxWorks
 Psion
Python has also been ported to the Java and .NET virtual machines. Let us know how to
set up the Python environment.

Local Environment Setup


Open a terminal window and type "python" to find out if it is already installed along with
its version. If Python is already installed, you will get a message given below:

$ python
Python 3.11.2 (main, Feb 8 2023, 14:49:24) [GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>>

Downloading Python
The most up-to-date and current source code, binaries, documentation, news, etc., is
available on the official website of Python
https://www.python.org/https://www.python.org/

You can download Python documentation from https://www.python.org/doc/. The


documentation is available in HTML, PDF, and PostScript formats.

28
Python Tutorial

Installing Python
Python distribution is available for a wide variety of platforms. You need to download only
the binary code applicable for your platform and install Python.
If the binary code for your platform is not available, you need a C compiler to compile the
source code manually. Compiling the source code offers more flexibility in terms of choice
of features that you require in your installation.
Here is a quick overview of installing Python on various platforms −

Install Python on Ubuntu Linux


To check whether Python is already installed, open the Linux terminal and enter the
following command −

$ python3.11 --version

In Ubuntu Linux, the easiest way to install Python is to use APT – Advanced Packaging
Tool. It is always recommended to update the list of packages in all the configured
repositories.

$ sudo apt update

Even after the update, the latest version of Python may not be available for install,
depending upon the version of Ubuntu you are using. To overcome this, add the
deadsnakes repository.

$ sudo apt-get install software-properties-common


$ sudo add-apt-repository ppa:deadsnakes/ppa

Update the package list again.

$ sudo apt update

To install the latest Python 3.11 version, enter the following command in the terminal −

$ sudo apt-get install python3.11

Check whether it has been properly installed.

$ python3
Python 3.11.2 (main, Feb 8 2023, 14:49:24) [GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> print ("Hello World")


Hello World

>>>

Install Python on other Linux


Here are the simple steps to install Python on Unix/Linux machine.

29
Python Tutorial

 Open a Web browser and go to https://www.python.org/downloads/.


 Follow the link to download zipped source code available for Unix/Linux.
 Download and extract files.
 Editing the Modules/Setup file if you want to customize some options.
Now issue the following commands:

$ run ./configure script


$ make
$ make install

This installs Python at standard location /usr/local/bin and its libraries at


/usr/local/lib/pythonXX where XX is the version of Python.

Using Yum Command


Red Hat Enterprise Linux (RHEL 8) does not install Python 3 by default. We usually use
yum command on CentOS and other related variants. The procedure for installing Python-
3 on RHEL 8 is as follows:

$ sudo yum install python3

Install Python on Windows


It should be noted that Python's version 3.10 onwards cannot be installed on Windows 7
or earlier operating systems.
The recommended way to install Python is to use the official installer. A link to the latest
stable version is given on the home page itself. It is also found at
https://www.python.org/downloads/windows/https://www.python.org/downloads/windo
ws/
You can find embeddable packages and installers for 32 as well as 64-bit architecture.

Let us download 64-bit Windows installer −


(https://www.python.org/ftp/python/3.11.2/python-3.11.2-
amd64.exehttps://www.python.org/ftp/python/3.11.2/python-3.11.2-amd64.exe)
30
Python Tutorial

Double click the file where it has been downloaded to start the installation.

Although you can straight away proceed by clicking the Install Now button, it is advised to
choose the installation folder with a relatively shorter path, and tick the second check box
to update the PATH variable.
Accept defaults for rest of the steps in this installation wizard to complete the installation.

Open the Windows Command Prompt terminal and run Python to check the success of
installation.

31
Python Tutorial

C:\Users\Acer>python
Python 3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934
64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

Python's standard library has an executable module called IDLE – short for Integrated
Development and Learning Environment. Find it from Window start menu and launch.

IDLE contains Python shell (interactive interpreter) and a customizable multi-window text
editor with features such as syntax highlighting, smart indent, auto completion etc. It is
cross-platform so works the same on Windows, MacOS and Linux. It also has a debugger
with provision to set breakpoints, stepping, and viewing of global and local namespaces.
Here are the steps to install Python on Windows machine.
 Open a Web browser and go to
https://www.python.org/downloads/https://www.python.org/downloads/.
 Follow the link for the Windows installer python-XYZ.msi file where XYZ is the
version you need to install.
 To use this installer python-XYZ.msi, the Windows system must support Microsoft
Installer 2.0. Save the installer file to your local machine and then run it to find out
if your machine supports MSI.
 Run the downloaded file. This brings up the Python install wizard, which is really
easy to use. Just accept the default settings, wait until the install is finished, and
you are done.

Macintosh Installation
Recent Macs come with Python installed, but it may be the old version. See
http://www.python.org/download/mac/ for instructions on getting the current version
along with extra tools to support development on the Mac. For older Mac OS's before Mac
OS X 10.3 (released in 2003), MacPython is available.

32
Python Tutorial

Jack Jansen maintains it and you can have full access to the entire documentation at his
website − http://www.cwi.nl/~jack/macpython.html. You can find complete installation
details for Mac OS installation.

Setting up PATH
Programs and other executable files are available in many directories, so operating
systems provide a search path that lists the directories that the OS searches for
executables.

The path is stored in an environment variable, which is a named string maintained by the
operating system. This variable contains information available to the command shell and
other programs.
The path variable is named as PATH in Unix or Path in Windows (Unix is case sensitive;
Windows is not).
In Mac OS, the installer handles the path details. To invoke the Python interpreter from
any particular directory, you must add the Python directory to your path.

Setting path at Unix/Linux


To add the Python directory to the path for a particular session in Unix −
 In the csh shell − type setenv PATH "$PATH:/usr/local/bin/python" and press
Enter.
 In the bash shell (Linux) − type export PATH="$PATH:/usr/local/bin/python"
and press Enter.
 In the sh or ksh shell − type PATH="$PATH:/usr/local/bin/python" and press
Enter.
Note − /usr/local/bin/python is the path of the Python directory

Setting path at Windows


To add the Python directory to the path for a particular session in Windows −
At the command prompt − type path %path%;C:\Python and press Enter.
Note − C:\Python is the path of the Python directory

Python Environment Variables


Here are important environment variables, which can be recognized by Python

Sr.No. Variable & Description


PYTHONPATH
It has a role similar to PATH. This variable tells the Python
interpreter where to locate the module files imported into
1 a program. It should include the Python source library
directory and the directories containing Python source
code. PYTHONPATH is sometimes preset by the Python
installer.
2 PYTHONSTARTUP

33
Python Tutorial

It contains the path of an initialization file containing


Python source code. It is executed every time you start
the interpreter. It is named as .pythonrc.py in Unix and it
contains commands that load utilities or modify
PYTHONPATH.
PYTHONCASEOK
3 It is used in Windows to instruct Python to find the first
case-insensitive match in an import statement. Set this
variable to any value to activate it.
PYTHONHOME
4 It is an alternative module search path. It is usually
embedded in the PYTHONSTARTUP or PYTHONPATH
directories to make switching module libraries easy.

Running Python

There are three different ways to start Python −

Interactive Interpreter

You can start Python from Unix, DOS, or any other system that provides you
a command-line interpreter or shell window.

Enter python in the command line.

Start coding right away in the interactive interpreter.

$python # Unix/Linux
or
python% # Unix/Linux
or
C:> python # Windows/DOS

Here is the list of all the available command line options −

Sr.No. Option & Description


-d
1 It provides debug
output.
-O
It generates
2 optimized bytecode
(resulting in .pyo
files).
-S
Do not run import
3 site to look for
Python paths on
startup.

34
Python Tutorial

-v
verbose output
4 (detailed trace on
import
statements).
-X
disable class-based
5 built-in exceptions
(just use strings);
obsolete starting
with version 1.6.
-c cmd
6 run Python script
sent in as cmd
string
File
7 run Python script
from given file

Script from the Command-line


A Python script can be executed at command line by invoking the interpreter on your
application, as in the following −

$python script.py # Unix/Linux


or
python% script.py # Unix/Linux
or
C: >python script.py # Windows/DOS

Note − Be sure the file permission mode allows execution.

Integrated Development Environment


You can run Python from a Graphical User Interface (GUI) environment as well, if you have
a GUI application on your system that supports Python.
 Unix − IDLE is the very first Unix IDE for Python.
 Windows − PythonWin is the first Windows interface for Python and is an IDE with
a GUI.
 Macintosh − The Macintosh version of Python along with the IDLE IDE is available
from the main website, downloadable as either MacBinary or BinHex'd files.
If you are not able to set up the environment properly, then you can take help from your
system admin. Make sure the Python environment is properly set up and working perfectly.
We have provided Python Online Compiler/Interpreter which helps you to Edit and
Execute the code directly from your browser. Try to click the icon to run the following
Python code to print conventional "Hello, World!".

Below code box allows you to change the value of the code. Try to change the
value inside print() and run it again to verify the result.

35
Python Tutorial

# This is my first Python program.


# This will print 'Hello, World!' as the output

print ("Hello, World!");

36
9. Python - Virtual EnvironmentPython Tutorial

Python Virtual Environment


Python virtual environments create a virtual installation of Python inside a project
directory. Users can then install and manage Python packages for each project. This allows
users to be able to install packages and modify their Python environment without fear of
breaking packages installed in other environments.

What is Virtual Environment in Python?


A Python virtual environment is:
 Considered as disposable.
 Used to contain a specific Python interpreter and software libraries and binaries
which are needed to support a project.
 Contained in a directory, conventionally either named venv or .venv in the project
directory.
 Not considered as movable or copyable.
When you install Python software on your computer, it is available for use from anywhere
in the file system. This is a system-wide installation.
While developing an application in Python, one or more libraries may be required to be
installed using the pip utility (e.g., pip3 install somelib). Moreover, an application (let
us say App1) may require a particular version of the library − say somelib 1.0. At the
same time another Python application (for example App2) may require newer version of
same library say somelib 2.0. Hence by installing a new version, the functionality of App1
may be compromised because of conflict between two different versions of same library.
This conflict can be avoided by providing two isolated environments of Python in the same
machine. These are called virtual environment. A virtual environment is a separate
directory structure containing isolated installation having a local copy of Python
interpreter, standard library and other modules.
The following figure shows the purpose of advantage of using virtual environment. Using
the global Python installation, more than one virtual environments are created, each
having different version of the same library, so that conflict is avoided.

37
Python Tutorial

Creation of Virtual Environments in Python using venv


This functionality is supported by venv module in standard Python distribution. Use
following commands to create a new virtual environment.

C:\Users\Acer>md\pythonapp
C:\Users\Acer>cd\pythonapp
C:\pythonapp>python -m venv myvenv

Here, myvenv is the folder in which a new Python virtual environment will be created
showing following directory structure −

Directory of C:\pythonapp\myvenv
22-02-2023 09:53 <DIR> .
22-02-2023 09:53 <DIR> ..
22-02-2023 09:53 <DIR> Include
22-02-2023 09:53 <DIR> Lib
22-02-2023 09:53 77 pyvenv.cfg
22-02-2023 09:53 <DIR> Scripts

The utilities for activating and deactivating the virtual environment as well as the local
copy of Python interpreter will be placed in the scripts folder.

Directory of C:\pythonapp\myvenv\scripts
22-02-2023 09:53 <DIR> .
22-02-2023 09:53 <DIR> ..
22-02-2023 09:53 2,063 activate
22-02-2023 09:53 992 activate.bat
22-02-2023 09:53 19,611 Activate.ps1
38
Python Tutorial

22-02-2023 09:53 393 deactivate.bat


22-02-2023 09:53 106,349 pip.exe
22-02-2023 09:53 106,349 pip3.10.exe
22-02-2023 09:53 106,349 pip3.exe
22-02-2023 09:53 242,408 python.exe
22-02-2023 09:53 232,688 pythonw.exe

Activating Virtual Environment


To enable this new virtual environment, execute activate.bat in Scripts folder.

C:\pythonapp>myvenv\scripts\activate
(myvenv) C:\pythonapp>

Note the name of the virtual environment in the parentheses. The Scripts folder contains
a local copy of Python interpreter. You can start a Python session in this virtual
environment.

Checking If Python is Running Inside a Virtual Environment


To confirm whether this Python session is in virtual environment check the sys.path.

(myvenv) C:\pythonapp>python
Python 3.10.1 (tags/v3.10.1:2cd268a, Dec 6 2021, 19:10:37) [MSC v.1929
64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', 'C:\\Python310\\python310.zip', 'C:\\Python310\\DLLs',
'C:\\Python310\\lib', 'C:\\Python310', 'C:\\pythonapp\\myvenv',
'C:\\pythonapp\\myvenv\\lib\\site-packages']
>>>

The scripts folder of this virtual environment also contains pip utilities. If you install a
package from PyPI, that package will be active only in current virtual environment.

Deactivating Virtual Environment


To deactivate this environment, run deactivate.bat.

39
10. Python - Syntax Python Tutorial

Python - Syntax
The Python syntax defines a set of rules that are used to create a Python Program. The
Python Programming Language Syntax has many similarities to Perl, C, and Java
Programming Languages. However, there are some definite differences between the
languages.

First Python Program


Let us execute a Python program to print "Hello, World!" in two different modes of Python
Programming. (a) Interactive Mode Programming (b) Script Mode Programming.

Python - Interactive Mode Programming


We can invoke a Python interpreter from command line by typing python at the command
prompt as following −

$ python3
Python 3.10.6 (main, Mar 10 2023, 10:55:28) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

Here >>> denotes a Python Command Prompt where you can type your commands. Let's
type the following text at the Python prompt and press the Enter −

>>> print ("Hello, World!")

If you are running older version of Python, like Python 2.4.x, then you would need to use
print statement without parenthesis as in print "Hello, World!". However, in Python version
3.x, this produces the following result −

Hello, World!

Python - Script Mode Programming


We can invoke the Python interpreter with a script parameter which begins the execution
of the script and continues until the script is finished. When the script is finished, the
interpreter is no longer active.
Let us write a simple Python program in a script which is simple text file. Python files have
extension .py. Type the following source code in a test.py file −

print ("Hello, World!")

We assume that you have Python interpreter path set in the PATH variable. Now, let's try
to run this program as follows −

$ python3 test.py

40
Python Tutorial

This produces the following result −

Hello, World!

Let us try another way to execute a Python script. Here is the modified test.py file −

#!/usr/bin/python3
print ("Hello, World!")

We assume that you have Python interpreter available in /usr/bin directory. Now, try to
run this program as follows −

$ chmod +x test.py # This is to make file executable


$./test.py

This produces the following result −

Hello, World!

Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or other
object. An identifier starts with a letter A to Z or a to z or an underscore (_) followed by
zero or more letters, underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers.

Python is a case sensitive programming language. Thus, Manpower and manpower


are two different identifiers in Python.

Here are naming conventions for Python identifiers −


 Python Class names start with an uppercase letter. All other identifiers start with a
lowercase letter.
 Starting an identifier with a single leading underscore indicates that the identifier
is private identifier.
 Starting an identifier with two leading underscores indicates a strongly private
identifier.
 If the identifier also ends with two trailing underscores, the identifier is a
language-defined special name.

Python Reserved Words


The following list shows the Python keywords or reserved words. These are reserved words
which cannot be used as constant or variable or any other identifier names. All the Python
keywords contain lowercase letters only.
and as assert
break class continue
def del elif
else except FALSE
finally for from
global if import

41
Python Tutorial

in is lambda
None nonlocal not
or pass raise
return TRUE try
while with yield

Python Lines and Indentation


Python programming provides no braces to indicate blocks of code for class and function
definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly
enforced.
The number of spaces in the indentation is variable, but all statements within the block
must be indented the same amount. For example −

if True:
print ("True")
else:
print ("False")

However, the following block generates an error −

if True:
print ("Answer")
print ("True")
else:
print ("Answer")
print ("False")

Thus, in Python all the continuous lines indented with same number of spaces would form
a block. The following example has various statement blocks −

Do not try to understand the logic at this point of time. Just make sure you
understood various blocks even if they are without braces.

import sys
try:
# open file stream
file = open(file_name, "w")
except IOError:
print "There was an error writing to", file_name
sys.exit()
print "Enter '", file_finish,
print "' When finished"
while file_text != file_finish:

42
Python Tutorial

file_text = raw_input("Enter text: ")


if file_text == file_finish:
# close the file
file.close
break
file.write(file_text)
file.write("\n")
file.close()
file_name = raw_input("Enter filename: ")
if len(file_name) == 0:
print "Next time please enter something"
sys.exit()
try:
file = open(file_name, "r")
except IOError:
print "There was an error reading file"
sys.exit()
file_text = file.read()
file.close()
print file_text

Python Multi-Line Statements


Statements in Python typically end with a new line. Python however, allows the use of the
line continuation character (\) to denote that the line should continue. For example −

total = item_one + \
item_two + \
item_three

Statements contained within the [], {}, or () brackets do not need to use the line
continuation character. For example, following statement works well in Python −

days = ['Monday', 'Tuesday', 'Wednesday',


'Thursday', 'Friday']

Quotations in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals,
as long as the same type of quote starts and ends the string.

43
Python Tutorial

The triple quotes are used to span the string across multiple lines. For example, all the
following are legal −

word = 'word'
print (word)

sentence = "This is a sentence."


print (sentence)

paragraph = """This is a paragraph. It is


made up of multiple lines and sentences."""
print (paragraph)

Comments in Python
A comment is a programmer-readable explanation or annotation in the Python source
code. They are added with the purpose of making the source code easier for humans to
understand, and are ignored by Python interpreter
Just like most modern languages, Python supports single-line (or end-of-line) and multi-
line (block) comments. Python comments are very much similar to the comments available
in PHP, BASH and Perl Programming languages.
A hash sign (#) that is not inside a string literal begins a comment. All characters after
the # and up to the end of the physical line are part of the comment and the Python
interpreter ignores them.

# First comment
print ("Hello, World!") # Second comment

This produces the following result −

Hello, World!

You can type a comment on the same line after a statement or expression −

name = "Madisetti" # This is again comment

You can comment multiple lines as follows −

# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.

Following triple-quoted string is also ignored by Python interpreter and can be used as a
multiline comment:

'''
This is a multiline

44
Python Tutorial

comment.
'''

Using Blank Lines in Python Programs


A line containing only whitespace, possibly with a comment, is known as a blank line and
Python totally ignores it.
In an interactive interpreter session, you must enter an empty physical line to terminate
a multiline statement.

Waiting for the User


The following line of the program displays the prompt, the statement saying “Press the
enter key to exit”, and waits for the user to take action −

#!/usr/bin/python
raw_input("\n\nPress the enter key to exit.")

Here, "\n\n" is used to create two new lines before displaying the actual line. Once the
user presses the key, the program ends. This is a nice trick to keep a console window open
until the user is done with an application.

Multiple Statements on a Single Line


The semicolon ( ; ) allows multiple statements on the single line given that neither
statement starts a new code block. Here is a sample snip using the semicolon −

import sys; x = 'foo'; sys.stdout.write(x + '\n')

Multiple Statement Groups as Suites


A group of individual statements, which make a single code block are called suites in
Python. Compound or complex statements, such as if, while, def, and class require a
header line and a suite.
Header lines begin the statement (with the keyword) and terminate with a colon ( : ) and
are followed by one or more lines which make up the suite. For example −

if expression :
suite
elif expression :
suite
else :
suite

Command Line Arguments in Python


Many programs can be run to provide you with some basic information about how they
should be run. Python enables you to do this with -h −

45
Python Tutorial

$ python3 -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-c cmd : program passed in as string (terminates option list)
-d : debug output from parser (also PYTHONDEBUG=x)
-E : ignore environment variables (such as PYTHONPATH)
-h : print this help message and exit

[ etc. ]

You can also program your script in such a way that it should accept various options.
Command Line Arguments is an advanced topic and should be studied a bit later once you
have gone through rest of the Python concepts.

46
11. Python - Variables Python Tutorial

Python Variables
Python variables are the reserved memory locations used to store values within a Python
Program. This means that when you create a variable, you reserve some space in the
memory.
Based on the data type of a variable, Python interpreter allocates memory and decides
what can be stored in the reserved memory. Therefore, by assigning different data types
to Python variables, you can store integers, decimals or characters in these variables.

Memory Addresses
Data items belonging to different data types are stored in computer's memory. Computer's
memory locations are having a number or address, internally represented in binary form.
Data is also stored in binary form as the computer works on the principle of binary
representation. In the following diagram, a string May and a number 18 is shown as stored
in memory locations.

If you know the assembly language, you can covert these data items and the memory
address, and give a machine language instruction. However, it is not easy for everybody.
Language translator such as Python interpreter performs this type of conversion. It stores
the object in a randomly chosen memory location. Python's built-in id() function returns
the address where the object is stored.

>>> "May"
May
>>> id("May")
2167264641264

47
Python Tutorial

>>> 18
18
>>> id(18)
140714055169352

Once the data is stored in the memory, it can be accessed repeatedly for performing a
certain process. Obviously, fetching the data from its ID is cumbersome. High level
languages like Python make it possible to give a suitable alias or a label to refer to the
memory location.
In the above example, let us label the location of May as month, and location in which 18
is stored as age. Python uses the assignment operator (=) to bind an object with the label.

>>> month="May"
>>> age=18

The data object (May) and its name (month) have the same id(). The id() of 18 and age
are also same.

>>> id(month)
2167264641264
>>> id(age)
140714055169352

The label is an identifier. It is usually called as a variable. A Python variable is a symbolic


name that is a reference or pointer to an object.

Creating Python Variables


Python variables do not need explicit declaration to reserve memory space or you can say
to create a variable. A Python variable is created automatically when you assign a value
to it. The equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to
the right of the = operator is the value stored in the variable. For example −

Example to Create Python Variables


This example creates different types (an integer, a float, and a string) of variables.

counter = 100 # Creates an integer variable


miles = 1000.0 # Creates a floating point variable
name = "Zara Ali" # Creates a string variable

Printing Python Variables


Once we create a Python variable and assign a value to it, we can print it using print()
function. Following is the extension of previous example and shows how to print different
variables in Python:

48
Python Tutorial

Example to Print Python Variables


This example prints variables.

counter = 100 # Creates an integer variable


miles = 1000.0 # Creates a floating point variable
name = "Zara Ali" # Creates a string variable

print (counter)
print (miles)
print (name)

Here, 100, 1000.0 and "Zara Ali" are the values assigned to counter, miles, and name
variables, respectively. When running the above Python program, this produces the
following result −

100
1000.0
Zara Ali

Deleting Python Variables


You can delete the reference to a number object by using the del statement. The syntax
of the del statement is −

del var1[,var2[,var3[....,varN]]]]

You can delete a single object or multiple objects by using the del statement. For example

del var
del var_a, var_b

Example
Following example shows how we can delete a variable and if we try to use a deleted
variable then Python interpreter will throw an error:

counter = 100
print (counter)

del counter
print (counter)

This will produce the following result:

100
Traceback (most recent call last):

49
Python Tutorial

File "main.py", line 7, in <module>


print (counter)
NameError: name 'counter' is not defined

Getting Type of a Variable


You can get the data type of a Python variable using the python built-in function type() as
follows.

Example: Printing Variables Type


x = "Zara"
y = 10
z = 10.10
print(type(x))
print(type(y))
print(type(z))

This will produce the following result:

<class 'str'>
<class 'int'>
<class 'float'>

Casting Python Variables


You can specify the data type of a variable with the help of casting as follows:
Example
This example demonstrates case sensitivity of variables.

x = str(10) # x will be '10'


y = int(10) # y will be 10
z = float(10) # z will be 10.0
print( "x =", x )
print( "y =", y )
print( "z =", z )

This will produce the following result:

x = 10
y = 10
z = 10.0

50
Python Tutorial

Case-Sensitivity of Python Variables


Python variables are case sensitive which means Age and age are two different variables:

age = 20
Age = 30

print( "age =", age )


print( "Age =", Age )

This will produce the following result:

age = 20
Age = 30

Python Variables - Multiple Assignment


Python allows to initialize more than one variables in a single statement. In the following
case, three variables have same value.

>>> a=10
>>> b=10
>>> c=10

Instead of separate assignments, you can do it in a single assignment statement as follows


>>> a=b=c=10
>>> print (a,b,c)
10 10 10

In the following case, we have three variables with different values.

>>> a=10
>>> b=20
>>> c=30

These separate assignment statements can be combined in one. You need to give comma
separated variable names on left, and comma separated values on the right of = operator.

>>> a,b,c = 10,20,30


>>> print (a,b,c)
10 20 30

Let's try few examples in script mode: −

a = b = c = 100

51
Python Tutorial

print (a)
print (b)
print (c)

This produces the following result:

100
100
100

Here, an integer object is created with the value 1, and all three variables are assigned to
the same memory location. You can also assign multiple objects to multiple variables. For
example −

a,b,c = 1,2,"Zara Ali"

print (a)
print (b)
print (c)

This produces the following result:

1
2
Zara Ali

Here, two integer objects with values 1 and 2 are assigned to variables a and b
respectively, and one string object with the value "Zara Ali" is assigned to the variable c.

Python Variables - Naming Convention


Every Python variable should have a unique name like a, b, c. A variable name can be
meaningful like color, age, name etc. There are certain rules which should be taken care
while naming a Python variable:
 A variable name must start with a letter or the underscore character
 A variable name cannot start with a number or any special character like $, (, * %
etc.
 A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ )
 Python variable names are case-sensitive which means Name and NAME are two
different variables in Python.
 Python reserved keywords cannot be used naming the variable.
If the name of variable contains multiple words, we should use these naming patterns −
 Camel case − First letter is a lowercase, but first letter of each subsequent word
is in uppercase. For example: kmPerHour, pricePerLitre
 Pascal case − First letter of each word is in uppercase. For example: KmPerHour,
PricePerLitre

52
Python Tutorial

 Snake case − Use single underscore (_) character to separate words. For
example: km_per_hour, price_per_litre

Example
Following are valid Python variable names:

counter = 100
_count = 100
name1 = "Zara"
name2 = "Nuha"
Age = 20
zara_salary = 100000

print (counter)
print (_count)
print (name1)
print (name2)
print (Age)
print (zara_salary)

This will produce the following result:

100
100
Zara
Nuha
20
100000

Example
Following are invalid Python variable names:

1counter = 100
$_count = 100
zara-salary = 100000
print (1counter)
print ($count)
print (zara-salary)

This will produce the following result:

File "main.py", line 3

53
Python Tutorial

1counter = 100
^
SyntaxError: invalid syntax

Example
Once you use a variable to identify a data object, it can be used repeatedly without its id()
value. Here, we have a variables height and width of a rectangle. We can compute the
area and perimeter with these variables.

>>> width=10
>>> height=20
>>> area=width*height
>>> area
200
>>> perimeter=2*(width+height)
>>> perimeter
60

Use of variables is especially advantageous when writing scripts or programs. Following


script also uses the above variables.

#! /usr/bin/python3
width = 10
height = 20
area = width*height
perimeter = 2*(width+height)
print ("Area = ", area)
print ("Perimeter = ", perimeter)

Save the above script with .py extension and execute from command-line. The result
would be −

Area = 200
Perimeter = 60

Python Local Variables


Python Local Variables are defined inside a function. We cannot access variable outside
the function.

A Python function is a piece of reusable code and you will learn more about
function in Python - Functions tutorial.

Example
Following is an example to show the usage of local variables:

54
Python Tutorial

def sum(x,y):
sum = x + y
return sum
print(sum(5, 10))

This will produce the following result −

15

Python Global Variables


Any variable created outside a function can be accessed within any function and so they
have global scope.
Example
Following is an example of global variables −

x = 5
y = 10
def sum():
sum = x + y
return sum
print(sum())

This will produce the following result −

15

Constants in Python
Python doesn't have any formally defined constants, However, you can indicate a variable
to be treated as a constant by using all-caps names with underscores. For example, the
name PI_VALUE indicates that you don't want the variable redefined or changed in any
way.

The naming convention using all-caps is sometimes referred to as screaming


snake case - where the all-caps refer to screaming and the underscores refer to
snakes.

Python vs C/C++ Variables


The concept of variable works differently in Python than in C/C++. In C/C++, a variable
is a named memory location. If a=10 and also b=10, both are two different memory
locations. Let us assume their memory address is 100 and 200 respectively.

55
Python Tutorial

If a different value is assigned to "a" - say 50, 10 in the address 100 is overwritten.

A Python variable refers to the object and not the memory location. An object is stored in
memory only once. Multiple variables are really the multiple labels to the same object.

The statement a=50 creates a new int object 50 in the memory at some other location,
leaving the object 10 referred by "b".

Further, if you assign some other value to b, the object 10 is not referred.

Python's garbage collector mechanism releases the memory occupied by any object that
is not referred.
Python's identity operator returns True if both the operands have same id() value.

>>> a=b=10
>>> a is b
True
>>> id(a), id(b)
(140731955278920, 140731955278920)

56
12. Python - Data Types Python Tutorial

Python Data Types


Python data types are actually classes, and the defined variables are their instances or
objects. Since Python is dynamically typed, the data type of a variable is determined at
runtime based on the assigned value.
In general, the data types are used to define the type of a variable. It represents the type
of data we are going to store in a variable and determines what operations can be done
on it.
Each programming language has its own classification of data items. With these datatypes,
we can store different types of data values.

Types of Data Types in Python


Python supports the following built-in data types −
 Numeric Data Types
o int
o float
o complex
 String Data Types
 Sequence Data Types
o list
o tuple
o range
 Binary Data Types
o bytes
o bytearray
o memoryview
 Dictionary Data Type
 Set Data Type
o set
o frozenset
 Boolean Data Type
 None Type

57
Python Tutorial

1. Python Numeric Data Types


Python numeric data types store numeric values. Number objects are created when you
assign a value to them. For example −

var1 = 1 # int data type


var2 = True # bool data type
var3 = 10.023 # float data type
var4 = 10+3j # complex data type

Python supports four different numerical types and each of them have built-in classes in
Python library, called int, bool, float and complex respectively −
 int (signed integers)
 float (floating point real values)
 complex (complex numbers)
A complex number is made up of two parts - real and imaginary. They are separated by
'+' or '-' signs. The imaginary part is suffixed by 'j' which is the imaginary number. The
square root of -1 (√-1), is defined as imaginary number. Complex number in Python is
represented as x+yj, where x is the real part, and y is the imaginary part. So, 5+6j is a
complex number.

>>> type(5+6j)
<class 'complex'>

Here are some examples of numbers −

int float complex


10 0 3.14j
0O777 15.2 45.j
-786 -21.9 9.322e-36j
80 32.3+e18 .876j
0x17 -90 -.6545+0J
-0x260 -3.25E+101 3e+26J
0x69 70.2-E12 4.53e-7j

Example of Numeric Data Types


Following is an example to show the usage of Integer, Float and Complex numbers:

# integer variable.
a=100
print("The type of variable having value", a, " is ", type(a))

# float variable.
c=20.345
print("The type of variable having value", c, " is ", type(c))

58
Python Tutorial

# complex variable.
d=10+3j
print("The type of variable having value", d, " is ", type(d))

2. Python String Data Type


Python string is a sequence of one or more Unicode characters, enclosed in single, double
or triple quotation marks (also called inverted commas). Python strings are immutable
which means when you perform an operation on strings, you always produce a new string
object of the same type, rather than mutating an existing string.
As long as the same sequence of characters is enclosed, single or double or triple quotes
don't matter. Hence, following string representations are equivalent.

>>> 'TutorialsPoint'
'TutorialsPoint'
>>> "TutorialsPoint"
'TutorialsPoint'
>>> '''TutorialsPoint'''
'TutorialsPoint'

A string in Python is an object of str class. It can be verified with type() function.

>>> type("Welcome To TutorialsPoint")


<class 'str'>

A string is a non-numeric data type. Obviously, we cannot perform arithmetic operations


on it. However, operations such as slicing and concatenation can be done. Python's str
class defines a number of useful methods for string processing. Subsets of strings can be
taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of
the string and working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator in Python.
Example of String Data Type

str = 'Hello World!'


print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string

This will produce the following result −

Hello World!

59
Python Tutorial

H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

3. Python Sequence Data Types


Sequence is a collection data type. It is an ordered collection of items. Items in the
sequence have a positional index starting with 0. It is conceptually similar to an array in
C or C++. There are following three sequence data types defined in Python.
 List Data Type
 Tuple Data Type
 Range Data Type
Python sequences are bounded and iterable - Whenever we say an iterable in Python, it
means a sequence data type (for example, a list).
(a) Python List Data Type
Python Lists are the most versatile compound data types. A Python list contains items
separated by commas and enclosed within square brackets ([]). To some extent, Python
lists are similar to arrays in C. One difference between them is that all the items belonging
to a Python list can be of different data type whereas C array can store elements related
to a particular data type.

>>> [2023, "Python", 3.11, 5+6j, 1.23E-4]

A list in Python is an object of list class. We can check it with type() function.

>>> type([2023, "Python", 3.11, 5+6j, 1.23E-4])


<class 'list'>

As mentioned, an item in the list may be of any data type. It means that a list object can
also be an item in another list. In that case, it becomes a nested list.

>>> [['One', 'Two', 'Three'], [1,2,3], [1.0, 2.0, 3.0]]

A list can have items which are simple numbers, strings, tuple, dictionary, set or object of
user defined class.
The values stored in a Python list can be accessed using the slice operator ([ ] and [:])
with indexes starting at 0 in the beginning of the list and working their way to end -1. The
plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition
operator.
Example of List Data Type

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]


tinylist = [123, 'john']

print (list) # Prints complete list

60
Python Tutorial

print (list[0]) # Prints first element of the list


print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists

This produce the following result −

['abcd', 786, 2.23, 'john', 70.2]


abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

(b) Python Tuple Data Type


Python tuple is another sequence data type that is similar to a list. A Python tuple consists
of a number of values separated by commas. Unlike lists, however, tuples are enclosed
within parentheses (...).
A tuple is also a sequence, hence each item in the tuple has an index referring to its
position in the collection. The index starts from 0.

>>> (2023, "Python", 3.11, 5+6j, 1.23E-4)

In Python, a tuple is an object of tuple class. We can check it with the type() function.

>>> type((2023, "Python", 3.11, 5+6j, 1.23E-4))


<class 'tuple'>

As in case of a list, an item in the tuple may also be a list, a tuple itself or an object of any
other Python class.

>>> (['One', 'Two', 'Three'], 1,2.0,3, (1.0, 2.0, 3.0))

To form a tuple, use of parentheses is optional. Data items separated by comma without
any enclosing symbols are treated as a tuple by default.

>>> 2023, "Python", 3.11, 5+6j, 1.23E-4


(2023, 'Python', 3.11, (5+6j), 0.000123)

Example of Tuple Data Type

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


tinytuple = (123, 'john')

print (tuple) # Prints the complete tuple


print (tuple[0]) # Prints first element of the tuple

61
Python Tutorial

print (tuple[1:3]) # Prints elements of the tuple starting from 2nd


till 3rd
print (tuple[2:]) # Prints elements of the tuple starting from 3rd
element
print (tinytuple * 2) # Prints the contents of the tuple twice
print (tuple + tinytuple) # Prints concatenated tuples

The code produces the following result −

('abcd', 786, 2.23, 'john', 70.2)


abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] )
and their elements and size can be changed i.e. lists are mutable, while tuples are enclosed
in parentheses ( ( ) ) and cannot be updated (immutable). Tuples can be thought of as
read-only lists.
The following code is invalid with tuple, because we attempted to update a tuple, which is
not allowed. Similar case is possible with lists −

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list

(c) Python Range Data Type


A Python range is an immutable sequence of numbers which is typically used to iterate
through a specific number of items.
It is represented by the Range class. The constructor of this class accepts a sequence of
numbers starting from 0 and increments to 1 until it reaches a specified number. Following
is the syntax of the function −

range(start, stop, step)

Here is the description of the parameters used −


 start: Integer number to specify starting position, (Its optional, Default: 0)
 stop: Integer number to specify ending position (It's mandatory)
 step: Integer number to specify increment, (Its optional, Default: 1)
Example of Range Data Type
Following is a program which uses for loop to print numbers from 0 to 4 −

for i in range(5):
print(i)

62
Python Tutorial

The code produces the following result −

0
1
2
3
4

Now let's modify above program to print the number starting from 2 instead of 0 −

for i in range(2, 5):


print(i)

This code produces the following result −

2
3
4

Again, let's modify the program to print the number starting from 1 but with an increment
of 2 instead of 1:

for i in range(1, 5, 2):


print(i)

This code produces the following result −

1
3

4. Python Binary Data Types


A binary data type in Python is a way to represent data as a series of binary digits, which
are 0's and 1's. It is like a special language computers understand to store and process
information efficiently.
This type of data is commonly used when dealing with things like files, images, or anything
that can be represented using just two possible values. So, instead of using regular
numbers or letters, binary sequence data types use a combination of 0s and 1s to
represent information.
Python provides three different ways to represent binary data. They are as follows −
 bytes
 bytearray
 memoryview
Let us discuss each of these data types individually −

(a) Python Bytes Data Type

63
Python Tutorial

The byte data type in Python represents a sequence of bytes. Each byte is an integer value
between 0 and 255. It is commonly used to store binary data, such as images, files, or
network packets.
We can create bytes in Python using the built-in bytes() function or by prefixing a sequence
of numbers with b.
Example of Bytes Data Type
In the following example, we are using the built-in bytes() function to explicitly specify a
sequence of numbers representing ASCII values −
 # Using bytes() function to create bytes
 b1 = bytes([65, 66, 67, 68, 69])
 print(b1)
The result obtained is as follows −

b'ABCDE'

Here we are using the "b" prefix before a string to automatically create a bytes object −

# Using prefix 'b' to create bytes


b2 = b'Hello'
print(b2)

Following is the output of the above code −

b'Hello'

(b) Python Bytearray Data Type


The bytearray data type in Python is quite similar to the bytes data type, but with one key
difference: it is mutable, meaning you can modify the values stored in it after it is created.
You can create a bytearray using various methods by passing an iterable of integers
representing byte values, by encoding a string, or by converting an existing bytes or
bytearray object. For this, we use bytearray() function.

Example of Bytearray Data Type


In the example below, we are creating a bytearray by passing an iterable of integers
representing byte values −

# Creating a bytearray from an iterable of integers


value = bytearray([72, 101, 108, 108, 111])
print(value)

The output obtained is as shown below −

bytearray(b'Hello')

Now, we are creating a bytearray by encoding a string using a "UTF-8" encoding −

# Creating a bytearray by encoding a string


val = bytearray("Hello", 'utf-8')

64
Python Tutorial

print(val)

The result produced is as follows −

bytearray(b'Hello')

(c) Python Memoryview Data Type


In Python, a memoryview is a built-in object that provides a view into the memory of the
original object, generally objects that support the buffer protocol, such as byte arrays
(bytearray) and bytes (bytes). It allows you to access the underlying data of the original
object without copying it, providing efficient memory access for large datasets.
You can create a memoryview using various methods. These methods include using the
memoryview() constructor, slicing bytes or bytearray objects, extracting from array
objects, or using built-in functions like open() when reading from files.

Example of Memoryview Data Type


In the given example, we are creating a memoryview object directly by passing a
supported object to the memoryview() constructor. The supported objects generally
include byte arrays (bytearray), bytes (bytes), and other objects that support the buffer
protocol −

data = bytearray(b'Hello, world!')


view = memoryview(data)
print(view)

Following is the output of the above code −

<memory at 0x00000186FFAA3580>

If you have an array object, you can create a memoryview using the buffer interface as
shown below −

import array
arr = array.array('i', [1, 2, 3, 4, 5])
view = memoryview(arr)
print(view)

The output obtained is as shown below −

<memory at 0x0000017963CD3580>

You can also create a memoryview by slicing a bytes or bytearray object −

data = b'Hello, world!'


# Creating a view of the last part of the data
view = memoryview(data[7:])
print(view)

The result obtained is as follows −

65
Python Tutorial

<memory at 0x00000200D9AA3580>

5. Python Dictionary Data Type


Python dictionaries are kind of hash table type. A dictionary key can be almost any Python
type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary
Python object.
Python dictionary is like associative arrays or hashes found in Perl and consist of key:value
pairs. The pairs are separated by comma and put inside curly brackets {}. To establish
mapping between key and value, the colon':' symbol is put between the two.

>>> {1:'one', 2:'two', 3:'three'}

In Python, dictionary is an object of the built-in dict class. We can check it with the type()
function.

>>> type({1:'one', 2:'two', 3:'three'})


<class 'dict'>

Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed
using square braces ([]).

Example of Dictionary Data Type


dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print (tinydict.keys()) # Prints all the keys
print (tinydict.values()) # Prints all the values

This code produces the following result −

This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']

Python's dictionary is not a sequence. It is a collection of items but each item (key:value
pair) is not identified by positional index as in string, list or tuple. Hence, slicing operation
cannot be done on a dictionary. Dictionary is a mutable object, so it is possible to perform
add, modify or delete actions with corresponding functionality defined in dict class. These
operations will be explained in a subsequent chapter.

66
Python Tutorial

6. Python Set Data Type


Set is a Python implementation of set as defined in Mathematics. A set in Python is a
collection, but is not an indexed or ordered collection as string, list or tuple. An object
cannot appear more than once in a set, whereas in List and Tuple, same object can appear
more than once.
Comma separated items in a set are put inside curly brackets or braces {}. Items in the
set collection can be of different data types.

>>> {2023, "Python", 3.11, 5+6j, 1.23E-4}


{(5+6j), 3.11, 0.000123, 'Python', 2023}

Note that items in the set collection may not follow the same order in which they are
entered. The position of items is optimized by Python to perform operations over set as
defined in mathematics.
Python's Set is an object of built-in set class, as can be checked with the type() function.

>>> type({2023, "Python", 3.11, 5+6j, 1.23E-4})


<class 'set'>

A set can store only immutable objects such as number (int, float, complex or bool),
string or tuple. If you try to put a list or a dictionary in the set collection, Python raises a
TypeError.

>>> {['One', 'Two', 'Three'], 1,2,3, (1.0, 2.0, 3.0)}


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

Hashing is a mechanism in computer science which enables quicker searching of objects


in computer's memory. Only immutable objects are hashable.
Even if a set doesn't allow mutable items, the set itself is mutable. Hence,
add/delete/update operations are permitted on a set object, using the methods in built-in
set class. Python also has a set of operators to perform set manipulation. The methods
and operators are explained in latter chapters

Example of Set

set1 = {123, 452, 5, 6}


set2 = {'Java', 'Python', 'JavaScript'}
print(set1)
print(set2)

This will generate the following output −

{123, 452, 5, 6}
{'Python', 'JavaScript', 'Java'}

67
Python Tutorial

7. Python Boolean Data Type


Python Boolean type is one of built-in data types which represents one of the two values
either True or False. Python bool() function allows you to evaluate the value of any
expression and returns either True or False based on the expression.
A Boolean number has only two possible values, as represented by the keywords, True
and False. They correspond to integer 1 and 0 respectively.

>>> type (True)


<class 'bool'>
>>> type(False)
<class 'bool'>

Example of Boolean Data Type


Following is a program which prints the value of boolean variables a and b −

a = True
# display the value of a
print(a)
# display the data type of a
print(type(a))

This code will produce the following result −

true
<class 'bool'>

Following is another program which evaluates the expressions and prints the return values

# Returns false as a is not equal to b


a = 2
b = 4
print(bool(a==b))

# Following also prints the same


print(a==b)

# Returns False as a is None


a = None
print(bool(a))

# Returns false as a is an empty sequence

68
Python Tutorial

a = ()
print(bool(a))

# Returns false as a is 0
a = 0.0
print(bool(a))

# Returns false as a is 10
a = 10
print(bool(a))

This produces the following result −

False
False
False
False
False
True

8. Python None Type


Python's none type is represented by the "nonetype." It is an object of its own data type.
The nonetype represents the null type of values or absence of a value.

Example of None Type


In the following example, we are assigning None to a variable x and printing its type,
which will be nonetype −

# Declaring a variable
# And, assigning a Null value (None)

x = None

# Printing its value and type


print("x = ", x)
print("type of x = ", type(x))

This produce the following result −

x = None
type of x = <class 'NoneType'>

69
Python Tutorial

Getting Data Type


To get the data types in Python, you can use the type() function. The type() is a built-in
function that returns the class of the given object.

Example
In the following example, we are getting the type of the values and variables −

# Getting type of values


print(type(123))
print(type(9.99))

# Getting type of variables


a = 10
b = 2.12
c = "Hello"
d = (10, 20, 30)
e = [10, 20, 30]

print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))

This produces the following result −

<class 'int'>
<class 'float'>
<class 'int'>
<class 'float'>
<class 'str'>
<class 'tuple'>
<class 'list'>

Setting Data Type


In Python, during declaring a variable or an object, you don't need to set the data types.
Data type is set automatically based on the assigned value.

Example

70
Python Tutorial

The following example demonstrates how a variable's data type is set based on the given
value −

# Declaring a variable
# And, assigning an integer value

x = 10

# Printing its value and type


print("x = ", x)
print("type of x = ", type(x))

# Now, assigning string value to


# the same variable
x = "Hello World!"

# Printing its value and type


print("x = ", x)
print("type of x = ", type(x))

This produces the following result −

x = 10
type of x = <class 'int'>
x = Hello World!
type of x = <class 'str'>

Primitive and Non-Primitive Data Types


The above-explained data types can also be categorized as primitive and non-primitive.

1. Primitive Types
The primitive data types are the fundamental data types that are used to create complex
data types (sometimes called complex data structures). There are mainly four primitive
data types, which are −
 Integers
 Floats
 Booleans, and
 Strings

2. Non-primitive Types
The non-primitive data types store values or collections of values. There are mainly four
types of non-primitive types, which are −
71
Python Tutorial

Lists
Tuples
Dictionaries, and
Sets

Python Data Type Conversion


Sometimes, you may need to perform conversions between the built-in data types. To
convert data between different Python data types, you simply use the type name as a
function.
Read: Python Type Casting

Example
Following is an example which converts different values to integer, floating point and string
values respectively −

print("Conversion to integer data type")


a = int(1) # a will be 1
b = int(2.2) # b will be 2
c = int("3.3") # c will be 3

print (a)
print (b)
print (c)

print("Conversion to floating point number")


a = float(1) # a will be 1.0
b = float(2.2) # b will be 2.2
c = float("3.3") # c will be 3.3

print (a)
print (b)
print (c)

print("Conversion to string")
a = str(1) # a will be "1"
b = str(2.2) # b will be "2.2"
c = str("3.3") # c will be "3.3"

72
Python Tutorial

print (a)
print (b)
print (c)

This produce the following result −

Conversion to integer data type


1
2
3
Conversion to floating point number
1.0
2.2
3.3
Conversion to string
1
2.2
3.3

Data Type Conversion Functions


There are several built-in functions to perform conversion from one data type to another.
These functions return a new object representing the converted value.

Sr.No. Function & Description


Python int() function
1 Converts x to an integer. base
specifies the base if x is a string.
Python long() function

2 Converts x to a long integer. base


specifies the base if x is a string. This
function has been deprecated.
Python float() function
3 Converts x to a floating-point
number.
Python complex() function
4
Creates a complex number.
Python str() function
5 Converts object x to a string
representation.
Python repr() function
6 Converts object x to an expression
string.
7 Python eval() function

73
Python Tutorial

Evaluates a string and returns an


object.
Python tuple() function
8
Converts s to a tuple.
Python list() function
9
Converts s to a list.
Python set() function
10
Converts s to a set.
Python dict() function
11 Creates a dictionary. d must be a
sequence of (key,value) tuples.
Python frozenset() function
12
Converts s to a frozen set.
Python chr() function
13
Converts an integer to a character.
Python unichr() function
14 Converts an integer to a Unicode
character.
Python ord() function
15 Converts a single character to its
integer value.
Python hex() function
16 Converts an integer to a hexadecimal
string.
Python oct() function
17 Converts an integer to an octal
string.

74
13. Python - Type Casting Python Tutorial

From a programming point of view, a type casting refers to converting an object of one
type into another. Here, we shall learn about type casting in Python Programming.

Python Type Casting is a process in which we convert a literal of one data type
to another data type. Python supports two types of casting − implicit and
explicit.

In Python there are different data types, such as numbers, sequences, mappings etc.
There may be a situation where, you have the available data of one type but you want to
use it in another form. For example, the user has input a string but you want to use it as
a number. Python's type casting mechanism let you do that.

Python Implicit Casting


When a compiler/interpreter of any language automatically converts object of one type
into other, it is called automatic or implicit casting. Python is a strongly typed language.
It doesn't allow automatic type conversion between unrelated data types. For example, a
string cannot be converted to any number type. However, an integer can be cast into a
float. Other languages such as JavaScript is a weakly typed language, where an integer is
coerced into a string for concatenation.
Note that memory requirement of each data type is different. For example, an integer
object in Python occupies 4 bytes of memory, while a float object needs 8 bytes because
of its fractional part. Hence, Python interpreter doesn't automatically convert a float to
int, because it will result in loss of data. On the other hand, int can be easily converted
into float by setting its fractional part to 0.
Implicit int to float casting takes place when any arithmetic operation on int and float
operands is done.
Consider we have one int and one float variable

<<< a=10 # int object


<<< b=10.5 # float object

To perform their addition, 10 − the integer object is upgraded to 10.0. It is a float, but
equivalent to its earlier numeric value. Now we can perform addition of two floats.

<<< c=a+b
<<< print (c)
20.5

In implicit type casting, a Python object with lesser byte size is upgraded to match the
bigger byte size of other object in the operation. For example, a Boolean object is first
upgraded to int and then to float, before the addition with a floating point object. In the
following example, we try to add a Boolean object in a float, please note that True is equal
to 1, and False is equal to 0.

a=True;

75
Python Tutorial

b=10.5;
c=a+b;
print (c);

This will produce the following result:

11.5

Python Explicit Casting


Although automatic or implicit casting is limited to int to float conversion, you can use
Python's built-in functions int(), float() and str() to perform the explicit conversions such
as string to integer.

Python int() Function


Python's built-in int() function converts an integer literal to an integer object, a float to
integer, and a string to integer if the string itself has a valid integer literal representation.
Using int() with an int object as argument is equivalent to declaring an int object directly.

<<< a = int(10)
<<< a
10

is same as −

<<< a = 10
<<< a
10
<<< type(a)
<class 'int>

If the argument to int() function is a float object or floating point expression, it returns an
int object. For example −

<<< a = int(10.5) #converts a float object to int


<<< a
10
<<< a = int(2*3.14) #expression results float, is converted to int
<<< a
6
<<< type(a)
<class 'int'>

The int() function also returns integer 1 if a Boolean object is given as argument.

<<< a=int(True)

76
Python Tutorial

<<< a
1
<<< type(a)
<class 'int'>

String to Integer
The int() function returns an integer from a string object, only if it contains a valid integer
representation.

<<< a = int("100")
<<< a
100
<<< type(a)
<class 'int'>
<<< a = ("10"+"01")
<<< a = int("10"+"01")
<<< a
1001
<<< type(a)
<class 'int'>

However, if the string contains a non-integer representation, Python raises ValueError.

<<< a = int("10.5")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '10.5'
<<< a = int("Hello World")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'Hello World'

The int() function also returns integer from binary, octal and hexa-decimal string. For this,
the function needs a base parameter which must be 2, 8 or 16 respectively. The string
should have a valid binary/octal/Hexa-decimal representation.

Binary String to Integer


The string should be made up of 1 and 0 only, and the base should be 2.

<<< a = int("110011", 2)
<<< a

77
Python Tutorial

51

The Decimal equivalent of binary number 110011 is 51.

Octal String to Integer


The string should only contain 0 to 7 digits, and the base should be 8.

<<< a = int("20", 8)
<<< a
16

The Decimal equivalent of octal 20 is 16.

Hexa-Decimal String to Integer


The string should contain only the Hexadecimal symbols i.e., 0-9 and A, B, C, D, E or F.
Base should be 16.

<<< a = int("2A9", 16)


<<< a
681

Decimal equivalent of Hexadecimal 2A9 is 681. You can easily verify these conversions
with calculator app in Windows, Ubuntu or Smartphones.
Following is an example to convert number, float and string into integer data type:

a = int(1) # a will be 1
b = int(2.2) # b will be 2
c = int("3") # c will be 3

print (a)
print (b)
print (c)

This will produce the following result −

1
2
3

Python float() Function


The float() is a built-in function in Python. It returns a float object if the argument is a
float literal, integer or a string with valid floating point representation.
Using float() with an float object as argument is equivalent to declaring a float object
directly

<<< a = float(9.99)

78
Python Tutorial

<<< a
9.99
<<< type(a)
<class 'float'>

is same as −

<<< a = 9.99
<<< a
9.99
<<< type(a)
<class 'float'>

If the argument to float() function is an integer, the returned value is a floating point with
fractional part set to 0.

<<< a = float(100)
<<< a
100.0
<<< type(a)
<class 'float'>

The float() function returns float object from a string, if the string contains a valid floating
point number, otherwise ValueError is raised.

<<< a = float("9.99")
<<< a
9.99
<<< type(a)
<class 'float'>
<<< a = float("1,234.50")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '1,234.50'

The reason of ValueError here is the presence of comma in the string.


For the purpose of string to float conversion, the scientific notation of floating point is also
considered valid.

<<< a = float("1.00E4")
<<< a
10000.0
<<< type(a)

79
Python Tutorial

<class 'float'>
<<< a = float("1.00E-4")
<<< a
0.0001
<<< type(a)
<class 'float'>

Following is an example to convert number, float and string into float data type:

a = float(1) # a will be 1.0


b = float(2.2) # b will be 2.2
c = float("3.3") # c will be 3.3

print (a)
print (b)
print (c)

This will produce the following result −

1.0
2.2
3.3

Python str() Function


We saw how a Python obtains integer or float number from corresponding string
representation. The str() function works the opposite. It surrounds an integer or a float
object with quotes (') to return a str object. The str() function returns the string
representation of any Python object. In this section, we shall see different examples of
str() function in Python.
The str() function has three parameters. First required parameter (or argument) is the
object whose string representation we want. Other two operators, encoding and errors,
are optional.
We shall execute str() function in Python console to easily verify that the returned object
is a string, with the enclosing quotation marks (').

Integer to string
You can convert any integer number into a string as follows:

<<< a = str(10)
<<< a
'10'
<<< type(a)
<class 'str'>

80
Python Tutorial

Float to String
The str() function converts floating point objects with both the notations of floating point,
standard notation with a decimal point separating integer and fractional part, and the
scientific notation to string object.

<<< a=str(11.10)
<<< a
'11.1'
<<< type(a)
<class 'str'>
<<< a = str(2/5)
<<< a
'0.4'
<<< type(a)
<class 'str'>

In the second case, a division expression is given as argument to str() function. Note that
the expression is evaluated first and then result is converted to string.
Floating points in scientific notations using E or e and with positive or negative power are
converted to string with str() function.

<<< a=str(10E4)
<<< a
'100000.0'
<<< type(a)
<class 'str'>
<<< a=str(1.23e-4)
<<< a
'0.000123'
<<< type(a)
<class 'str'>

When Boolean constant is entered as argument, it is surrounded by (') so that True


becomes 'True'. List and Tuple objects can also be given argument to str() function. The
resultant string is the list/tuple surrounded by (').

<<< a=str('True')
<<< a
'True'
<<< a=str([1,2,3])
<<< a
'[1, 2, 3]'

81
Python Tutorial

<<< a=str((1,2,3))
<<< a
'(1, 2, 3)'
<<< a=str({1:100, 2:200, 3:300})
<<< a
'{1: 100, 2: 200, 3: 300}'

Following is an example to convert number, float and string into string data type:

a = str(1) # a will be "1"


b = str(2.2) # b will be "2.2"
c = str("3.3") # c will be "3.3"

print (a)
print (b)
print (c)

This will produce the following result −

1
2.2
3.3

Conversion of Sequence Types


List, Tuple and String are Python's sequence types. They are ordered or indexed collection
of items.
A string and tuple can be converted into a list object by using the list() function. Similarly,
the tuple() function converts a string or list to a tuple.
We shall take an object of each of these three sequence types and study their inter-
conversion.

<<< a=[1,2,3,4,5] # List Object


<<< b=(1,2,3,4,5) # Tuple Object
<<< c="Hello" # String Object

### list() separates each character in the string and builds the list
<<< obj=list(c)
<<< obj
['H', 'e', 'l', 'l', 'o']

### The parentheses of tuple are replaced by square brackets

82
Python Tutorial

<<< obj=list(b)
<<< obj
[1, 2, 3, 4, 5]

### tuple() separates each character from string and builds a tuple of
characters
<<< obj=tuple(c)
<<< obj
('H', 'e', 'l', 'l', 'o')

### square brackets of list are replaced by parentheses.


<<< obj=tuple(a)
<<< obj
(1, 2, 3, 4, 5)

### str() function puts the list and tuple inside the quote symbols.
<<< obj=str(a)
<<< obj
'[1, 2, 3, 4, 5]'

<<< obj=str(b)
<<< obj
'(1, 2, 3, 4, 5)'

Thus Python's explicit type casting feature allows conversion of one data type to other with
the help of its built-in functions.

Data Type Conversion Functions


There are several built-in functions to perform conversion from one data type to another.
These functions return a new object representing the converted value.

Sr.No. Function & Description


Python int() function
1
Converts x to an integer. base specifies the base if x is a string.

Python long() function

2 Converts x to a long integer. base specifies the base if x is a string. This


function has been deprecated.

3 Python float() function

83
Python Tutorial

Converts x to a floating-point number.

Python complex() function


4
Creates a complex number.
Python str() function
5
Converts object x to a string representation.

Python repr() function


6
Converts object x to an expression string.

Python eval() function


7
Evaluates a string and returns an object.

Python tuple() function


8
Converts s to a tuple.
Python list() function
9
Converts s to a list.
Python set() function
10
Converts s to a set.
Python dict() function
11
Creates a dictionary. d must be a sequence of (key,value) tuples.

Python frozenset() function


12
Converts s to a frozen set.
Python chr() function
13
Converts an integer to a character.
Python unichr() function
14
Converts an integer to a Unicode character.

Python ord() function


15
Converts a single character to its integer value.

Python hex() function


16
Converts an integer to a hexadecimal string.

Python oct() function


17
Converts an integer to an octal string.

84
14. Python - Unicode System Python Tutorial

What is Unicode System?


Software applications often require to display messages output in a variety in different
languages such as in English, French, Japanese, Hebrew, or Hindi. Python's string type
uses the Unicode Standard for representing characters. It makes the program possible to
work with all these different possible characters.
A character is the smallest possible component of a text. 'A', 'B', 'C', etc., are all different
characters. So are 'È' and 'Í'. A unicode string is a sequence of code points, which are
numbers from 0 through 0x10FFFF (1,114,111 decimal). This sequence of code points
needs to be represented in memory as a set of code units, and code units are then mapped
to 8-bit bytes.

Character Encoding
A sequence of code points is represented in memory as a set of code units, mapped to 8-
bit bytes. The rules for translating a Unicode string into a sequence of bytes are called a
character encoding.
Three types of encodings are present, UTF-8, UTF-16 and UTF-32. UTF stands for Unicode
Transformation Format.

Python's Unicode Support


Python 3.0 onwards has built-in support for Unicode. The str type contains Unicode
characters, hence any string created using single, double or the triple-quoted string syntax
is stored as Unicode. The default encoding for Python source code is UTF-8.
Hence, string may contain literal representation of a Unicode character (3/4) or its Unicode
value (\u00BE).

Example

var = "3/4"
print (var)
var = "\u00BE"
print (var)

This above code will produce the following output −

3/4
¾

Example
In the following example, a string '10' is stored using the Unicode values of 1 and 0 which
are \u0031 and u0030 respectively.

85
Python Tutorial

var = "\u0031\u0030"
print (var)

It will produce the following output −

10

Strings display the text in a human-readable format, and bytes store the characters as
binary data. Encoding converts data from a character string to a series of bytes. Decoding
translates the bytes back to human-readable characters and symbols. It is important not
to confuse these two methods. Encode is a string method, while decode is a method of the
Python byte object.

Example
In the following example, we have a string variable that consists of ASCII characters.
ASCII is a subset of Unicode character set. The encode() method is used to convert it into
a bytes object.

string = "Hello"
tobytes = string.encode('utf-8')
print (tobytes)
string = tobytes.decode('utf-8')
print (string)

The decode() method converts byte object back to the str object. The encoding method
used is utf-8.

b'Hello'
Hello

Example
In the following example, the Rupee symbol (₹) is stored in the variable using its Unicode
value. We convert the string to bytes and back to str.

string = "\u20B9"
print (string)
tobytes = string.encode('utf-8')
print (tobytes)
string = tobytes.decode('utf-8')
print (string)

When you execute the above code, it will produce the following output −


b'\xe2\x82\xb9'

86
Python Tutorial

87
15. Python - Literals Python Tutorial

What are Python Literals?


Python literals or constants are the notation for representing a fixed value in source code.
In contrast to variables, literals (123, 4.3, "Hello") are static values or you can say
constants which do not change throughout the operation of the program or application.
For example, in the following assignment statement:

x = 10

Here 10 is a literal as numeric value representing 10, which is directly stored in memory.
However,

y = x*2

Here, even if the expression evaluates to 20, it is not literally included in source code. You
can also declare an int object with built-in int() function. However, this is also an indirect
way of instantiation and not with literal.

x = int(10)

Different Types of Python Literals


Python provides following literals which will be explained in this tutorial:
 Integer Literal
 Float Literal
 Complex Literal
 String Literal
 List Literal
 Tuple Literal
 Dictionary Literal

Python Integer Literal


Any representation involving only the digit symbols (0 to 9) creates an object of int type.
The object so declared may be referred by a variable using an assignment operator.
Integer literals consist three different types of different literal values decimal, octal, and
hexadecimal literals.

1. Decimal Literal
Decimal literals represent the signed or unsigned numbers. Digitals from 0 to 9 are used
to create a decimal literal value.
Look at the below statement assigning decimal literal to the variable −

x = 10
y = -25

88
Python Tutorial

z = 0

2. Octal Literal
Python allows an integer to be represented as an octal number or a hexadecimal number.
A numeric representation with only eight digit symbols (0 to 7) but prefixed by 0o or 0O
is an octal number in Python.
Look at the below statement assigning octal literal to the variable −

x = 0O34

3. Hexadecimal Literal
Similarly, a series of hexadecimal symbols (0 to 9 and a to f), prefixed by 0x or 0X
represents an integer in Hexadecimal form in Python.
Look at the below statement assigning hexadecimal literal to the variable −

x = 0X1C

However, it may be noted that, even if you use octal or hexadecimal literal notation,
Python internally treats them as of int type.
Example

# Using Octal notation


x = 0O34
print ("0O34 in octal is", x, type(x))
# Using Hexadecimal notation
x = 0X1c
print ("0X1c in Hexadecimal is", x, type(x))

When you run this code, it will produce the following output −

0O34 in octal is 28 <class 'int'>


0X1c in Hexadecimal is 28 <class 'int'>

Python Float Literal


A floating point number consists of an integral part and a fractional part. Conventionally,
a decimal point symbol (.) separates these two parts in a literal representation of a float.
For example,
Example of Float Literal

x = 25.55
y = 0.05
z = -12.2345

For a floating point number which is too large or too small, where number of digits before
or after decimal point is more, a scientific notation is used for a compact literal

89
Python Tutorial

representation. The symbol E or e followed by positive or negative integer, follows after


the integer part.
Example of Float Scientific Notation Literal
For example, a number 1.23E05 is equivalent to 123000.00. Similarly, 1.23e-2 is
equivalent to 0.0123

# Using normal floating point notation


x = 1.23
print ("1.23 in normal float literal is", x, type(x))
# Using Scientific notation
x = 1.23E5
print ("1.23E5 in scientific notation is", x, type(x))
x = 1.23E-2
print ("1.23E-2 in scientific notation is", x, type(x))

Here, you will get the following output −

1.23 in normal float literal is 1.23 <class 'float'>


1.23E5 in scientific notation is 123000.0 <class 'float''>
1.23E-2 in scientific notation is 0.0123 <class 'float''>

Python Complex Literal


A complex number comprises of a real and imaginary component. The imaginary
component is any number (integer or floating point) multiplied by square root of "-1"

(√ −1). In literal representation (√-1) is representation by "j" or "J". Hence, a literal


representation of a complex number takes a form x+yj.
Example of Complex Type Literal

#Using literal notation of complex number


x = 2+3j
print ("2+3j complex literal is", x, type(x))
y = 2.5+4.6j
print ("2.5+4.6j complex literal is", x, type(x))

This code will produce the following output −

2+3j complex literal is (2+3j) <class 'complex'>


2.5+4.6j complex literal is (2+3j) <class 'complex'>

Python String Literal


A string object is one of the sequence data types in Python. It is an immutable sequence
of Unicode code points. Code point is a number corresponding to a character according to
Unicode standard. Strings are objects of Python's built-in class 'str'.
90
Python Tutorial

String literals are written by enclosing a sequence of characters in single quotes ('hello'),
double quotes ("hello") or triple quotes ('''hello''' or """hello""").
Example of String Literal

var1='hello'
print ("'hello' in single quotes is:", var1, type(var1))
var2="hello"
print ('"hello" in double quotes is:', var1, type(var1))
var3='''hello'''
print ("''''hello'''' in triple quotes is:", var1, type(var1))
var4="""hello"""
print ('"""hello""" in triple quotes is:', var1, type(var1))

Here, you will get the following output −

'hello' in single quotes is: hello <class 'str'>


"hello" in double quotes is: hello <class 'str'>
''''hello'''' in triple quotes is: hello <class 'str'>
"""hello""" in triple quotes is: hello <class 'str'>

Example of String Literal with Double Quotes Inside String


If it is required to embed double quotes as a part of string, the string itself should be put
in single quotes. On the other hand, if single quoted text is to be embedded, string should
be written in double quotes.

var1='Welcome to "Python Tutorial" from TutorialsPoint'


print (var1)
var2="Welcome to 'Python Tutorial' from TutorialsPoint"
print (var2)

It will produce the following output −

Welcome to "Python Tutorial" from TutorialsPoint


Welcome to 'Python Tutorial' from TutorialsPoint

Python List Literal


List object in Python is a collection of objects of other data type. List is an ordered collection
of items not necessarily of same type. Individual object in the collection is accessed by
index starting with zero.
Literal representation of a list object is done with one or more items which are separated
by comma and enclosed in square brackets [].
Example of List Type Literal

L1=[1,"Ravi",75.50, True]

91
Python Tutorial

print (L1, type(L1))

It will produce the following output −

[1, 'Ravi', 75.5, True] <class 'list'>

Python Tuple Literal


Tuple object in Python is a collection of objects of other data type. Tuple is an ordered
collection of items not necessarily of same type. Individual object in the collection is
accessed by index starting with zero.
Literal representation of a tuple object is done with one or more items which are separated
by comma and enclosed in parentheses ().
Example of Tuple Type Literal

T1=(1,"Ravi",75.50, True)
print (T1, type(T1))

It will produce the following output −

[1, 'Ravi', 75.5, True] <class tuple>

Example of Tuple Type Literal Without Parenthesis


Default delimiter for Python sequence is parentheses, which means a comma separated
sequence without parentheses also amounts to declaration of a tuple.

T1=1,"Ravi",75.50, True
print (T1, type(T1))

Here too, you will get the same output −

[1, 'Ravi', 75.5, True] <class tuple>

Python Dictionary Literal


Like list or tuple, dictionary is also a collection data type. However, it is not a sequence.
It is an unordered collection of items, each of which is a key-value pair. Value is bound to
key by the ":" symbol. One or more key:value pairs separated by comma are put inside
curly brackets to form a dictionary object.
Example of Dictionary Type Literal

capitals={"USA":"New York", "France":"Paris", "Japan":"Tokyo",


"India":"New Delhi"}
numbers={1:"one", 2:"Two", 3:"three",4:"four"}
points={"p1":(10,10), "p2":(20,20)}

print (capitals, type(capitals))


print (numbers, type(numbers))

92
Python Tutorial

print (points, type(points))

Key should be an immutable object. Number, string or tuple can be used as key. Key
cannot appear more than once in one collection. If a key appears more than once, only
the last one will be retained. Values can be of any data type. One value can be assigned
to more than one keys. For example,

staff={"Krishna":"Officer", "Rajesh":"Manager", "Ragini":"officer",


"Anil":"Clerk", "Kavita":"Manager"}

93
16. Python - Operators Python Tutorial

Python Operators
Python operators are special symbols used to perform specific operations on one or more
operands. The variables, values, or expressions can be used as operands. For example,
Python's addition operator (+) is used to perform addition operations on two variables,
values, or expressions.
The following are some of the terms related to Python operators:
 Unary operators: Python operators that require one operand to perform a specific
operation are known as unary operators.
 Binary operators: Python operators that require two operands to perform a
specific operation are known as binary operators.
 Operands: Variables, values, or expressions that are used with the operator to
perform a specific operation are known as operands.

Types of Python Operators


Python operators are divided in the following categories −
 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators
Let us have a look at all the operators one by one.

Python Arithmetic Operators


Python Arithmetic operators are used to perform basic mathematical operations such as
addition, subtraction, multiplication, etc.
The following table contains all arithmetic operators with their symbols, names, and
examples (assume that the values of a and b are 10 and 20, respectively) −

Operator Name Example


+ Addition a + b = 30

- Subtraction a – b = -10

* Multiplication a * b = 200

/ Division b/a=2

% Modulus b%a=0

** Exponent a**b =10**20

// Floor Division 9//2 = 4

94
Python Tutorial

Example of Python Arithmetic Operators

a = 21
b = 10
c = 0

c = a + b
print ("a: {} b: {} a+b: {}".format(a,b,c))

c = a - b
print ("a: {} b: {} a-b: {}".format(a,b,c) )

c = a * b
print ("a: {} b: {} a*b: {}".format(a,b,c))

c = a / b
print ("a: {} b: {} a/b: {}".format(a,b,c))

c = a % b
print ("a: {} b: {} a%b: {}".format(a,b,c))

a = 2
b = 3
c = a**b
print ("a: {} b: {} a**b: {}".format(a,b,c))

a = 10
b = 5
c = a//b
print ("a: {} b: {} a//b: {}".format(a,b,c))

Output

a: 21 b: 10 a+b: 31
a: 21 b: 10 a-b: 11
a: 21 b: 10 a*b: 210
a: 21 b: 10 a/b: 2.1

95
Python Tutorial

a: 21 b: 10 a%b: 1
a: 2 b: 3 a**b: 8
a: 10 b: 5 a//b: 2

Python Comparison Operators


Python comparison operators compare the values on either side of them and decide the
relation among them. They are also called Relational operators.
The following table contains all comparison operators with their symbols, names, and
examples (assume that the values of a and b are 10 and 20, respectively) −

Operator Name Example

== Equal (a == b) is not true.

!= Not equal (a != b) is true.


> Greater than (a > b) is not true.
< Less than (a < b) is true.

>= Greater than or equal to (a >= b) is not true.

<= Less than or equal to (a <= b) is true.

Example of Python Comparison Operators

a = 21
b = 10
if ( a == b ):
print ("Line 1 - a is equal to b")
else:
print ("Line 1 - a is not equal to b")

if ( a != b ):
print ("Line 2 - a is not equal to b")
else:
print ("Line 2 - a is equal to b")

if ( a < b ):
print ("Line 3 - a is less than b" )
else:
print ("Line 3 - a is not less than b")

if ( a > b ):

96
Python Tutorial

print ("Line 4 - a is greater than b")


else:
print ("Line 4 - a is not greater than b")

a,b=b,a #values of a and b swapped. a becomes 10, b becomes 21

if ( a <= b ):
print ("Line 5 - a is either less than or equal to b")
else:
print ("Line 5 - a is neither less than nor equal to b")

if ( b >= a ):
print ("Line 6 - b is either greater than or equal to b")
else:
print ("Line 6 - b is neither greater than nor equal to b")

Output

Line 1 - a is not equal to b


Line 2 - a is not equal to b
Line 3 - a is not less than b
Line 4 - a is greater than b
Line 5 - a is either less than or equal to b
Line 6 - b is either greater than or equal to b

Python Assignment Operators


Python Assignment operators are used to assign values to variables. Following is a table
which shows all Python assignment operators.
The following table contains all assignment operators with their symbols, names, and
examples −

Operator Example Same As


= a = 10 a = 10
+= a += 30 a = a + 30
-= a -= 15 a = a - 15
*= a *= 10 a = a * 10
/= a /= 5 a=a/5
%= a %= 5 a=a%5
**= a **= 4 a = a ** 4
//= a //= 5 a = a // 5
&= a &= 5 a=a&5

97
Python Tutorial

|= a |= 5 a=a|5
^= a ^= 5 a=a^5
>>= a >>= 5 a = a >> 5
<<= a <<= 5 a = a << 5

Example of Python Assignment Operators

a = 21
b = 10
c = 0
print ("a: {} b: {} c : {}".format(a,b,c))
c = a + b
print ("a: {} c = a + b: {}".format(a,c))

c += a
print ("a: {} c += a: {}".format(a,c))

c *= a
print ("a: {} c *= a: {}".format(a,c))

c /= a
print ("a: {} c /= a : {}".format(a,c))

c = 2
print ("a: {} b: {} c : {}".format(a,b,c))
c %= a
print ("a: {} c %= a: {}".format(a,c))

c **= a
print ("a: {} c **= a: {}".format(a,c))

c //= a
print ("a: {} c //= a: {}".format(a,c))

Output

a: 21 b: 10 c: 0
a: 21 c = a + b: 31
a: 21 c += a: 52
a: 21 c *= a: 1092

98
Python Tutorial

a: 21 c /= a : 52.0
a: 21 b: 10 c : 2
a: 21 c %= a: 2
a: 21 c **= a: 2097152
a: 21 c //= a: 99864

Python Bitwise Operators


Python bitwise operator works on bits and performs bit by bit operation. These operators
are used to compare binary numbers.
The following table contains all bitwise operators with their symbols, names, and examples

Operator Name Example


& AND a&b
| OR a|b
^ XOR a^b
~ NOT ~a
<< Zero fill left shift a << 3
>> Signed right shift a >> 3

Example of Python Bitwise Operators

a = 20
b = 10

print ('a=',a,':',bin(a),'b=',b,':',bin(b))
c = 0

c = a & b;
print ("result of AND is ", c,':',bin(c))

c = a | b;
print ("result of OR is ", c,':',bin(c))

c = a ^ b;
print ("result of EXOR is ", c,':',bin(c))

c = ~a;
print ("result of COMPLEMENT is ", c,':',bin(c))

99
Python Tutorial

c = a << 2;
print ("result of LEFT SHIFT is ", c,':',bin(c))

c = a >> 2;
print ("result of RIGHT SHIFT is ", c,':',bin(c))

Output

a= 20 : 0b10100 b= 10 : 0b1010
result of AND is 0 : 0b0
result of OR is 30 : 0b11110
result of EXOR is 30 : 0b11110
result of COMPLEMENT is -21 : -0b10101
result of LEFT SHIFT is 80 : 0b1010000
result of RIGHT SHIFT is 5 : 0b101

Python Logical Operators


Python logical operators are used to combine two or more conditions and check the final
result.
The following table contains all logical operators with their symbols, names, and examples

Operator Name Example

and AND a and b

or OR a or b

not NOT not(a)

Example of Python Logical Operators

var = 5

print(var > 3 and var < 10)


print(var > 3 or var < 4)
print(not (var > 3 and var < 10))

Output

True
True
False

Python Membership Operators

100
Python Tutorial

Python's membership operators test for membership in a sequence, such as strings, lists,
or tuples.
There are two membership operators as explained below −

Operator Description Example

Returns True if it finds a


in variable in the specified a in b
sequence, false otherwise.

returns True if it does not finds


not in a variable in the specified a not in b
sequence and false otherwise.

Example of Python Membership Operators

a = 10
b = 20
list = [1, 2, 3, 4, 5 ]

print ("a:", a, "b:", b, "list:", list)

if ( a in list ):
print ("a is present in the given list")
else:
print ("a is not present in the given list")

if ( b not in list ):
print ("b is not present in the given list")
else:
print ("b is present in the given list")

c=b/a
print ("c:", c, "list:", list)
if ( c in list ):
print ("c is available in the given list")
else:
print ("c is not available in the given list")

Output

101
Python Tutorial

a: 10 b: 20 list: [1, 2, 3, 4, 5]
a is not present in the given list
b is not present in the given list
c: 2.0 list: [1, 2, 3, 4, 5]
c is available in the given list

Python Identity Operators


Python identity operators compare the memory locations of two objects.
There are two Identity operators explained below −

Operator Description Example

Returns True if both


is variables are the same a is b
object and false otherwise.

Returns True if both


is not variables are not the same a is not b
object and false otherwise.

Example of Python Identity Operators

a = [1, 2, 3, 4, 5]
b = [1, 2, 3, 4, 5]
c = a

print(a is c)
print(a is b)

print(a is not c)
print(a is not b)

Output

True
False
False
True

102
Python Tutorial

Python Operators Precedence


Operators precedence decides the order of the evaluation in which an operator is
evaluated. Python operators have different levels of precedence. The following table
contains the list of operators having highest to lowest precedence −
The following table lists all operators from highest precedence to lowest.

Sr.No. Operator & Description


**
1
Exponentiation (raise to the power)
~+-

2 Complement, unary plus and minus


(method names for the last two are +@
and -@)
* / % //
3 Multiply, divide, modulo and floor
division
+-
4
Addition and subtraction
>> <<
5
Right and left bitwise shift
&
6
Bitwise 'AND'
^|
7
Bitwise exclusive `OR' and regular `OR'

<= < > >=


8
Comparison operators
<> == !=
9
Equality operators
= %= /= //= -= += *= **=
10
Assignment operators
is is not
11
Identity operators
in not in
12
Membership operators
not or and
13
Logical operators
Read more about the Python operators precedence here: Python operators precedence

103
17. Python - Arithmetic OperatorsPython Tutorial

Python Arithmetic Operators


Python arithmetic operators are used to perform mathematical operations such as
addition, subtraction, multiplication, division, and more on numbers. Arithmetic operators
are binary operators in the sense they operate on two operands. Python fully supports
mixed arithmetic. That is, the two operands can be of two different number types. In such
a situation.

Types of Arithmetic Operators


Following is the table which lists down all the arithmetic operators available in Python:

Operator Name Example


+ Addition a + b = 30
- Subtraction a – b = -10
* Multiplication a * b = 200
/ Division b/a=2
% Modulus b%a=0

** Exponent a**b =10**20

// Floor Division 9//2 = 4

Let us study these operators with examples.

Addition Operator
The addition operator is represented by the + symbol. It is a basic arithmetic operator. It
adds the two numeric operands on the either side and returns the addition result.
Example to add two integer numbers
In the following example, the two integer variables are the operands for the "+" operator.

a=10
b=20
print ("Addition of two integers")
print ("a =",a,"b =",b,"addition =",a+b)

It will produce the following output −

Addition of two integers


a = 10 b = 20 addition = 30

Example to add integer and float numbers


Addition of integer and float results in a float.

104
Python Tutorial

a=10
b=20.5
print ("Addition of integer and float")
print ("a =",a,"b =",b,"addition =",a+b)

It will produce the following output −

Addition of integer and float


a = 10 b = 20.5 addition = 30.5

Example to add two complex numbers


The result of adding float to complex is a complex number.

a=10+5j
b=20.5
print ("Addition of complex and float")
print ("a=",a,"b=",b,"addition=",a+b)

It will produce the following output −

Addition of complex and float


a= (10+5j) b= 20.5 addition= (30.5+5j)

Subtraction Operator
The subtraction operator is represented by the - symbol. It subtracts the second operand
from the first. The resultant number is negative if the second operand is larger.
Example to subtract two integer numbers
First example shows subtraction of two integers.

a=10
b=20
print ("Subtraction of two integers:")
print ("a =",a,"b =",b,"a-b =",a-b)
print ("a =",a,"b =",b,"b-a =",b-a)

Result −

Subtraction of two integers


a = 10 b = 20 a-b = -10
a = 10 b = 20 b-a = 10

Example to subtract integer and float numbers


Subtraction of an integer and a float follows the same principle.

a=10

105
Python Tutorial

b=20.5
print ("subtraction of integer and float")
print ("a=",a,"b=",b,"a-b=",a-b)
print ("a=",a,"b=",b,"b-a=",b-a)

It will produce the following output −

subtraction of integer and float


a= 10 b= 20.5 a-b= -10.5
a= 10 b= 20.5 b-a= 10.5

Example to subtract complex numbers


In the subtraction involving a complex and a float, real component is involved in the
operation.

a=10+5j
b=20.5
print ("subtraction of complex and float")
print ("a=",a,"b=",b,"a-b=",a-b)
print ("a=",a,"b=",b,"b-a=",b-a)

It will produce the following output −

subtraction of complex and float


a= (10+5j) b= 20.5 a-b= (-10.5+5j)
a= (10+5j) b= 20.5 b-a= (10.5-5j)

Multiplication Operator
The * (asterisk) symbol is defined as multiplication operator in Python (as in many
languages). It returns the product of the two operands on its either side. If any of the
operands negative, the result is also negative. If both are negative, the result is positive.
Changing the order of operands doesn't change the result
Example to multiply two integers

a=10
b=20
print ("Multiplication of two integers")
print ("a =",a,"b =",b,"a*b =",a*b)

It will produce the following output −

Multiplication of two integers


a = 10 b = 20 a*b = 200

Example to multiply integer and float numbers

106
Python Tutorial

In multiplication, a float operand may have a standard decimal point notation, or a


scientific notation.

a=10
b=20.5
print ("Multiplication of integer and float")
print ("a=",a,"b=",b,"a*b=",a*b)

a=-5.55
b=6.75E-3
print ("Multiplication of float and float")
print ("a =",a,"b =",b,"a*b =",a*b)

It will produce the following output −

Multiplication of integer and float


a = 10 b = 20.5 a-b = -10.5
Multiplication of float and float
a = -5.55 b = 0.00675 a*b = -0.037462499999999996

Example to multiply complex numbers


For the multiplication operation involving one complex operand, the other operand
multiplies both the real part and imaginary part.

a=10+5j
b=20.5
print ("Multiplication of complex and float")
print ("a =",a,"b =",b,"a*b =",a*b)

It will produce the following output −

Multiplication of complex and float


a = (10+5j) b = 20.5 a*b = (205+102.5j)

Division Operator
The "/" symbol is usually called as forward slash. The result of division operator is
numerator (left operand) divided by denominator (right operand). The resultant number
is negative if any of the operands is negative. Since infinity cannot be stored in the
memory, Python raises ZeroDivisionError if the denominator is 0.
The result of division operator in Python is always a float, even if both operands are
integers.
Example to divide two numbers

a=10
b=20

107
Python Tutorial

print ("Division of two integers")


print ("a=",a,"b=",b,"a/b=",a/b)
print ("a=",a,"b=",b,"b/a=",b/a)

It will produce the following output −

Division of two integers


a= 10 b= 20 a/b= 0.5
a= 10 b= 20 b/a= 2.0

Example to divide two float numbers


In Division, a float operand may have a standard decimal point notation, or a scientific
notation.

a=10
b=-20.5
print ("Division of integer and float")
print ("a=",a,"b=",b,"a/b=",a/b)
a=-2.50
b=1.25E2
print ("Division of float and float")
print ("a=",a,"b=",b,"a/b=",a/b)

It will produce the following output −

Division of integer and float


a= 10 b= -20.5 a/b= -0.4878048780487805
Division of float and float
a= -2.5 b= 125.0 a/b= -0.02

Example to divide complex numbers


When one of the operands is a complex number, division between the other operand and
both parts of complex number (real and imaginary) object takes place.

a=7.5+7.5j
b=2.5
print ("Division of complex and float")
print ("a =",a,"b =",b,"a/b =",a/b)
print ("a =",a,"b =",b,"b/a =",b/a)

It will produce the following output −

Division of complex and float


a = (7.5+7.5j) b = 2.5 a/b = (3+3j)

108
Python Tutorial

a = (7.5+7.5j) b = 2.5 b/a = (0.16666666666666666-0.16666666666666666j)

If the numerator is 0, the result of division is always 0 except when denominator is 0, in


which case, Python raises ZeroDivisionError wirh Division by Zero error message.

a=0
b=2.5
print ("a=",a,"b=",b,"a/b=",a/b)
print ("a=",a,"b=",b,"b/a=",b/a)

It will produce the following output −

a= 0 b= 2.5 a/b= 0.0


Traceback (most recent call last):
File "C:\Users\mlath\examples\example.py", line 20, in <module>
print ("a=",a,"b=",b,"b/a=",b/a)
~^~
ZeroDivisionError: float division by zero

Modulus Operator
Python defines the "%" symbol, which is known aa Percent symbol, as Modulus (or modulo)
operator. It returns the remainder after the denominator divides the numerator. It can
also be called Remainder operator. The result of the modulus operator is the number that
remains after the integer quotient. To give an example, when 10 is divided by 3, the
quotient is 3 and remainder is 1. Hence, 10%3 (normally pronounced as 10 mod 3) results
in 1.
Example for modulus operation on integers
If both the operands are integers, the modulus value is an integer. If numerator is
completely divisible, remainder is 0. If numerator is smaller than denominator, modulus
is equal to the numerator. If denominator is 0, Python raises ZeroDivisionError.

a=10
b=2
print ("a=",a, "b=",b, "a%b=", a%b)
a=10
b=4
print ("a=",a, "b=",b, "a%b=", a%b)
print ("a=",a, "b=",b, "b%a=", b%a)
a=0
b=10
print ("a=",a, "b=",b, "a%b=", a%b)
print ("a=", a, "b=", b, "b%a=",b%a)

109
Python Tutorial

It will produce the following output −

a= 10 b= 2 a%b= 0
a= 10 b= 4 a%b= 2
a= 10 b= 4 b%a= 4
a= 0 b= 10 a%b= 0
Traceback (most recent call last):
File "C:\Users\mlath\examples\example.py", line 13, in <module>
print ("a=", a, "b=", b, "b%a=",b%a)
~^~
ZeroDivisionError: integer modulo by zero

Example for modulus operation on floats


If any of the operands is a float, the mod value is always float.

a=10
b=2.5
print ("a=",a, "b=",b, "a%b=", a%b)
a=10
b=1.5
print ("a=",a, "b=",b, "a%b=", a%b)
a=7.7
b=2.5
print ("a=",a, "b=",b, "a%b=", a%b)
a=12.4
b=3
print ("a=",a, "b=",b, "a%b=", a%b)

It will produce the following output −

a= 10 b= 2.5 a%b= 0.0


a= 10 b= 1.5 a%b= 1.0
a= 7.7 b= 2.5 a%b= 0.20000000000000018
a= 12.4 b= 3 a%b= 0.40000000000000036

Python doesn't accept complex numbers to be used as operand in modulus operation. It


throws TypeError: unsupported operand type(s) for %.

Exponent Operator
Python uses ** (double asterisk) as the exponent operator (sometimes called raised to
operator). So, for a**b, you say a raised to b, or even bth power of a.

110
Python Tutorial

If in the exponentiation expression, both operands are integer, result is also an integer.
In case either one is a float, the result is float. Similarly, if either one operand is complex
number, exponent operator returns a complex number.
If the base is 0, the result is 0, and if the index is 0 then the result is always 1.
Example of exponent operator

a=10
b=2
print ("a=",a, "b=",b, "a**b=", a**b)
a=10
b=1.5
print ("a=",a, "b=",b, "a**b=", a**b)
a=7.7
b=2
print ("a=",a, "b=",b, "a**b=", a**b)
a=1+2j
b=4
print ("a=",a, "b=",b, "a**b=", a**b)
a=12.4
b=0
print ("a=",a, "b=",b, "a**b=", a**b)
print ("a=",a, "b=",b, "b**a=", b**a)

It will produce the following output −

a= 10 b= 2 a**b= 100
a= 10 b= 1.5 a**b= 31.622776601683793
a= 7.7 b= 2 a**b= 59.290000000000006
a= (1+2j) b= 4 a**b= (-7-24j)
a= 12.4 b= 0 a**b= 1.0
a= 12.4 b= 0 b**a= 0.0

Floor Division Operator


Floor division is also called as integer division. Python uses // (double forward slash)
symbol for the purpose. Unlike the modulus or modulo which returns the remainder, the
floor division gives the quotient of the division of operands involved.
If both operands are positive, floor operator returns a number with fractional part removed
from it. For example, the floor division of 9.8 by 2 returns 4 (pure division is 4.9, strip the
fractional part, result is 4).

111
Python Tutorial

But if one of the operands is negative, the result is rounded away from zero (towards
negative infinity). Floor division of -9.8 by 2 returns 5 (pure division is -4.9, rounded away
from 0).
Example of floor division operator

a=9
b=2
print ("a=",a, "b=",b, "a//b=", a//b)
a=9
b=-2
print ("a=",a, "b=",b, "a//b=", a//b)
a=10
b=1.5
print ("a=",a, "b=",b, "a//b=", a//b)
a=-10
b=1.5
print ("a=",a, "b=",b, "a//b=", a//b)

It will produce the following output −

a= 9 b= 2 a//b= 4
a= 9 b= -2 a//b= -5
a= 10 b= 1.5 a//b= 6.0
a= -10 b= 1.5 a//b= -7.0

Precedence and Associativity of Arithmetic Operators


Operator(s) Description Associativity
Associativity of Exponent operator
** Exponent Operator
is from Right to Left.
Modulus, Associativity of Modulus,
Multiplication, Multiplication, Division, and Floor
%, *, /, //
Division, and Floor Division operators are from Left to
Division Right.
Addition and Associativity of Addition and
+, – Subtraction Subtraction operators are
Operators from Left to Right.

Arithmetic Operators with Complex Numbers


Arithmetic operators behave slightly differently when the both operands are complex
number objects.

Addition and subtraction of complex numbers


112
Python Tutorial

Addition and subtraction of complex numbers is a simple addition/subtraction of respective


real and imaginary components.

a=2.5+3.4j
b=-3+1.0j
print ("Addition of complex numbers - a=",a, "b=",b, "a+b=", a+b)
print ("Subtraction of complex numbers - a=",a, "b=",b, "a-b=", a-b)

It will produce the following output −

Addition of complex numbers - a= (2.5+3.4j) b= (-3+1j) a+b= (-0.5+4.4j)


Subtraction of complex numbers - a= (2.5+3.4j) b= (-3+1j) a-b= (5.5+2.4j)

Multiplication of complex numbers


Multiplication of complex numbers is similar to multiplication of two binomials in algebra.
If "a+bj" and "x+yj" are two complex numbers, then their multiplication is given by this
formula −

(a+bj)*(x+yj) = ax+ayj+xbj+byj2 = (ax-by)+(ay+xb)j

For example,

a=6+4j
b=3+2j
c=a*b
c=(18-8)+(12+12)j
c=10+24j

The following program confirms the result −

a=6+4j
b=3+2j
print ("Multplication of complex numbers - a=",a, "b=",b, "a*b=", a*b)

To understand the how the division of two complex numbers takes place, we should use
the conjugate of a complex number. Python's complex object has a conjugate() method
that returns a complex number with the sign of imaginary part reversed.

>>> a=5+6j
>>> a.conjugate()
(5-6j)

Division of complex numbers


To divide two complex numbers, divide and multiply the numerator as well as the
denominator with the conjugate of denominator.

113
Python Tutorial

a=6+4j
b=3+2j
c=a/b
c=(6+4j)/(3+2j)
c=(6+4j)*(3-2j)/3+2j)*(3-2j)
c=(18-12j+12j+8)/(9-6j+6j+4)
c=26/13
c=2+0j

To verify, run the following code −

a=6+4j
b=3+2j
print ("Division of complex numbers - a=",a, "b=",b, "a/b=", a/b)

Complex class in Python doesn't support the modulus operator (%) and floor division
operator (//).

114
18. Python - Comparison Operators
Python Tutorial

Python Comparison Operators


Comparison operators in Python are very important in Python's conditional statements (if,
else and elif) and looping statements (while and for loops). The comparison operators also
called relational operators. Some of the well known operators are "<" stands for less than,
and ">" stands for greater than operator.
Python uses two more operators, combining "=" symbol with these two. The "<=" symbol
is for less than or equal to operator and the ">=" symbol is for greater than or equal to
operator.

Different Comparison Operators in Python


Python has two more comparison operators in the form of "==" and "!=". They are for is
equal to and is not equal to operators. Hence, there are six comparison operators in Python
and they are listed below in this table:

Operator Name Example


< Less than a<b
> Greater than a>b
<= Less than or equal to a<=b
>= Greater than or equal to a>=b
== Is equal to a==b
!= Is not equal to a!=b
Comparison operators are binary in nature, requiring two operands. An expression
involving a comparison operator is called a Boolean expression, and always returns either
True or False.
Example

a=5
b=7
print (a>b)
print (a<b)

It will produce the following output −

False
True

Both the operands may be Python literals, variables or expressions. Since Python supports
mixed arithmetic, you can have any number type operands.
Example
The following code demonstrates the use of Python's comparison operators with integer
numbers −

115
Python Tutorial

print ("Both operands are integer")


a=5
b=7
print ("a=",a, "b=",b, "a>b is", a>b)
print ("a=",a, "b=",b,"a<b is",a<b)
print ("a=",a, "b=",b,"a==b is",a==b)
print ("a=",a, "b=",b,"a!=b is",a!=b)

It will produce the following output −

Both operands are integer


a= 5 b= 7 a>b is False
a= 5 b= 7 a<b is True
a= 5 b= 7 a==b is False
a= 5 b= 7 a!=b is True

Comparison of Float Number


In the following example, an integer operand and a float operand are compared.
Example

print ("comparison of int and float")


a=10
b=10.0
print ("a=",a, "b=",b, "a>b is", a>b)
print ("a=",a, "b=",b,"a<b is",a<b)
print ("a=",a, "b=",b,"a==b is",a==b)
print ("a=",a, "b=",b,"a!=b is",a!=b)

It will produce the following output −

comparison of int and float


a= 10 b= 10.0 a>b is False
a= 10 b= 10.0 a<b is False
a= 10 b= 10.0 a==b is True
a= 10 b= 10.0 a!=b is False

Comparison of Complex Numbers


Although complex object is a number data type in Python, its behavior is different from
others. Python doesn't support < and > operators, however it does support equality (==)
and inequality (!=) operators.
Example

116
Python Tutorial

print ("comparison of complex numbers")


a=10+1j
b=10.-1j
print ("a=",a, "b=",b,"a==b is",a==b)
print ("a=",a, "b=",b,"a!=b is",a!=b)

It will produce the following output −

comparison of complex numbers


a= (10+1j) b= (10-1j) a==b is False
a= (10+1j) b= (10-1j) a!=b is True
You get a TypeError with less than or greater than operators.

Example

print ("comparison of complex numbers")


a=10+1j
b=10.-1j
print ("a=",a, "b=",b,"a<b is",a<b)
print ("a=",a, "b=",b,"a>b is",a>b)

It will produce the following output −

comparison of complex numbers


Traceback (most recent call last):
File "C:\Users\mlath\examples\example.py", line 5, in <module>
print ("a=",a, "b=",b,"a<b is",a<b)
^^^
TypeError: '<' not supported between instances of 'complex' and
'complex

Comparison of Booleans
Boolean objects in Python are really integers: True is 1 and False is 0. In fact, Python
treats any non-zero number as True. In Python, comparison of Boolean objects is possible.
"False < True" is True!
Example

print ("comparison of Booleans")


a=True
b=False
print ("a=",a, "b=",b,"a<b is",a<b)
print ("a=",a, "b=",b,"a>b is",a>b)

117
Python Tutorial

print ("a=",a, "b=",b,"a==b is",a==b)


print ("a=",a, "b=",b,"a!=b is",a!=b)

It will produce the following output −

comparison of Booleans
a= True b= False a<b is False
a= True b= False a>b is True
a= True b= False a==b is False
a= True b= False a!=b is True

Comparison of Sequence Types


In Python, comparison of only similar sequence objects can be performed. A string object
is comparable with another string only. A list cannot be compared with a tuple, even if
both have same items.
Example

print ("comparison of different sequence types")


a=(1,2,3)
b=[1,2,3]
print ("a=",a, "b=",b,"a<b is",a<b)

It will produce the following output −

comparison of different sequence types


Traceback (most recent call last):
File "C:\Users\mlath\examples\example.py", line 5, in <module>
print ("a=",a, "b=",b,"a<b is",a<b)
^^^
TypeError: '<' not supported between instances of 'tuple' and 'list'

Sequence objects are compared by lexicographical ordering mechanism. The comparison


starts from item at 0th index. If they are equal, comparison moves to next index till the
items at certain index happen to be not equal, or one of the sequences is exhausted. If
one sequence is an initial sub-sequence of the other, the shorter sequence is the smaller
(lesser) one.
Which of the operands is greater depends on the difference in values of items at the index
where they are unequal. For example, 'BAT'>'BAR' is True, as T comes after R in Unicode
order.
If all items of two sequences compare equal, the sequences are considered equal.
Example

print ("comparison of strings")


a='BAT'

118
Python Tutorial

b='BALL'
print ("a=",a, "b=",b,"a<b is",a<b)
print ("a=",a, "b=",b,"a>b is",a>b)
print ("a=",a, "b=",b,"a==b is",a==b)
print ("a=",a, "b=",b,"a!=b is",a!=b)

It will produce the following output −

comparison of strings
a= BAT b= BALL a<b is False
a= BAT b= BALL a>b is True
a= BAT b= BALL a==b is False
a= BAT b= BALL a!=b is True

In the following example, two tuple objects are compared −


Example

print ("comparison of tuples")


a=(1,2,4)
b=(1,2,3)
print ("a=",a, "b=",b,"a<b is",a<b)
print ("a=",a, "b=",b,"a>b is",a>b)
print ("a=",a, "b=",b,"a==b is",a==b)
print ("a=",a, "b=",b,"a!=b is",a!=b)

It will produce the following output −

a= (1, 2, 4) b= (1, 2, 3) a<b is False


a= (1, 2, 4) b= (1, 2, 3) a>b is True
a= (1, 2, 4) b= (1, 2, 3) a==b is False
a= (1, 2, 4) b= (1, 2, 3) a!=b is True

Comparison of Dictionary Objects


The use of "<" and ">" operators for Python's dictionary is not defined. In case of these
operands, TypeError: '<' not supported between instances of 'dict' and 'dict' is reported.
Equality comparison checks if the length of both the dict items is same. Length of
dictionary is the number of key-value pairs in it.
Python dictionaries are simply compared by length. The dictionary with fewer elements is
considered less than a dictionary with more elements.
Example

print ("comparison of dictionary objects")


a={1:1,2:2}

119
Python Tutorial

b={2:2, 1:1, 3:3}


print ("a=",a, "b=",b,"a==b is",a==b)
print ("a=",a, "b=",b,"a!=b is",a!=b)

It will produce the following output −

comparison of dictionary objects


a= {1: 1, 2: 2} b= {2: 2, 1: 1, 3: 3} a==b is False
a= {1: 1, 2: 2} b= {2: 2, 1: 1, 3: 3} a!=b is True

120
19. Python - Assignment Operators
Python Tutorial

Python Assignment Operator


The = (equal to) symbol is defined as assignment operator in Python. The value of Python
expression on its right is assigned to a single variable on its left. The = symbol as in
programming in general (and Python in particular) should not be confused with its usage
in Mathematics, where it states that the expressions on the either side of the symbol are
equal.
Example of Assignment Operator in Python
Consider following Python statements −

a = 10
b = 5
a = a + b
print (a)

At the first instance, at least for somebody new to programming but who knows maths,
the statement "a=a+b" looks strange. How could a be equal to "a+b"? However, it needs
to be reemphasized that the = symbol is an assignment operator here and not used to
show the equality of LHS and RHS.
Because it is an assignment, the expression on right evaluates to 15, the value is assigned
to a.
In the statement "a+=b", the two operators "+" and "=" can be combined in a "+="
operator. It is called as add and assign operator. In a single statement, it performs addition
of two operands "a" and "b", and result is assigned to operand on left, i.e. "a".

Augmented Assignment Operators in Python


In addition to the simple assignment operators, Python provides few more assignment
operators for advanced use. They are called cumulative or augmented assignment
operators. In this chapter, we shall learn to use augmented assignment operators defined
in Python.
Python has the augmented assignment operators for all arithmetic and comparison
operators.
Python augmented assignment operators combines addition and assignment in one
statement. Since Python supports mixed arithmetic, the two operands may be of different
types. However, the type of left operand changes to the operand of on right, if it is wider.
Example
The += operator is an augmented operator. It is also called cumulative addition operator,
as it adds "b" in "a" and assigns the result back to a variable.
The following are the augmented assignment operators in Python:

121
Python Tutorial

 Augmented Addition Operator


 Augmented Subtraction Operator
 Augmented Multiplication Operator
 Augmented Division Operator
 Augmented Modulus Operator
 Augmented Exponent Operator
 Augmented Floor division Operator

Augmented Addition Operator (+=)


Following examples will help in understanding how the "+=" operator works −

a=10
b=5
print ("Augmented addition of int and int")
a+=b # equivalent to a=a+b
print ("a=",a, "type(a):", type(a))

a=10
b=5.5
print ("Augmented addition of int and float")
a+=b # equivalent to a=a+b
print ("a=",a, "type(a):", type(a))

a=10.50
b=5+6j
print ("Augmented addition of float and complex")
a+=b #equivalent to a=a+b
print ("a=",a, "type(a):", type(a))
It will produce the following output −
Augmented addition of int and int
a= 15 type(a): <class 'int'>
Augmented addition of int and float
a= 15.5 type(a): <class 'float'>
Augmented addition of float and complex
a= (15.5+6j) type(a): <class 'complex'>

Augmented Subtraction Operator (-=)


Use -= symbol to perform subtract and assign operations in a single statement. The "a-
=b" statement performs "a=a-b" assignment. Operands may be of any number type.
Python performs implicit type casting on the object which is narrower in size.

122
Python Tutorial

a=10
b=5
print ("Augmented subtraction of int and int")
a-=b #equivalent to a=a-b
print ("a=",a, "type(a):", type(a))

a=10
b=5.5
print ("Augmented subtraction of int and float")
a-=b #equivalent to a=a-b
print ("a=",a, "type(a):", type(a))

a=10.50
b=5+6j
print ("Augmented subtraction of float and complex")
a-=b #equivalent to a=a-b
print ("a=",a, "type(a):", type(a))

It will produce the following output −

Augmented subtraction of int and int


a= 5 type(a): <class 'int'>
Augmented subtraction of int and float
a= 4.5 type(a): <class 'float'>
Augmented subtraction of float and complex
a= (5.5-6j) type(a): <class 'complex'>

Augmented Multiplication Operator (*=)


The "*=" operator works on similar principle. "a*=b" performs multiply and assign
operations, and is equivalent to "a=a*b". In case of augmented multiplication of two
complex numbers, the rule of multiplication as discussed in the previous chapter is
applicable.

a=10
b=5
print ("Augmented multiplication of int and int")
a*=b #equivalent to a=a*b
print ("a=",a, "type(a):", type(a))

123
Python Tutorial

a=10
b=5.5
print ("Augmented multiplication of int and float")
a*=b #equivalent to a=a*b
print ("a=",a, "type(a):", type(a))

a=6+4j
b=3+2j
print ("Augmented multiplication of complex and complex")
a*=b #equivalent to a=a*b
print ("a=",a, "type(a):", type(a))

It will produce the following output −

Augmented multiplication of int and int


a= 50 type(a): <class 'int'>
Augmented multiplication of int and float
a= 55.0 type(a): <class 'float'>
Augmented multiplication of complex and complex
a= (10+24j) type(a): <class 'complex'>

Augmented Division Operator (/=)


The combination symbol "/=" acts as divide and assignment operator, hence "a/=b" is
equivalent to "a=a/b". The division operation of int or float operands is float. Division of
two complex numbers returns a complex number. Given below are examples of augmented
division operator.

a=10
b=5
print ("Augmented division of int and int")
a/=b #equivalent to a=a/b
print ("a=",a, "type(a):", type(a))

a=10
b=5.5
print ("Augmented division of int and float")
a/=b #equivalent to a=a/b
print ("a=",a, "type(a):", type(a))

124
Python Tutorial

a=6+4j
b=3+2j
print ("Augmented division of complex and complex")
a/=b #equivalent to a=a/b
print ("a=",a, "type(a):", type(a))

It will produce the following output −

Augmented division of int and int


a= 2.0 type(a): <class 'float'>
Augmented division of int and float
a= 1.8181818181818181 type(a): <class 'float'>
Augmented division of complex and complex
a= (2+0j) type(a): <class 'complex'>

Augmented Modulus Operator (%=)


To perform modulus and assignment operation in a single statement, use the %= operator.
Like the mod operator, its augmented version also is not supported for complex number.

a=10
b=5
print ("Augmented modulus operator with int and int")
a%=b #equivalent to a=a%b
print ("a=",a, "type(a):", type(a))

a=10
b=5.5
print ("Augmented modulus operator with int and float")
a%=b #equivalent to a=a%b
print ("a=",a, "type(a):", type(a))

It will produce the following output −

Augmented modulus operator with int and int


a= 0 type(a): <class 'int'>
Augmented modulus operator with int and float
a= 4.5 type(a): <class 'float'>

Augmented Exponent Operator (**=)


The "**=" operator results in computation of "a" raised to "b", and assigning the value
back to "a". Given below are some examples −

125
Python Tutorial

a=10
b=5
print ("Augmented exponent operator with int and int")
a**=b #equivalent to a=a**b
print ("a=",a, "type(a):", type(a))

a=10
b=5.5
print ("Augmented exponent operator with int and float")
a**=b #equivalent to a=a**b
print ("a=",a, "type(a):", type(a))

a=6+4j
b=3+2j
print ("Augmented exponent operator with complex and complex")
a**=b #equivalent to a=a**b
print ("a=",a, "type(a):", type(a))

It will produce the following output −

Augmented exponent operator with int and int


a= 100000 type(a): <class 'int'>
Augmented exponent operator with int and float
a= 316227.7660168379 type(a): <class 'float'>
Augmented exponent operator with complex and complex
a= (97.52306038414744-62.22529992036203j) type(a): <class 'complex'>

Augmented Floor division Operator (//=)


For performing floor division and assignment in a single statement, use the "//=" operator.
"a//=b" is equivalent to "a=a//b". This operator cannot be used with complex numbers.

a=10
b=5
print ("Augmented floor division operator with int and int")
a//=b #equivalent to a=a//b
print ("a=",a, "type(a):", type(a))

a=10
b=5.5

126
Python Tutorial

print ("Augmented floor division operator with int and float")


a//=b #equivalent to a=a//b
print ("a=",a, "type(a):", type(a))

It will produce the following output −

Augmented floor division operator with int and int


a= 2 type(a): <class 'int'>
Augmented floor division operator with int and float
a= 1.0 type(a): <class 'float'>

127
20. Python - Logical Operators Python Tutorial

Python Logical Operators


Python logical operators are used to form compound Boolean expressions. Each operand
for these logical operators is itself a Boolean expression. For example,
Example

age > 16 and marks > 80


percentage < 50 or attendance < 75

Along with the keyword False, Python interprets None, numeric zero of all types, and
empty sequences (strings, tuples, lists), empty dictionaries, and empty sets as False. All
other values are treated as True.
There are three logical operators in Python. They are "and", "or" and "not". They must be
in lowercase.

Logical "and" Operator


For the compound Boolean expression to be True, both the operands must be True. If any
or both operands evaluate to False, the expression returns False.

Logical "and" Operator Truth Table


The following table shows the scenarios.

a b a and b
F F F
F T F
T F F
T T T

Logical "or" Operator


In contrast, the or operator returns True if any of the operands is True. For the compound
Boolean expression to be False, both the operands have to be False.

Logical "or" Operator Truth Table


The following table shows the result of the "or" operator with different conditions:

a b a or b
F F F
F T T
T F T
T T T

128
Python Tutorial

Logical "not" Operator


This is a unary operator. The state of Boolean operand that follows, is reversed. As a
result, not True becomes False and not False becomes True.

Logical "not" Operator Truth Table


a not(a)
F T
T F

How the Python interpreter evaluates the logical operators?


The expression "x and y" first evaluates "x". If "x" is false, its value is returned; otherwise,
"y" is evaluated and the resulting value is returned.

The expression "x or y" first evaluates "x"; if "x" is true, its value is returned; otherwise,
"y" is evaluated and the resulting value is returned.

Python Logical Operators Examples


Some use cases of logical operators are given below −

129
Python Tutorial

Example 1: Logical Operators with Boolean Conditions


x = 10
y = 20
print("x > 0 and x < 10:",x > 0 and x < 10)
print("x > 0 and y > 10:",x > 0 and y > 10)
print("x > 10 or y > 10:",x > 10 or y > 10)
print("x%2 == 0 and y%2 == 0:",x%2 == 0 and y%2 == 0)
print ("not (x+y>15):", not (x+y)>15)

It will produce the following output −

x > 0 and x < 10: False


x > 0 and y > 10: True
x > 10 or y > 10: True
x%2 == 0 and y%2 == 0: True
not (x+y>15): False

Example 2: Logical Operators with Non- Boolean Conditions


We can use non-boolean operands with logical operators. Here, we need to not that any
non-zero numbers, and non-empty sequences evaluate to True. Hence, the same truth
tables of logical operators apply.
In the following example, numeric operands are used for logical operators. The variables
"x", "y" evaluate to True, "z" is False

x = 10
y = 20
z = 0
print("x and y:",x and y)
print("x or y:",x or y)
print("z or x:",z or x)
print("y or z:", y or z)

It will produce the following output −

x and y: 20
x or y: 10
z or x: 10
y or z: 20

Example 3: Logical Operators with Strings and Tuples

130
Python Tutorial

The string variable is treated as True and an empty tuple as False in the following example

a="Hello"
b=tuple()
print("a and b:",a and b)
print("b or a:",b or a)

It will produce the following output −

a and b: ()
b or a: Hello

Example 4: Logical Operators to Compare Sequences (Lists)


Finally, two list objects below are non-empty. Hence x and y returns the latter, and x or y
returns the former.

x=[1,2,3]
y=[10,20,30]
print("x and y:",x and y)
print("x or y:",x or y)

It will produce the following output −

x and y: [10, 20, 30]


x or y: [1, 2, 3]

131
21. Python - Bitwise Operators Python Tutorial

Python Bitwise Operators


Python bitwise operators are normally used to perform bitwise operations on integer-type
objects. However, instead of treating the object as a whole, it is treated as a string of bits.
Different operations are done on each bit in the string.
Python has six bitwise operators - &, |, ^, ~, << and >>. All these operators (except ~)
are binary in nature, in the sense they operate on two operands. Each operand is a binary
digit (bit) 1 or 0.
The following are the bitwise operators in Python -
 Bitwise AND Operator
 Bitwise OR Operator
 Bitwise XOR Operator
 Bitwise NOT Operator
 Bitwise Left Shift Operator
 Biwtise Right Shift Operator

Python Bitwise AND Operator (&)


Bitwise AND operator is somewhat similar to logical and operator. It returns True only if
both the bit operands are 1 (i.e. True). All the combinations are −

0 & 0 is 0
1 & 0 is 0
0 & 1 is 0
1 & 1 is 1

When you use integers as the operands, both are converted in equivalent binary, the &
operation is done on corresponding bit from each number, starting from the least
significant bit and going towards most significant bit.
Example of Bitwise AND Operator in Python
Let us take two integers 60 and 13, and assign them to variables a and b respectively.

a=60
b=13
print ("a:",a, "b:",b, "a&b:",a&b)

It will produce the following output −

a: 60 b: 13 a&b: 12

To understand how Python performs the operation, obtain the binary equivalent of each
variable.

print ("a:", bin(a))

132
Python Tutorial

print ("b:", bin(b))

It will produce the following output −

a: 0b111100
b: 0b1101

For the sake of convenience, use the standard 8-bit format for each number, so that "a"
is 00111100 and "b" is 00001101. Let us manually perform and operation on each
corresponding bits of these two numbers.

0011 1100
&
0000 1101
-------------
0000 1100

Convert the resultant binary back to integer. You'll get 12, which was the result obtained
earlier.

>>> int('00001100',2)
12

Python Bitwise OR Operator (|)


The "|" symbol (called pipe) is the bitwise OR operator. If any bit operand is 1, the result
is 1 otherwise it is 0.

0 | 0 is 0
0 | 1 is 1
1 | 0 is 1
1 | 1 is 1

Example of Bitwise OR Operator in Python


Take the same values of a=60, b=13. The "|" operation results in 61. Obtain their binary
equivalents.

a=60
b=13
print ("a:",a, "b:",b, "a|b:",a|b)
print ("a:", bin(a))
print ("b:", bin(b))

It will produce the following output −

a: 60 b: 13 a|b: 61
a: 0b111100

133
Python Tutorial

b: 0b1101

To perform the "|" operation manually, use the 8-bit format.

0011 1100
|
0000 1101
-------------
0011 1101

Convert the binary number back to integer to tally the result −

>>> int('00111101',2)
61

Python Bitwise XOR Operator (^)


The term XOR stands for exclusive OR. It means that the result of OR operation on two
bits will be 1 if only one of the bits is 1.

0 ^ 0 is 0
0 ^ 1 is 1
1 ^ 0 is 1
1 ^ 1 is 0

Example of Bitwise XOR Operator in Python


Let us perform XOR operation on a=60 and b=13.

a=60
b=13
print ("a:",a, "b:",b, "a^b:",a^b)

It will produce the following output −

a: 60 b: 13 a^b: 49

We now perform the bitwise XOR manually.

0011 1100
^
0000 1101
-------------
0011 0001

The int() function shows 00110001 to be 49.

>>> int('00110001',2)
49

134
Python Tutorial

Python Bitwise NOT Operator (~)


This operator is the binary equivalent of logical NOT operator. It flips each bit so that 1 is
replaced by 0, and 0 by 1, and returns the complement of the original number. Python
uses 2's complement method. For positive integers, it is obtained simply by reversing the
bits. For negative number, -x, it is written using the bit pattern for (x-1) with all of the
bits complemented (switched from 1 to 0 or 0 to 1). Hence: (for 8 bit representation)

-1 is complement(1 - 1) = complement(0) = "11111111"


-10 is complement(10 - 1) = complement(9) = complement("00001001") = "11110110".

Example of Bitwise NOT Operator in Python


For a=60, its complement is −

a=60
print ("a:",a, "~a:", ~a)

It will produce the following output −

a: 60 ~a: -61

Python Bitwise Left Shift Operator (<<)


Left shift operator shifts most significant bits to right by the number on the right side of
the "<<" symbol. Hence, "x << 2" causes two bits of the binary representation of to right.
Example of Bitwise Left Shift Operator in Python
Let us perform left shift on 60.

a=60
print ("a:",a, "a<<2:", a<<2)

It will produce the following output −

a: 60 a<<2: 240

How does this take place? Let us use the binary equivalent of 60, and perform the left shift
by 2.

0011 1100
<<
2
-------------
1111 0000

Convert the binary to integer. It is 240.

>>> int('11110000',2)
240

Python Bitwise Right Shift Operator (>>)

135
Python Tutorial

Right shift operator shifts least significant bits to left by the number on the right side of
the ">>" symbol. Hence, "x >> 2" causes two bits of the binary representation of to left.
Example of Bitwise Right Shift Operator in Python
Let us perform right shift on 60.

a=60
print ("a:",a, "a>>2:", a>>2)

It will produce the following output −

a: 60 a>>2: 15

Manual right shift operation on 60 is shown below −

0011 1100
>>
2
-------------
0000 1111

Use int() function to covert the above binary number to integer. It is 15.

>>> int('00001111',2)
15

136
22. Python - Membership Operators
Python Tutorial

Python Membership Operators


The membership operators in Python help us determine whether an item is present in a
given container type object, or in other words, whether an item is a member of the given
container type object.

Types of Python Membership Operators


Python has two membership operators: in and not in. Both return a Boolean result. The
result of in operator is opposite to that of not in operator.

The 'in' Operator


The "in" operator is used to check whether a substring is present in a bigger string, any
item is present in a list or tuple, or a sub-list or sub-tuple is included in a list or tuple.
Example of Python Membership "in" Operator
In the following example, different substrings are checked whether they belong to the
string var="TutorialsPoint". Python differentiates characters on the basis of their Unicode
value. Hence "To" is not the same as "to". Also note that if the "in" operator returns True,
the "not in" operator evaluates to False.

var = "TutorialsPoint"
a = "P"
b = "tor"
c = "in"
d = "To"
print (a, "in", var, ":", a in var)
print (b, "in", var, ":", b in var)
print (c, "in", var, ":", c in var)
print (d, "in", var, ":", d in var)

It will produce the following output −

P in TutorialsPoint : True
tor in TutorialsPoint : True
in in TutorialsPoint : True
To in TutorialsPoint : False

The 'not in' Operator


The "not in" operator is used to check a sequence with the given value is not present in
the object like string, list, tuple, etc.
137
Python Tutorial

Example of Python Membership "not in" Operator

var = "TutorialsPoint"
a = "P"
b = "tor"
c = "in"
d = "To"
print (a, "not in", var, ":", a not in var)
print (b, "not in", var, ":", b not in var)
print (c, "not in", var, ":", c not in var)
print (d, "not in", var, ":", d not in var)

It will produce the following output −

P not in TutorialsPoint : False


tor not in TutorialsPoint : False
in not in TutorialsPoint : False
To not in TutorialsPoint : True

Membership Operator with Lists and Tuples


You can use the "in/not in" operator to check the membership of an item in the list or
tuple.

var = [10,20,30,40]
a = 20
b = 10
c = a-b
d = a/2
print (a, "in", var, ":", a in var)
print (b, "not in", var, ":", b not in var)
print (c, "in", var, ":", c in var)
print (d, "not in", var, ":", d not in var)

It will produce the following output −

20 in [10, 20, 30, 40] : True


10 not in [10, 20, 30, 40] : False
10 in [10, 20, 30, 40] : True
10.0 not in [10, 20, 30, 40] : False

In the last case, "d" is a float but still it compares to True with 10 (an int) in the list. Even
if a number expressed in other formats like binary, octal or hexadecimal are given, the
membership operators tell if it is inside the sequence.
138
Python Tutorial

>>> 0x14 in [10, 20, 30, 40]


True

Example
However, if you try to check if two successive numbers are present in a list or tuple, the
in operator returns False. If the list/tuple contains the successive numbers as a sequence
itself, then it returns True.

var = (10,20,30,40)
a = 10
b = 20
print ((a,b), "in", var, ":", (a,b) in var)
var = ((10,20),30,40)
a = 10
b = 20
print ((a,b), "in", var, ":", (a,b) in var)

It will produce the following output −

(10, 20) in (10, 20, 30, 40) : False


(10, 20) in ((10, 20), 30, 40) : True

Membership Operator with Sets


Python's membership operators also work well with the set objects.

var = {10,20,30,40}
a = 10
b = 20
print (b, "in", var, ":", b in var)
var = {(10,20),30,40}
a = 10
b = 20
print ((a,b), "in", var, ":", (a,b) in var)

It will produce the following output −

20 in {40, 10, 20, 30} : True


(10, 20) in {40, 30, (10, 20)} : True

Membership Operator with Dictionaries


Use of in as well as not in operators with dictionary object is allowed. However, Python
checks the membership only with the collection of keys and not values.

139
Python Tutorial

var = {1:10, 2:20, 3:30}


a = 2
b = 20
print (a, "in", var, ":", a in var)
print (b, "in", var, ":", b in var)

It will produce the following output −

2 in {1: 10, 2: 20, 3: 30} : True


20 in {1: 10, 2: 20, 3: 30} : False

140
23. Python - Identity Operators Python Tutorial

Python Identity Operators


The identity operators compare the objects to determine whether they share the same
memory and refer to the same object type (data type).
Python provided two identity operators; we have listed them as follows:
 'is' Operator
 'is not' Operator

Python 'is' Operator


The 'is' operator evaluates to True if both the operand objects share the same memory
location. The memory location of the object can be obtained by the "id()" function. If the
"id()" of both variables is same, the "is" operator returns True.
Example of Python Identity 'is' Operator

a = [1, 2, 3, 4, 5]
b = [1, 2, 3, 4, 5]
c = a

# Comparing and printing return values


print(a is c)
print(a is b)

# Printing IDs of a, b, and c


print("id(a) : ", id(a))
print("id(b) : ", id(b))
print("id(c) : ", id(c))

It will produce the following output −

True
False
id(a) : 140114091859456
id(b) : 140114091906944
id(c) : 140114091859456

Python 'is not' Operator

141
Python Tutorial

The 'is not' operator evaluates to True if both the operand objects do not share the same
memory location or both operands are not the same objects.
Example of Python Identity 'is not' Operator

a = [1, 2, 3, 4, 5]
b = [1, 2, 3, 4, 5]
c = a

# Comparing and printing return values


print(a is not c)
print(a is not b)

# Printing IDs of a, b, and c


print("id(a) : ", id(a))
print("id(b) : ", id(b))
print("id(c) : ", id(c))

It will produce the following output −

False
True
id(a) : 140559927442176
id(b) : 140559925598080
id(c) : 140559927442176

Python Identity Operators Examples with Explanations


Example 1

a="TutorialsPoint"
b=a
print ("id(a), id(b):", id(a), id(b))
print ("a is b:", a is b)
print ("b is not a:", b is not a)

It will produce the following output −

id(a), id(b): 2739311598832 2739311598832


a is b: True
b is not a: False

The list and tuple objects behave differently, which might look strange in the first instance.
In the following example, two lists "a" and "b" contain same items. But their id() differs.

142
Python Tutorial

Example 2

a=[1,2,3]
b=[1,2,3]
print ("id(a), id(b):", id(a), id(b))
print ("a is b:", a is b)
print ("b is not a:", b is not a)

It will produce the following output −

id(a), id(b): 1552612704640 1552567805568


a is b: False
b is not a: True

The list or tuple contains the memory locations of individual items only and not the items
itself. Hence "a" contains the addresses of 10,20 and 30 integer objects in a certain
location which may be different from that of "b".
Example 3

print (id(a[0]), id(a[1]), id(a[2]))


print (id(b[0]), id(b[1]), id(b[2]))

It will produce the following output −

140734682034984 140734682035016 140734682035048


140734682034984 140734682035016 140734682035048

Because of two different locations of "a" and "b", the "is" operator returns False even if
the two lists contain same numbers.

143
24. Python Operator PrecedencePython Tutorial

Python Operator Precedence


An expression may have multiple operators to be evaluated. The operator precedence
defines the order in which operators are evaluated. In other words, the order of operator
evaluation is determined by the operator precedence.
If a certain expression contains multiple operators, their order of evaluation is determined
by the order of precedence. For example, consider the following expression

>>> a = 2+3*5

Here, what will be the value of a? - yes it will be 17 (multiply 3 by 5 first and then add 2)
or 25 (adding 2 and 3 and then multiply with 5)? Python’s operator precedence rule comes
into picture here.
If we consider only the arithmetic operators in Python, the traditional BODMAS rule is also
employed by Python interpreter, where the brackets are evaluated first, the division and
multiplication operators next, followed by addition and subtraction operators. Hence, a will
become 17 in the above expression.
In addition to the operator precedence, the associativity of operators is also important. If
an expression consists of operators with same level of precedence, the associativity
determines the order. Most of the operators have left to right associativity. It means, the
operator on the left is evaluated before the one on the right.
Let us consider another expression:

>>> b = 10/5*4

In this case, both * (multiplication) and / (division) operators have same level of
precedence. However, the left to right associativity rule performs the division first (10/5
= 2) and then the multiplication (2*4 = 8).

Python Operator Precedence Table


The following table lists all the operators in Python in their decreasing order of precedence.
Operators in the same cell under the Operators column have the same precedence.

Sr.No. Operator & Description


(),[], {}
1
Parentheses and braces
[index], [index:index]
2
Subscription, slicing,
await x
3
Await expression
**
4
Exponentiation
+x, -x, ~x
5
Positive, negative, bitwise NOT

144
Python Tutorial

*, @, /, //, %

6 Multiplication, matrix
multiplication, division, floor
division, remainder
+, -
7
Addition and subtraction
<<, >>
8
Left Shifts, Right Shifts
&
9
Bitwise AND
^
10
Bitwise XOR
|
11
Bitwise OR
in, not in, is, is not, <, <=,
>, >=, !=, ==
12 Comparisons, including
membership tests and identity
tests
not x
13
Boolean NOT
and
14
Boolean AND
or
15
Boolean OR
if – else
16
Conditional expression
lambda
17
Lambda expression
:=
18
Walrus operator

Python Operator Precedence Example


a = 20
b = 10
c = 15
d = 5
e = 0
e = (a + b) * c / d #( 30 * 15 ) / 5
print ("Value of (a + b) * c / d is ", e)

e = ((a + b) * c) / d # (30 * 15 ) / 5
print ("Value of ((a + b) * c) / d is ", e)

145
Python Tutorial

e = (a + b) * (c / d); # (30) * (15/5)


print ("Value of (a + b) * (c / d) is ", e)

e = a + (b * c) / d; # 20 + (150/5)
print ("Value of a + (b * c) / d is ", e)

When you execute the above program, it produces the following result −

Value of (a + b) * c / d is 90.0
Value of ((a + b) * c) / d is 90.0
Value of (a + b) * (c / d) is 90.0
Value of a + (b * c) / d is 50.0

146
25. Python - Comments Python Tutorial

Python Comments
Python comments are programmer-readable explanation or annotations in the Python
source code. They are added with the purpose of making the source code easier for
humans to understand, and are ignored by Python interpreter. Comments enhance the
readability of the code and help the programmers to understand the code very carefully.
Example
If we execute the code given below, the output produced will simply print "Hello, World!"
to the console, as comments are ignored by the Python interpreter and do not affect the
execution of the program −

# This is a comment
print("Hello, World!")

Python supports three types of comments as shown below −


 Single-line comments
 Multi-line comments
 Docstring Comments

Single Line Comments in Python


Single-line comments in Python start with a hash symbol (#) and extend to the end of the
line. They are used to provide short explanations or notes about the code. They can be
placed on their own line above the code they describe, or at the end of a line of code
(known as an inline comment) to provide context or clarification about that specific line.
Example: Standalone Single-Line Comment
A standalone single-line comment is a comment that occupies an entire line by itself,
starting with a hash symbol (#). It is placed above the code it describes or annotates.
In this example, the standalone single-line comment is placed above the "greet" function
"−

# Standalone single line comment is placed here


def greet():
print("Hello, World!")
greet()

Example: Inline Single-Line Comment


An inline single-line comment is a comment that appears on the same line as a piece of
code, following the code and preceded by a hash symbol (#).
Here the inline single-line comment follows the print("Hello, World!") statement −

print("Hello, World!") # Inline single line comment is placed here

147
Python Tutorial

Multi Line Comments in Python


In Python, multi-line comments are used to provide longer explanations or notes that span
multiple lines. While Python does not have a specific syntax for multi-line comments, there
are two common ways to achieve this: consecutive single-line comments and triple-quoted
strings −
Consecutive Single-Line Comments
Consecutive single-line comments refer to using the hash symbol (#) at the beginning of
each line. This method is often used for longer explanations or to sections of parts of the
code.
Example
In this example, multiple lines of comments are used to explain the purpose and logic of
the factorial function −

# This function calculates the factorial of a number


# using an iterative approach. The factorial of a number
# n is the product of all positive integers less than or
# equal to n. For example, factorial(5) is 5*4*3*2*1 = 120.
def factorial(n):
if n < 0:
return "Factorial is not defined for negative numbers"
result = 1
for i in range(1, n + 1):
result *= i
return result

number = 5
print(f"The factorial of {number} is {factorial(number)}")

Multi Line Comment Using Triple Quoted Strings


We can use triple-quoted strings (''' or """) to create multi-line comments. These strings
are technically string literals but can be used as comments if they are not assigned to any
variable or used in expressions.
This pattern is often used for block comments or when documenting sections of code that
require detailed explanations.
Example
Here, the triple-quoted string provides a detailed explanation of the "gcd" function,
describing its purpose and the algorithm used −

"""
This function calculates the greatest common divisor (GCD)
of two numbers using the Euclidean algorithm. The GCD of

148
Python Tutorial

two numbers is the largest number that divides both of them


without leaving a remainder.
"""
def gcd(a, b):
while b:
a, b = b, a % b
return a

result = gcd(48, 18)


print("The GCD of 48 and 18 is:", result)

Using Comments for Documentation


In Python, documentation comments, also known as docstrings, provide a way to
incorporate documentation within your code. This can be useful for explaining the purpose
and usage of modules, classes, functions, and methods. Effective use of documentation
comments helps other developers understand your code and its purpose without needing
to read through all the details of the implementation.

Python Docstrings
In Python, docstrings are a special type of comment that is used to document modules,
classes, functions, and methods. They are written using triple quotes (''' or """) and are
placed immediately after the definition of the entity they document.
Docstrings can be accessed programmatically, making them an integral part of Python’s
built-in documentation tools.
Example of a Function Docstring

def greet(name):
"""
This function greets the person whose name is passed as a parameter.

Parameters:
name (str): The name of the person to greet

Returns:
None
"""
print(f"Hello, {name}!")
greet("Alice")

149
Python Tutorial

Accessing Docstrings
Docstrings can be accessed using the .__doc__ attribute or the help() function. This makes
it easy to view the documentation for any module, class, function, or method directly from
the interactive Python shell or within the code.
Example: Using the .__doc__ attribute

def greet(name):
"""
This function greets the person whose name is passed as a parameter.

Parameters:
name (str): The name of the person to greet

Returns:
None
"""
print(greet.__doc__)

Example: Using the help() Function

def greet(name):
"""
This function greets the person whose name is passed as a parameter.

Parameters:
name (str): The name of the person to greet

Returns:
None
"""
help(greet)

150
26. Python - User Input Python Tutorial

Provide User Input in Python


In this chapter, we will learn how Python accepts the user input from the console, and
displays the output on the same console.
Every computer application should have a provision to accept input from the user when it
is running. This makes the application interactive. Depending on how it is developed, an
application may accept the user input in the form of text entered in the console
(sys.stdin), a graphical layout, or a web-based interface.

Python User Input Functions


Python provides us with two built-in functions to read the input from the keyboard.
 The input () Function
 The raw_input () Function
Python interpreter works in interactive and scripted mode. While the interactive mode is
good for quick evaluations, it is less productive. For repeated execution of same set of
instructions, scripted mode should be used.
Let us write a simple Python script to start with.

#! /usr/bin/python3.11
name = "Kiran"
city = "Hyderabad"
print ("Hello My name is", name)
print ("I am from", city)

Save the above code as hello.py and run it from the command-line. Here's the output

C:\python311> python hello.py


Hello My name is Kiran
I am from Hyderabad

The program simply prints the values of the two variables in it. If you run the program
repeatedly, the same output will be displayed every time. To use the program for another
name and city, you can edit the code, change name to say "Ravi" and city to "Chennai".
Every time you need to assign different value, you will have to edit the program, save and
run, which is not the ideal way.

The input() Function


Obviously, you need some mechanism to assign different values to the variable in the
runtime − while the program is running. Python's input() function does the same job.
Following is the syntax of Python's standard library input() function.

151
Python Tutorial

>>> var = input()

When the interpreter encounters input() function, it waits for the user to enter data from
the standard input stream (keyboard) till the Enter key is pressed. The sequence of
characters may be stored in a string variable for further use.
On reading the Enter key, the program proceeds to the next statement. Let change our
program to store the user input in name and city variables.

#! /usr/bin/python3.11
name = input()
city = input()

print ("Hello My name is", name)


print ("I am from ", city)

When you run, you will find the cursor waiting for user's input. Enter values for name and
city. Using the entered data, the output will be displayed.

Ravi
Chennai
Hello My name is Ravi
I am from Chennai

Now, the variables are not assigned any specific value in the program. Every time you run,
different values can be input. So, your program has become truly interactive.
Inside the input() function, you may give a prompt text, which will appear before the
cursor when you run the code.

#! /usr/bin/python3.11
name = input("Enter your name : ")
city = input("Enter your city : ")
print ("Hello My name is", name)
print ("I am from ", city)

When you run the program displays the prompt message, basically helping the user what
to enter.

Enter your name: Praveen Rao


Enter your city: Bengaluru
Hello My name is Praveen Rao
I am from Bengaluru

The raw_input() Function


The raw_input() function works similar to input() function. Here only point is that this
function was available in Python 2.7, and it has been renamed to input() in Python 3.6

152
Python Tutorial

Following is the syntax of the raw_input() function:

>>> var = raw_input ([prompt text])

Let's re-write the above program using raw_input() function:

#! /usr/bin/python3.11

name = raw_input("Eneter your name - ")


city = raw_input("Enter city name - ")

print ("Hello My name is", name)


print ("I am from ", city)

When you run, you will find the cursor waiting for user's input. Enter values for name and
city. Using the entered data, the output will be displayed.

Eneter your name - Ravi


Enter city name - Chennai
Hello My name is Ravi
I am from Chennai

Taking Numeric Input in Python


Let us write a Python code that accepts width and height of a rectangle from the user and
computes the area.

#! /usr/bin/python3.11

width = input("Enter width : ")


height = input("Enter height : ")

area = width*height
print ("Area of rectangle = ", area)

Run the program, and enter width and height.

Enter width: 20
Enter height: 30
Traceback (most recent call last):
File "C:\Python311\var1.py", line 5, in <module>
area = width*height
TypeError: can't multiply sequence by non-int of type 'str'

153
Python Tutorial

Why do you get a TypeError here? The reason is, Python always read the user input as a
string. Hence, width="20" and height="30" are the strings and obviously you cannot
perform multiplication of two strings.
To overcome this problem, we shall use int(), another built-in function from Python's
standard library. It converts a string object to an integer.
To accept an integer input from the user, read the input in a string, and type cast it to
integer with int() function −

w = input("Enter width : ")


width = int(w)

h = input("Enter height : ")


height = int(h)

You can combine the input and type cast statements in one −

#! /usr/bin/python3.11

width = int(input("Enter width : "))


height = int(input("Enter height : "))

area = width*height
print ("Area of rectangle = ", area)

Now you can input any integer value to the two variables in the program −

Enter width: 20
Enter height: 30
Area of rectangle = 600

Python's float() function converts a string into a float object. The following program
accepts the user input and parses it to a float variable − rate, and computes the interest
on an amount which is also input by the user.

#! /usr/bin/python3.11

amount = float(input("Enter Amount : "))


rate = float(input("Enter rate of interest : "))

interest = amount*rate/100
print ("Amount: ", amount, "Interest: ", interest)

The program ask user to enter amount and rate; and displays the result as follows −

Enter Amount: 12500

154
Python Tutorial

Enter rate of interest: 6.5


Amount: 12500.0 Interest: 812.5

The print() Function


Python's print() function is a built-in function. It is the most frequently used function, that
displays value of Python expression given in parenthesis, on Python's console, or standard
output (sys.stdout).

print ("Hello World ")

Any number of Python expressions can be there inside the parenthesis. They must be
separated by comma symbol. Each item in the list may be any Python object, or a valid
Python expression.

#! /usr/bin/python3.11

a = "Hello World"
b = 100
c = 25.50
d = 5+6j
print ("Message: a)
print (b, c, b-c)
print(pow(100, 0.5), pow(c,2))

The first call to print() displays a string literal and a string variable. The second prints
value of two variables and their subtraction. The pow() function computes the square root
of a number and square value of a variable.

Message Hello World


100 25.5 74.5
10.0 650.25

If there are multiple comma separated objects in the print() function's parenthesis, the
values are separated by a white space " ". To use any other character as a separator,
define a sep parameter for the print() function. This parameter should follow the list of
expressions to be printed.
In the following output of print() function, the variables are separated by comma.

#! /usr/bin/python3.11

city="Hyderabad"
state="Telangana"
country="India"
print(city, state, country, sep=',')

155
Python Tutorial

The effect of sep=',' can be seen in the result −

Hyderabad,Telangana,India

The print() function issues a newline character ('\n') at the end, by default. As a result,
the output of the next print() statement appears in the next line of the console.

city="Hyderabad"
state="Telangana"
print("City:", city)
print("State:", state)

Two lines are displayed as the output −

City: Hyderabad
State: Telangana

To make these two lines appear in the same line, define end parameter in the first print()
function and set it to a whitespace string " ".

city="Hyderabad"
state="Telangana"
country="India"

print("City:", city, end=" ")


print("State:", state)

Output of both the print() functions appear in continuation.

City: Hyderabad State: Telangana

156
27. Python - Numbers Python Tutorial

Python has built-in support to store and process numeric data (Python Numbers). Most
of the times you work with numbers in almost every Python application. Obviously, any
computer application deals with numbers. This tutorial will discuss about different types
of Python Numbers and their properties.

Python - Number Types


There are three built-in number types available in Python:
 integers (int)
 floating point numbers (float)
 complex numbers
Python also has a bult-in Boolean data type called bool. It can be treated as a sub-type of
int type, since it's two possible values True and False represent the integers 1 and 0
respectively.

Python − Integer Numbers


In Python, any number without the provision to store a fractional part is an integer. (Note
that if the fractional part in a number is 0, it doesn't mean that it is an integer. For
example, a number 10.0 is not an integer, it is a float with 0 fractional part whose numeric
value is 10.) An integer can be zero, positive or a negative whole number. For example,
1234, 0, -55 all represent to integers in Python.
There are three ways to form an integer object. With (a) literal representation, (b) any
expression evaluating to an integer, and (c) using int() function.
Literal is a notation used to represent a constant directly in the source code. For example

>>> a =10

However, look at the following assignment of the integer variable c.

a = 10
b = 20
c = a + b

print ("a:", a, "type:", type(a))


print ("c:", c, "type:", type(c))

It will produce the following output −

a: 10 type: <class 'int'>


c: 30 type: <class 'int'>

157
Python Tutorial

Here, c is indeed an integer variable, but the expression a + b is evaluated first, and its
value is indirectly assigned to c.
The third method of forming an integer object is with the return value of int() function. It
converts a floating point number or a string to an integer.

>>> a=int(10.5)
>>> b=int("100")

You can represent an integer as a binary, octal or hexa-decimal number. However,


internally the object is stored as an integer.

Binary Numbers in Python


A number consisting of only the binary digits (1 and 0) and prefixed with "0b" is a binary
number. If you assign a binary number to a variable, it still is an int variable.
A represent an integer in binary form, store it directly as a literal, or use int() function, in
which the base is set to 2

a=0b101
print ("a:",a, "type:",type(a))

b=int("0b101011", 2)
print ("b:",b, "type:",type(b))

It will produce the following output −

a: 5 type: <class 'int'>


b: 43 type: <class 'int'>

There is also a bin() function in Python. It returns a binary string equivalent of an integer.

a=43
b=bin(a)
print ("Integer:",a, "Binary equivalent:",b)

It will produce the following output −

Integer: 43 Binary equivalent: 0b101011

Octal Numbers in Python


An octal number is made up of digits 0 to 7 only. In order to specify that the integer uses
octal notation, it needs to be prefixed by "0o" (lowercase O) or "0O" (uppercase O). A
literal representation of octal number is as follows −

a=0O107
print (a, type(a))

It will produce the following output −

71 <class 'int'>

158
Python Tutorial

Note that the object is internally stored as integer. Decimal equivalent of octal number
107 is 71.
Since octal number system has 8 symbols (0 to 7), its base is 7. Hence, while using int()
function to convert an octal string to integer, you need to set the base argument to 8.

a=int('20',8)
print (a, type(a))

It will produce the following output −

16 <class 'int'>

Decimal equivalent of octal 30 is 16.


In the following code, two int objects are obtained from octal notations and their addition
is performed.

a=0O56
print ("a:",a, "type:",type(a))

b=int("0O31",8)
print ("b:",b, "type:",type(b))

c=a+b
print ("addition:", c)

It will produce the following output −

a: 46 type: <class 'int'>


b: 25 type: <class 'int'>
addition: 71

To obtain the octal string for an integer, use oct() function.

a=oct(71)
print (a, type(a))

Hexa-decimal Numbers in Python


As the name suggests, there are 16 symbols in the Hexadecimal number system. They
are 0-9 and A to F. The first 10 digits are same as decimal digits. The alphabets A, B, C,
D, E and F are equivalents of 11, 12, 13, 14, 15, and 16 respectively. Upper or lower cases
may be used for these letter symbols.
For the literal representation of an integer in Hexadecimal notation, prefix it by "0x" or
"0X".

a=0XA2
print (a, type(a))

159
Python Tutorial

It will produce the following output −

162 <class 'int'>

To convert a hexadecimal string to integer, set the base to 16 in the int() function.

a=int('0X1e', 16)
print (a, type(a))

Try out the following code snippet. It takes a Hexadecimal string, and returns the integer.

num_string = "A1"
number = int(num_string, 16)
print ("Hexadecimal:", num_string, "Integer:",number)

It will produce the following output −

Hexadecimal: A1 Integer: 161

However, if the string contains any symbol apart from the Hexadecimal symbol chart an
error will be generated.

num_string = "A1X001"
print (int(num_string, 16))

The above program generates the following error −

Traceback (most recent call last):


File "/home/main.py", line 2, in
print (int(num_string, 16))
ValueError: invalid literal for int() with base 16: 'A1X001'

Python's standard library has hex() function, with which you can obtain a hexadecimal
equivalent of an integer.

a=hex(161)
print (a, type(a))

It will produce the following output −

0xa1 <class 'str'>

Though an integer can be represented as binary or octal or hexadecimal, internally it is


still integer. So, when performing arithmetic operation, the representation doesn't matter.

a=10 #decimal
b=0b10 #binary
c=0O10 #octal
d=0XA #Hexadecimal
e=a+b+c+d

160
Python Tutorial

print ("addition:", e)

It will produce the following output −

addition: 30

Python − Floating Point Numbers


A floating point number has an integer part and a fractional part, separated by a decimal
point symbol (.). By default, the number is positive, prefix a dash (-) symbol for a negative
number.
A floating point number is an object of Python's float class. To store a float object, you
may use a literal notation, use the value of an arithmetic expression, or use the return
value of float() function.
Using literal is the most direct way. Just assign a number with fractional part to a variable.
Each of the following statements declares a float object.

>>> a=9.99
>>> b=0.999
>>> c=-9.99
>>> d=-0.999

In Python, there is no restriction on how many digits after the decimal point can a floating
point number have. However, to shorten the representation, the E or e symbol is used. E
stands for Ten raised to. For example, E4 is 10 raised to 4 (or 4th power of 10), e-3 is 10
raised to -3.
In scientific notation, number has a coefficient and exponent part. The coefficient should
be a float greater than or equal to 1 but less than 10. Hence, 1.23E+3, 9.9E-5, and 1E10
are the examples of floats with scientific notation.

>>> a=1E10
>>> a
10000000000.0
>>> b=9.90E-5
>>> b
9.9e-05
>>> 1.23E3
1230.0

The second approach of forming a float object is indirect, using the result of an expression.
Here, the quotient of two floats is assigned to a variable, which refers to a float object.

a=10.33
b=2.66
c=a/b

161
Python Tutorial

print ("c:", c, "type", type(c))

It will produce the following output −

c: 3.8834586466165413 type <class 'float'>

Python's float() function returns a float object, parsing a number or a string if it has the
appropriate contents. If no arguments are given in the parenthesis, it returns 0.0, and for
an int argument, fractional part with 0 is added.

>>> a=float()
>>> a
0.0
>>> a=float(10)
>>> a
10.0

Even if the integer is expressed in binary, octal or hexadecimal, the float() function returns
a float with fractional part as 0.

a=float(0b10)
b=float(0O10)
c=float(0xA)

print (a,b,c, sep=",")

It will produce the following output −

2.0,8.0,10.0

The float() function retrieves a floating point number out of a string that encloses a float,
either in standard decimal point format, or having scientific notation.

a=float("-123.54")
b=float("1.23E04")
print ("a=",a,"b=",b)

It will produce the following output −

a= -123.54 b= 12300.0

In mathematics, infinity is an abstract concept. Physically, infinitely large number can


never be stored in any amount of memory. For most of the computer hardware
configurations, however, a very large number with 400th power of 10 is represented by
Inf. If you use "Infinity" as argument for float() function, it returns Inf.

a=1.00E400
print (a, type(a))
a=float("Infinity")

162
Python Tutorial

print (a, type(a))

It will produce the following output −

inf <class 'float'>


inf <class 'float'>

One more such entity is Nan (stands for Not a Number). It represents any value that is
undefined or not representable.

>>> a=float('Nan')
>>> a
Nan

Python − Complex Numbers


In this section, we shall know in detail about Complex data type in Python. Complex
numbers find their applications in mathematical equations and laws in electromagnetism,
electronics, optics, and quantum theory. Fourier transforms use complex numbers. They
are used in calculations with wavefunctions, designing filters, signal integrity in digital
electronics, radio astronomy, etc.
A complex number consists of a real part and an imaginary part, separated by either "+"
or "−". The real part can be any floating point (or itself a complex number) number. The
imaginary part is also a float/complex, but multiplied by an imaginary number.

In mathematics, an imaginary number "i" is defined as the square root of -1 (√-1).


Therefore, a complex number is represented as "x+yi", where x is the real part, and "y"
is the coefficient of imaginary part.
Quite often, the symbol "j" is used instead of "I" for the imaginary number, to avoid
confusion with its usage as current in theory of electricity. Python also uses "j" as the
imaginary number. Hence, "x+yj" is the representation of complex number in Python.
Like int or float data type, a complex object can be formed with literal representation or
using complex() function. All the following statements form a complex object.

>>> a=5+6j
>>> a
(5+6j)
>>> type(a)
<class 'complex'>
>>> a=2.25-1.2J
>>> a
(2.25-1.2j)
>>> type(a)
<class 'complex'>
>>> a=1.01E-2+2.2e3j

163
Python Tutorial

>>> a
(0.0101+2200j)
>>> type(a)
<class 'complex'>

Note that the real part as well as the coefficient of imaginary part have to be floats, and
they may be expressed in standard decimal point notation or scientific notation.
Python's complex() function helps in forming an object of complex type. The function
receives arguments for real and imaginary part, and returns the complex number.
There are two versions of complex() function, with two arguments and with one argument.
Use of complex() with two arguments is straightforward. It uses first argument as real
part and second as coefficient of imaginary part.

a=complex(5.3,6)
b=complex(1.01E-2, 2.2E3)
print ("a:", a, "type:", type(a))
print ("b:", b, "type:", type(b))

It will produce the following output −

a: (5.3+6j) type: <class 'complex'>


b: (0.0101+2200j) type: <class 'complex'>

In the above example, we have used x and y as float parameters. They can even be of
complex data type.

a=complex(1+2j, 2-3j)
print (a, type(a))

It will produce the following output −

(4+4j) <class 'complex'>

Surprised by the above example? Put "x" as 1+2j and "y" as 2-3j. Try to perform manual
computation of "x+yj" and you'll come to know.

complex(1+2j, 2-3j)
=(1+2j)+(2-3j)*j
=1+2j +2j+3
=4+4j

If you use only one numeric argument for complex() function, it treats it as the value of
real part; and imaginary part is set to 0.

a=complex(5.3)
print ("a:", a, "type:", type(a))

It will produce the following output −

164
Python Tutorial

a: (5.3+0j) type: <class 'complex'>

The complex() function can also parse a string into a complex number if its only argument
is a string having complex number representation.
In the following snippet, user is asked to input a complex number. It is used as argument.
Since Python reads the input as a string, the function extracts the complex object from it.

a= "5.5+2.3j"
b=complex(a)
print ("Complex number:", b)

It will produce the following output −

Complex number: (5.5+2.3j)

Python's built-in complex class has two attributes real and imag − they return the real and
coefficient of imaginary part from the object.

a=5+6j
print ("Real part:", a.real, "Coefficient of Imaginary part:", a.imag)

It will produce the following output −

Real part: 5.0 Coefficient of Imaginary part: 6.0

The complex class also defines a conjugate() method. It returns another complex number
with the sign of imaginary component reversed. For example, conjugate of x+yj is x-yj.

>>> a=5-2.2j
>>> a.conjugate()
(5+2.2j)

Number Type Conversion


Python converts numbers internally in an expression containing mixed types to a common
type for evaluation. But sometimes, you need to coerce a number explicitly from one type
to another to satisfy the requirements of an operator or function parameter.
 Type int(x) to convert x to a plain integer.
 Type long(x) to convert x to a long integer.
 Type float(x) to convert x to a floating-point number.
 Type complex(x) to convert x to a complex number with real part x and imaginary
part zero. In the same way type complex(x, y) to convert x and y to a complex
number with real part x and imaginary part y. x and y are numeric expressions
Let us see various numeric and math-related functions.

Theoretic and Representation Functions


Python includes following theoretic and representation functions in the math module −

Sr.No. Function & Description


1 math.ceil(x)

165
Python Tutorial

The ceiling of x: the smallest integer not less than x

math.comb(n,k)

2 This function is used to find the returns the number of ways to


choose "x" items from "y" items without repetition and without
order.

math.copysign(x, y)

3 This function returns a float with the magnitude (absolute value) of


x but the sign of y.

math.cmp(x, y)

4 This function is used to compare the values of to objects. This


function is deprecated in Python3.

math.fabs(x)
5 This function is used to calculate the absolute value of a given
integer.
math.factorial(n)
6
This function is used to find the factorial of a given integer.

math.floor(x)
7
This function calculates the floor value of a given integer.

math.fmod(x, y)

8 The fmod() function in math module returns same result as


the "%" operator. However fmod() gives more accurate result of
modulo division than modulo operator.

math.frexp(x)

9 This function is used to calculate the mantissa and exponent of a


given number.

math.fsum(iterable)

10 This function returns the floating point sum of all numeric items in
an iterable i.e. list, tuple, array.

math.gcd(*integers)

11 This function is used to calculate the greatest common divisor of all


the given integers.

math.isclose()

12 This function is used to determine whether two given numeric


values are close to each other.

13 math.isfinite(x)

166
Python Tutorial

This function is used to determine whether the given number is a


finite number.

math.isinf(x)

14 This function is used to determine whether the given value is


infinity (+ve or, -ve).

math.isnan(x)
15 This function is used to determine whether the given number is
"NaN".
math.isqrt(n)

16 This function calculates the integer square-root of the given non


negative integer.

math.lcm(*integers)

17 This function is used to calculate the least common factor of the


given integer arguments.

math.ldexp(x, i)

18 This function returns product of first number with exponent of


second number. So, ldexp(x,y) returns x*2**y. This is inverse of
frexp() function.

math.modf(x)
19 This returns the fractional and integer parts of x in a two-item
tuple.
math.nextafter(x, y, steps)
20
This function returns the next floating-point value after x towards y.

math.perm(n, k)

21 This function is used to calculate the permutation. It returns the


number of ways to choose x items from y items without repetition
and with order.

math.prod(iterable, *, start)

22 This function is used to calculate the product of all numeric items in


the iterable (list, tuple) given as argument.

math.remainder(x,y)

23 This function returns the remainder of x with respect to y. This is


the difference x − n*y, where n is the integer closest to the
quotient x / y.

24 math.trunk(x)

167
Python Tutorial

This function returns integral part of the number, removing the


fractional part. trunc() is equivalent to floor() for positive x, and
equivalent to ceil() for negative x.

math.ulp(x)

25 This function returns the value of the least significant bit of the float
x. trunc() is equivalent to floor() for positive x, and equivalent to
ceil() for negative x.

Power and Logarithmic Functions


Sr.No. Function & Description
math.cbrt(x)

1 This function is used to calculate the cube root of a


number.

math.exp(x)
2
This function calculate the exponential of x: ex

math.exp2(x)

3 This function returns 2 raised to power x. It is


equivalent to 2**x.

math.expm1(x)

4 This function returns e raised to the power x,


minus 1. Here e is the base of natural logarithms.

math.log(x)

5 This function calculates the natural logarithm of x,


for x> 0.

math.log1p(x)

6 This function returns the natural logarithm of 1+x


(base e). The result is calculated in a way which is
accurate for x near zero.

math.log2(x)

7 This function returns the base-2 logarithm of x.


This is usually more accurate than log(x, 2).

8 math.log10(x)

168
Python Tutorial

The base-10 logarithm of x for x> 0.

math.pow(x, y)
9
The value of x**y.
math.sqrt(x)
10
The square root of x for x > 0

Trigonometric Functions
Python includes following functions that perform trigonometric calculations in the math
module −

Sr.No. Function & Description


math.acos(x)
1
This function returns the arc cosine of x, in radians.

math.asin(x)
2
This function returns the arc sine of x, in radians.

math.atan(x)
3
This function returns the arc tangent of x, in radians.

math.atan2(y, x)
4
This function returns atan(y / x), in radians.

math.cos(x)
5
This function returns the cosine of x radians.

math.sin(x)
6
This function returns the sine of x radians.

math.tan(x)
7
This function returns the tangent of x radians.

math.hypot(x, y)

8
This function returns the Euclidean norm, sqrt(x*x + y*y).

Angular conversion Functions


Following are the angular conversion function provided by Python math module −

Sr.No. Function & Description


math.degrees(x)

1 This function converts the given angle from radians to


degrees.

2 math.radians(x)

169
Python Tutorial

This function converts the given angle from degrees to


radians.

Mathematical Constants
The Python math module defines the following mathematical constants −

Sr.No. Constants & Description


math.pi

1 This represents the mathematical constant pi, which


equals to "3.141592..." to available precision.

good.e

2 This represents the mathematical constant e, which is


equal to "2.718281..." to available precision.

math. number

3 This represents the mathematical constant Tau (denoted


by τ ). It is equivalent to the ratio of circumference to
radius, and is equal to 2Π.

math.inf

4 This represents positive infinity. For negative infinity


use "−math.inf".

math. in

5 This constant is a floating-point "not a number" (NaN)


value. Its value is equivalent to the output of
float('nan').

Hyperbolic Functions
Hyperbolic functions are analogs of trigonometric functions that are based on hyperbolas
instead of circles. Following are the hyperbolic functions of the Python math module −

Sr.No. Function & Description


math.acosh(x)

1 This function is used to calculate the inverse hyperbolic cosine


of the given value.

2 math.asinh(x)

170
Python Tutorial

This function is used to calculate the inverse hyperbolic sine of


a given number.

math.atanh(x)

3 This function is used to calculate the inverse hyperbolic


tangent of a number.

math.cosh(x)

4 This function is used to calculate the hyperbolic cosine of the


given value.

math.birth(x)

5 This function is used to calculate the hyperbolic sine of a given


number.

math.tanh(x)

6 This function is used to calculate the hyperbolic tangent of a


number.

Special Functions
Following are the special functions provided by the Python math module −

Sr.No. Function & Description


math.erf(x)

1 This function returns the value of the Gauss error


function for the given parameter.

math.erfc(x)

2 This function is the complementary for the error


function. Value of erf(x) is equivalent to 1-erf(x).

math.gamma(x)

3 This is used to calculate the factorial of the complex


numbers. It is defined for all the complex numbers
except the non-positive integers.

math.lgamma(x)

4 This function is used to calculate the natural logarithm of


the absolute value of the Gamma function at x.

171
Python Tutorial

Random Number Functions


Random numbers are used for games, simulations, testing, security, and privacy
applications. Python includes following functions in the random module.

Sr.No. Function & Description


random.choice(seq)
1
A random item from a list, tuple, or string.

random.randrange([start,] stop [,step])


2
A randomly selected element from range(start, stop,
step)
random.random()

3 A random float r, such that 0 is less than or equal to r


and r is less than 1

random.seed([x])

This function sets the integer starting value used in


4 generating random numbers. Call this function before
calling any other random module function. Returns
None.

random.shuffle(seq)

5 This function is used to randomize the items of the given


sequence.

random.uniform(a, b)

6 This function returns a random floating point value r,


such that a is less than or equal to r and r is less than b.

Built-in Mathematical Functions


Following mathematical functions are built into the Python interpreter, hence you don't
need to import them from any module.

Sr.No. Function & Description


Python abs() function

1 The abs() function returns the absolute value of x, i.e. the


positive distance between x and zero.

2 Python max() function

172
Python Tutorial

The max() function returns the largest of its arguments or


largest number from the iterable (list or tuple).

Python min() function

3 The function min() returns the smallest of its arguments


i.e. the value closest to negative infinity, or smallest
number from the iterable (list or tuple)

Python pow() function

4 The pow() function returns x raised to y. It is equivalent


to x**y.

Python round() Function

5 round() is a built-in function in Python. It returns x


rounded to n digits from the decimal point.

Python sum() function

The sum() function returns the sum of all numeric items


6 in any iterable (list or tuple). It has an
optional start argument which is 0 by default. If given,
the numbers in the list are added to start value.

173
28. Python - Booleans Python Tutorial

Python Booleans (bool)


In Python, bool is a sub-type of int type. A bool object has two possible values, and it is
initialized with Python keywords, True and False.
Example

>>> a=True
>>> b=False
>>> type(a), type(b)
(<class 'bool'>, <class 'bool'>)

A bool object is accepted as argument to type conversion functions. With True as


argument, the int() function returns 1, float() returns 1.0; whereas for False, they return
0 and 0.0 respectively. We have a one argument version of complex() function.
If the argument is a complex object, it is taken as real part, setting the imaginary
coefficient to 0.
Example

a=int(True)
print ("bool to int:", a)
a=float(False)
print ("bool to float:", a)
a=complex(True)
print ("bool to complex:", a)

On running this code, you will get the following output −

bool to int: 1
bool to float: 0.0
bool to complex: (1+0j)

Python Boolean Expression


Python boolean expression is an expression that evaluates to a Boolean value. It almost
always involves a comparison operator. In the below example, we will see how the
comparison operators can give us the Boolean values. The bool() method is used to return
the truth value of an expresison.

Syntax: bool([x])
Returns True if X evaluates to true else false.
Without parameters it returns false.

174
Python Tutorial

Below we have examples which use numbers streams and Boolean values as parameters
to the bool function. The results come out as true or false depending on the parameter.
Example

# Check true
a = True
print(bool(a))
# Check false
a = False
print(bool(a))
# Check 0
a = 0.0
print(bool(a))
# Check 1
a = 1.0
print(bool(a))
# Check Equality
a = 5
b = 10
print(bool( a==b))
# Check None
a = None
print(bool(a))
# Check an empty sequence
a = ()
print(bool(a))
# Check an emtpty mapping
a = {}
print(bool(a))
# Check a non empty string
a = 'Tutorialspoint'
print(bool(a))

175
Python Tutorial

Python Control Statements

176
29. Python - Control Flow Python Tutorial

Python program control flow is regulated by various types of conditional statements,


loops, and function calls. By default, the instructions in a computer program are
executed in a sequential manner, from top to bottom, or from start to end. However,
such sequentially executing programs can perform only simplistic tasks. We would like
the program to have a decision-making ability, so that it performs different steps
depending on different conditions.

Most programming languages including Python provide functionality to control the flow of
execution of instructions. Normally, there are two type of control flow statements in any
programming language and Python also supports them.

Decision Making Statements


Decision making statements are used in the Python programs to make them able to
decide which of the alternative group of instructions to be executed, depending on value
of a certain Boolean expression.

The following diagram illustrates how decision-making statements work −

The if Statements
Python provides if..elif..else control statements as a part of decision marking. It consists
of three different blocks, which are if block, elif (short of else if) block and else block.

177
Python Tutorial

Example
Following is a simple example which makes use of if..elif..else. You can try to run this
program using different marks and verify the result.

marks = 80
result = ""
if marks < 30:
result = "Failed"
elif marks > 75:
result = "Passed with distinction"
else:
result = "Passed"

print(result)

This will produce following result:

Passed with distinction

The match Statement


Python supports Match-Case statement, which can also be used as a part of decision
making. If a pattern matches the expression, the code under that case will execute.

Example
Following is a simple example which makes use of match statement.

def checkVowel(n):
match n:
case 'a': return "Vowel alphabet"
case 'e': return "Vowel alphabet"
case 'i': return "Vowel alphabet"
case 'o': return "Vowel alphabet"
case 'u': return "Vowel alphabet"
case _: return "Simple alphabet"
print (checkVowel('a'))
print (checkVowel('m'))
print (checkVowel('o'))

This will produce following result:

Vowel alphabet

178
Python Tutorial

Simple alphabet
Vowel alphabet

Loops or Iteration Statements


Most of the processes require a group of instructions to be repeatedly executed. In
programming terminology, it is called a loop. Instead of the next step, if the flow is
redirected towards any earlier step, it constitutes a loop.

The following diagram illustrates how the looping works −

If the control goes back unconditionally, it forms an infinite loop which is not desired as
the rest of the code would never get executed.

In a conditional loop, the repeated iteration of block of statements goes on till a certain
condition is met. Python supports a number of loops like for loop, while loop which we
will study in next chapters.

The for Loop


The for loop iterates over the items of any sequence, such as a list, tuple or a string.

Example
Following is an example which makes use of For Loop to iterate through an array in
Python:

words = ["one", "two", "three"]


for x in words:

179
Python Tutorial

print(x)

This will produce following result:

one
two
three

The while Loop


The while loop repeatedly executes a target statement as long as a given boolean
expression is true.

Example
Following is an example which makes use of While Loop to print first 5 numbers in
Python:

i = 1
while i < 6:
print(i)
i += 1

This will produce following result:

1
2
3
4
5

Jump Statements
The jump statements are used to jump on a specific statement by breaking the current
flow of the program. In Python, there are two jump statements break and continue.

The break Statement


It terminates the current loop and resumes execution at the next statement.

Example
The following example demonstrates the use of break statement −

x = 0

180
Python Tutorial

while x < 10:


print("x:", x)
if x == 5:
print("Breaking...")
break
x += 1

print("End")

This will produce following result:

x: 0
x: 1
x: 2
x: 3
x: 4
x: 5
Breaking...
End

The continue Statement


It skips the execution of the program block and returns the control to the beginning of
the current loop to start the next iteration.

Example
The following example demonstrates the use of continue statement −

for letter in "Python":


# continue when letter is 'h'
if letter == "h":
continue
print("Current Letter :", letter)

This will produce following result:

Current Letter : P
Current Letter : y
Current Letter : t

181
Python Tutorial

Current Letter : o
Current Letter : n

182
30. Python - Decision Making Python Tutorial

Python's decision making functionality is in its keywords − if..elif...else. The if keyword


requires a boolean expression, followed by colon (:) symbol. The colon (:) symbol starts
an indented block. The statements with the same level of indentation are executed if the
boolean expression in if statement is True. If the expression is not True (False), the
interpreter bypasses the indented block and proceeds to execute statements at earlier
indentation level.

Decision structures evaluate multiple expressions which produce TRUE or FALSE as


outcome. You need to determine which action to take and which statements to execute if
outcome is TRUE or FALSE otherwise.

Following is the general form of a typical decision making structure found in most of the
programming languages −

Python programming language assumes any non-zero and non-null values as TRUE, and
if it is either zero or null, then it is assumed as FALSE value.

Types of Decision Making Statements in Python


Python programming language provides following types of decision making statements.
Click the following links to check their detail.

Sr.No. Statement & Description


1 if statements

183
Python Tutorial

An if statement consists of a boolean


expression followed by one or more
statements.
if...else statements

2 An if statement can be followed by an


optional else statement, which executes
when the boolean expression is FALSE.
nested if statements
3 You can use one if or else if statement
inside another if or else if statement(s).

Let us go through each decision making briefly −

Single Statement Suites


If the suite of an if clause consists only of a single line, it may go on the same line as the
header statement.

Example
Here is an example of a one-line if clause −

var = 100
if ( var == 100 ) : print ("Value of expression is 100")
print ("Good bye!")

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

Value of expression is 100


Good bye!

if...else statement
In this decision making statement, if the if condition is true, then the statements within
this block are executed, otherwise, the else block is executed.

The program will choose which block of code to execute based on whether the condition
in the if statement is true or false.

Example
The following example shows the use of if...else statement.

var = 100
if ( var == 100 ):
print ("Value of var is equal to 100")

184
Python Tutorial

else:
print("Value of var is not equal to 100")

On running the above code, it will show the following output −

Value of var is equal to 100

Nested if statements
A nested if is another decision making statement in which one if statement resides inside
another. It allows us to check multiple conditions sequentially.

Example
In this example, we will see the use of nested-if statement.

var = 100
if ( var == 100 ):
print("The number is equal to 100")
if var % 2 == 0:
print("The number is even")
else:
print("The given number is odd")
elif var == 0:
print("The given number is zero")
else:
print("The given number is negative")

On executing the above code, it will display the below output −

The number is equal to 100


The number is even

185
31. Python - if Statement Python Tutorial

Python If Statement
The if statement in Python evaluates whether a condition is true or false. It contains a
logical expression that compares data, and a decision is made based on the result of the
comparison.

Syntax of the if Statement


if expression:
# statement(s) to be executed

If the boolean expression evaluates to TRUE, then the statement(s) inside the if block is
executed. If boolean expression evaluates to FALSE, then the first set of code after the
end of the if block is executed.

Flow Diagram (Flowchart) of the if Statement


The below diagram shows flowchart of the if statement −

Example of Python if Statement


Let us consider an example of a customer entitled to 10% discount if his purchase
amount is > 1000; if not, then no discount is applicable. The following flowchart shows
the whole decision making process −

186
Python Tutorial

First, set a discount variable to 0 and an amount variable to 1200. Then, use an if
statement to check whether the amount is greater than 1000. If this condition is true,
calculate the discount amount. If a discount is applicable, deduct it from the original
amount.

Python code for the above flowchart can be written as follows −

discount = 0
amount = 1200

# Check he amount value


if amount > 1000:
discount = amount * 10 / 100

print("amount = ", amount - discount)

187
Python Tutorial

Here the amout is 1200, hence discount 120 is deducted. On executing the code, you will
get the following output −

amount = 1080.0

Change the variable amount to 800, and run the code again. This time, no discount is
applicable. And, you will get the following output −

amount = 800

188
32. Python if-else Statement Python Tutorial

Python if else Statement

The if-else statement in Python is used to execute a block of code when the condition in
the if statement is true, and another block of code when the condition is false.

Syntax of if-else Statement


The syntax of an if-else statement in Python is as follows −

if boolean_expression:
# code block to be executed
# when boolean_expression is true
else:
# code block to be executed
# when boolean_expression is false

If the boolean expression evaluates to TRUE, then the statement(s) inside the if block
will be executed otherwise statements of the else block will be executed.

Flowchart of if-else Statement


This flowchart shows how if-else statement is used −

189
Python Tutorial

If the expr is True, block of stmt1, 2, 3 is executed then the default flow continues with
stmt7. However, if the expr is False, block stmt4, 5, 6 runs then the default flow
continues.

Python implementation of the above flowchart is as follows −

if expr==True:
stmt1
stmt2
stmt3
else:
stmt4
stmt5
stmt6
Stmt7

Python if-else Statement Example


Let us understand the use of if-else statements with the following example. Here,
variable age can take different values. If the expression age > 18 is true, then eligible to
vote message will be displayed otherwise not eligible to vote message will be displayed.
Following flowchart illustrates this logic −

190
Python Tutorial

Now, let's see the Python implementation the above flowchart.

age=25
print ("age: ", age)
if age >=18:
print ("eligible to vote")
else:
print ("not eligible to vote")

On executing this code, you will get the following output −

age: 25
eligible to vote

To test the else block, change the age to 12, and run the code again.

age: 12
not eligible to vote

Python if elif else Statement


The if elif else statement allows you to check multiple expressions for TRUE and execute
a block of code as soon as one of the conditions evaluates to TRUE.

Similar to the else block, the elif block is also optional. However, a program can contain
only one else block whereas there can be an arbitrary number of elif blocks following an
if block.

191
Python Tutorial

Syntax of Python if elif else Statement


if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)

How if elif else Works?


The keyword elif is a short form of else if. It allows the logic to be arranged in a cascade
of elif statements after the first if statement. If the first if statement evaluates to false,
subsequent elif statements are evaluated one by one and comes out of the cascade if
any one is satisfied.

Last in the cascade is the else block which will come in picture when all preceding if/elif
conditions fails.

Example
Suppose there are different slabs of discount on a purchase −

 20% on amount exceeding 10000,


 10% for amount between 5-10000,
 5% if it is between 1 to 5000.
 no discount if amount<1000

The following flowchart illustrates these conditions −

192
Python Tutorial

We can write a Python code for the above logic with if-else statements −

amount = 2500
print('Amount = ',amount)
if amount > 10000:
discount = amount * 20 / 100
else:
if amount > 5000:
discount = amount * 10 / 100
else:
if amount > 1000:
discount = amount * 5 / 100
else:
discount = 0

print('Payable amount = ',amount - discount)

Set amount to test all possible conditions: 800, 2500, 7500 and 15000. The outputs will
vary accordingly −

Amount: 800
Payable amount = 800
Amount: 2500

193
Python Tutorial

Payable amount = 2375.0


Amount: 7500
Payable amount = 6750.0
Amount: 15000
Payable amount = 12000.0

While the code will work perfectly fine, if you look at the increasing level of indentation
at each if and else statement, it will become difficult to manage if there are still more
conditions.

Python if elif else Statement Example


The elif statement makes the code easy to read and comprehend. Following is the
Python code for the same logic with if elif else statements −

amount = 2500
print('Amount = ',amount)
if amount > 10000:
discount = amount * 20 / 100
elif amount > 5000:
discount = amount * 10 / 100
elif amount > 1000:
discount = amount * 5 / 100
else:
discount=0

print('Payable amount = ',amount - discount)

The output of the above code is as follows −

Amount: 2500
Payable amount = 2375.0

194
33. Python - Nested if StatementPython Tutorial

Python supports nested if statements which means we can use a conditional if and if...else
statement inside an existing if statement.
There may be a situation when you want to check for additional conditions after the initial
one resolves to true. In such a situation, you can use the nested if construct.
Additionally, within a nested if construct, you can include an if...elif...else construct inside
another if...elif...else construct.

Syntax of Nested if Statement


The syntax of the nested if construct with else condition will be like this −

if boolean_expression1:
statement(s)
if boolean_expression2:
statement(s)

Flowchart of Nested if Statement


Following is the flowchart of Python nested if statement −

Example of Nested if Statement


The below example shows the working of nested if statements −

195
Python Tutorial

num = 36
print ("num = ", num)
if num % 2 == 0:
if num % 3 == 0:
print ("Divisible by 3 and 2")
print("....execution ends....")

When you run the above code, it will display the following result −

num = 36
Divisible by 3 and 2
....execution ends....

Nested if Statement with else Condition


As mentioned earlier, we can nest if-else statement within an if statement. If the if
condition is true, the first if-else statement will be executed otherwise, statements inside
the else block will be executed.

Syntax
The syntax of the nested if construct with else condition will be like this −

if expression1:
statement(s)
if expression2:
statement(s)
else
statement(s)
else:
if expression3:
statement(s)
else:
statement(s)

Example
Now let's take a Python code to understand how it works −

num=8
print ("num = ",num)
if num%2==0:
if num%3==0:

196
Python Tutorial

print ("Divisible by 3 and 2")


else:
print ("divisible by 2 not divisible by 3")
else:
if num%3==0:
print ("divisible by 3 not divisible by 2")
else:
print ("not Divisible by 2 not divisible by 3")

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

num = 8
divisible by 2 not divisible by 3
num = 15
divisible by 3 not divisible by 2
num = 12
Divisible by 3 and 2
num = 5
not Divisible by 2 not divisible by 3

197
34. Python - Match-Case Statement
Python Tutorial

Python match-case Statement


A Python match-case statement takes an expression and compares its value to successive
patterns given as one or more case blocks. Only the first pattern that matches gets
executed. It is also possible to extract components (sequence elements or object
attributes) from the value into variables.
With the release of Python 3.10, a pattern matching technique called match-case has been
introduced, which is similar to the switch-case construct available in C/C++/Java etc. Its
basic use is to compare a variable against one or more values. It is more similar to pattern
matching in languages like Rust or Haskell than a switch statement in C or C++.

Syntax
The following is the syntax of match-case statement in Python -

match variable_name:
case 'pattern 1' : statement 1
case 'pattern 2' : statement 2
...
case 'pattern n' : statement n

Example
The following code has a function named weekday(). It receives an integer argument,
matches it with all possible weekday number values, and returns the corresponding name
of day.

def weekday(n):
match n:
case 0: return "Monday"
case 1: return "Tuesday"
case 2: return "Wednesday"
case 3: return "Thursday"
case 4: return "Friday"
case 5: return "Saturday"
case 6: return "Sunday"
case _: return "Invalid day number"
print (weekday(3))
print (weekday(6))
print (weekday(7))

198
Python Tutorial

On executing, this code will produce the following output −

Thursday
Sunday
Invalid day number

The last case statement in the function has "_" as the value to compare. It serves as the
wildcard case, and will be executed if all other cases are not true.

Combined Cases in Match Statement


Sometimes, there may be a situation where for more than one cases, a similar action has
to be taken. For this, you can combine cases with the OR operator represented by "|"
symbol.
Example
The code below shows how to combine cases in match statement. It defines a function
named access() and has one string argument, representing the name of the user. For
admin or manager user, the system grants full access; for Guest, the access is limited;
and for the rest, there's no access.

def access(user):
match user:
case "admin" | "manager": return "Full access"
case "Guest": return "Limited access"
case _: return "No access"
print (access("manager"))
print (access("Guest"))
print (access("Ravi"))

On running the above code, it will show the following result −

Full access
Limited access
No access

List as the Argument in Match Case Statement


Since Python can match the expression against any literal, you can use a list as a case
value. Moreover, for variable number of items in the list, they can be parsed to a sequence
with "*" operator.
Example
In this code, we use list as argument in match case statement.

def greeting(details):
match details:
case [time, name]:

199
Python Tutorial

return f'Good {time} {name}!'


case [time, *names]:
msg=''
for name in names:
msg+=f'Good {time} {name}!\n'
return msg

print (greeting(["Morning", "Ravi"]))


print (greeting(["Afternoon","Guest"]))
print (greeting(["Evening", "Kajal", "Praveen", "Lata"]))

On executing, this code will produce the following output −

Good Morning Ravi!


Good Afternoon Guest!
Good Evening Kajal!
Good Evening Praveen!
Good Evening Lata!

Using "if" in "Case" Clause


Normally Python matches an expression against literal cases. However, it allows you to
include if statement in the case clause for conditional computation of match variable.
Example
In the following example, the function argument is a list of amount and duration, and the
intereset is to be calculated for amount less than or more than 10000. The condition is
included in the case clause.

def intr(details):
match details:
case [amt, duration] if amt<10000:
return amt*10*duration/100
case [amt, duration] if amt>=10000:
return amt*15*duration/100
print ("Interest = ", intr([5000,5]))
print ("Interest = ", intr([15000,3]))

On executing, this code will produce the following output −

Interest = 2500.0
Interest = 6750.0

200
35. Python - Loops Python Tutorial

Python Loops
Python loops allow us to execute a statement or a group of statements multiple times.
In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on. There may be a situation when you need
to execute a block of code several number of times.
Programming languages provide various control structures that allow for more complicated
execution paths.

Flowchart of a Loop
The following diagram illustrates a loop statement −

Types of Loops in Python


Python programming language provides following types of loops to handle looping
requirements −

Sr.No. Loop Type & Description


while loop
Repeats a statement or group of
1 statements while a given condition is
TRUE. It tests the condition before
executing the loop body.
2 for loop

201
Python Tutorial

Executes a sequence of statements


multiple times and abbreviates the code
that manages the loop variable.
nested loops
3 You can use one or more loop inside any
another while, for or do..while loop.

Python Loop Control Statements


Loop control statements change execution from its normal sequence. When execution
leaves a scope, all automatic objects that were created in that scope are destroyed.
Python supports the following control statements. Click the following links to check their
detail.
Let us go through the loop control statements briefly

Sr.No. Control Statement & Description


break statement

1 Terminates the loop statement and transfers execution to the


statement immediately following the loop.

continue statement

2 Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.

pass statement

3 The pass statement in Python is used when a statement is required


syntactically but you do not want any command or code to
execute.

202
36. Python - For Loops Python Tutorial

The for loop in Python provides the ability to loop over the items of any sequence, such as
a list, tuple or a string. It performs the same action on each item of the sequence. This
loop starts with the for keyword, followed by a variable that represents the current item
in the sequence.
The in keyword links the variable to the sequence you want to iterate over. A colon (:) is
used at the end of the loop header, and the indented block of code beneath it is executed
once for each item in the sequence.

Syntax of Python for Loop


for iterating_var in sequence:
statement(s)

Here, the iterating_var is a variable to which the value of each sequence item will be
assigned during each iteration. Statements represents the block of code that you want to
execute repeatedly.
Before the loop starts, the sequence is evaluated. If it's a list, the expression list (if any)
is evaluated first. Then, the first item (at index 0) in the sequence is assigned to
iterating_var variable.
During each iteration, the block of statements is executed with the current value of
iterating_var. After that, the next item in the sequence is assigned to iterating_var, and
the loop continues until the entire sequence is exhausted.

Flowchart of Python for Loop


The following flow diagram illustrates the working of for loop −

Python for Loop with Strings


A string is a sequence of Unicode letters, each having a positional index. Since, it is a
sequence, you can iterate over its characters using the for loop.

203
Python Tutorial

Example
The following example compares each character and displays if it is not a vowel ('a', 'e',
'i', 'o', 'u').

zen = '''
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
'''
for char in zen:
if char not in 'aeiou':
print (char, end='')

On executing, this code will produce the following output −

Btfl s bttr thn gly.


Explct s bttr thn mplct.
Smpl s bttr thn cmplx.
Cmplx s bttr thn cmplctd.

Python for Loop with Tuples


Python's tuple object is also an indexed sequence, and hence you can traverse its items
with a for loop.
Example
In the following example, the for loop traverses a tuple containing integers and returns
the total of all numbers.

numbers = (34,54,67,21,78,97,45,44,80,19)
total = 0
for num in numbers:
total += num
print ("Total =", total)

On running this code, it will produce the following output −

Total = 539

Python for Loop with Lists


Python's list object is also an indexed sequence, and hence you can iterate over its items
using a for loop.
Example

204
Python Tutorial

In the following example, the for loop traverses a list containing integers and prints only
those which are divisible by 2.

numbers = [34,54,67,21,78,97,45,44,80,19]
total = 0
for num in numbers:
if num%2 == 0:
print (num)

When you execute this code, it will show the following result −

34
54
78
44
80

Python for Loop with Range Objects


Python's built-in range() function returns an iterator object that streams a sequence of
numbers. This object contains integers from start to stop, separated by step parameter.
You can run a for loop with range as well.

Syntax
The range() function has the following syntax −

range(start, stop, step)

Where,
 Start − Starting value of the range. Optional. Default is 0
 Stop − The range goes upto stop-1
 Step − Integers in the range increment by the step value. The default is 1.
Example
In this example, we will see the use of range with for loop.

for num in range(5):


print (num, end=' ')
print()
for num in range(10, 20):
print (num, end=' ')
print()
for num in range(1, 10, 2):
print (num, end=' ')

When you run the above code, it will produce the following output −

205
Python Tutorial

0 1 2 3 4
10 11 12 13 14 15 16 17 18 19
1 3 5 7 9

Python for Loop with Dictionaries


Unlike a list, tuple or a string, dictionary data type in Python is not a sequence, as the
items do not have a positional index. However, traversing a dictionary is still possible with
the for loop.
Example
Running a simple for loop over the dictionary object traverses the keys used in it.

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}


for x in numbers:
print (x)

On executing, this code will produce the following output −

10
20
30
40

Once we are able to get the key, its associated value can be easily accessed either by
using square brackets operator or with the get() method.
Example
The following example illustrates the above mentioned approach.

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}


for x in numbers:
print (x,":",numbers[x])

It will produce the following output −

10 : Ten
20 : Twenty
30 : Thirty
40 : Forty

The items(), keys() and values() methods of dict class return the view objects dict_items,
dict_keys and dict_values respectively. These objects are iterators, and hence we can run
a for loop over them.

Example

206
Python Tutorial

The dict_items object is a list of key-value tuples over which a for loop can be run as
follows −

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}


for x in numbers.items():
print (x)

It will produce the following output −

(10, 'Ten')
(20, 'Twenty')
(30, 'Thirty')
(40, 'Forty')

Using else Statement with For Loop


Python supports else statements associated with a loop statement. However, the else
statement is executed when the loop has exhausted iterating the list.
Example
The following example illustrates the combination of an else statement with a for
statement that searches for prime numbers from 10 to 20.

#For loop to iterate between 10 to 20


for num in range(10, 20):
#For loop to iterate on the factors
for i in range(2,num):
#If statement to determine the first factor
if num%i == 0:
#To calculate the second factor
j=num/i
print ("%d equals %d * %d" % (num,i,j))
#To move to the next number
break
else:
print (num, "is a prime number")
break

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

10 equals 2 * 5
11 is a prime number
12 equals 2 * 6
13 is a prime number

207
Python Tutorial

14 equals 2 * 7
15 equals 3 * 5
16 equals 2 * 8
17 is a prime number
18 equals 2 * 9
19 is a prime number

208
37. Python for-else Loops Python Tutorial

Python - For Else Loop


Python supports an optional else block to be associated with a for loop. If a else block is
used with a for loop, it is executed only when the for loop terminates normally.
The for loop terminates normally when it completes all its iterations without encountering
a break statement, which allows us to exit the loop when a certain condition is met.

Flowchart of For Else Loop


The following flowchart illustrates use of for-else loop −

Syntax of For Else Loop


Following is the syntax of for loop with optional else block −

for variable_name in iterable:


#stmts in the loop
.
.
.
else:
#stmts in else clause
.
.

Example of For Else Loop

209
Python Tutorial

The following example illustrates the combination of an else statement with a for
statement in Python. Till the count is less than 5, the iteration count is printed. As it
becomes 5, the print statement in else block is executed, before the control is passed to
the next statement in the main program.

for count in range(6):


print ("Iteration no. {}".format(count))
else:
print ("for loop over. Now in else block")
print ("End of for loop")

On executing, this code will produce the following output −

Iteration no. 1
Iteration no. 2
Iteration no. 3
Iteration no. 4
Iteration no. 5
for loop over. Now in else block
End of for loop

For-Else Construct without break statement


As mentioned earlier in this tutorial, the else block executes only when the loop terminates
normally i.e. without using break statement.
In the following program, we use the for-else loop without break statement.

for i in ['T','P']:
print(i)
else:
# Loop else statement
# there is no break statement in for loop, hence else part gets executed
directly
print("ForLoop-else statement successfully executed")

On executing, the above program will generate the following output −

T
P
ForLoop-else statement successfully executed

210
Python Tutorial

For-Else Construct with break statement


In case of forceful termination (by using break statement) of the loop, else statement is
overlooked by the interpreter and hence its execution is skipped.
Example
The following program shows how else conditions work in case of a break statement.

for i in ['T','P']:
print(i)
break
else:
# Loop else statement
# terminated after 1st iteration due to break statement in for loop
print("Loop-else statement successfully executed")

On executing, the above program will generate the following output −

For-Else with break statement and if conditions


If we use for-else construct with break statement and if condition, the for loop will iterate
over the iterators and within this loop, you can use an if block to check for a specific
condition. If the loop completes without encountering a break statement, the code in the
else block is executed.
Example
The following program shows how else conditions works in case of break statement and
conditional statements.

# creating a function to check whether the list item is a positive


# or a negative number
def positive_or_negative():
# traversing in a list
for i in [5,6,7]:
# checking whether the list element is greater than 0
if i>=0:
# printing positive number if it is greater than or equal to 0
print ("Positive number")
else:
# Else printing Negative number and breaking the loop
print ("Negative number")
break
# Else statement of the for loop

211
Python Tutorial

else:
# Statement inside the else block
print ("Loop-else Executed")
# Calling the above-created function
positive_or_negative()

On executing, the above program will generate the following output −

Positive number
Positive number
Positive number
Loop-else Executed

212
38. Python - While Loops Python Tutorial

Python while Loop


A while loop in Python programming language repeatedly executes a target statement as
long as the specified boolean expression is true. This loop starts with while keyword
followed by a boolean expression and colon symbol (:). Then, an indented block of
statements starts.
Here, statement(s) may be a single statement or a block of statements with uniform
indent. The condition may be any expression, and true is any non-zero value. As soon as
the expression becomes false, the program control passes to the line immediately following
the loop.
If it fails to turn false, the loop continues to run, and doesn't stop unless forcefully stopped.
Such a loop is called infinite loop, which is undesired in a computer program.

Syntax of while Loop


The syntax of a while loop in Python programming language is −

while expression:
statement(s)

In Python, all the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python uses
indentation as its method of grouping statements.

Flowchart of While loop


The following flow diagram illustrates the while loop −

Example 1
The following example illustrates the working of while loop. Here, the iteration run till value
of count will become 5.

count=0

213
Python Tutorial

while count<5:
count+=1
print ("Iteration no. {}".format(count))

print ("End of while loop")

On executing, this code will produce the following output −

Iteration no. 1
Iteration no. 2
Iteration no. 3
Iteration no. 4
Iteration no. 5
End of while loop

Example 2
Here is another example of using the while loop. For each iteration, the program asks for
user input and keeps repeating till the user inputs a non-numeric string. The isnumeric()
function returns true if input is an integer, false otherwise.

var = '0'
while var.isnumeric() == True:
var = "test"
if var.isnumeric() == True:
print ("Your input", var)
print ("End of while loop")

On running the code, it will produce the following output −

enter a number..10
Your input 10
enter a number..100
Your input 100
enter a number..543
Your input 543
enter a number..qwer
End of while loop

Python Infinite while Loop


A loop becomes infinite if a condition never becomes FALSE. You must be cautious when
using while loops because of the possibility that this condition never resolves to a FALSE
value. This results in a loop that never ends. Such a loop is called an infinite loop.

214
Python Tutorial

An infinite loop might be useful in client/server programming where the server needs to
run continuously so that client programs can communicate with it as and when required.
Example
Let's take an example to understand how the infinite loop works in Python −

var = 1
while var == 1 : # This constructs an infinite loop
num = int(input("Enter a number :"))
print ("You entered: ", num)
print ("Good bye!")

On executing, this code will produce the following output −

Enter a number :20


You entered: 20
Enter a number :29
You entered: 29
Enter a number :3
You entered: 3
Enter a number :11
You entered: 11
Enter a number :22
You entered: 22
Enter a number :Traceback (most recent call last):
File "examples\test.py", line 5, in
num = int(input("Enter a number :"))
KeyboardInterrupt

The above example goes in an infinite loop and you need to use CTRL+C to exit
the program.

Python while-else Loop


Python supports having an else statement associated with a while loop. If the else
statement is used with a while loop, the else statement is executed when the condition
becomes false before the control shifts to the main line of execution.

Flowchart of While loop with else Statement


The following flow diagram shows how to use else statement with while loop −

215
Python Tutorial

Example
The following example illustrates the combination of an else statement with a while
statement. Till the count is less than 5, the iteration count is printed. As it becomes 5, the
print statement in else block is executed, before the control is passed to the next statement
in the main program.

count=0
while count<5:
count+=1
print ("Iteration no. {}".format(count))
else:
print ("While loop over. Now in else block")
print ("End of while loop")

On running the above code, it will print the following output −

Iteration no. 1
Iteration no. 2
Iteration no. 3
Iteration no. 4
Iteration no. 5
While loop over. Now in else block
End of while loop

Single Statement Suites


Similar to the if statement syntax, if your while clause consists only of a single statement,
it may be placed on the same line as the while header.
Example
The following example shows how to use one-line while clause.

flag = 0
while (flag): print ("Given flag is really true!")

216
Python Tutorial

print ("Good bye!")

When you run this code, it will display the following output −

Good bye!

Change the flag value to "1" and try the above program. If you do so, it goes into infinite
loop and you need to press CTRL+C keys to exit.

217
39. Python - break Statement Python Tutorial

Python break Statement


Python break statement is used to terminate the current loop and resumes execution at
the next statement, just like the traditional break statement in C.
The most common use for Python break statement is when some external condition is
triggered requiring a sudden exit from a loop. The break statement can be used in both
Python while and for loops.
If you are using nested loops in Python, the break statement stops the execution of the
innermost loop and start executing the next line of code after the block.

Syntax of break Statement


The syntax for a break statement in Python is as follows −

looping statement:
condition check:
break

Flow Diagram of break Statement


Following is the flowchart of the break statement −

break Statement with for loop


If we use break statement inside a for loop, it interrupts the normal flow of program and
exit the loop before completing the iteration.

218
Python Tutorial

Example
In this example, we will see the working of break statement in for loop.

for letter in 'Python':


if letter == 'h':
break
print ("Current Letter :", letter)
print ("Good bye!")

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

Current Letter : P
Current Letter : y
Current Letter : t
Good bye!
break Statement with while loop

Similar to the for loop, we can use the break statement to skip the code inside while loop
after the specified condition becomes TRUE.
Example
The code below shows how to use break statement with while loop.

var = 10
while var > 0:
print ('Current variable value :', var)
var = var -1
if var == 5:
break

print ("Good bye!")

On executing the above code, it produces the following result −

Current variable value : 10


Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Good bye!

219
Python Tutorial

break Statement with Nested Loops


In nested loops, one loop is defined inside another. The loop that enclose another loop
(i.e. inner loop) is called as outer loop.
When we use a break statement with nested loops, it behaves as follows −
When break statement is used inside the inner loop, only the inner loop will be skipped
and the program will continue executing statements after the inner loop
And, when the break statement is used in the outer loop, both the outer and inner loops
will be skipped and the program will continue executing statements immediate to the outer
loop.
Example
The following program demonstrates the use of break in a for loop iterating over a list.
Here, the specified number will be searched in the list. If it is found, then the loop
terminates with the "found" message.

no = 33
numbers = [11,33,55,39,55,75,37,21,23,41,13]
for num in numbers:
if num == no:
print ('number found in list')
break
else:
print ('number not found in list')

The above program will produce the following output −

number found in list

220
40. Python - Continue StatementPython Tutorial

Python continue Statement


Python continue statement is used to skip the execution of the program block and returns
the control to the beginning of the current loop to start the next iteration. When
encountered, the loop starts next iteration without executing the remaining statements in
the current iteration.
The continue statement is just the opposite to that of break. It skips the remaining
statements in the current loop and starts the next iteration.

Syntax of continue Statement


looping statement:
condition check:
continue

Flow Diagram of continue Statement


The flow diagram of the continue statement looks like this −

Python continue Statement with for Loop


In Python, the continue statement is allowed to be used with a for loop. Inside the for
loop, you should include an if statement to check for a specific condition. If the condition
becomes TRUE, the continue statement will skip the current iteration and proceed with the
next iteration of the loop.
Example
Let's see an example to understand how the continue statement works in for loop.

221
Python Tutorial

for letter in 'Python':


if letter == 'h':
continue
print ('Current Letter :', letter)
print ("Good bye!")

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

Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Good bye!

Python continue Statement with while Loop


Python continue statement is used with 'for' loops as well as 'while' loops to skip the
execution of the current iteration and transfer the program's control to the next iteration.
Example: Checking Prime Factors
Following code uses continue statement to find the prime factors of a given number. To
find prime factors, we need to successively divide the given number starting with 2,
increment the divisor and continue the same process till the input reduces to 1.

num = 60
print ("Prime factors for: ", num)
d=2
while num > 1:
if num%d==0:
print (d)
num=num/d
continue
d=d+1

On executing, this code will produce the following output −

Prime factors for: 60


2
2
3
5

222
Python Tutorial

Assign different value (say 75) to num in the above program and test the result for its
prime factors.

Prime factors for: 75


3
5
5

223
41. Python - pass Statement Python Tutorial

Python pass Statement


Python pass statement is used when a statement is required syntactically but you do not
want any command or code to execute. It is a null which means nothing happens when it
executes. This is also useful in places where piece of code will be added later, but a
placeholder is required to ensure the program runs without errors.
For instance, in a function or class definition where the implementation is yet to be written,
pass statement can be used to avoid the SyntaxError. Additionally, it can also serve as a
placeholder in control flow statements like for and while loops.

Syntax of pass Statement


Following is the syntax of Python pass statement −

pass

Example of pass Statement


The following code shows how you can use the pass statement in Python −

for letter in 'Python':


if letter == 'h':
pass
print ('This is pass block')
print ('Current Letter :', letter)
print ("Good bye!")

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

Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!

Dumpy Infinite Loop with pass Statement


This is simple enough to create an infinite loop using pass statement in Python.
Example

224
Python Tutorial

If you want to code an infinite loop that does nothing each time through, do it as shown
below −

while True: pass


# Type Ctrl-C to stop

Because the body of the loop is just an empty statement, Python gets stuck in this loop.

Using Ellipses (...) as pass Statement Alternative


Python 3.X allows ellipses (coded as three consecutive dots ...) to be used in place of pass
statement. Both serve as placeholders for code that are going to be written later.
Example
For example if we create a function which does not do anything especially for code to be
filled in later, then we can make use of ...

def func1():
# Alternative to pass
...

# Works on same line too


def func2(): ...
# Does nothing if called
func1()
func2()

225
42. Python - Nested Loops Python Tutorial

In Python, when you write one or more loops within a loop statement that is known as a
nested loop. The main loop is considered as outer loop and loop(s) inside the outer loop
are known as inner loops.
The Python programming language allows the usage of one loop inside another loop. A
loop is a code block that executes specific instructions repeatedly. There are two types of
loops, namely for and while, using which we can create nested loops.

You can put any type of loop inside of any other type of loop. For example, a
for loop can be inside a while loop or vice versa.

Python Nested for Loop


The for loop with one or more inner for loops is called nested for loop. A for loop is used
to loop over the items of any sequence, such as a list, tuple or a string and performs the
same action on each item of the sequence.

Python Nested for Loop Syntax


The syntax for a Python nested for loop statement in Python programming language is as
follows −

for iterating_var in sequence:


for iterating_var in sequence:
statements(s)
statements(s)

Python Nested for Loop Example


The following program uses a nested for loop to iterate over months and days lists.

months = ["jan", "feb", "mar"]


days = ["sun", "mon", "tue"]

for x in months:
for y in days:
print(x, y)

print("Good bye!")

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

jan sun
jan mon

226
Python Tutorial

jan tue
feb sun
feb mon
feb tue
mar sun
mar mon
mar tue
Good bye!

Python Nested while Loop


The while loop having one or more inner while loops are nested while loop. A while loop is
used to repeat a block of code for an unknown number of times until the specified boolean
expression becomes TRUE.

Python Nested while Loop Syntax


The syntax for a nested while loop statement in Python programming language is as follows

while expression:
while expression:
statement(s)
statement(s)

Python Nested while Loop Example


The following program uses a nested while loop to find the prime numbers from 2 to 100

i = 2
while(i < 25):
j = 2
while(j <= (i/j)):
if not(i%j): break
j = j + 1
if (j > i/j) : print (i, " is prime")
i = i + 1

print ("Good bye!")

On executing, the above code produces following result −

2 is prime
3 is prime
227
Python Tutorial

5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
Good bye!

228
Python Tutorial

Python Functions & Modules

229
43. Python - Functions Python Tutorial

A Python 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.
A top-to-down approach towards building the processing logic involves defining blocks of
independent reusable functions. A Python function may be invoked from any other function
by passing required data (called parameters or arguments). The called function returns its
result back to the calling environment.

Types of Python Functions


Python provides the following types of functions −

Sr.No Type & Description


Built-in functions
Python's standard library includes number of built-in functions. Some of
1 Python's built-in functions are print(), int(), len(), sum(), etc. These
functions are always available, as they are loaded into computer's memory
as soon as you start Python interpreter.
Functions defined in built-in modules

2 The standard library also bundles a number of modules. Each module


defines a group of functions. These functions are not readily available. You
need to import them into the memory from their respective modules.
User-defined functions

3 In addition to the built-in functions and functions in the built-in modules,


you can also create your own functions. These functions are called user-
defined functions.

Defining a Python Function

230
Python Tutorial

You can define custom 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 to Define a Python Function


def function_name( parameters ):
"function_docstring"
function_suite
return [expression]

By default, parameters have a positional behavior and you need to add the values in the
same order that they were defined.
Once the function is defined, you can execute it by calling it from another function or
directly from the Python prompt.
Example to Define a Python Function
The following example shows how to define a function greetings(). The bracket is empty
so there aren't any parameters. Here, the first line is a docstring and the function block
ends with return statement.

def greetings():
"This is docstring of greetings function"
print ("Hello World")
return

When this function is called, Hello world message will be printed.

Calling a Python 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 call it by using the function name itself. If the function requires any
parameters, they should be passed within parentheses. If the function doesn't require any
parameters, the parentheses should be left empty.
Example to Call a Python Function
Following is the example to call printme() function −

# Function definition is here

231
Python Tutorial

def printme( str ):


"This prints a passed string into this function"
print (str)
return;

# Now you can call the 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 output −

I'm first call to user defined function!


Again second call to the same function

Pass by Reference vs Value


In programming languages like C and C++, there are two main ways to pass variables to
a function, which are Call by Value and Call by Reference (also known as pass by reference
and pass by value). However, the way we pass variables to functions in Python differs
from others.
 call by value − When a variable is passed to a function while calling, the value of
actual arguments is copied to the variables representing the formal arguments.
Thus, any changes in formal arguments does not get reflected in the actual
argument. This way of passing variable is known as call by value.
 call by reference − In this way of passing variable, a reference to the object in
memory is passed. Both the formal arguments and the actual arguments (variables
in the calling code) refer to the same object. Hence, any changes in formal
arguments does get reflected in the actual argument.

Python uses pass by reference mechanism. As variable in Python is a label or reference to


the object in the memory, both the variables used as actual argument as well as formal
arguments really refer to the same object in the memory. We can verify this fact by
checking the id() of the passed variable before and after passing.
Example
In the following example, we are checking the id() of a variable.

232
Python Tutorial

def testfunction(arg):
print ("ID inside the function:", id(arg))

var = "Hello"
print ("ID before passing:", id(var))
testfunction(var)

If the above code is executed, the id() before passing and inside the function will be
displayed.

ID before passing: 1996838294128


ID inside the function: 1996838294128

The behavior also depends on whether the passed object is mutable or immutable. Python
numeric object is immutable. When a numeric object is passed, and the function changes
the value of the formal argument, it actually creates a new object in the memory, leaving
the original variable unchanged.
Example
The following example shows how an immutable object behaves when it is passed to a
function.

def testfunction(arg):
print ("ID inside the function:", id(arg))
arg = arg + 1
print ("new object after increment", arg, id(arg))

var=10
print ("ID before passing:", id(var))
testfunction(var)
print ("value after function call", var)

It will produce the following output −

ID before passing: 140719550297160


ID inside the function: 140719550297160
new object after increment 11 140719550297192
value after function call 10

Let us now pass a mutable object (such as a list or dictionary) to a function. It is also
passed by reference, as the id() of list before and after passing is same. However, if we
modify the list inside the function, its global representation also reflects the change.
Example
Here we pass a list, append a new item, and see the contents of original list object, which
we will find has changed.

233
Python Tutorial

def testfunction(arg):
print ("Inside function:",arg)
print ("ID inside the function:", id(arg))
arg=arg.append(100)

var=[10, 20, 30, 40]


print ("ID before passing:", id(var))
testfunction(var)
print ("list after function call", var)

It will produce the following output −

ID before passing: 2716006372544


Inside function: [10, 20, 30, 40]
ID inside the function: 2716006372544
list after function call [10, 20, 30, 40, 100]

Python Function Arguments


Function arguments are the values or variables passed into a function when it is called.
The behavior of a function often depends on the arguments passed to it.
While defining a function, you specify a list of variables (known as formal parameters)
within the parentheses. These parameters act as placeholders for the data that will be
passed to the function when it is called. When the function is called, value to each of the
formal arguments must be provided. Those are called actual arguments.

Example
Let's modify greetings function and use name as an argument. A string passed to the
function as actual argument becomes name variable inside the function.

def greetings(name):
"This is docstring of greetings function"
print ("Hello {}".format(name))
return

234
Python Tutorial

greetings("Samay")
greetings("Pratima")
greetings("Steven")

This code will produce the following output −

Hello Samay
Hello Pratima
Hello Steven

Types of Python Function Arguments


Based on how the arguments are declared while defining a Python function, they are
classified into the following categories −
 Positional or Required Arguments
 Keyword Arguments
 Default Arguments
 Positional-only Arguments
 Keyword-only arguments
 Arbitrary or Variable-length Arguments

Positional or Required Arguments


Required arguments are the ones passed to a function in correct positional order. Here,
the number of arguments in the function call should match exactly with the function
definition, otherwise the code gives a syntax error.
Example
In the code below, we call the function printme() without any parameters which will give
error.

# 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>

235
Python Tutorial

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.
Example 1
The following example shows how to use keyword arguments in Python.

# 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

Example 2
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

236
Python Tutorial

Default Arguments
A default argument assumes a default value if a value is not provided in the function call
for that argument.
Example
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

Positional-only arguments
Those arguments that can only be specified by their position in the function call is called
as Positional-only arguments. They are defined by placing a "/" in the function's parameter
list after all positional-only parameters. This feature was introduced with the release of
Python 3.8.
The benefit of using this type of argument is that it ensures the functions are called with
the correct arguments in the correct order. The positional-only arguments should be
passed to a function as positional arguments, not keyword arguments.
Example
In the following example, we have defined two positional-only arguments namely "x" and
"y". This method should be called with positional arguments in the order in which the
arguments are declared, otherwise, we will get an error.

def posFun(x, y, /, z):


print(x + y + z)

print("Evaluating positional-only arguments: ")

237
Python Tutorial

posFun(33, 22, z=11)

It will produce the following output −

Evaluating positional-only arguments:


66

Keyword-only arguments
Those arguments that must be specified by their name while calling the function is known
as Keyword-only arguments. They are defined by placing an asterisk ("*") in the function's
parameter list before any keyword-only parameters. This type of argument can only be
passed to a function as a keyword argument, not a positional argument.
Example
In the code below, we have defined a function with three keyword-only arguments. To call
this method, we need to pass keyword arguments, otherwise, we will encounter an error.

def posFun(*, num1, num2, num3):


print(num1 * num2 * num3)

print("Evaluating keyword-only arguments: ")


posFun(num1=6, num2=8, num3=5)

It will produce the following output −

Evaluating keyword-only arguments:


240

Arbitrary or 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 non-keyword
variable arguments. This tuple remains empty if no additional arguments are specified
during the function call.
Example
Following is a simple example of Python variable-length arguments.

238
Python Tutorial

# 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

In the next few chapters, we will discuss these function arguments at length.

Order of Python Function Arguments


A function can have arguments of any of the types defined above. However, the arguments
must be declared in the following order −
 The argument list begins with the positional-only args, followed by the slash (/)
symbol.
 It is followed by regular positional args that may or may not be called as keyword
arguments.
 Then there may be one or more args with default values.
 Next, arbitrary positional arguments represented by a variable prefixed with single
asterisk, that is treated as tuple. It is the next.
 If the function has any keyword-only arguments, put an asterisk before their names
start. Some of the keyword-only arguments may have a default value.
 Last in the bracket is argument with two asterisks ** to accept arbitrary number
of keyword arguments.
The following diagram shows the order of formal arguments −

239
Python Tutorial

Python Function with Return Value


The return keyword as the last statement in function definition indicates end of function
block, and the program flow goes back to the calling function. Although reduced indent
after the last statement in the block also implies return but using explicit return is a good
practice.
Along with the flow control, the function can also return value of an expression to the
calling function. The value of returned expression can be stored in a variable for further
processing.
Example
Let us define the add() function. It adds the two values passed to it and returns the
addition. The returned value is stored in a variable called result.

def add(x,y):
z=x+y
return z
a=10
b=20
result = add(a,b)
print ("a = {} b = {} a+b = {}".format(a, b, result))

It will produce the following output −

a = 10 b = 20 a+b = 30

The Anonymous Functions


The functions are called anonymous when they are not declared in the standard manner
by using the def keyword. Instead, they are defined using the lambda keyword.
 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 is 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.

240
Python Tutorial

Syntax
The syntax of lambda functions contains only a single statement, which is as follows −

lambda [arg1 [,arg2,.....argn]]:expression

Example
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

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.
Example
Following is a simple example of local and global scope −

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)

241
Python Tutorial

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

242
44. Python - Default ArgumentsPython Tutorial

Python Default Arguments


Python allows a function definition with default value assigned to one or more formal
arguments. Python uses the default value for such an argument to which no valu has been
assigned. If any value is passed, the default value is overridden with the actual value
passed.

Default arguments in Python are the function arguments that will be used if no
arguments are passed to the function call.

Example of Default Arguments


The following example shows use of Python default arguments. Here, the second call to
the function will not pass value to "city" argument, hence its default value "Hyderabad"
will be used.

# Function definition
def showinfo( name, city = "Hyderabad" ):
"This prints a passed info into this function"
print ("Name:", name)
print ("City:", city)
return

# Now call showinfo function


showinfo(name = "Ansh", city = "Delhi")
showinfo(name = "Shrey")

It will produce the following output −

Name: Ansh
City: Delhi
Name: Shrey
City: Hyderabad

Example: Calling Function Without Keyword Arguments


Let us look at another example that assigns default value to a function argument. The
function percent() has a default argument named "maxmarks" which is set to 200. Hence,
we can omit the value of third argument while calling the function.

# function definition
243
Python Tutorial

def percent(phy, maths, maxmarks=200):


val = (phy + maths) * 100/maxmarks
return val

phy = 60
maths = 70
# function calling with default argument
result = percent(phy, maths)
print ("percentage:", result)

phy = 40
maths = 46
result = percent(phy, maths, 100)
print ("percentage:", result)

On executing, this code will produce the following output −

percentage: 65.0
percentage: 86.0

Mutable Objects as Default Argument


Python evaluates default arguments once when the function is defined, not each time the
function is called. Therefore, if you use a mutable default argument and modify it within
the given function, the same values are referenced in the subsequent function calls.

Those Python objects that can be changed after creation are called as mutable
objects.

Example
The code below explains how to use mutable objects as default argument in Python.

def fcn(nums, numericlist = []):


numericlist.append(nums + 1)
print(numericlist)

# function calls
fcn(66)
fcn(68)
fcn(70)

On executing the above code, it will produce the following output −

244
Python Tutorial

[67]
[67, 69]
[67, 69, 71]

245
45. Python - Keyword ArgumentsPython Tutorial

Keyword Arguments
Python allows to pass function arguments in the form of keywords which are also called
named arguments. Variables in the function definition are used as keywords. When the
function is called, you can explicitly mention the name and its value.

Calling Function with Keyword Arguments


The following example demonstrates keyword arguments in Python. In the second function
call, we have used keyword arguments.

# 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


# by positional arguments
printinfo ("Naveen", 29)

# by keyword arguments
printinfo(name="miki", age = 30)

It will produce the following output −

Name: Naveen
Age 29
Name: miki
Age 30

Order of Keyword Arguments


By default, the function assigns the values to arguments in the order of appearance.
However, while using keyword arguments, it is not necessary to follow the order of formal
arguments in function definition. Use of keyword arguments is optional. You can use mixed
calling. You can pass values to some arguments without keywords, and for others with
keyword.
Example

246
Python Tutorial

Let us try to understand with the help of following function definition −

def division(num, den):


quotient = num/den
print ("num:{} den:{} quotient:{}".format(num, den, quotient))

division(10,5)
division(5,10)

Since the values are assigned as per the position, the output is as follows −

num:10 den:5 quotient:2.0


num:5 den:10 quotient:0.5

Example
Instead of passing the values with positional arguments, let us call the function with
keyword arguments −

def division(num, den):


quotient = num/den
print ("num:{} den:{} quotient:{}".format(num, den, quotient))

division(num=10, den=5)
division(den=5, num=10)

Unlike positional arguments, the order of keyword arguments does not matter. Hence, it
will produce the following output −

num:10 den:5 quotient:2.0


num:10 den:5 quotient:2.0

However, the positional arguments must be before the keyword arguments while using
mixed calling.
Example
Try to call the division() function with the keyword arguments as well as positional
arguments.

def division(num, den):


quotient = num/den
print ("num:{} den:{} quotient:{}".format(num, den, quotient))

division(num = 5, 10)

As the Positional argument cannot appear after keyword arguments, Python raises the
following error message −

247
Python Tutorial

division(num=5, 10)
^
SyntaxError: non-keyword arg after keyword arg

248
46. Python - Keyword-Only Arguments
Python Tutorial

Keyword-Only Arguments
You can use the variables in formal argument list as keywords to pass value. Use of
keyword arguments is optional. But, you can force the function to accept arguments by
keyword only. You should put an astreisk (*) before the keyword-only arguments list.
Let us say we have a function with three arguments, out of which we want second and
third arguments to be keyword-only. For that, put * after the first argument.

Example of Keyword-Only Arguments


The built-in print() function is an example of keyword-only arguments. You can give list of
expressions to be printed in the parentheses. The printed values are separated by a white
space by default. You can specify any other separation character instead using "sep"
argument.

print ("Hello", "World", sep="-")

It will print −

Hello-World

Example: Using "sep" as non-keyword Argument


The sep argument of the print() function is keyword-only. Try using it as non-keyword
argument.

print ("Hello", "World", "-")

You'll get different output, not as desired −

Hello World -

Using Keyword-Only argument in User-Defined Method


To make an argument keyword-only, put the astreisk (*) before it while creating the user-
defined function.
Those Python functions that are defined by us within a given class to perform certain
actions are called as user-defined function. They are not predefined by Python.
Example
In the following user defined function "intr()" the "rate" argument is keyword-only. To call
this function, the value for rate must be passed by keyword.

def intr(amt,*, rate):


val = amt*rate/100
return val

249
Python Tutorial

interest = intr(1000, rate=10)


print(interest)
100.0

However, if you try to use the default positional way of calling the above function, you will
encounter an error.
Example
The code below shows it is not possible to use positional arguments when keyword-only
arguments are required.

def intr(amt, *, rate):


val = amt * rate / 100
return val

interest = intr(1000, 10)


print(interest)

On executing, this code will show the following result −

interest = intr(1000, 10)


^^^^^^^^^^^^^^
TypeError: intr() takes 1 positional argument but 2 were given

250
47. Python - Positional Arguments
Python Tutorial

Positional Arguments
The list of variables declared in the parentheses at the time of defining a function are the
formal arguments. These arguments are also known as positional arguments. A function
may be defined with any number of formal arguments.
While calling a function −
 All the arguments are required.
 The number of actual arguments must be equal to the number of formal arguments.
 They Pick up values in the order of definition.
 The type of arguments must match.
 Names of formal and actual arguments need not be same.

Positional Arguments Examples


Let's discuss some examples of Positional arguments −
Example 1
The following example shows the use of positional argument.

def add(x,y):
z = x+y
print ("x={} y={} x+y={}".format(x,y,z))
a = 10
b = 20
add(a, b)

It will produce the following output −

x=10 y=20 x+y=30

Here, the add() function has two formal arguments, both are numeric. When integers 10
and 20 passed to it. The variable "a" takes 10 and "b" takes 20, in the order of declaration.
The add() function displays the addition.
Example 2
Python also raises error when the number of arguments don't match. If you give only one
argument and check the result you can see an error.

def add(x,y):
z=x+y
print (z)
a=10;
add(a)

251
Python Tutorial

The error generated will be as shown below −

TypeError: add() missing 1 required positional argument: 'y'

Example 3
Similarly, if you pass more than the number of formal arguments an error will be generated
stating the same −

def add(x,y):
z=x+y
print ("x={} y={} x+y={}".format(x,y,z))
add(10, 20, 30)

Following is the output −

TypeError: add() takes 2 positional arguments but 3 were given

Example 4
Data type of corresponding actual and formal arguments must match. Change a to a string
value and see the result.

def add(x,y):
z=x+y
print (z)
a="Hello"
b=20
add(a,b)

It will produce the following error −

z=x+y
~^~
TypeError: can only concatenate str (not "int") to str

Difference between Positional and Keyword argument


The below table explains the difference between positional and keyword argument −

Positional Argument Keyword Argument


Only the names of arguments are
Keyword arguments are passed to a function
used to pass data to the given
in name=value form.
function.
Arguments are passed in the
While passing arguments, their order can be
order defined in function
changed.
declaration.
Syntax: function(param1,
Syntax: function(param1 = value1,...)
param2,...)

252
Python Tutorial

253
48. Python - Positional-Only Arguments
Python Tutorial

Positional Only Arguments


It is possible in Python to define a function in which one or more arguments can not accept
their value with keywords. Such arguments are called positional-only arguments.
To make an argument positional-only, use the forward slash (/) symbol. All the arguments
before this symbol will be treated as positional-only.
Python's built-in input() function is an example of positional-only arguments. The syntax
of input function is −

input(prompt = "")

Prompt is an explanatory string for the benefit of the user. However, you cannot use the
prompt keyword inside the parentheses.
Example
In this example, we are using prompt keyword, which will lead to error.

name = input(prompt="Enter your name ")

On executing, this code will show the following error message −<>

name = input (prompt="Enter your name ")


^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: input() takes no keyword arguments

Positional-Only Arguments Examples


Let's understand positional-only arguments with the help of some examples −
Example 1
In this example, we make both the arguments of intr() function as positional-only by
putting "/" at the end.

def intr(amt, rate, /):


val = amt * rate / 100
return val

print(intr(316200, 4))

When you run the code, it will show the following result −

12648.0

Example 2

254
Python Tutorial

If we try to use the arguments as keywords, Python raises errors as shown in the below
example.

def intr(amt, rate, /):


val = amt * rate / 100
return val

print(intr(amt=1000, rate=10))

On running this code, it will show following error message −

interest = intr(amt=1000, rate=10)


^^^^^^^^^^^^^^^^^^^^^^^
TypeError: intr() got some positional-only arguments passed as keyword
arguments: 'amt, rate'

Example 3
A function may be defined in such a way that it has some keyword-only and some
positional-only arguments. Here, x is a required positional-only argument, y is a regular
positional argument, and z is a keyword-only argument.

def myfunction(x, /, y, *, z):


print (x, y, z)

myfunction(10, y=20, z=30)


myfunction(10, 20, z=30)

The above code will show the following output −

10 20 30
10 20 30

255
49. Python - Arbitrary or, Variable-length Arguments
Python Tutorial

Arbitrary Arguments (*args)


You may want to define a function that is able to accept arbitrary or variable number of
arguments. Moreover, the arbitrary number of arguments might be positional or keyword
arguments.
 An argument prefixed with a single asterisk * for arbitrary positional arguments.
 An argument prefixed with two asterisks ** for arbitrary keyword arguments.

Arbitrary Arguments Example


Given below is an example of arbitrary or variable length positional arguments −

# sum of numbers
def add(*args):
s=0
for x in args:
s=s+x
return s
result = add(10,20,30,40)
print (result)

result = add(1,2,3)
print (result)

The args variable prefixed with "*" stores all the values passed to it. Here, args becomes
a tuple. We can run a loop over its items to add the numbers.
It will produce the following output −

100
6

Required Arguments with Arbitrary Arguments


It is also possible to have a function with some required arguments before the sequence
of variable number of values.
Example
The following example has avg() function. Assume that a student can take any number of
tests. First test is mandatory. He can take as many tests as he likes to better his score.
The function calculates the average of marks in first test and his maximum score in the
rest of tests.

256
Python Tutorial

The function has two arguments, first is the required argument and second to hold any
number of values.

#avg of first test and best of following tests


def avg(first, *rest):
second=max(rest)
return (first+second)/2

result=avg(40,30,50,25)
print (result)

Following call to avg() function passes first value to the required argument first, and the
remaining values to a tuple named rest. We then find the maximum and use it to calculate
the average.
It will produce the following output −

45.0

Arbitrary Keyword Arguments (**kwargs)


If a variable in the argument list has two asterisks prefixed to it, the function can accept
arbitrary number of keyword arguments. The variable becomes a dictionary of
keyword:value pairs.
Example
The following code is an example of a function with arbitrary keyword arguments. The
addr() function has an argument **kwargs which is able to accept any number of address
elements like name, city, phno, pin, etc. Inside the function kwargs dictionary of kw:value
pairs is traversed using items() method.

def addr(**kwargs):
for k,v in kwargs.items():
print ("{}:{}".format(k,v))

print ("pass two keyword args")


addr(Name="John", City="Mumbai")
print ("pass four keyword args")

# pass four keyword args


addr(Name="Raam", City="Mumbai", ph_no="9123134567", PIN="400001")

It will produce the following output −

pass two keyword args


Name:John
City:Mumbai

257
Python Tutorial

pass four keyword args


Name:Raam
City:Mumbai
ph_no:9123134567
PIN:400001

Multiple Arguments with Arbitrary Keyword Arguments


If the function uses mixed types of arguments, the arbitrary keyword arguments should
be after positional, keyword and arbitrary positional arguments in the argument list.
Example
Imagine a case where science and maths are mandatory subjects, in addition to which
student may choose any number of elective subjects.
The following code defines a percent() function where marks in science and marks are
stored in required arguments, and the marks in variable number of elective subjects in
**optional argument.

def percent(math, sci, **optional):


print ("maths:", math)
print ("sci:", sci)
s=math+sci
for k,v in optional.items():
print ("{}:{}".format(k,v))
s=s+v
return s/(len(optional)+2)

result=percent(math=80, sci=75, Eng=70, Hist=65, Geo=72)


print ("percentage:", result)

It will produce the following output −

maths: 80
sci: 75
Eng:70
Hist:65
Geo:72
percentage: 72.4

258
50. Python Variable Scope Python Tutorial

The scope of a variable in Python is defined as the specific area or region where the variable
is accessible to the user. The scope of a variable depends on where and how it is defined.
In Python, a variable can have either a global or a local scope.

Types of Scope for Variables in Python


On the basis of scope, the Python variables are classified in three categories −
 Local Variables
 Global Variables
 Nonlocal Variables

Local Variables
A local variable is defined within a specific function or block of code. It can only be accessed
by the function or block where it was defined, and it has a limited scope. In other words,
the scope of local variables is limited to the function they are defined in and attempting to
access them outside of this function will result in an error. Always remember, multiple
local variables can exist with the same name.
Example
The following example shows the scope of local variables.

def myfunction():
a = 10
b = 20
print("variable a:", a)
print("variable b:", b)
return a+b

print (myfunction())

In the above code, we have accessed the local variables through its function. Hence, the
code will produce the following output −

variable a: 10
variable b: 20
30

Global Variables
A global variable can be accessed from any part of the program, and it is defined outside
any function or block of code. It is not specific to any block or function.
Example

259
Python Tutorial

The following example shows the scope of global variable. We can access them inside as
well as outside of the function scope.

#global variables
name = 'TutorialsPoint'
marks = 50
def myfunction():
# accessing inside the function
print("name:", name)
print("marks:", marks)
# function call
myfunction()

The above code will produce the following output −

name: TutorialsPoint
marks: 50

Nonlocal Variables
The Python variables that are not defined in either local or global scope are called nonlocal
variables. They are used in nested functions.
Example
The following example demonstrates the how nonlocal variables works.

def yourfunction():
a = 5
b = 6
# nested function
def myfunction():
# nonlocal function
nonlocal a
nonlocal b
a = 10
b = 20
print("variable a:", a)
print("variable b:", b)
return a+b
print (myfunction())
yourfunction()

The above code will produce the below output −

260
Python Tutorial

variable a: 10
variable b: 20
30

Namespace and Scope of Python Variables


A namespace is a collection of identifiers, such as variable names, function names, class
names, etc. In Python, namespace is used to manage the scope of variables and to prevent
naming conflicts.
Python provides the following types of namespaces −
 Built-in namespace contains built-in functions and built-in exceptions. They are
loaded in the memory as soon as Python interpreter is loaded and remain till the
interpreter is running.
 Global namespace contains any names defined in the main program. These
names remain in memory till the program is running.
 Local namespace contains names defined inside a function. They are available till
the function is running.
These namespaces are nested one inside the other. Following diagram shows relationship
between namespaces.

The life of a certain variable is restricted to the namespace in which it is defined. As a


result, it is not possible to access a variable present in the inner namespace from any
outer namespace.

Python globals() Function


Python's standard library includes a built-in function globals(). It returns a dictionary of
symbols currently available in global namespace.

261
Python Tutorial

Run the globals() function directly from the Python prompt.

>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__':
<class '_frozen_importlib.BuiltinImporter'>, '__spec__': None,
'__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}

It can be seen that the built-in module which contains definitions of all built-in functions
and built-in exceptions is loaded.
Example
Save the following code that contains few variables and a function with few more variables
inside it.

name = 'TutorialsPoint'
marks = 50
result = True
def myfunction():
a = 10
b = 20
return a+b

print (globals())

Calling globals() from inside this script returns following dictionary object −

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__':


<_frozen_importlib_external.SourceFileLoader object at 0x00000263E7255250>,
'__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins'
(built-in)>, '__file__': 'C:\\Users\\user\\examples\\main.py', '__cached__':
None, 'name': 'TutorialsPoint', 'marks': 50, 'result': True, 'myfunction':
<function myfunction at 0x00000263E72004A0>}

The global namespace now contains variables in the program and their values and the
function object in it (and not the variables in the function).

Python locals() Function


Python's standard library includes a built-in function called locals(). It returns a dictionary
of symbols currently available in the local namespace of the function.
Example
Modify the above script to print dictionary of global and local namespaces from within the
function.

name = 'TutorialsPoint'
marks = 50
result = True
def myfunction():

262
Python Tutorial

a = 10
b = 20
c = a+b
print ("globals():", globals())
print ("locals():", locals())
return c
myfunction()

The output shows that locals() returns a dictionary of variables and their values currently
available in the function.

globals(): {'__name__': '__main__', '__doc__': None, '__package__': None,


'__loader__': <_frozen_importlib_external.SourceFileLoader object at
0x00000169AE265250>, '__spec__': None, '__annotations__': {}, '__builtins__':
<module 'builtins' (built-in)>, '__file__':
'C:\\Users\\mlath\\examples\\main.py', '__cached__': None, 'name':
'TutorialsPoint', 'marks': 50, 'result': True, 'myfunction': <function
myfunction at 0x00000169AE2104A0>}
locals(): {'a': 10, 'b': 20, 'c': 30}

Since both globals() and locals() functions return dictionary, you can access value of a
variable from respective namespace with dictionary get() method or index operator.

print (globals()['name']) # displays TutorialsPoint


print (locals().get('a')) # displays 10

Namespace Conflict in Python


If a variable of same name is present in global as well as local scope, Python interpreter
gives priority to the one in local namespace.
Example
In the following example, we define a local and a global variable.

marks = 50 # this is a global variable


def myfunction():
marks = 70 # this is a local variable
print (marks)

myfunction()
print (marks) # prints global value

It will produce the following output −

70
50

263
Python Tutorial

Example
If you try to manipulate value of a global variable from inside a function, Python raises
UnboundLocalError as shown in example below −

# this is a global variable


marks = 50
def myfunction():
marks = marks + 20
print (marks)

myfunction()
# prints global value
print (marks)

It will produce the following error message −

marks = marks + 20
^^^^^
UnboundLocalError: cannot access local variable 'marks' where it is not
associated with a value

Example
To modify a global variable, you can either update it with a dictionary syntax, or use the
global keyword to refer it before modifying.

var1 = 50 # this is a global variable


var2 = 60 # this is a global variable
def myfunction():
"Change values of global variables"
globals()['var1'] = globals()['var1']+10
global var2
var2 = var2 + 20

myfunction()
print ("var1:",var1, "var2:",var2) #shows global variables with changed values

On executing the code, it will produce the following output −

var1: 60 var2: 80

Example

264
Python Tutorial

Lastly, if you try to access a local variable in global scope, Python raises NameError as the
variable in local scope can't be accessed outside it.

var1 = 50 # this is a global variable


var2 = 60 # this is a global variable
def myfunction(x, y):
total = x+y
print ("Total is a local variable: ", total)

myfunction(var1, var2)
print (total) # This gives NameError

It will produce the following error message −

Total is a local variable: 110


Traceback (most recent call last):
File "C:\Users\user\examples\main.py", line 9, in <module>
print (total) # This gives NameError
^^^^^
NameError: name 'total' is not defined

265
51. Python - Function Annotations
Python Tutorial

Function Annotations
The function annotation feature of Python enables you to add additional explanatory
metadata about the arguments declared in a function definition, and also the return data
types. They are not considered by Python interpreter while executing the function. Python
IDEs use them for providing a detailed documentation to the programmer.
Although you can use the docstring feature of Python for documentation of a function, it
may be obsolete if certain changes in the function's prototype are made. Hence, the
annotation feature was introduced in Python as a result of PEP 3107.
Annotations are any valid Python expressions added to the arguments or return data type.
Simplest example of annotation is to prescribe the data type of the arguments. Annotation
is mentioned as an expression after putting a colon in front of the argument.
Example
Remember that Python is a dynamically typed language, and doesn't enforce any type
checking at runtime. Hence annotating the arguments with data types doesn't have any
effect while calling the function. Even if non-integer arguments are given, Python doesn't
detect any error.

def myfunction(a: int, b: int):


c = a+b
return c

print (myfunction(10,20))
print (myfunction("Hello ", "Python"))

It will produce the following output −

30
Hello Python

Function Annotations with Return Type


Annotations are ignored at runtime, but are helpful for the IDEs and static type checker
libraries such as mypy.
You can give annotation for the return data type as well. After the parentheses and before
the colon symbol, put an arrow (->) followed by the annotation.
Example
In this example, we are providing annotation for return type.

def myfunction(a: int, b: int) -> int:

266
Python Tutorial

c = a+b
return c
print(myfunction(56,88))
print(myfunction.__annotations__)

This will generate the following output −

144
{'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}

Function Annotations with Expression


As using the data type as annotation is ignored at runtime, you can put any expression
which acts as the metadata for the arguments. Hence, function may have any arbitrary
expression as annotation.
Example
In the below example, we are using expression as a function annotation.

def total(x : 'marks in Physics', y: 'marks in chemistry'):


return x+y
print(total(86, 88))
print(total.__annotations__)

Following is the output −

174
{'x': 'marks in Physics', 'y': 'marks in chemistry'}

Function Annotations with Default Arguments


If you want to specify a default argument along with the annotation, you need to put it
after the annotation expression. Default arguments must come after the required
arguments in the argument list.
Example 1
The following example demonstrates how to provide annotation for default arguments of
a function.

def myfunction(a: "physics", b:"Maths" = 20) -> int:


c = a+b
return c
print (myfunction(10))

The function in Python is also an object, and one of its attributes is __annotations__. You
can check with dir() function.

print (dir(myfunction))

267
Python Tutorial

This will print the list of myfunction object containing __annotations__ as one of the
attributes.

['__annotations__', '__builtins__', '__call__', '__class__', '__closure__',


'__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__',
'__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__getstate__',
'__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__',
'__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__',
'__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__']

Example 2
The __annotations__ attribute itself is a dictionary in which arguments are keys and
anotations their values.

def myfunction(a: "physics", b:"Maths" = 20) -> int:


c = a+b
return c
print (myfunction.__annotations__)

It will produce the following output −

{'a': 'physics', 'b': 'Maths', 'return': <class 'int'>}

Example 3
You may have arbitrary positional and/or arbitrary keyword arguments for a function.
Annotations can be given for them also.

def myfunction(*args: "arbitrary args", **kwargs: "arbitrary keyword args") ->


int:
pass
print (myfunction.__annotations__)

It will produce the following output −

{'args': 'arbitrary args', 'kwargs': 'arbitrary keyword args', 'return': <class


'int'>}

Example 4
In case you need to provide more than one annotation expressions to a function argument,
give it in the form of a dictionary object in front of the argument itself.

def division(num: dict(type=float, msg='numerator'), den: dict(type=float,


msg='denominator')) -> float:
return num/den
print (division.__annotations__)

It will produce the following output −

268
Python Tutorial

{'num': {'type': <class 'float'>, 'msg': 'numerator'}, 'den': {'type': <class


'float'>, 'msg': 'denominator'}, 'return': <class 'float'>}

269
52. Python - Modules Python Tutorial

Python Modules
The concept of module in Python further enhances the modularity. You can define more
than one related functions together and load required functions. A module is a file
containing definition of functions, classes, variables, constants or any other Python object.
Contents of this file can be made available to any other program. Python has the import
keyword for this purpose.

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.

Example of Python Module

import math
print ("Square root of 100:", math.sqrt(100))

It will produce the following output −

Square root of 100: 10.0

Python Built-in Modules


Python's standard library comes bundled with a large number of modules. They are called
built-in modules. Most of these built-in modules are written in C (as the reference
implementation of Python is in C), and pre-compiled into the library. These modules come
with useful functionality like system-specific OS management, disk IO, networking, etc.
Here is a select list of built-in modules −

Sr.No. Name & Brief Description


os
1 This module provides a unified interface to a
number of operating system functions.
string
2 This module contains a number of functions
for string processing
re
This module provides a set of powerful
3 regular expression facilities. Regular
expression (RegEx), allows powerful string
search and matching for a pattern in a string
4 math

270
Python Tutorial

This module implements a number of


mathematical operations for floating point
numbers. These functions are generally thin
wrappers around the platform C library
functions.
cmath

5 This module contains a number of


mathematical operations for complex
numbers.
datetime

6 This module provides functions to deal with


dates and the time within a day. It wraps the
C runtime library.
gc
7 This module provides an interface to the
built-in garbage collector.
asyncio
8 This module defines functionality required for
asynchronous processing
Collections
9 This module provides advanced Container
datatypes.
functools

10 This module has Higher-order functions and


operations on callable objects. Useful in
functional programming
operator
11 Functions corresponding to the standard
operators.
pickle
12 Convert Python objects to streams of bytes
and back.
socket
13
Low-level networking interface.
sqlite3
14 A DB-API 2.0 implementation using SQLite
3.x.
statistics
15
Mathematical statistics functions
typing
16
Support for type hints
venv
17
Creation of virtual environments.
json
18
Encode and decode the JSON format.
wsgiref
19 WSGI Utilities and Reference
Implementation.

271
Python Tutorial

unittest
20
Unit testing framework for Python.
random
21
Generate pseudo-random numbers
sys
22 Provides functions that acts strongly with the
interpreter.
requests

23 It simplifies HTTP requests by offering a


user-friendly interface for sending and
handling responses.

It simplifies HTTP requests by offering a user-friendly interface for sending and handling
responses.

Python User-defined Modules


Any text file with .py extension and containing Python code is basically a module. It can
contain definitions of one or more functions, variables, constants as well as classes. Any
Python object from a module can be made available to interpreter session or another
Python script by import statement. A module can also include runnable code.

Creating a Python Module


Creating a module is nothing but saving a Python code with the help of any editor. Let us
save the following code as mymodule.py

def SayHello(name):
print ("Hi {}! How are you?".format(name))
return

You can now import mymodule in the current Python terminal.

>>> import mymodule


>>> mymodule.SayHello("Harish")
Hi Harish! How are you?

You can also import one module in another Python script. Save the following code as
example.py

import mymodule
mymodule.SayHello("Harish")

Run this script from command terminal

Hi Harish! How are you?

272
Python Tutorial

The import Statement


In Python, the import keyword has been provided to load a Python object from one module.
The object may be a function, a class, a variable etc. If a module contains multiple
definitions, all of them will be loaded in the namespace.
Let us save the following code having three functions as mymodule.py.

def sum(x,y):
return x+y

def average(x,y):
return (x+y)/2

def power(x,y):
return x**y

The import mymodule statement loads all the functions in this module in the current
namespace. Each function in the imported module is an attribute of this module object.

>>> dir(mymodule)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', 'average', 'power', 'sum']

To call any function, use the module object's reference. For example, mymodule.sum().

import mymodule
print ("sum:",mymodule.sum(10,20))
print ("average:",mymodule.average(10,20))
print ("power:",mymodule.power(10, 2))

It will produce the following output −

sum:30
average:15.0
power:100

The from ... import Statement


The import statement will load all the resources of the module in the current namespace.
It is possible to import specific objects from a module by using this syntax. For example

Out of three functions in mymodule, only two are imported in following executable script
example.py

from mymodule import sum, average


print ("sum:",sum(10,20))

273
Python Tutorial

print ("average:",average(10,20))

It will produce the following output −

sum: 30
average: 15.0

Note that function need not be called by prefixing name of its module to it.

The from...import * Statement


It is also possible to import all the names from a module into the current namespace by
using the following import statement −

from modname import *

This provides an easy way to import all the items from a module into the current
namespace; however, this statement should be used sparingly.

The import ... as Statement


You can assign an alias name to the imported module.

from modulename as alias

The alias should be prefixed to the function while calling.


Take a look at the following example −

import mymodule as x
print ("sum:",x.sum(10,20))
print ("average:", x.average(10,20))
print ("power:", x.power(10, 2))

Locating Modules
When you import a module, the Python interpreter searches for the module in the following
sequences −
 The current directory.
 If the module isn't found, Python then searches each directory in the shell variable
PYTHONPATH.
 If all else fails, Python checks the default path. On UNIX, this default path is
normally /usr/local/lib/python/.
The module search path is stored in the system module sys as the sys.path variable. The
sys.path variable contains the current directory, PYTHONPATH, and the installation-
dependent default.

The PYTHONPATH Variable


The PYTHONPATH is an environment variable, consisting of a list of directories. The syntax
of PYTHONPATH is the same as that of the shell variable PATH.

274
Python Tutorial

Here is a typical PYTHONPATH from a Windows system −

set PYTHONPATH = c:\python20\lib;

And here is a typical PYTHONPATH from a UNIX system −

set PYTHONPATH = /usr/local/lib/python

Namespaces and Scoping


Variables are names (identifiers) that map to objects. A namespace is a dictionary of
variable names (keys) and their corresponding objects (values).
 A Python statement can access variables in a local namespace and in the global
namespace. If a local and a global variable have the same name, the local variable
shadows the global variable.
 Each function has its own local namespace. Class methods follow the same scoping
rule as ordinary functions.
 Python makes educated guesses on whether variables are local or global. It
assumes that any variable assigned a value in a function is local.
 In order to assign a value to a global variable within a function, you must first use
the global statement.
 The statement global VarName tells Python that VarName is a global variable.
Python stops searching the local namespace for the variable.
Example
For example, we define a variable Money in the global namespace. Within the function
Money, we assign Money a value, therefore Python assumes Money as a local variable.
However, we accessed the value of the local variable Money before setting it, so an
UnboundLocalError is the result. Uncommenting the global statement fixes the problem.

Money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1

print (Money)
AddMoney()
print (Money)

Module Attributes
In Python, a module is an object of module class, and hence it is characterized by
attributes.
Following are the module attributes −
 __file__ returns the physical name of the module.
 __package__ returns the package to which the module belongs.
 __doc__ returns the docstring at the top of the module if any

275
Python Tutorial

 __dict__ returns the entire scope of the module


 __name__ returns the name of the module
Example
Assuming that the following code is saved as mymodule.py

"The docstring of mymodule"


def sum(x,y):
return x+y

def average(x,y):
return (x+y)/2

def power(x,y):
return x**y

Let us check the attributes of mymodule by importing it in the following script −

import mymodule

print ("__file__ attribute:", mymodule.__file__)


print ("__doc__ attribute:", mymodule.__doc__)
print ("__name__ attribute:", mymodule.__name__)

It will produce the following output −

__file__ attribute: C:\math\examples\mymodule.py


__doc__ attribute: The docstring of mymodule
__name__ attribute: mymodule

The __name__Attribute
The __name__ attribute of a Python module has great significance. Let us explore it in
more detail.
In an interactive shell, __name__ attribute returns '__main__'

>>> __name__
'__main__'

If you import any module in the interpreter session, it returns the name of the module as
the __name__ attribute of that module.

>>> import math


>>> math.__name__
'math'

276
Python Tutorial

From inside a Python script, the __name__ attribute returns '__main__'

#example.py
print ("__name__ attribute within a script:", __name__)
Run this in the command terminal −

__name__ attribute within a script: __main__

This attribute allows a Python script to be used as executable or as a module. Unlike in


C++, Java, C# etc., in Python, there is no concept of the main() function. The Python
program script with .py extension can contain function definitions as well as executable
statements.
Save mymodule.py and with the following code −

"The docstring of mymodule"


def sum(x,y):
return x+y

print ("sum:",sum(10,20))

You can see that sum() function is called within the same script in which it is defined.

sum: 30

Now let us import this function in another script example.py.

import mymodule
print ("sum:",mymodule.sum(10,20))

It will produce the following output −

sum: 30
sum: 30

The output "sum:30" appears twice. Once when mymodule module is imported, the
executable statements in imported module also run. Second output is from the calling
script, i.e., example.py program.
What we want to explain is that when a module is imported, only the function should be
imported, its executable statements should not run. This can be done by checking the
value of __name__. If it is __main__, means it is being run and not imported, include the
executable statements like function calls conditionally.
Add if statement in mymodule.py as shown −

"The docstring of mymodule"


def sum(x,y):
return x+y

if __name__ == "__main__":
277
Python Tutorial

print ("sum:",sum(10,20))

Now if you run example.py program, you will find that the sum:30 output appears only
once.

sum: 30

The dir( ) Function


The dir() built-in function returns a sorted list of strings containing the names defined by
a module.
The list contains the names of all the modules, variables and functions that are defined in
a module. Following is a simple example −

# Import built-in module math


import math

content = dir(math)
print (content)

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

['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan',


'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp',
'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',
'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh',
'sqrt', 'tan', 'tanh']

The reload() Function


Sometimes you may need to reload a module, especially when working with the interactive
interpreter session of Python.
Assume that we have a test module (test.py) with the following function −

def SayHello(name):
print ("Hi {}! How are you?".format(name))
return

We can import the module and call its function from Python prompt as −

>>> import test


>>> test.SayHello("Deepak")
Hi Deepak! How are you?

However, suppose you need to modify the SayHello() function, such as −

def SayHello(name, course):

278
Python Tutorial

print ("Hi {}! How are you?".format(name))


print ("Welcome to {} Tutorial by TutorialsPoint".format(course))
return

Even if you edit the test.py file and save it, the function loaded in the memory won't
update. You need to reload it, using reload() function in imp module.

>>> import imp


>>> imp.reload(test)
>>> test.SayHello("Deepak", "Python")
Hi Deepak! How are you?
Welcome to Python Tutorial by TutorialsPoint

Packages in Python
A package is a hierarchical file directory structure that defines a single Python application
environment that consists of modules, subpackages and, sub-subpackages, and so on.
Consider a file Pots.py available in Phone directory. This file has following line of source
code −

def Pots():
print "I'm Pots Phone"

Similar way, we have another two files having different functions with the same name as
above −
 Phone/Isdn.py file having function Isdn()
 Phone/G3.py file having function G3()
Now, create one more file __init__.py in Phone directory −
 Phone/__init__.py
To make all of your functions available when you've imported Phone, you need to put
explicit import statements in __init__.py as follows −

from Pots import Pots


from Isdn import Isdn
from G3 import G3

After you add these lines to __init__.py, you have all of these classes available when you
import the Phone package.

# Now import your Phone Package.


import Phone

Phone.Pots()
Phone.Isdn()
Phone.G3()

279
Python Tutorial

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

I'm Pots Phone


I'm 3G Phone
I'm ISDN Phone

In the above example, we have taken example of a single function in each file, but you
can keep multiple functions in your files. You can also define different Python classes in
those files and then you can create your packages out of those classes.

280
53. Python - Built-in Functions Python Tutorial

Built-in Functions in Python?


Built-in functions are those functions that are pre-defined in the Python interpreter and
you don't need to import any module to use them. These functions help to perform a wide
variety of operations on strings, iterators, and numbers. For instance, the built-in functions
like sum(), min(), and max() are used to simplify mathematical operations.

How to Use Built-in Function in Python?


To use built-in functions in your code, simply call the specific function by passing the
required parameter (if any) inside the parentheses. Since these functions are pre-defined,
you don't need to import any module or package.
Example of Using Built-in Functions
Consider the following example demonstrating the use of built-in functions in your code:

# Using print() and len() function

text = "Tutorials Point"

print(len(text)) # Prints 15

In the above example, we are using two built-in functions print() and len().

List of Python Built-in Functions


As of Python 3.12.2 version, the list of built-in functions is given below −

Sr.No. Function & Description


Python aiter() function
1 Returns an asynchronous iterator for an
asynchronous iterable.
Python all() function
2
Returns true when all elements in iterable is true.
Python anext() function
3 Returns the next item from the given
asynchronous iterator.
Python any() function
4
Checks if any Element of an Iterable is True.
Python ascii() function
5 Returns String Containing Printable
Representation.
Python bin() function
6
Converts integer to binary string.
7 Python bool() function

281
Python Tutorial

Converts a Value to Boolean.


Python breakpoint() function
8 This function drops you into the debugger at the
call site and calls sys.breakpointhook().
Python bytearray() function
9
Returns array of given byte size.
Python bytes() function
10
Returns immutable bytes object.
Python callable() function
11
Checks if the Object is Callable.
Python chr() function
12
Returns a Character (a string) from an Integer.
Python classmethod() function
13
Returns class method for given function.
Python compile() function
14
Returns a code object.
Python complex() function
15
Creates a Complex Number.
Python delattr() function
16
Deletes Attribute From the Object.
Python dict() function
17
Creates a Dictionary.
Python dir() function
18
Tries to Return Attributes of Object.
Python divmod() function
19
Returns a Tuple of Quotient and Remainder.
Python enumerate() function
20
Returns an Enumerate Object.
Python eval() function
21
Runs Code Within Program.
Python exec() function
22
Executes Dynamically Created Program.
Python filter() function
23
Constructs iterator from elements which are true.
Python float() function
24 Returns floating point number from number,
string.
Python format() function
25
Returns formatted representation of a value.
Python frozenset() function
26
Returns immutable frozenset object.
Python getattr() function
27
Returns value of named attribute of an object.
Python globals() function
28
Returns dictionary of current global symbol table.
29 Python hasattr() function

282
Python Tutorial

Returns whether object has named attribute.


Python hash() function
30
Returns hash value of an object.
Python help() function
31
Invokes the built-in Help System.
Python hex() function
32
Converts to Integer to Hexadecimal.
Python id() function
33
Returns Identify of an Object.
Python input() function
34
Reads and returns a line of string.
Python int() function
35
Returns integer from a number or string.
Python isinstance() function
36
Checks if a Object is an Instance of Class.
Python issubclass() function
37
Checks if a Class is Subclass of another Class.
Python iter() function
38
Returns an iterator.
Python len() function
39
Returns Length of an Object.
Python list() function
40
Creates a list in Python.
Python locals() function
41
Returns dictionary of a current local symbol table.
Python map() function
42
Applies Function and Returns a List.
Python memoryview() function
43
Returns memory view of an argument.
Python next() function
44
Retrieves next item from the iterator.
Python object() function
45
Creates a featureless object.
Python oct() function
46
Returns the octal representation of an integer.
Python open() function
47
Returns a file object.
Python ord() function
48
Returns an integer of the Unicode character.
Python print() function
49
Prints the Given Object.
Python property() function
50
Returns the property attribute.
Python range() function
51
Returns a sequence of integers.
52 Python repr() function

283
Python Tutorial

Returns a printable representation of the object.


Python reversed() function
53
Returns the reversed iterator of a sequence.
Python set() function
54
Constructs and returns a set.
Python setattr() function
55
Sets the value of an attribute of an object.
Python slice() function
56
Returns a slice object.
Python sorted() function
57
Returns a sorted list from the given iterable.
Python staticmethod() function
58
Transforms a method into a static method.
Python str() function
59
Returns the string version of the object.
Python super() function
60
Returns a proxy object of the base class.
Python tuple() function
61
Returns a tuple.
Python type() function
62
Returns the type of the object.
Python vars() function
63
Returns the __dict__ attribute.
Python zip() function
64
Returns an iterator of tuples.
Python __import__() function
65
Function called by the import statement.
Python unichr() function
66 Converts a Unicode code point to its
corresponding Unicode character.
Python long() function
67
Represents integers of arbitrary size.

Built-in Mathematical Functions


There are some additional built-in functions that are used for performing only
mathematical operations in Python, they are listed below −

Sr.No. Function & Description


Python abs() function
1 The abs() function returns the absolute value of
x, i.e. the positive distance between x and zero.
Python max() function

2 The max() function returns the largest of its


arguments or largest number from the iterable
(list or tuple).
3 Python min() function

284
Python Tutorial

The function min() returns the smallest of its


arguments i.e. the value closest to negative
infinity, or smallest number from the iterable (list
or tuple)
Python pow() function
The pow() function returns x raised to y. It is
4 equivalent to x**y. The function has third
optional argument mod. If given, it returns
(x**y) % mod value
Python round() Function
5 round() is a built-in function in Python. It returns
x rounded to n digits from the decimal point.
Python sum() function
The sum() function returns the sum of all numeric
6 items in any iterable (list or tuple). An optional
start argument is 0 by default. If given, the
numbers in the list are added to start value.

Advantages of Using Built-in Functions


The following are the advantages of using built-in functions:
 The use of the built-in functions simplifies and reduces the code length and
enhances the readability of the code.
 Instead of writing the same logic repeatedly, you can use these functions across
different sections of the program. This not only saves time but also helps in
maintaining consistency of code.
 These functions provide a wide range of functionalities including mathematical
operations, datatype conversion, and performing operations on iterators.
 These functions have descriptive names that make the code easier to understand
and maintain. Developers need not write additional complex code for performing
certain operations.

Frequently Asked Questions about Built-in Functions

How do I handle errors with built-in functions?


While working with built-in functions, you may encounter errors and to handle those errors
you can use the try-except blocks. This may help you identify the type of error and
exceptions raised.

Can we extend the functionality of built-in functions?


Yes, we can extend the functionality of built-in functions by using them with other methods
and by applying our logic as per the need. However, it will not affect the pre-defined
feature of the used function.

Can I create my built-in functions?


No, you cannot create your built-in function. But, Python allows a user to create user-
defined functions.

285
Python Tutorial

How do I use built-in functions?


Using a built-in function is very simple, call it by its name followed by parentheses, and
pass the required arguments inside the parentheses.

286
Python Tutorial

Python Strings

287
54. Python - Strings Python Tutorial

In Python, a string is an immutable sequence of Unicode characters. Each character has a


unique numeric value as per the UNICODE standard. But, the sequence as a whole, doesn't
have any numeric value even if all the characters are digits. To differentiate the string
from numbers and other identifiers, the sequence of characters is included within single,
double or triple quotes in its literal representation. Hence, 1234 is a number (integer) but
'1234' is a string.

Creating Python Strings


As long as the same sequence of characters is enclosed, single or double or triple quotes
don't matter. Hence, following string representations are equivalent.
Example

>>> 'Welcome To TutorialsPoint'


'Welcome To TutorialsPoint'
>>> "Welcome To TutorialsPoint"
'Welcome To TutorialsPoint'
>>> '''Welcome To TutorialsPoint'''
'Welcome To TutorialsPoint'
>>> """Welcome To TutorialsPoint"""
'Welcome To TutorialsPoint'

Looking at the above statements, it is clear that, internally Python stores strings as
included in single quotes.

In older versions strings are stored internally as 8-bit ASCII, hence it is


required to attach 'u' to make it Unicode. Since Python 3, all strings are
represented in Unicode. Therefore, it is no longer necessary now to add 'u'
after the string.

Accessing Values in Strings


Python does not support a character type; these are treated as strings of length one, thus
also considered a substring.
To access substrings, use the square brackets for slicing along with the index or indices to
obtain your substring. For example −

var1 = 'Hello World!'


var2 = "Python Programming"

print ("var1[0]: ", var1[0])


print ("var2[1:5]: ", var2[1:5])

288
Python Tutorial

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

var1[0]: H
var2[1:5]: ytho

Updating Strings
You can "update" an existing string by (re)assigning a variable to another string. The new
value can be related to its previous value or to a completely different string altogether.
For example −

var1 = 'Hello World!'


print ("Updated String :- ", var1[:6] + 'Python')

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

Updated String :- Hello Python

Visit our Python - Modify Strings tutorial to know more about updating/modifying strings.

Escape Characters
Following table is a list of escape or non-printable characters that can be represented with
backslash notation.
An escape character gets interpreted; in a single quoted as well as double quoted strings.

Backslash Hexadecimal
Description
notation character
\a 0x07 Bell or alert
\b 0x08 Backspace
\cx Control-x
\C-x Control-x
\e 0x1b Escape
\f 0x0c Formfeed
\M-\C-x Meta-Control-x
\n 0x0a Newline
Octal notation, where n is in
\nnn
the range 0.7
\r 0x0d Carriage return
\s 0x20 Space
\t 0x09 Tab
\v 0x0b Vertical tab
\x Character x
Hexadecimal notation, where
\xnn n is in the range 0.9, a.f, or
A.F

String Special Operators


Assume string variable a holds 'Hello' and variable b holds 'Python', then −

289
Python Tutorial

Backslash Hexadecimal
Description
notation character
\a 0x07 Bell or alert
\b 0x08 Backspace
\cx Control-x
\C-x Control-x
\e 0x1b Escape
\f 0x0c Formfeed
\M-\C-x Meta-Control-x
\n 0x0a Newline
Octal notation, where n is in
\nnn
the range 0.7
\r 0x0d Carriage return
\s 0x20 Space
\t 0x09 Tab
\v 0x0b Vertical tab
\x Character x
Hexadecimal notation, where
\xnn n is in the range 0.9, a.f, or
A.F

String Formatting Operator


One of Python's coolest features is the string format operator %. This operator is unique
to strings and makes up for the pack of having functions from C's printf() family. Following
is a simple example −

print ("My name is %s and weight is %d kg!" % ('Zara', 21))

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

My name is Zara and weight is 21 kg!

Here is the list of complete set of symbols which can be used along with % −

Sr.No. Format Symbol & Conversion


%c
1
character
%s
2 string conversion via str() prior to
formatting
%i
3
signed decimal integer
%d
4
signed decimal integer
%u
5
unsigned decimal integer
%o
6
octal integer
7 %x

290
Python Tutorial

hexadecimal integer (lowercase letters)


%X
8 hexadecimal integer (UPPERcase
letters)
%e
9 exponential notation (with lowercase
'e')
%E
10 exponential notation (with UPPERcase
'E')
%f
11
floating point real number
%g
12
the shorter of %f and %e
%G
13
the shorter of %f and %E
Other supported symbols and functionality are listed in the following table −

Sr.No. Symbol & Functionality


*
1 argument specifies width or
precision
-
2
left justification
+
3
display the sign
<sp>
4 leave a blank space before a
positive number
#
add the octal leading zero ( '0' )
5 or hexadecimal leading '0x' or
'0X', depending on whether 'x' or
'X' were used.
0
6 pad from left with zeros (instead
of spaces)
%
7 '%%' leaves you with a single
literal '%'
(var)
8 mapping variable (dictionary
arguments)
m.n.
m is the minimum total width and
9 n is the number of digits to
display after the decimal point (if
appl.)

291
Python Tutorial

Visit our Python - String Formatting tutorial to learn about various ways to format strings.

Double Quotes in Python Strings


You want to embed some text in double quotes as a part of string, the string itself should
be put in single quotes. To embed a single quoted text, string should be written in double
quotes.
Example

var = 'Welcome to "Python Tutorial" from TutorialsPoint'


print ("var:", var)

var = "Welcome to 'Python Tutorial' from TutorialsPoint"


print ("var:", var)

It will produce the following output −

var: Welcome to "Python Tutorial" from TutorialsPoint


var: Welcome to 'Python Tutorial' from TutorialsPoint

Triple Quotes
To form a string with triple quotes, you may use triple single quotes, or triple double
quotes − both versions are similar.
Example

var = '''Welcome to TutorialsPoint'''


print ("var:", var)

var = """Welcome to TutorialsPoint"""


print ("var:", var)

It will produce the following output −

var: Welcome to TutorialsPoint


var: Welcome to TutorialsPoint

Python Multiline Strings


Triple quoted string is useful to form a multi-line string.
Example

var = '''
Welcome To
Python Tutorial
from TutorialsPoint
'''

292
Python Tutorial

print ("var:", var)

It will produce the following output −

var:
Welcome To
Python Tutorial
from TutorialsPoint

Arithmetic Operators with Strings


A string is a non-numeric data type. Obviously, we cannot use arithmetic operators with
string operands. Python raises TypeError in such a case.

print ("Hello"-"World")

On executing the above program it will generate the following error −

>>> "Hello"-"World"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'str' and 'str'

Getting Type of Python Strings


A string in Python is an object of str class. It can be verified with type() function.
Example

var = "Welcome To TutorialsPoint"


print (type(var))

It will produce the following output −

<class 'str'>

Built-in String Methods


Python includes the following built-in methods to manipulate strings −

Sr.No. Methods with Description


capitalize()
1
Capitalizes first letter of string.
casefold()

2 Converts all uppercase letters in string to


lowercase. Similar to lower(), but works on
UNICODE characters alos.
center(width, fillchar)

3 Returns a space-padded string with the


original string centered to a total of width
columns.

293
Python Tutorial

count(str, beg= 0,end=len(string))

4 Counts how many times str occurs in string or


in a substring of string if starting index beg
and ending index end are given.
decode(encoding='UTF-8',errors='strict')

5 Decodes the string using the codec registered


for encoding. encoding defaults to the default
string encoding.
encode(encoding='UTF-8',errors='strict')

6 Returns encoded string version of string; on


error, default is to raise a ValueError unless
errors is given with 'ignore' or 'replace'.
endswith(suffix, beg=0, end=len(string))
Determines if string or a substring of string (if
7 starting index beg and ending index end are
given) ends with suffix; returns true if so and
false otherwise.
expandtabs(tabsize=8)

8 Expands tabs in string to multiple spaces;


defaults to 8 spaces per tab if tabsize not
provided.
find(str, beg=0 end=len(string))
Determine if str occurs in string or in a
9 substring of string if starting index beg and
ending index end are given returns index if
found and -1 otherwise.
format(*args, **kwargs)
10 This method is used to format the current
string value.
format_map(mapping)

11 This method is also use to format the current


string the only difference is it uses a mapping
object.
index(str, beg=0, end=len(string))
12 Same as find(), but raises an exception if str
not found.
isalnum()

13 Returns true if string has at least 1 character


and all characters are alphanumeric and false
otherwise.
isalpha()

14 Returns true if string has at least 1 character


and all characters are alphabetic and false
otherwise.
isascii()
15 Returns True is all the characters in the string
are from the ASCII character set.
16 isdecimal()

294
Python Tutorial

Returns true if a unicode string contains only


decimal characters and false otherwise.
isdigit()
17 Returns true if string contains only digits and
false otherwise.
isidentifier()
18 Checks whether the string is a valid Python
identifier.
islower()

19 Returns true if string has at least 1 cased


character and all cased characters are in
lowercase and false otherwise.
isnumeric()
20 Returns true if a unicode string contains only
numeric characters and false otherwise.
isprintable()
21 Checks whether all the characters in the string
are printable.
isspace()
22 Returns true if string contains only whitespace
characters and false otherwise.
istitle()
23 Returns true if string is properly "titlecased"
and false otherwise.
isupper()

24 Returns true if string has at least one cased


character and all cased characters are in
uppercase and false otherwise.
join(seq)

25 Merges (concatenates) the string


representations of elements in sequence seq
into a string, with separator string.
ljust(width[, fillchar])

26 Returns a space-padded string with the


original string left-justified to a total of width
columns.
lower()
27 Converts all uppercase letters in string to
lowercase.
lstrip()
28
Removes all leading white space in string.
maketrans()
29 Returns a translation table to be used in
translate function.
partition()
30 Splits the string in three string tuple at the
first occurrence of separator.
31 removeprefix()

295
Python Tutorial

Returns a string after removing the prefix


string.
removesuffix()
32 Returns a string after removing the suffix
string.
replace(old, new [, max])
33 Replaces all occurrences of old in string with
new or at most max occurrences if max given.
rfind(str, beg=0,end=len(string))
34 Same as find(), but search backwards in
string.
rindex( str, beg=0, end=len(string))
35 Same as index(), but search backwards in
string.
rjust(width,[, fillchar])

36 Returns a space-padded string with the


original string right-justified to a total of width
columns.
rpartition()
37 Splits the string in three string tuple at the
ladt occurrence of separator.
rsplit()
38 Splits the string from the end and returns a
list of substrings.
rstrip()
39
Removes all trailing whitespace of string.
split(str="", num=string.count(str))

40 Splits string according to delimiter str (space if


not provided) and returns list of substrings;
split into at most num substrings if given.
splitlines( num=string.count('\n'))

41 Splits string at all (or num) NEWLINEs and


returns a list of each line with NEWLINEs
removed.
startswith(str, beg=0,end=len(string))
Determines if string or a substring of string (if
42 starting index beg and ending index end are
given) starts with substring str; returns true if
so and false otherwise.
strip([chars])
43
Performs both lstrip() and rstrip() on string.
swapcase()
44
Inverts case for all letters in string.
title()

45 Returns "titlecased" version of string, that is,


all words begin with uppercase and the rest
are lowercase.
46 translate(table, deletechars="")

296
Python Tutorial

Translates string according to translation table


str(256 chars), removing those in the del
string.
upper()
47 Converts lowercase letters in string to
uppercase.
zfill (width)
Returns original string leftpadded with zeros to
48 a total of width characters; intended for
numbers, zfill() retains any sign given (less
one zero).

Built-in Functions with Strings


Following are the built-in functions we can use with strings −

Sr.No. Function with Description

len(list)
1
Returns the length of the string.
max(list)
2 Returns the max alphabetical
character from the string str.
min(list)
3 Returns the min alphabetical
character from the string str.

297
55. Python Slicing Strings Python Tutorial

Python String slicing is a way of creating a sub-string from a given string. In this process,
we extract a portion or piece of a string. Usually, we use the slice operator "[ : ]" to
perform slicing on a Python String. Before proceeding with string slicing let's understand
string indexing.
In Python, a string is an ordered sequence of Unicode characters. Each character in the
string has a unique index in the sequence. The index starts with 0. First character in the
string has its positional index 0. The index keeps incrementing towards the end of string.
If a string variable is declared as var="HELLO PYTHON", index of each character in the
string is as follows −

Python String Indexing


Python allows you to access any individual character from the string by its index. In this
case, 0 is the lower bound and 11 is the upper bound of the string. So, var[0] returns H,
var[6] returns P. If the index in square brackets exceeds the upper bound, Python raises
IndexError.
Example
In the below example, we accessing the characters of a string through index.

var = "HELLO PYTHON"


print(var[0])
print(var[7])
print(var[11])
print(var[12])

On running the code, it will produce the following output −

H
Y
N
ERROR!

298
Python Tutorial

Traceback (most recent call last):


File "<main.py>", line 5, in <module>
IndexError: string index out of range

Python String Negative & Positive Indexing


One of the unique features of Python sequence types (and therefore a string object) is
that it has a negative indexing scheme also. In the example above, a positive indexing
scheme is used where the index increments from left to right. In case of negative indexing,
the character at the end has -1 index and the index decrements from right to left, as a
result the first character H has -12 index.

Example
Let us use negative indexing to fetch N, Y, and H characters.

var = "HELLO PYTHON"


print(var[-1])
print(var[-5])
print(var[-12])

On executing the above code, it will give the following result −

N
Y
H

We can therefore use positive or negative index to retrieve a character from the string.
In Python, string is an immutable object. The object is immutable if it cannot be modified
in-place, once stored in a certain memory location. You can retrieve any character from
the string with the help of its index, but you cannot replace it with another character.

299
Python Tutorial

Example
In the following example, character Y is at index 7 in HELLO PYTHON. Try to replace Y with
y and see what happens.

var="HELLO PYTHON"
var[7]="y"
print (var)

It will produce the following output −

Traceback (most recent call last):


File "C:\Users\users\example.py", line 2, in <module>
var[7]="y"
~~~^^^
TypeError: 'str' object does not support item assignment

The TypeError is because the string is immutable.

Python String Slicing


Python defines ":" as string slicing operator. It returns a substring from the original string.
Its general usage is as follows −

substr=var[x:y]

The ":" operator needs two integer operands (both of which may be omitted, as we shall
see in subsequent examples). The first operand x is the index of the first character of the
desired slice. The second operand y is the index of the character next to the last in the
desired string. So var(x:y] separates characters from xth position to (y-1)th position from
the original string.
Example

var="HELLO PYTHON"

print ("var:",var)
print ("var[3:8]:", var[3:8])

It will produce the following output −

var: HELLO PYTHON


var[3:8]: LO PY

Python String Slicing With Negative Indexing


Like positive indexes, negative indexes can also be used for slicing.
Example
The below example shows how to slice a string using negative indexes.

var="HELLO PYTHON"

300
Python Tutorial

print ("var:",var)
print ("var[3:8]:", var[3:8])
print ("var[-9:-4]:", var[-9:-4])

It will produce the following output −

var: HELLO PYTHON


var[3:8]: LO PY
var[-9:-4]: LO PY

Default Values of Indexes with String Slicing


Both the operands for Python's Slice operator are optional. The first operand defaults to
zero, which means if we do not give the first operand, the slice starts of character at 0th
index, i.e. the first character. It slices the leftmost substring up to "y-1" characters.
Example
In this example, we are performing slice operation using default values.

var="HELLO PYTHON"
print ("var:",var)
print ("var[0:5]:", var[0:5])
print ("var[:5]:", var[:5])

It will produce the following output −

var: HELLO PYTHON


var[0:5]: HELLO
var[:5]: HELLO

Example
Similarly, y operand is also optional. By default, it is "-1", which means the string will be
sliced from the xth position up to the end of string.

var="HELLO PYTHON"
print ("var:",var)
print ("var[6:12]:", var[6:12])
print ("var[6:]:", var[6:])

It will produce the following output −

var: HELLO PYTHON


var[6:12]: PYTHON
var[6:]: PYTHON

301
Python Tutorial

Example
Naturally, if both the operands are not used, the slice will be equal to the original string.
That's because "x" is 0, and "y" is the last index+1 (or -1) by default.

var="HELLO PYTHON"
print ("var:",var)
print ("var[0:12]:", var[0:12])
print ("var[:]:", var[:])

It will produce the following output −

var: HELLO PYTHON


var[0:12]: HELLO PYTHON
var[:]: HELLO PYTHON

Example
The left operand must be smaller than the operand on right, for getting a substring of the
original string. Python doesn't raise any error, if the left operand is greater, bu returns a
null string.

var="HELLO PYTHON"
print ("var:",var)
print ("var[-1:7]:", var[-1:7])
print ("var[7:0]:", var[7:0])

It will produce the following output −

var: HELLO PYTHON


var[-1:7]:
var[7:0]:

Return Type of String Slicing


Slicing returns a new string. You can very well perform string operations like
concatenation, or slicing on the sliced string.
Example

var="HELLO PYTHON"

print ("var:",var)
print ("var[:6][:2]:", var[:6][:2])

var1=var[:6]
print ("slice:", var1)
print ("var1[:2]:", var1[:2])

302
Python Tutorial

It will produce the following output −

var: HELLO PYTHON


var[:6][:2]: HE
slice: HELLO
var1[:2]: HE

303
56. Python - Modify Strings Python Tutorial

String modification refers to the process of changing the characters of a string. If we talk
about modifying a string in Python, what we are talking about is creating a new string that
is a variation of the original one.
In Python, a string (object of str class) is of immutable type. Here, immutable refers to an
object that cannot be modified in place once it's created in memory. Unlike a list, we
cannot overwrite any character in the sequence, nor can we insert or append characters
to it directly. If we need to modify a string, we will use certain string methods that return
a new string object. However, the original string remains unchanged.
We can use any of the following tricks as a workaround to modify a string.

Converting a String to a List


Both strings and lists in Python are sequence types, they are interconvertible. Thus, we
can cast a string to a list, modify the list using methods like insert(), append(), or remove()
and then convert the list back to a string to obtain a modified version.
Suppose, we have a string variable s1 with WORD as its value and we are required to
convert it into a list. For this operation, we can use the list() built-in function and insert a
character L at index 3. Then, we can concatenate all the characters using join() method
of str class.
Example
The below example practically illustrates how to convert a string into a list.

s1="WORD"
print ("original string:", s1)
l1=list(s1)

l1.insert(3,"L")

print (l1)

s1=''.join(l1)
print ("Modified string:", s1)

It will produce the following output −

original string: WORD


['W', 'O', 'R', 'L', 'D']
Modified string: WORLD

304
Python Tutorial

Using the Array Module


To modify a string, construct an array object using the Python standard library named
array module. It will create an array of Unicode type from a string variable.
Example
In the below example, we are using array module to modify the specified string.

import array as ar

# initializing a string
s1="WORD"
print ("original string:", s1)

# converting it to an array
sar=ar.array('u', s1)

# inserting an element
sar.insert(3,"L")

# getting back the modified string


s1=sar.tounicode()
print ("Modified string:", s1)

It will produce the following output −

original string: WORD


Modified string: WORLD

Using the StringIO Class


Python's io module defines the classes to handle streams. The StringIO class represents a
text stream using an in-memory text buffer. A StringIO object obtained from a string
behaves like a File object. Hence we can perform read/write operations on it. The
getvalue() method of StringIO class returns a string.
Example
Let us use the above discussed principle in the following program to modify a string.

import io

s1="WORD"
print ("original string:", s1)

305
Python Tutorial

sio=io.StringIO(s1)
sio.seek(3)
sio.write("LD")
s1=sio.getvalue()

print ("Modified string:", s1)

It will produce the following output −

original string: WORD


Modified string: WORLD

306
57. Python - String ConcatenationPython Tutorial

Concatenate Strings in Python


String concatenation in Python is the operation of joining two or more strings together.
The result of this operation will be a new string that contains the original strings. The
diagram below shows a general string concatenation operation −

In Python, there are numerous ways to concatenate strings. We are going to discuss the
following −

Using '+' operator


Concatenating String with space
Using multiplication operator
Using '+' and '*' operators together

String Concatenation using '+' operator


The "+" operator is well-known as an addition operator, returning the sum of two numbers.
However, the "+" symbol acts as string concatenation operator in Python. It works with
two string operands, and results in the concatenation of the two.
The characters of the string on the right of plus symbol are appended to the string on its
left. Result of concatenation is a new string.
Example
The following example shows string concatenation operation in Python using + operator.

str1="Hello"
str2="World"
print ("String 1:",str1)
print ("String 2:",str2)
str3=str1+str2
print("String 3:",str3)

307
Python Tutorial

It will produce the following output −

String 1: Hello
String 2: World
String 3: HelloWorld

Concatenating String with space


To insert a whitespace between two strings, we can use a third empty string.
Example
In the below example, we are inserting space between two strings while concatenation.

str1="Hello"
str2="World"
blank=" "
print ("String 1:",str1)
print ("String 2:",str2)
str3=str1+blank+str2
print("String 3:",str3)

It will produce the following output −

String 1: Hello
String 2: World
String 3: Hello World

String Concatenation by Multiplying


Another symbol *, which we normally use for multiplication of two numbers, can also be
used with string operands. Here, * acts as a repetition operator in Python. One of the
operands must be an integer, and the second a string. The integer operand specifies the
number of copies of the string operand to be concatenated.
In this example, the * operator concatenates multiple copies of the string.

newString = "Hello" * 3
print(newString)

The above code will produce the following output −

HelloHelloHello

String Concatenation with '+' and '*' Operators


Both the repetition operator (*) and the concatenation operator (+), can be used in a
single expression to concatenate strings. The "*" operator has a higher precedence over
the "+" operator.
Example

308
Python Tutorial

In the below example, we are concatenating strings using the + and * operator together.

str1="Hello"
str2="World"
print ("String 1:",str1)
print ("String 2:",str2)
str3=str1+str2*3
print("String 3:",str3)
str4=(str1+str2)*3
print ("String 4:", str4)

To form str3 string, Python concatenates 3 copies of World first, and then appends the
result to Hello

String 3: HelloWorldWorldWorld

In the second case, the strings str1 and str2 are inside parentheses, hence their
concatenation takes place first. Its result is then replicated three times.

String 4: HelloWorldHelloWorldHelloWorld

Apart from + and *, no other arithmetic operators can be used with string

309
58. Python - String Formatting Python Tutorial

String formatting in Python is the process of building a string representation dynamically


by inserting the value of numeric expressions in an already existing string. Python's string
concatenation operator doesn't accept a non-string operand. Hence, Python offers
following string formatting techniques −
 Using % operator
 Using format() method of str class
 Using f-string
 Using String Template class

Using % operator
The "%" (modulo) operator often referred to as the string formatting operator. It takes a
format string along with a set of variables and combine them to create a string that contain
values of the variables formatted in the specified way.
Example
To insert a string into a format string using the "%" operator, we use "%s" as shown in
the below example −

name = "Tutorialspoint"
print("Welcome to %s!" % name)

It will produce the following output −

Welcome to Tutorialspoint!

Using format() method


It is a built-in method of str class. The format() method works by defining placeholders
within a string using curly braces "{}". These placeholders are then replaced by the values
specified in the method's arguments.
Example
In the below example, we are using format() method to insert values into a string
dynamically.

str = "Welcome to {}"


print(str.format("Tutorialspoint"))

On running the above code, it will produce the following output −

Welcome to Tutorialspoint

Using f-string
The f-strings, also known as formatted string literals, is used to embed expressions inside
string literals. The "f" in f-strings stands for formatted and prefixing it with strings creates

310
Python Tutorial

an f-string. The curly braces "{}" within the string will then act as placeholders that is
filled with variables, expressions, or function calls.
Example
The following example illustrates the working of f-strings with expressions.

item1_price = 2500
item2_price = 300
total = f'Total: {item1_price + item2_price}'
print(total)

The output of the above code is as follows −

Total: 2800

Using String Template class


The String Template class belongs to the string module and provides a way to format
strings by using placeholders. Here, placeholders are defined by a dollar sign ($) followed
by an identifier.
Example
The following example shows how to use Template class to format strings.

from string import Template

# Defining template string


str = "Hello and Welcome to $name !"

# Creating Template object


templateObj = Template(str)

# now provide values


new_str = templateObj.substitute(name="Tutorialspoint")
print(new_str)

It will produce the following output −

Hello and Welcome to Tutorialspoint !

311
59. Python - Escape CharactersPython Tutorial

Escape Character
An escape character is a character followed by a backslash (\). It tells the Interpreter that
this escape character (sequence) has a special meaning. For instance, \n is an escape
sequence that represents a newline. When Python encounters this sequence in a string, it
understands that it needs to start a new line.
Unless an 'r' or 'R' prefix is present, escape sequences in string and byte literals are
interpreted according to rules similar to those used by Standard C. In Python, a string
becomes a raw string if it is prefixed with "r" or "R" before the quotation symbols. Hence
'Hello' is a normal string whereas r'Hello' is a raw string.
Example
In the below example, we are practically demonstrating raw and normal string.

# normal string
normal = "Hello"
print (normal)

# raw string
raw = r"Hello"
print (raw)

Output of the above code is shown below −

Hello
Hello

In normal circumstances, there is no difference between the two. However, when the
escape character is embedded in the string, the normal string actually interprets the
escape sequence, whereas the raw string doesn't process the escape character.
Example
In the following example, when a normal string is printed the escape character '\n' is
processed to introduce a newline. However, because of the raw string operator 'r' the
effect of escape character is not translated as per its meaning.

normal = "Hello\nWorld"
print (normal)

raw = r"Hello\nWorld"
print (raw)

On running the above code, it will print the following result −

312
Python Tutorial

Hello
World
Hello\nWorld

Escape Characters in Python


The following table shows the different escape characters used in Python -

Sr.No Escape Sequence & Meaning


\<newline>
1
Backslash and newline ignored
\\
2
Backslash (\)
\'
3
Single quote (')
\"
4
Double quote (")
\a
5
ASCII Bell (BEL)
\b
6
ASCII Backspace (BS)
\f
7
ASCII Formfeed (FF)
\n
8
ASCII Linefeed (LF)
\r
9
ASCII Carriage Return (CR)
\t
10
ASCII Horizontal Tab (TAB)
\v
11
ASCII Vertical Tab (VT)
\ooo
12
Character with octal value ooo
\xhh
13
Character with hex value hh

Escape Characters Example


The following code shows the usage of escape sequences listed in the above table −

# ignore \
s = 'This string will not include \
backslashes or newline characters.'
print (s)

# escape backslash

313
Python Tutorial

s=s = 'The \\character is called backslash'


print (s)

# escape single quote


s='Hello \'Python\''
print (s)

# escape double quote


s="Hello \"Python\""
print (s)

# escape \b to generate ASCII backspace


s='Hel\blo'
print (s)

# ASCII Bell character


s='Hello\a'
print (s)

# newline
s='Hello\nPython'
print (s)

# Horizontal tab
s='Hello\tPython'
print (s)

# form feed
s= "hello\fworld"
print (s)

# Octal notation
s="\101"
print(s)

# Hexadecimal notation
314
Python Tutorial

s="\x41"
print (s)

It will produce the following output −

This string will not include backslashes or newline characters.


The \character is called backslash
Hello 'Python'
Hello "Python"
Helo
Hello
Hello
Python
Hello Python
hello
world
A
A

315
60. Python - String Methods Python Tutorial

Python's built-in str class defines different methods. They help in manipulating strings.
Since string is an immutable object, these methods return a copy of the original string,
performing the respective processing on it. The string methods can be classified in
following categories −

Case Conversion Methods


This category of built-in methods of Python's str class deal with the conversion of alphabet
characters in the string object. Following methods fall in this category −

Sr.No. Method & Description


capitalize()
1
Capitalizes first letter of string
casefold()

2 Converts all uppercase letters in string to


lowercase. Similar to lower(), but works on
UNICODE characters alos
lower()
3 Converts all uppercase letters in string to
lowercase.
swapcase()
4
Inverts case for all letters in string.
title()

5 Returns "titlecased" version of string, that


is, all words begin with uppercase and the
rest are lowercase.
upper()
6 Converts lowercase letters in string to
uppercase.

Alignment Methods
Following methods in the str class control the alignment of characters within the string
object.

Sr.No. Methods & Description


center(width, fillchar)
Returns a string padded with
1 fillchar with the original string
centered to a total of width
columns.
ljust(width[, fillchar])
Returns a space-padded string
2 with the original string left-
justified to a total of width
columns.

316
Python Tutorial

rjust(width,[, fillchar])
Returns a space-padded string
3 with the original string right-
justified to a total of width
columns.
expandtabs(tabsize = 8)
Expands tabs in string to
4 multiple spaces; defaults to 8
spaces per tab if tabsize not
provided.
zfill (width)
Returns original string
5 leftpadded with zeros to a total
of width characters; intended
for numbers, zfill() retains any
sign given (less one zero).

Split and Join Methods


Python has the following methods to perform split and join operations −

Sr.No. Method & Description


lstrip()
1 Removes all leading whitespace in
string.
rstrip()
2 Removes all trailing whitespace of
string.
strip()
3 Performs both lstrip() and rstrip()
on string
rsplit()
4 Splits the string from the end and
returns a list of substrings
split()

5 Splits string according to delimiter


(space if not provided) and returns
list of substrings.
splitlines()

6 Splits string at NEWLINEs and


returns a list of each line with
NEWLINEs removed.
partition()

7 Splits the string in three string


tuple at the first occurrence of
separator
rpartition()

8 Splits the string in three string


tuple at the ladt occurrence of
separator

317
Python Tutorial

join()
Concatenates the string
9 representations of elements in
sequence into a string, with
separator string.
removeprefix()
10 Returns a string after removing the
prefix string
removesuffix()
11 Returns a string after removing the
suffix string

Boolean String Methods


Following methods in str class return True or False.

Sr.No. Methods & Description


isalnum()

1 Returns true if string has at least 1 character


and all characters are alphanumeric and false
otherwise.
isalpha()

2 Returns true if string has at least 1 character


and all characters are alphabetic and false
otherwise.
isdigit()
3 Returns true if the string contains only digits
and false otherwise.
islower()

4 Returns true if string has at least 1 cased


character and all cased characters are in
lowercase and false otherwise.
isnumeric()
5 Returns true if a unicode string contains only
numeric characters and false otherwise.
isspace()
6 Returns true if string contains only
whitespace characters and false otherwise.
istitle()
7 Returns true if string is properly "titlecased"
and false otherwise.
isupper()

8 Returns true if string has at least one cased


character and all cased characters are in
uppercase and false otherwise.
isascii()
9 Returns True is all the characters in the string
are from the ASCII character set
10 isdecimal()

318
Python Tutorial

Checks if all the characters are decimal


characters
isidentifier()
11 Checks whether the string is a valid Python
identifier
isprintable()
12 Checks whether all the characters in the
string are printable

Find and Replace Methods


Following are the Find and Replace methods in Python −

Sr.No. Method & Description


count(sub, beg ,end)
Counts how many times sub occurs in
1 string or in a substring of string if
starting index beg and ending index
end are given.
find(sub, beg, end)
Determine if sub occurs in string or in
2 a substring of string if starting index
beg and ending index end are given
returns index if found and -1
otherwise.
index(sub, beg, end)
3 Same as find(), but raises an
exception if str not found.
replace(old, new [, max])

4 Replaces all occurrences of old in


string with new or at most max
occurrences if max given.
rfind(sub, beg, end)
5 Same as find(), but search backwards
in string.
rindex( sub, beg, end)
6 Same as index(), but search
backwards in string.
startswith(sub, beg, end)
Determines if string or a substring of
7 string (if starting index beg and ending
index end are given) starts with
substring sub; returns true if so and
false otherwise.
8 endswith(suffix, beg, end)

Translation Methods
Following are the Translation methods of the string −

Sr.No. Method & Description

319
Python Tutorial

maketrans()
1 Returns a translation table to be
used in translate function.
translate(table, deletechars="")

2 Translates string according to


translation table str(256 chars),
removing those in the del string.

320
61. Python - String Exercises Python Tutorial

Example 1
Python program to find number of vowels in a given string.

mystr = "All animals are equal. Some are more equal"


vowels = "aeiou"
count=0
for x in mystr:
if x.lower() in vowels: count+=1
print ("Number of Vowels:", count)

It will produce the following output −

Number of Vowels: 18

Example 2
Python program to convert a string with binary digits to integer.

mystr = '10101'

def strtoint(mystr):
for x in mystr:
if x not in '01': return "Error. String with non-binary characters"
num = int(mystr, 2)
return num
print ("binary:{} integer: {}".format(mystr,strtoint(mystr)))

It will produce the following output −

binary:10101 integer: 21
Change mystr to '10, 101'

binary:10,101 integer: Error. String with non-binary characters

Example 3
Python program to drop all digits from a string.

digits = [str(x) for x in range(10)]


mystr = 'He12llo, Py00th55on!'

321
Python Tutorial

chars = []
for x in mystr:
if x not in digits:
chars.append(x)
newstr = ''.join(chars)
print (newstr)

It will produce the following output −

Hello, Python!

Exercise Programs
 Python program to sort the characters in a string
 Python program to remove duplicate characters from a string
 Python program to list unique characters with their count in a string
 Python program to find number of words in a string
 Python program to remove all non-alphabetic characters from a string

322
Python Tutorial

Python Lists

323
62. Python - Lists Python Tutorial

Python Lists
List is one of the built-in data types in Python. A Python list is a sequence of comma
separated items, enclosed in square brackets [ ]. The items in a Python list need not be
of the same data type.
Following are some examples of Python lists −

list1 = ["Rohan", "Physics", 21, 69.75]


list2 = [1, 2, 3, 4, 5]
list3 = ["a", "b", "c", "d"]
list4 = [25.50, True, -55, 1+2j]

List is an ordered collection of items. Each item in a list has a unique position index,
starting from 0.
A list in Python is similar to an array in C, C++ or Java. However, the major difference is
that in C/C++/Java, the array elements must be of same type. On the other hand, Python
lists may have objects of different data types.

A Python list is mutable. Any item from the list can be accessed using its
index, and can be modified. One or more objects from the list can be removed or
added. A list may have same item at more than one index positions.

Accessing Values in Lists


To access values in lists, use the square brackets for slicing along with the index or indices
to obtain value available at that index. For example −

list1 = ['physics', 'chemistry', 1997, 2000];


list2 = [1, 2, 3, 4, 5, 6, 7 ];
print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])

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

list1[0]: physics
list2[1:5]: [2, 3, 4, 5]

Updating Lists
You can update single or multiple elements of lists by giving the slice on the left-hand side
of the assignment operator, and you can add to elements in a list with the append()
method. For example −

324
Python Tutorial

list = ['physics', 'chemistry', 1997, 2000];


print ("Value available at index 2 : ")
print (list[2])
list[2] = 2001;
print ("New value available at index 2 : ")
print (list[2])

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

Value available at index 2 :


1997
New value available at index 2 :
2001

Delete List Elements


To remove a list element, you can use either the del statement if you know exactly which
element(s) you are deleting or the remove() method if you do not know. For example −

list1 = ['physics', 'chemistry', 1997, 2000];


print (list1)
del list1[2];
print ("After deleting value at index 2 : ")
print (list1)

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

['physics', 'chemistry', 1997, 2000]

After deleting value at index 2 :

['physics', 'chemistry', 2000]

Note − remove() method is discussed in subsequent section.

Python List Operations


In Python, List is a sequence. Hence, we can concatenate two lists with "+" operator and
concatenate multiple copies of a list with "*" operator. The membership operators "in" and
"not in" work with list object.

Python Expression Results Description


[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition
3 in [1, 2, 3] TRUE Membership

325
Python Tutorial

Indexing, Slicing, and Matrixes


Because lists are sequences, indexing and slicing work the same way for lists as they do
for strings.
Assuming following input −

L = ['spam', 'Spam', 'SPAM!']

Python Expression Results Description


L[2] SPAM! Offsets start at zero
Negative: count from
L[-2] Spam
the right
Slicing fetches
L[1:] ['Spam', 'SPAM!']
sections

Python List Methods


Python includes following list methods −

Sr.No. Methods with Description


list.append(obj)
1
Appends object obj to list.
list.clear()
2
Clears the contents of list.
list.copy()
3
Returns a copy of the list object.
list.count(obj)
4 Returns count of how many times obj
occurs in list
list.extend(seq)
5
Appends the contents of seq to list
list.index(obj)
6 Returns the lowest index in list that obj
appears
list.insert(index, obj)
7
Inserts object obj into list at offset index
list.pop(obj=list[-1])
8 Removes and returns last object or obj
from list
list.remove(obj)
9
Removes object obj from list
list.reverse()
10
Reverses objects of list in place
list.sort([func])
11 Sorts objects of list, use compare func if
given

Built-in Functions with Lists


Following are the built-in functions we can use with lists −

326
Python Tutorial

Sr.No. Function with Description


cmp(list1, list2)
1
Compares elements of both lists.
len(list)
2
Gives the total length of the list.
max(list)
3 Returns item from the list with max
value.
min(list)
4 Returns item from the list with min
value.
list(seq)
5
Converts a tuple into list.

327
63. Python - Access List Items Python Tutorial

Access List Items


In Python, a list is a sequence of elements or objects, i.e. an ordered collection of objects.
Similar to arrays, each element in a list corresponds to an index.
To access the values within a list, we need to use the square brackets "[]" notation and,
specify the index of the elements we want to retrieve.

The index starts from 0 for the first element and increments by one for each
subsequent element. Index of the last item in the list is always "length-1",
where "length" represents the total number of items in the list.

In addition to this, Python provides various other ways to access list items such as slicing,
negative indexing, extracting a sublist from a list etc. Let us go through this one-by-one

Accessing List Items with Indexing


As discussed above to access the items in a list using indexing, just specify the index of
the element with in the square brackets ("[]") as shown below −

mylist[4]

Example
Following is the basic example to access list items −

list1 = ["Rohan", "Physics", 21, 69.75]


list2 = [1, 2, 3, 4, 5]

print ("Item at 0th index in list1: ", list1[0])


print ("Item at index 2 in list2: ", list2[2])

It will produce the following output −

Item at 0th index in list1: Rohan


Item at index 2 in list2: 3

Access List Items with Negative Indexing


Negative indexing in Python is used to access elements from the end of a list, with -1
referring to the last element, -2 to the second last, and so on.
We can also access list items with negative indexing by using negative integers to
represent positions from the end of the list.
Example
In the following example, we are accessing list items with negative indexing −

328
Python Tutorial

list1 = ["a", "b", "c", "d"]


list2 = [25.50, True, -55, 1+2j]

print ("Item at 0th index in list1: ", list1[-1])


print ("Item at index 2 in list2: ", list2[-3])

We get the output as shown below −

Item at 0th index in list1: d


Item at index 2 in list2: True

Access List Items with Slice Operator


The slice operator in Python is used to fetch one or more items from the list. We can access
list items with the slice operator by specifying the range of indices we want to extract. It
uses the following syntax −

[start:stop]

Where,
 start is the starting index (inclusive).
 stop is the ending index (exclusive).
If we do not provide any indices, the slice operator defaults to starting from index 0 and
stopping at the last item in the list.
Example
In the following example, we are retrieving sublist from index 1 to last in "list1" and index
0 to 1 in "list2", and retrieving all elements in "list3" −

list1 = ["a", "b", "c", "d"]


list2 = [25.50, True, -55, 1+2j]
list3 = ["Rohan", "Physics", 21, 69.75]

print ("Items from index 1 to last in list1: ", list1[1:])


print ("Items from index 0 to 1 in list2: ", list2[:2])
print ("Items from index 0 to index last in list3", list3[:])

Following is the output of the above code −

Items from index 1 to last in list1: ['b', 'c', 'd']


Items from index 0 to 1 in list2: [25.5, True]
Items from index 0 to index last in list3 ['Rohan', 'Physics', 21, 69.75]

329
Python Tutorial

Access Sub List from a List


A sublist is a part of a list that consists of a consecutive sequence of elements from the
original list. We can access a sublist from a list by using the slice operator with appropriate
start and stop indices.
Example
In this example, we are fetching sublist from index "1 to 2" in "list1" and index "0 to 1" in
"list2" using slice operator −

list1 = ["a", "b", "c", "d"]


list2 = [25.50, True, -55, 1+2j]

print ("Items from index 1 to 2 in list1: ", list1[1:3])


print ("Items from index 0 to 1 in list2: ", list2[0:2])

The output obtained is as follows −

Items from index 1 to 2 in list1: ['b', 'c']


Items from index 0 to 1 in list2: [25.5, True]

330
64. Python - Change List Items Python Tutorial

Change List Items


List is a mutable data type in Python. It means, the contents of list can be modified in
place, after the object is stored in the memory. You can assign a new value at a given
index position in the list

Syntax
list1[i] = newvalue

Example
In the following code, we change the value at index 2 of the given list.

list3 = [1, 2, 3, 4, 5]
print ("Original list ", list3)
list3[2] = 10
print ("List after changing value at index 2: ", list3)

It will produce the following output −

Original list [1, 2, 3, 4, 5]


List after changing value at index 2: [1, 2, 10, 4, 5]

Change Consecutive List Items


You can replace more consecutive items in a list with another sublist.
Example
In the following code, items at index 1 and 2 are replaced by items in another sublist.

list1 = ["a", "b", "c", "d"]


print ("Original list: ", list1)
list2 = ['Y', 'Z']
list1[1:3] = list2
print ("List after changing with sublist: ", list1)

It will produce the following output −

Original list: ['a', 'b', 'c', 'd']


List after changing with sublist: ['a', 'Y', 'Z', 'd']

331
Python Tutorial

Change a Range of List Items


If the source sublist has more items than the slice to be replaced, the extra items in the
source will be inserted. Take a look at the following code −
Example

list1 = ["a", "b", "c", "d"]


print ("Original list: ", list1)
list2 = ['X','Y', 'Z']
list1[1:3] = list2
print ("List after changing with sublist: ", list1)

It will produce the following output −

Original list: ['a', 'b', 'c', 'd']


List after changing with sublist: ['a', 'X', 'Y', 'Z', 'd']

Example
If the sublist with which a slice of original list is to be replaced, has lesser items, the items
with match will be replaced and rest of the items in original list will be removed.
In the following code, we try to replace "b" and "c" with "Z" (one less item than items to
be replaced). It results in Z replacing b and c removed.

list1 = ["a", "b", "c", "d"]


print ("Original list: ", list1)
list2 = ['Z']
list1[1:3] = list2
print ("List after changing with sublist: ", list1)

It will produce the following output −

Original list: ['a', 'b', 'c', 'd']


List after changing with sublist: ['a', 'Z', 'd']

332
65. Python - Add List Items Python Tutorial

Add List Items


Adding list items in Python implies inserting new elements into an existing list. Lists are
mutable, meaning they can be modified after creation, allowing for the addition, removal,
or modification of their elements.
Adding items in a list typically refers to appending new elements to the end of the list,
inserting them at specific positions within the list, or extending the list with elements from
another iterable object.
We can add list items in Python using various methods such as append(), extend() and
insert(). Let us explore through all these methods in this tutorial.

Adding List Items Using append() Method


The append() method in Python is used to add a single element to the end of a list.
We can add list items using the append() method by specifying the element we want to
add within the parentheses, like my_list.append(new_item), which adds new_item to the
end of my_list.
Example
In the following example, we are adding an element "e" to the end of the list "list1" using
the append() method −

list1 = ["a", "b", "c", "d"]


print ("Original list: ", list1)
list1.append('e')
print ("List after appending: ", list1)

Output
Following is the output of the above code −

Original list: ['a', 'b', 'c', 'd']


List after appending: ['a', 'b', 'c', 'd', 'e']

Adding List Items Using insert() Method


The insert() method in Python is used to add an element at a specified index (position)
within a list, shifting existing elements to accommodate the new one.
We can add list items using the insert() method by specifying the index position where we
want to insert the new item and the item itself within the parentheses, like
my_list.insert(index, new_item).
Example
In this example, we have an original list containing various items. We use the insert()
method to add new elements to the list at specific positions −

333
Python Tutorial

list1 = ["Rohan", "Physics", 21, 69.75]

list1.insert(2, 'Chemistry')
print ("List after appending: ", list1)

list1.insert(-1, 'Pass')
print ("List after appending: ", list1)

After appending 'Chemistry' to the list, we get the following output −

List after appending: ['Rohan', 'Physics', 'Chemistry', 21, 69.75]

Then, by inserting 'Pass' at the index "-1", which originally referred to 69.75, we get −

List after appending: ['Rohan', 'Physics', 'Chemistry', 21, 'Pass', 69.75]

We can see that "Pass" is not inserted at the updated index "-1", but the previous index
"-1". This behavior is because when appending or inserting items into a list, Python does
not dynamically update negative index positions.

Adding List Items Using extend() Method


The extend() method in Python is used to add multiple elements from an iterable (such as
another list) to the end of a list.
We can add list items using the extend() method by passing another iterable containing
the elements we want to add, like my_list.extend(iterable), which appends each element
from the iterable to the end of my_list.
Example
In the below example, we are using the extend() method to add the elements from
"another_list" to the end of "list1" −

# Original list
list1 = [1, 2, 3]
# Another list to extend with
another_list = [4, 5, 6]

list1.extend(another_list)
print("Extended list:", list1)

Output
Output of the above code is as follows −

Extended list: [1, 2, 3, 4, 5, 6]

334
66. Python - Remove List Items Python Tutorial

Removing List Items


Removing list items in Python implies deleting elements from an existing list. Lists are
ordered collections of items, and sometimes you need to remove certain elements from
them based on specific criteria or indices. When we remove list items, we are reducing the
size of the list or eliminating specific elements.
We can remove list items in Python using various methods such as remove(), pop() and
clear(). Additionally, we can use the del statement to remove items at a specific index. Let
us explore through all these methods in this tutorial.

Remove List Item Using remove() Method


The remove() method in Python is used to remove the first occurrence of a specified item
from a list.
We can remove list items using the remove() method by specifying the value we want to
remove within the parentheses, like my_list.remove(value), which deletes the first
occurrence of value from my_list.
Example
In the following example, we are deleting the element "Physics" from the list "list1" using
the remove() method −

list1 = ["Rohan", "Physics", 21, 69.75]


print ("Original list: ", list1)

list1.remove("Physics")
print ("List after removing: ", list1)

It will produce the following output −

Original list: ['Rohan', 'Physics', 21, 69.75]


List after removing: ['Rohan', 21, 69.75]

Remove List Item Using pop() Method


The pop() method in Python is used to remove and return the last element from a list if
no index is specified. It can also remove and return the element at a specified index,
altering the original list.
We can remove list items using the pop() method by calling it without any arguments
my_list.pop(), which removes and returns the last item from my_list, or by providing the
index of the item we want to remove my_list.pop(index), which removes and returns the
item at that index.

335
Python Tutorial

Example
The following example shows how you can use the pop() method to remove list items −

list2 = [25.50, True, -55, 1+2j]


print ("Original list: ", list2)
list2.pop(2)
print ("List after popping: ", list2)

We get the output as shown below −

Original list: [25.5, True, -55, (1+2j)]


List after popping: [25.5, True, (1+2j)]

Remove List Item Using clear() Method


The clear() method in Python is used to remove all elements from a list, leaving it empty.
We can remove all list items using the clear() method by calling it on the list object like
my_list.clear(), which empties my_list, leaving it with no elements.
Example
In this example, we are using the clear() method to remove all elements from the list
"my_list" −

my_list = [1, 2, 3, 4, 5]

# Clearing the list


my_list.clear()
print("Cleared list:", my_list)

Output of the above code is as follows −

Cleared list: []

Remove List Item Using del Keyword


The del keyword in Python is used to delete element either at a specific index or a slice of
indices from memory.
We can remove list items using the del keyword by specifying the index or slice of the
items we want to delete, like del my_list[index] to delete a single item or del
my_list[start:stop] to delete a range of items.
Example
In the below example, we are using the "del" keyword to delete an element at the index
"2" from the list "list1" −

list1 = ["a", "b", "c", "d"]


print ("Original list: ", list1)
del list1[2]

336
Python Tutorial

print ("List after deleting: ", list1)

The result produced is as follows −

Original list: ['a', 'b', 'c', 'd']


List after deleting: ['a', 'b', 'd']

Example
In here, we are deleting a series of consecutive items from a list with the slicing operator

list2 = [25.50, True, -55, 1+2j]


print ("List before deleting: ", list2)
del list2[0:2]
print ("List after deleting: ", list2)

It will produce the following output −

List before deleting: [25.5, True, -55, (1+2j)]


List after deleting: [-55, (1+2j)]

337
67. Python - Loop Lists Python Tutorial

Loop Through List Items


Looping through list items in Python refers to iterating over each element within a list. We
do so to perform the desired operations on each item. These operations include list
modification, conditional operations, string manipulation, data analysis, etc.
Python provides various methods for looping through list items, with the most common
being the for loop. We can also use the while loop to iterate through list items, although
it requires additional handling of the loop control variable explicitly i.e. an index.

Loop Through List Items with For Loop


A for loop in Python is used to iterate over a sequence (like a list, tuple, dictionary, string,
or range) or any other iterable object. It allows you to execute a block of code repeatedly
for each item in the sequence.
In a for loop, you can access each item in a sequence using a variable, allowing you to
perform operations or logic based on that item's value. We can loop through list items
using for loop by iterating over each item in the list.
Syntax
Following is the basic syntax to loop through items in a list using a for loop in Python −

for item in list:


# Code block to execute

Example
In the following example, we are using a for loop to iterate through each element in the
list "lst" and retrieving each element followed by a space on the same line −

lst = [25, 12, 10, -21, 10, 100]


for num in lst:
print (num, end = ' ')

Output
Following is the output of the above code −

25 12 10 -21 10 100

Loop Through List Items with While Loop


A while loop in Python is used to repeatedly execute a block of code as long as a specified
condition evaluates to "True".

338
Python Tutorial

We can loop through list items using the while loop by initializing an index variable, then
iterating through the list using the index variable and incrementing it until reaching the
end of the list.

An index variable is used within a loop to keep track of the current position
or index in a sequence, such as a list or array. It is generally initialized
before the loop and updated within the loop to iterate over the sequence.

Syntax
Following is the basic syntax for looping through items in a list using a while loop in Python

while condition:
# Code block to execute

Example
In the below example, we iterate through each item in the list "my_list" using a while loop.
We use an index variable "index" to access each item sequentially, incrementing it after
each iteration to move to the next item −

my_list = [1, 2, 3, 4, 5]
index = 0

while index < len(my_list):


print(my_list[index])
index += 1

Output
Output of the above code is as follows −

1
2
3
4
5

Loop Through List Items with Index


An index is a numeric value representing the position of an element within a sequence,
such as a list, starting from 0 for the first element.
We can loop through list items using index by iterating over a range of indices
corresponding to the length of the list and accessing each element using the index within
the loop.
Example
This example initializes a list "lst" with integers and creates a range of indices
corresponding to the length of the list. Then, it iterates over each index in the range and
prints the value at that index in the list "lst" −
339
Python Tutorial

lst = [25, 12, 10, -21, 10, 100]


indices = range(len(lst))
for i in indices:
print ("lst[{}]: ".format(i), lst[i])

Output
We get the output as shown below −

lst[0]: 25
lst[1]: 12
lst[2]: 10
lst[3]: -21
lst[4]: 10
lst[5]: 100

Iterate using List Comprehension


A list comprehension in Python is a concise way to create lists by applying an expression
to each element of an iterable. These expressions can be arithmetic operations, function
calls, conditional expressions etc.
We can iterate using list comprehension by specifying the expression and the iterable (like
a list, tuple, dictionary, string, or range). Following is the syntax −

[expression for item in iterable]

This applies the expression to each item in the iterable and creates a list of results.
Example
In this example, we use list comprehension to iterate through each number in a list of
numbers, square each one, and store the squared result in the new list "squared_numbers"

numbers = [1, 2, 3, 4, 5]
squared_numbers = [num ** 2 for num in numbers]
print (squared_numbers)

Output
We get the output as shown below −

[1, 4, 9, 16, 25]

Iterate using the enumerate() Function


The enumerate() function in Python is used to iterate over an iterable object while also
providing the index of each element.
We can iterate using the enumerate() function by applying it to the iterable. Following is
the syntax −

340
Python Tutorial

for index, item in enumerate(iterable):

This provides both the index and item of each element in the iterable during iteration
Example
In the following example, we are using the enumerate() function to iterate through a list
"fruits" and retrieve each fruit along with its corresponding index −

fruits = ["apple", "banana", "cherry"]


for index, fruit in enumerate(fruits):
print(index, fruit)

Output
We get the output as shown below −

0 apple
1 banana
2 cherry

341
68. Python - List ComprehensionPython Tutorial

List Comprehension in Python


A list comprehension is a concise way to create lists. It is similar to set builder notation in
mathematics. It is used to define a list based on an existing iterable object, such as a list,
tuple, or string, and apply an expression to each element in the iterable.

Syntax of Python List Comprehension


The basic syntax of list comprehension is −

new_list = [expression for item in iterable if condition]

Where,
 expression is the operation or transformation to apply to each item in the iterable.
 item is the variable representing each element in the iterable.
 iterable is the sequence of elements to iterate over.
 condition (optional) is an expression that filters elements based on a specified
condition.

Example of Python List Comprehension


Suppose we want to convert all the letters in the string "hello world" to their upper-case
form. Using list comprehension, we iterate through each character, check if it is a letter,
and if so, convert it to uppercase, resulting in a list of uppercase letters −

string = "hello world"


uppercase_letters = [char.upper() for char in string if char.isalpha()]
print(uppercase_letters)

The result obtained is displayed as follows −

['H', 'E', 'L', 'L', 'O', 'W', 'O', 'R', 'L', 'D']

List Comprehensions and Lambda


In Python, lambda is a keyword used to create anonymous functions. An anonymous
function is a function defined without a name. These functions are created using the
lambda keyword followed by a comma-separated list of arguments, followed by a colon :,
and then the expression to be evaluated.
We can use list comprehension with lambda by applying the lambda function to each
element of an iterable within the comprehension, generating a new list.
Example
In the following example, we are using list comprehension with a lambda function to double
each element in a given list "original_list". We iterate over each element in the
"original_list" and apply the lambda function to double it −

342
Python Tutorial

original_list = [1, 2, 3, 4, 5]
doubled_list = [(lambda x: x * 2)(x) for x in original_list]
print(doubled_list)

Following is the output of the above code −

[2, 4, 6, 8, 10]

Nested Loops in Python List Comprehension


A nested loop in Python is a loop inside another loop, where the inner loop is executed
multiple times for each iteration of the outer loop.
We can use nested loops in list comprehension by placing one loop inside another, allowing
for concise creation of lists from multiple iterations.
Example
In this example, all combinations of items from two lists in the form of a tuple are added
in a third list object −

list1=[1,2,3]
list2=[4,5,6]
CombLst=[(x,y) for x in list1 for y in list2]
print (CombLst)

It will produce the following output −

[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]

Conditionals in Python List Comprehension


Conditionals in Python refer to the use of statements like "if", "elif", and "else" to control
the flow of a code based on certain conditions. They allow you to execute different blocks
of code depending on whether a condition evaluates to "True" or "False".
We can use conditionals in list comprehension by including them after the iterable and
before the loop, which filters elements from the iterable based on the specified condition
while generating the list.
Example
The following example uses conditionals within a list comprehension to generate a list of
even numbers from 1 to 20 −

list1=[x for x in range(1,21) if x%2==0]


print (list1)

We get the output as follows −

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

343
Python Tutorial

List Comprehensions vs For Loop


List comprehensions and for loops are both used for iteration, but they differ in terms of
syntax and usage.
List comprehensions are like shortcuts for creating lists in Python. They let you generate
a new list by applying an operation to each item in an existing list.
For loop, on the other hand, is a control flow statement used to iterate over elements of
an iterable one by one, executing a block of code for each element.

List comprehensions are often preferred for simpler operations, while for loops
offer more flexibility for complex tasks.

Example Using For Loop


Suppose we want to separate each letter in a string and put all non-vowel letters in a list
object. We can do it by a for loop as shown below −

chars=[]
for ch in 'TutorialsPoint':
if ch not in 'aeiou':
chars.append(ch)
print (chars)

The chars list object is displayed as follows −

['T', 't', 'r', 'l', 's', 'P', 'n', 't']

Example Using List Comprehension


We can easily get the same result by a list comprehension technique. A general usage of
list comprehension is as follows −

listObj = [x for x in iterable]

Applying this, chars list can be constructed by the following statement −

chars = [ char for char in 'TutorialsPoint' if char not in 'aeiou']


print (chars)

The chars list will be displayed as before −

['T', 't', 'r', 'l', 's', 'P', 'n', 't']

Example
The following example uses list comprehension to build a list of squares of numbers
between 1 to 10 −

squares = [x*x for x in range(1,11)]


print (squares)

The squares list object is −

344
Python Tutorial

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Advantages of List Comprehension


Following are the advantages of using list comprehension −
 Conciseness − List comprehensions are more concise and readable compared to
traditional for loops, allowing you to create lists with less code.
 Efficiency − List comprehensions are generally faster and more efficient than for
loops because they are optimized internally by Python's interpreter.
 Clarity − List comprehensions result in clearer and more expressive code, making
it easier to understand the purpose and logic of the operation being performed.
 Reduced Chance of Errors − Since list comprehensions are more compact, there
is less chance of errors compared to traditional for loops, reducing the likelihood of
bugs in your code.

345
69. Python - Sort Lists Python Tutorial

Sorting Lists in Python


Sorting a list in Python is a way to arrange the elements of the list in either ascending or
descending order based on a defined criterion, such as numerical or lexicographical order.
This can be achieved using the built-in sorted() function or by calling the sort() method
on the list itself, both of which modify the original list or return a new sorted list depending
on the method used.

Sorting Lists Using sort() Method


The python sort() method is used to sort the elements of a list in place. This means that
it modifies the original list and does not return a new list.
Syntax
The syntax for using the sort() method is as follows −

list_name.sort(key=None, reverse=False)

Where,
 list_name is the name of the list to be sorted.
 key (optional) is a function that defines the sorting criterion. If provided, it is
applied to each element of the list for sorting. Default is None.
 reverse (optional) is a boolean value. If True, the list will be sorted in descending
order. If False (default), the list will be sorted in ascending order.

Example of Sorting List in Lexicographical Order


In the following example, we are using the sort() function to sort the items of the list
alphanumerically −

list1 = ['physics', 'Biology', 'chemistry', 'maths']


print ("list before sort:", list1)
list1.sort()
print ("list after sort : ", list1)

It will produce the following output −

list before sort: ['physics', 'Biology', 'chemistry', 'maths']


list after sort : ['Biology', 'chemistry', 'maths', 'physics']

Example of Sorting List in Numerical Order


Here, we are using the sort() function to sort the given list in numerical order −

list2 = [10,16, 9, 24, 5]


print ("list before sort", list2)

346
Python Tutorial

list2.sort()
print ("list after sort : ", list2)

The output produced is as shown below −

list before sort [10, 16, 9, 24, 5]


list after sort : [5, 9, 10, 16, 24]

Sorting Lists Using sorted() Method


The sorted() function in Python is a built-in function used to sort the elements of an iterable
(such as a list, tuple, or string) and returns a new sorted list, leaving the original iterable
unchanged.
Syntax
The syntax for using the sorted() method is as follows −

sorted(iterable, key=None, reverse=False)

Where,
 iterable is the iterable (e.g., list, tuple, string) whose elements are to be sorted.
 key (optional) is a function that defines the sorting criterion. If provided, it is
applied to each element of the iterable for sorting. Default is None.
 reverse (optional) is a boolean value. If True, the iterable will be sorted in
descending order. If False (default), the iterable will be sorted in ascending order.
Example
In the following example, we are using the sorted() function to sort a list of numbers and
retrieve a new sorted list −

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
# Sorting in descending order
sorted_numbers_desc = sorted(numbers, reverse=True)
print(sorted_numbers_desc)

Following is the output of the above code −

[9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]

Sorting List Items with Callback Function


In Python, a callback function refers to a function that is passed as an argument to another
function and is invoked or called within that function
We can sort list items with a callback function by using the sorted() function or sort()
function in Python. Both of these functions allows us to specify a custom sorting criterion
using the "key" parameter, which accepts a callback function. This callback function defines
how the elements should be compared and sorted.

Example Using str.lower() as key Parameter

347
Python Tutorial

The str.lower() method in Python is used to convert all the characters in a string to
lowercase. It returns a new string with all alphabetic characters converted to lowercase
while leaving non-alphabetic characters unchanged.
In this example, we are passing the str.lower() method as an argument to the "key"
parameter within the sort() function −

list1 = ['Physics', 'biology', 'Biomechanics', 'psychology']


print ("list before sort", list1)
list1.sort(key=str.lower)
print ("list after sort : ", list1)

It will produce the following output −

list before sort ['Physics', 'biology', 'Biomechanics', 'psychology']


list after sort : ['biology', 'Biomechanics', 'Physics', 'psychology']

Example using user-defined Function as key Parameter


We can also use a user-defined function as the key parameter in sort() method.
In this example, the myfunction() uses % operator to return the remainder, based on
which the sorting is performed −

def myfunction(x):
return x%10
list1 = [17, 23, 46, 51, 90]
print ("list before sort", list1)
list1.sort(key=myfunction)
print ("list after sort : ", list1)

It will produce the following output −

list before sort [17, 23, 46, 51, 90]


list after sort: [90, 51, 23, 46, 17]

348
70. Python - Copy Lists Python Tutorial

Copying a List in Python


Copying a list in Python refers to creating a new list that contains the same elements as
the original list. There are different methods for copying a list, including, using slice
notation, the list() function, and using the copy() method.
Each method behaves differently in terms of whether it creates a shallow copy or a deep
copy. Let us discuss about all of these deeply in this tutorial.

Shallow Copy on a Python List


A shallow copy in Python creates a new object, but instead of copying the elements
recursively, it copies only the references to the original elements. This means that the new
object is a separate entity from the original one, but if the elements themselves are
mutable, changes made to those elements in the new object will affect the original object
as well.

Example of Shallow Copy


Let us illustrate this with the following example −

import copy
# Original list
original_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Creating a shallow copy
shallow_copied_list = copy.copy(original_list)
# Modifying an element in the shallow copied list
shallow_copied_list[0][0] = 100
# Printing both lists
print("Original List:", original_list)
print("Shallow Copied List:", shallow_copied_list)

As you can see, even though we only modified the first element of the first sublist in the
shallow copied list, the same change is reflected in the original list as well.
This is because a shallow copy only creates new references to the original objects, rather
than creating copies of the objects themselves −

Original List: [[100, 2, 3], [4, 5, 6], [7, 8, 9]]


Shallow Copied List: [[100, 2, 3], [4, 5, 6], [7, 8, 9]]

349
Python Tutorial

Deep Copy on a Python List


A deep copy in Python creates a completely new object and recursively copies all the
objects referenced by the original object. This means that even nested objects within the
original object are duplicated, resulting in a fully independent copy where changes made
to the copied object do not affect the original object, and vice versa.

Example of Deep Copy


Let us illustrate this with the following example −

import copy
# Original list
original_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Creating a deep copy
deep_copied_list = copy.deepcopy(original_list)
# Modifying an element in the deep copied list
deep_copied_list[0][0] = 100
# Printing both lists
print("Original List:", original_list)
print("Deep Copied List:", deep_copied_list)

As you can see, when we modify the first element of the first sublist in the deep copied
list, it does not affect the original list.
This is because a deep copy creates a new object and recursively copies all the nested
objects, ensuring that the copied object is fully independent from the original one −

Original List: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]


Deep Copied List: [[100, 2, 3], [4, 5, 6], [7, 8, 9]]

Copying List Using Slice Notation


Slice notation in Python allows you to create a subsequence of elements from a sequence
(like a list, tuple, or string) by specifying a start index, an end index, and an optional step
size. The syntax for slice notation is as follows −

[start:end:step]

Where, start is the index where the slice starts, end is the index where the slice ends
(exclusive), and step is the step size between elements.
We can copy a list using slice notation by specifying the entire range of indices of the
original list. This effectively creates a new list with the same elements as the original list.

Any modifications made to the copied list will not affect the original list,
and vice versa, because they are separate objects in memory.

Example

350
Python Tutorial

In this example, we are creating a slice of the "original_list", effectively copying all its
elements into a new list "copied_list" −

# Original list
original_list = [1, 2, 3, 4, 5]
# Copying the list using slice notation
copied_list = original_list[1:4]
# Modifying the copied list
copied_list[0] = 100
# Printing both lists
print("Original List:", original_list)
print("Copied List:", copied_list)

We get the result as shown below −

Original List: [1, 2, 3, 4, 5]


Copied List: [100, 3, 4]

Copying List Using the list() Function


The list() function in Python is a built-in function used to create a new list object. It can
accept an iterable (like another list, tuple, set, etc.) as an argument and create a new list
containing the elements of that iterable. If no argument is provided, an empty list is
created.
We can copy a list using the list() function by passing the original list as an argument. This
will create a new list object containing the same elements as the original list.
Example
In the example below, we are creating a new list object "copied_list" containing the same
elements as "original_list" using the list() function −

# Original list
original_list = [1, 2, 3, 4, 5]
# Copying the list using the list() constructor
copied_list = list(original_list)
# Printing both lists
print("Original List:", original_list)
print("Copied List:", copied_list)

Following is the output of the above code −

Original List: [1, 2, 3, 4, 5]


Copied List: [1, 2, 3, 4, 5]

351
Python Tutorial

Copying List using the copy() Function


In Python, the copy() function is used to create a shallow copy of a list or other mutable
objects. This function is part of the copy module in Python's standard library.
We can copy a list using the copy() function by invoking it on the original list. This creates
a new list object that contains the same elements as the original list.
Example
In the following example, we are using the copy() function to creates a new list object
"copied_list" containing the same elements as "original_list" −

import copy
original_list = [1, 2, 3, 4, 5]
# Copying the list using the copy() function
copied_list = copy.copy(original_list)
print("Copied List:", copied_list)

Output of the above code is as shown below −

Copied List: [1, 2, 3, 4, 5]

352
71. Python - Join Lists Python Tutorial

Join Lists in Python


Joining lists in Python refers to combining the elements of multiple lists into a single list.
This can be achieved using various methods, such as concatenation, list comprehension,
or using built-in functions like extend() or + operator.
Joining lists does not modify the original lists but creates a new list containing the
combined elements.

Join Lists Using Concatenation Operator


The concatenation operator in Python, denoted by +, is used to join two sequences, such
as strings, lists, or tuples, into a single sequence. When applied to lists, the concatenation
operator joins the elements of the two (or more) lists to create a new list containing all
the elements from both lists.
We can join a list using the concatenation operator by simply using the + symbol to
concatenate the lists.
Example
In the following example, we are concatenating the elements of two lists "L1" and "L2",
creating a new list "joined_list" containing all the elements from both lists −

# Two lists to be joined


L1 = [10,20,30,40]
L2 = ['one', 'two', 'three', 'four']
# Joining the lists
joined_list = L1 + L2

# Printing the joined list


print("Joined List:", joined_list)

Following is the output of the above code −

Joined List: [10, 20, 30, 40, 'one', 'two', 'three', 'four']

Join Lists Using List Comprehension


List comprehension is a concise way to create lists in Python. It is used to generate new
lists by applying an expression to each item in an existing iterable, such as a list, tuple, or
range. The syntax for list comprehension is −

new_list = [expression for item in iterable]

This creates a new list where expression is evaluated for each item in the iterable.

353
Python Tutorial

We can join a list using list comprehension by iterating over multiple lists and appending
their elements to a new list.
Example
In this example, we are joining two lists, L1 and L2, into a single list using list
comprehension. The resulting list, joined_list, contains all elements from both L1 and L2

# Two lists to be joined


L1 = [36, 24, 3]
L2 = [84, 5, 81]
# Joining the lists using list comprehension
joined_list = [item for sublist in [L1, L2] for item in sublist]
# Printing the joined list
print("Joined List:", joined_list)

Output of the above code is as follows −

Joined List: [36, 24, 3, 84, 5, 81]

Join Lists Using append() Function


The append() function in Python is used to add a single element to the end of a list. This
function modifies the original list by adding the element to the end of the list.
We can join a list using the append() function by iterating over the elements of one list
and appending each element to another list.
Example
In the example belo