Python Tutorial Final
Python Tutorial Final
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 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.
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.
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.
v
Python Tutorial
Table of Contents
About the Tutorial .......................................................................................................................................... i
What is Python?.............................................................................................................................................. i
Prerequisites .................................................................................................................................................. v
Table of Contents.......................................................................................................................................... vi
vi
Python Tutorial
vii
Python Tutorial
viii
Python Tutorial
ix
Python Tutorial
x
Python Tutorial
xi
Python Tutorial
xii
Python Tutorial
xiii
Python Tutorial
xiv
Python Tutorial
xv
Python Tutorial
Python Basics
1
1. Python – Overview Python Tutorial
>>>import this
2
Python Tutorial
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.
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.
5
Python Tutorial
6
3. Python - Features Python Tutorial
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
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
10
4. Python vs C++ Python Tutorial
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
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 −
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.
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 −
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.
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.
Python is a dynamic-typed
Typing C++ is a static-typed language.
language.
15
Python Tutorial
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.
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.
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
PS C:\> python
17
Python Tutorial
$ 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.
For Windows OS, open the command prompt terminal (CMD) and run the program as
shown below −
C:\>python hello.py
Hello World
$ python3 hello.py
Hello World
#!/usr/bin/python3
18
Python Tutorial
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
Hello World
FAQs
19
6. Python - Application Areas Python Tutorial
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
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:
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.
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.
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.
#! /usr/bin/python3.11
$ chmod +x prog.py
You can now execute the script directly, without using it as a command-line argument.
$ ./hello.py
25
Python Tutorial
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.
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?.
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
Directory of F:\Python311
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.
$ 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/
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 −
$ 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.
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.
To install the latest Python 3.11 version, enter the following command in the terminal −
$ 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.
>>>
29
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.
33
Python Tutorial
Running Python
Interactive Interpreter
You can start Python from Unix, DOS, or any other system that provides you
a command-line interpreter or shell window.
$python # Unix/Linux
or
python% # Unix/Linux
or
C:> python # Windows/DOS
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
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
36
9. Python - Virtual EnvironmentPython Tutorial
37
Python Tutorial
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
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.
(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.
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.
$ 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 −
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!
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
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 −
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.
41
Python Tutorial
in is lambda
None nonlocal not
or pass raise
return TRUE try
while with yield
if True:
print ("True")
else:
print ("False")
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
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 −
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)
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
Hello, World!
You can type a comment on the same line after a statement or expression −
# 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.
'''
#!/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.
if expression :
suite
elif expression :
suite
else :
suite
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
48
Python Tutorial
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
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)
100
Traceback (most recent call last):
49
Python Tutorial
<class 'str'>
<class 'int'>
<class 'float'>
x = 10
y = 10
z = 10.0
50
Python Tutorial
age = 20
Age = 30
age = 20
Age = 30
>>> a=10
>>> b=10
>>> c=10
>>> a=b=c=10
>>> print (a,b,c)
10 10 10
>>> 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 = 100
51
Python Tutorial
print (a)
print (b)
print (c)
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 −
print (a)
print (b)
print (c)
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.
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)
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)
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
#! /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
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))
15
x = 5
y = 10
def sum():
sum = x + y
return sum
print(sum())
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.
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
57
Python Tutorial
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'>
# 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))
>>> 'TutorialsPoint'
'TutorialsPoint'
>>> "TutorialsPoint"
'TutorialsPoint'
>>> '''TutorialsPoint'''
'TutorialsPoint'
A string in Python is an object of str class. It can be verified with type() function.
Hello World!
59
Python Tutorial
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
A list in Python is an object of list class. We can check it with type() function.
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.
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
60
Python Tutorial
In Python, a tuple is an object of tuple class. We can check it with the type() function.
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.
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.
61
Python Tutorial
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 −
for i in range(5):
print(i)
62
Python Tutorial
0
1
2
3
4
Now let's modify above program to print the number starting from 2 instead of 0 −
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:
1
3
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 −
b'Hello'
bytearray(b'Hello')
64
Python Tutorial
print(val)
bytearray(b'Hello')
<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)
<memory at 0x0000017963CD3580>
65
Python Tutorial
<memory at 0x00000200D9AA3580>
In Python, dictionary is an object of the built-in dict class. We can check it with the type()
function.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed
using square braces ([]).
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
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.
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.
Example of Set
{123, 452, 5, 6}
{'Python', 'JavaScript', 'Java'}
67
Python Tutorial
a = True
# display the value of a
print(a)
# display the data type of a
print(type(a))
true
<class 'bool'>
Following is another program which evaluates the expressions and prints the return values
−
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))
False
False
False
False
False
True
# Declaring a variable
# And, assigning a Null value (None)
x = None
x = None
type of x = <class 'NoneType'>
69
Python Tutorial
Example
In the following example, we are getting the type of the values and variables −
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
<class 'int'>
<class 'float'>
<class 'int'>
<class 'float'>
<class 'str'>
<class 'tuple'>
<class 'list'>
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
x = 10
type of x = <class 'int'>
x = Hello World!
type of x = <class 'str'>
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
Example
Following is an example which converts different values to integer, floating point and string
values respectively −
print (a)
print (b)
print (c)
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)
73
Python Tutorial
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.
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);
11.5
<<< 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 −
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'>
<<< 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.
<<< a = int("110011", 2)
<<< a
77
Python Tutorial
51
<<< a = int("20", 8)
<<< a
16
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)
1
2
3
<<< 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'
<<< 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:
print (a)
print (b)
print (c)
1.0
2.2
3.3
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'>
<<< 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:
print (a)
print (b)
print (c)
1
2.2
3.3
### list() separates each character in the string and builds the list
<<< obj=list(c)
<<< obj
['H', 'e', 'l', 'l', 'o']
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')
### 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.
83
Python Tutorial
84
14. Python - Unicode System Python Tutorial
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.
Example
var = "3/4"
print (var)
var = "\u00BE"
print (var)
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)
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
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)
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
When you run this code, it will produce the following output −
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
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))
L1=[1,"Ravi",75.50, True]
91
Python Tutorial
T1=(1,"Ravi",75.50, True)
print (T1, type(T1))
T1=1,"Ravi",75.50, True
print (T1, type(T1))
92
Python Tutorial
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,
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.
- Subtraction a – b = -10
* Multiplication a * b = 200
/ Division b/a=2
% Modulus b%a=0
94
Python Tutorial
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
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
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
97
Python Tutorial
|= a |= 5 a=a|5
^= a ^= 5 a=a^5
>>= a >>= 5 a = a >> 5
<<= a <<= 5 a = a << 5
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
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
or OR a or b
var = 5
Output
True
True
False
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 −
a = 10
b = 20
list = [1, 2, 3, 4, 5 ]
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
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
103
17. Python - Arithmetic OperatorsPython Tutorial
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)
104
Python Tutorial
a=10
b=20.5
print ("Addition of integer and float")
print ("a =",a,"b =",b,"addition =",a+b)
a=10+5j
b=20.5
print ("Addition of complex and float")
print ("a=",a,"b=",b,"addition=",a+b)
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 −
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)
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)
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)
106
Python Tutorial
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)
a=10+5j
b=20.5
print ("Multiplication of complex and float")
print ("a =",a,"b =",b,"a*b =",a*b)
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
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)
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)
108
Python Tutorial
a=0
b=2.5
print ("a=",a,"b=",b,"a/b=",a/b)
print ("a=",a,"b=",b,"b/a=",b/a)
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
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
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)
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)
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
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)
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
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)
For example,
a=6+4j
b=3+2j
c=a*b
c=(18-8)+(12+12)j
c=10+24j
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)
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
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
a=5
b=7
print (a>b)
print (a<b)
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
116
Python Tutorial
Example
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
117
Python Tutorial
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
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)
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
119
Python Tutorial
120
19. Python - Assignment Operators
Python Tutorial
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".
121
Python Tutorial
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'>
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))
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))
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))
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))
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))
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
127
20. Python - Logical Operators Python Tutorial
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.
a b a and b
F F F
F T F
T F F
T T T
a b a or b
F F F
F T T
T F T
T T T
128
Python Tutorial
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.
129
Python Tutorial
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)
x and y: 20
x or y: 10
z or x: 10
y or z: 20
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)
a and b: ()
b or a: Hello
x=[1,2,3]
y=[10,20,30]
print("x and y:",x and y)
print("x or y:",x or y)
131
21. Python - Bitwise Operators Python Tutorial
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)
a: 60 b: 13 a&b: 12
To understand how Python performs the operation, obtain the binary equivalent of each
variable.
132
Python Tutorial
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
0 | 0 is 0
0 | 1 is 1
1 | 0 is 1
1 | 1 is 1
a=60
b=13
print ("a:",a, "b:",b, "a|b:",a|b)
print ("a:", bin(a))
print ("b:", bin(b))
a: 60 b: 13 a|b: 61
a: 0b111100
133
Python Tutorial
b: 0b1101
0011 1100
|
0000 1101
-------------
0011 1101
>>> int('00111101',2)
61
0 ^ 0 is 0
0 ^ 1 is 1
1 ^ 0 is 1
1 ^ 1 is 0
a=60
b=13
print ("a:",a, "b:",b, "a^b:",a^b)
a: 60 b: 13 a^b: 49
0011 1100
^
0000 1101
-------------
0011 0001
>>> int('00110001',2)
49
134
Python Tutorial
a=60
print ("a:",a, "~a:", ~a)
a: 60 ~a: -61
a=60
print ("a:",a, "a<<2:", a<<2)
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
>>> int('11110000',2)
240
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)
a: 60 a>>2: 15
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
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)
P in TutorialsPoint : True
tor in TutorialsPoint : True
in in TutorialsPoint : True
To in TutorialsPoint : False
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)
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)
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
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)
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)
139
Python Tutorial
140
23. Python - Identity Operators Python Tutorial
a = [1, 2, 3, 4, 5]
b = [1, 2, 3, 4, 5]
c = a
True
False
id(a) : 140114091859456
id(b) : 140114091906944
id(c) : 140114091859456
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
False
True
id(a) : 140559927442176
id(b) : 140559925598080
id(c) : 140559927442176
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)
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)
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
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
>>> 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).
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
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; # 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!")
147
Python Tutorial
number = 5
print(f"The factorial of {number} is {factorial(number)}")
"""
This function calculates the greatest common divisor (GCD)
of two numbers using the Euclidean algorithm. The GCD of
148
Python Tutorial
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__)
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
#! /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
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.
151
Python Tutorial
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()
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.
152
Python Tutorial
#! /usr/bin/python3.11
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.
#! /usr/bin/python3.11
area = width*height
print ("Area of rectangle = ", area)
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 −
You can combine the input and type cast statements in one −
#! /usr/bin/python3.11
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
interest = amount*rate/100
print ("Amount: ", amount, "Interest: ", interest)
The program ask user to enter amount and rate; and displays the result as follows −
154
Python Tutorial
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.
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
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)
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"
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.
>>> a =10
a = 10
b = 20
c = a + b
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")
a=0b101
print ("a:",a, "type:",type(a))
b=int("0b101011", 2)
print ("b:",b, "type:",type(b))
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)
a=0O107
print (a, type(a))
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))
16 <class 'int'>
a=0O56
print ("a:",a, "type:",type(a))
b=int("0O31",8)
print ("b:",b, "type:",type(b))
c=a+b
print ("addition:", c)
a=oct(71)
print (a, type(a))
a=0XA2
print (a, type(a))
159
Python Tutorial
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)
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))
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))
a=10 #decimal
b=0b10 #binary
c=0O10 #octal
d=0XA #Hexadecimal
e=a+b+c+d
160
Python Tutorial
print ("addition:", e)
addition: 30
>>> 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
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)
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)
a= -123.54 b= 12300.0
a=1.00E400
print (a, type(a))
a=float("Infinity")
162
Python Tutorial
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
>>> 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))
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))
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))
164
Python Tutorial
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)
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)
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)
165
Python Tutorial
math.comb(n,k)
math.copysign(x, y)
math.cmp(x, y)
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)
math.frexp(x)
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)
math.isclose()
13 math.isfinite(x)
166
Python Tutorial
math.isinf(x)
math.isnan(x)
15 This function is used to determine whether the given number is
"NaN".
math.isqrt(n)
math.lcm(*integers)
math.ldexp(x, i)
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)
math.prod(iterable, *, start)
math.remainder(x,y)
24 math.trunk(x)
167
Python Tutorial
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.
math.exp(x)
2
This function calculate the exponential of x: ex
math.exp2(x)
math.expm1(x)
math.log(x)
math.log1p(x)
math.log2(x)
8 math.log10(x)
168
Python Tutorial
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 −
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).
2 math.radians(x)
169
Python Tutorial
Mathematical Constants
The Python math module defines the following mathematical constants −
good.e
math. number
math.inf
math. in
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 −
2 math.asinh(x)
170
Python Tutorial
math.atanh(x)
math.cosh(x)
math.birth(x)
math.tanh(x)
Special Functions
Following are the special functions provided by the Python math module −
math.erfc(x)
math.gamma(x)
math.lgamma(x)
171
Python Tutorial
random.seed([x])
random.shuffle(seq)
random.uniform(a, b)
172
Python Tutorial
173
28. Python - Booleans Python Tutorial
>>> a=True
>>> b=False
>>> type(a), type(b)
(<class 'bool'>, <class 'bool'>)
a=int(True)
print ("bool to int:", a)
a=float(False)
print ("bool to float:", a)
a=complex(True)
print ("bool to complex:", a)
bool to int: 1
bool to float: 0.0
bool to complex: (1+0j)
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
176
29. Python - Control Flow Python Tutorial
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.
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)
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'))
Vowel alphabet
178
Python Tutorial
Simple alphabet
Vowel alphabet
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.
Example
Following is an example which makes use of For Loop to iterate through an array in
Python:
179
Python Tutorial
print(x)
one
two
three
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
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.
Example
The following example demonstrates the use of break statement −
x = 0
180
Python Tutorial
print("End")
x: 0
x: 1
x: 2
x: 3
x: 4
x: 5
Breaking...
End
Example
The following example demonstrates the use of continue statement −
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
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.
183
Python Tutorial
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!")
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")
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")
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.
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.
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.
discount = 0
amount = 1200
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
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.
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.
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.
if expr==True:
stmt1
stmt2
stmt3
else:
stmt4
stmt5
stmt6
Stmt7
190
Python Tutorial
age=25
print ("age: ", age)
if age >=18:
print ("eligible to vote")
else:
print ("not eligible to vote")
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
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
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 −
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
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
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.
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
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.
if boolean_expression1:
statement(s)
if boolean_expression2:
statement(s)
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....
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
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
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
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.
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"))
Full access
Limited access
No access
def greeting(details):
match details:
case [time, name]:
199
Python Tutorial
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]))
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 −
201
Python Tutorial
continue statement
2 Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.
pass statement
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.
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.
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='')
numbers = (34,54,67,21,78,97,45,44,80,19)
total = 0
for num in numbers:
total += num
print ("Total =", total)
Total = 539
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
Syntax
The range() function has the following syntax −
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.
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
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.
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 −
(10, 'Ten')
(20, 'Twenty')
(30, 'Thirty')
(40, 'Forty')
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
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.
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 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")
T
P
ForLoop-else statement successfully executed
210
Python Tutorial
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")
211
Python Tutorial
else:
# Statement inside the else block
print ("Loop-else Executed")
# Calling the above-created function
positive_or_negative()
Positive number
Positive number
Positive number
Loop-else Executed
212
38. Python - While Loops Python Tutorial
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.
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))
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")
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
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!")
The above example goes in an infinite loop and you need to use CTRL+C to exit
the program.
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")
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
flag = 0
while (flag): print ("Given flag is really true!")
216
Python Tutorial
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
looping statement:
condition check:
break
218
Python Tutorial
Example
In this example, we will see the working of break statement in for loop.
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
219
Python Tutorial
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')
220
40. Python - Continue StatementPython Tutorial
221
Python Tutorial
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Good bye!
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
222
Python Tutorial
Assign different value (say 75) to num in the above program and test the result for its
prime factors.
223
41. Python - pass Statement Python Tutorial
pass
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!
224
Python Tutorial
If you want to code an infinite loop that does nothing each time through, do it as shown
below −
Because the body of the loop is just an empty statement, Python gets stuck in this loop.
def func1():
# Alternative to pass
...
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.
for x in months:
for y in days:
print(x, y)
print("Good bye!")
jan sun
jan mon
226
Python Tutorial
jan tue
feb sun
feb mon
feb tue
mar sun
mar mon
mar tue
Good bye!
while expression:
while expression:
statement(s)
statement(s)
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
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
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.
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.
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
231
Python Tutorial
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.
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)
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)
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")
Hello Samay
Hello Pratima
Hello Steven
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.
My string
Example 2
The following example gives more clear picture. Note that the order of parameters does
not matter.
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 −
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.
237
Python Tutorial
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.
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
Output is:
10
Output is:
70
60
50
In the next few chapters, we will discuss these function arguments at length.
239
Python Tutorial
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))
a = 10 b = 20 a+b = 30
240
Python Tutorial
Syntax
The syntax of lambda functions contains only a single statement, which is as follows −
Example
Following is the example to show how lambda form of function works −
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
241
Python Tutorial
return total;
242
44. Python - Default ArgumentsPython Tutorial
Default arguments in Python are the function arguments that will be used if no
arguments are passed to the function call.
# Function definition
def showinfo( name, city = "Hyderabad" ):
"This prints a passed info into this function"
print ("Name:", name)
print ("City:", city)
return
Name: Ansh
City: Delhi
Name: Shrey
City: Hyderabad
# function definition
243
Python Tutorial
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)
percentage: 65.0
percentage: 86.0
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.
# function calls
fcn(66)
fcn(68)
fcn(70)
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.
# by keyword arguments
printinfo(name="miki", age = 30)
Name: Naveen
Age 29
Name: miki
Age 30
246
Python Tutorial
division(10,5)
division(5,10)
Since the values are assigned as per the position, the output is as follows −
Example
Instead of passing the values with positional arguments, let us call the function with
keyword arguments −
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 −
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.
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.
It will print −
Hello-World
Hello World -
249
Python Tutorial
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.
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.
def add(x,y):
z = x+y
print ("x={} y={} x+y={}".format(x,y,z))
a = 10
b = 20
add(a, b)
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
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)
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)
z=x+y
~^~
TypeError: can only concatenate str (not "int") to str
252
Python Tutorial
253
48. Python - Positional-Only Arguments
Python Tutorial
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.
On executing, this code will show the following error message −<>
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.
print(intr(amt=1000, rate=10))
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.
10 20 30
10 20 30
255
49. Python - Arbitrary or, Variable-length Arguments
Python Tutorial
# 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
256
Python Tutorial
The function has two arguments, first is the required argument and second to hold any
number of values.
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
def addr(**kwargs):
for k,v in kwargs.items():
print ("{}:{}".format(k,v))
257
Python Tutorial
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.
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()
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()
260
Python Tutorial
variable a: 10
variable b: 20
30
261
Python Tutorial
>>> 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 −
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).
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.
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.
myfunction()
print (marks) # prints global value
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 −
myfunction()
# prints global value
print (marks)
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.
myfunction()
print ("var1:",var1, "var2:",var2) #shows global variables with changed values
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.
myfunction(var1, var2)
print (total) # This gives NameError
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.
print (myfunction(10,20))
print (myfunction("Hello ", "Python"))
30
Hello Python
266
Python Tutorial
c = a+b
return c
print(myfunction(56,88))
print(myfunction.__annotations__)
144
{'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}
174
{'x': 'marks in Physics', 'y': 'marks in chemistry'}
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.
Example 2
The __annotations__ attribute itself is a dictionary in which arguments are keys and
anotations their values.
Example 3
You may have arbitrary positional and/or arbitrary keyword arguments for a function.
Annotations can be given for them also.
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.
268
Python Tutorial
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.
import math
print ("Square root of 100:", math.sqrt(100))
270
Python Tutorial
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
It simplifies HTTP requests by offering a user-friendly interface for sending and handling
responses.
def SayHello(name):
print ("Hi {}! How are you?".format(name))
return
You can also import one module in another Python script. Save the following code as
example.py
import mymodule
mymodule.SayHello("Harish")
272
Python Tutorial
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))
sum:30
average:15.0
power:100
273
Python Tutorial
print ("average:",average(10,20))
sum: 30
average: 15.0
Note that function need not be called by prefixing name of its module to it.
This provides an easy way to import all the items from a module into the current
namespace; however, this statement should be used sparingly.
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.
274
Python Tutorial
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
def average(x,y):
return (x+y)/2
def power(x,y):
return x**y
import 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.
276
Python Tutorial
#example.py
print ("__name__ attribute within a script:", __name__)
Run this in the command terminal −
print ("sum:",sum(10,20))
You can see that sum() function is called within the same script in which it is defined.
sum: 30
import mymodule
print ("sum:",mymodule.sum(10,20))
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 −
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
content = dir(math)
print (content)
def SayHello(name):
print ("Hi {}! How are you?".format(name))
return
We can import the module and call its function from Python prompt as −
278
Python Tutorial
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.
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 −
After you add these lines to __init__.py, you have all of these classes available when you
import the Phone package.
Phone.Pots()
Phone.Isdn()
Phone.G3()
279
Python Tutorial
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
print(len(text)) # Prints 15
In the above example, we are using two built-in functions print() and len().
281
Python Tutorial
282
Python Tutorial
283
Python Tutorial
284
Python Tutorial
285
Python Tutorial
286
Python Tutorial
Python Strings
287
54. Python - Strings Python Tutorial
Looking at the above statements, it is clear that, internally Python stores strings as
included in single quotes.
288
Python Tutorial
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 −
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
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
Here is the list of complete set of symbols which can be used along with % −
290
Python Tutorial
291
Python Tutorial
Visit our Python - String Formatting tutorial to learn about various ways to format strings.
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
Python Tutorial
from TutorialsPoint
'''
292
Python Tutorial
var:
Welcome To
Python Tutorial
from TutorialsPoint
print ("Hello"-"World")
>>> "Hello"-"World"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'str' and 'str'
<class 'str'>
293
Python Tutorial
294
Python Tutorial
295
Python Tutorial
296
Python Tutorial
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 −
H
Y
N
ERROR!
298
Python Tutorial
Example
Let us use negative indexing to fetch N, Y, and H characters.
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)
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])
var="HELLO PYTHON"
300
Python Tutorial
print ("var:",var)
print ("var[3:8]:", var[3:8])
print ("var[-9:-4]:", var[-9:-4])
var="HELLO PYTHON"
print ("var:",var)
print ("var[0:5]:", var[0:5])
print ("var[:5]:", var[:5])
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:])
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[:])
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])
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
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.
s1="WORD"
print ("original string:", s1)
l1=list(s1)
l1.insert(3,"L")
print (l1)
s1=''.join(l1)
print ("Modified string:", s1)
304
Python Tutorial
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")
import io
s1="WORD"
print ("original string:", s1)
305
Python Tutorial
sio=io.StringIO(s1)
sio.seek(3)
sio.write("LD")
s1=sio.getvalue()
306
57. Python - String ConcatenationPython Tutorial
In Python, there are numerous ways to concatenate strings. We are going to discuss the
following −
str1="Hello"
str2="World"
print ("String 1:",str1)
print ("String 2:",str2)
str3=str1+str2
print("String 3:",str3)
307
Python Tutorial
String 1: Hello
String 2: World
String 3: HelloWorld
str1="Hello"
str2="World"
blank=" "
print ("String 1:",str1)
print ("String 2:",str2)
str3=str1+blank+str2
print("String 3:",str3)
String 1: Hello
String 2: World
String 3: Hello World
newString = "Hello" * 3
print(newString)
HelloHelloHello
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
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)
Welcome to Tutorialspoint!
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)
Total: 2800
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)
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)
312
Python Tutorial
Hello
World
Hello\nWorld
# ignore \
s = 'This string will not include \
backslashes or newline characters.'
print (s)
# escape backslash
313
Python Tutorial
# 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)
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 −
Alignment Methods
Following methods in the str class control the alignment of characters within the string
object.
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).
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
318
Python Tutorial
Translation Methods
Following are the Translation methods of the string −
319
Python Tutorial
maketrans()
1 Returns a translation table to be
used in translate function.
translate(table, deletechars="")
320
61. Python - String Exercises Python Tutorial
Example 1
Python program to find number of vowels in a given string.
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)))
binary:10101 integer: 21
Change mystr to '10, 101'
Example 3
Python program to drop all digits from a string.
321
Python Tutorial
chars = []
for x in mystr:
if x not in digits:
chars.append(x)
newstr = ''.join(chars)
print (newstr)
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 −
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.
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
325
Python Tutorial
326
Python Tutorial
327
63. Python - Access List Items Python Tutorial
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
−
mylist[4]
Example
Following is the basic example to access list items −
328
Python Tutorial
[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" −
329
Python Tutorial
330
64. Python - Change List Items Python Tutorial
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)
331
Python Tutorial
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.
332
65. Python - Add List Items Python Tutorial
Output
Following is the output of the above code −
333
Python Tutorial
list1.insert(2, 'Chemistry')
print ("List after appending: ", list1)
list1.insert(-1, 'Pass')
print ("List after appending: ", list1)
Then, by inserting 'Pass' at the index "-1", which originally referred to 69.75, we get −
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.
# 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 −
334
66. Python - Remove List Items Python Tutorial
list1.remove("Physics")
print ("List after removing: ", list1)
335
Python Tutorial
Example
The following example shows how you can use the pop() method to remove list items −
my_list = [1, 2, 3, 4, 5]
Cleared list: []
336
Python Tutorial
Example
In here, we are deleting a series of consecutive items from a list with the slicing operator
−
337
67. Python - Loop Lists Python Tutorial
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 −
Output
Following is the output of the above code −
25 12 10 -21 10 100
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
Output
Output of the above code is as follows −
1
2
3
4
5
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
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 −
340
Python Tutorial
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 −
Output
We get the output as shown below −
0 apple
1 banana
2 cherry
341
68. Python - List ComprehensionPython Tutorial
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.
['H', 'E', 'L', 'L', 'O', 'W', 'O', 'R', 'L', 'D']
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)
[2, 4, 6, 8, 10]
list1=[1,2,3]
list2=[4,5,6]
CombLst=[(x,y) for x in list1 for y in list2]
print (CombLst)
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
343
Python Tutorial
List comprehensions are often preferred for simpler operations, while for loops
offer more flexibility for complex tasks.
chars=[]
for ch in 'TutorialsPoint':
if ch not in 'aeiou':
chars.append(ch)
print (chars)
Example
The following example uses list comprehension to build a list of squares of numbers
between 1 to 10 −
344
Python Tutorial
345
69. Python - Sort Lists Python Tutorial
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.
346
Python Tutorial
list2.sort()
print ("list after sort : ", list2)
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)
[9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]
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 −
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)
348
70. Python - Copy Lists Python Tutorial
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 −
349
Python Tutorial
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 −
[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)
# 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)
351
Python Tutorial
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)
352
71. Python - Join Lists Python Tutorial
Joined List: [10, 20, 30, 40, 'one', 'two', 'three', 'four']
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
−