0% found this document useful (0 votes)
296 views

Python Unit-1

The document provides an introduction to the Python programming language, including its history, uses, advantages, and applications. It describes Python's popularity, versatility, and high demand in various fields including web development, AI, and more. The document aims to help beginners learn Python concepts from basic to advanced levels.

Uploaded by

Chatla Chetan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
296 views

Python Unit-1

The document provides an introduction to the Python programming language, including its history, uses, advantages, and applications. It describes Python's popularity, versatility, and high demand in various fields including web development, AI, and more. The document aims to help beginners learn Python concepts from basic to advanced levels.

Uploaded by

Chatla Chetan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

UNIT-1

INTRODUCTION
INTRODUCTION TO PYTHON
Python
Today, Python is one of the most popular programming languages. Although it is a general-
purpose language, it is used in various areas of applications such as Machine Learning, Artificial
Intelligence, web development, IoT, and more.

This Python tutorial has been written for the beginners to help them understand the basic to
advanced concepts of Python Programming Language. After completing this tutorial, you will
find yourself at a great level of expertise in Python, from where you can take yourself to the next
levels to become a world class Software Engineer.

What is Python?
Python is a very popular general-purpose interpreted, interactive, object-oriented, and high-level
programming language. Python is dynamically-typed and garbage-collected programming
language. It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source
code is also available under the GNU General Public License (GPL).

Python supports multiple programming paradigms, including Procedural, Object Oriented and
Functional programming language. Python design philosophy emphasizes code readability with
the use of significant indentation.
This tutorial gives a complete understanding of Python programming language starting from
basic conceopts to advanced concepts. This tutorial will take you through simple and practical
approaches while learning Python Programming language.

Python Jobs
Today, Python is very high in demand and all the major companies are looking for great Python
Programmers to develop websites, software components, and applications or to work with Data
Science, AI, and ML technologies. When we are developing this tutorial in 2022, there is a high
shortage of Python Programmers where as market demands more number of Python
Programmers due to it's application in Machine Learning, Artificial Intelligence etc.

Today a Python Programmer with 3-5 years of experience is asking for around $150,000 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:

1
 Google
 Intel
 NASA
 PayPal
 Facebook
 IBM
 Amazon
 Netflix
 Pinterest
 Uber
 Many more...

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

Why to Learn Python?


Python is consistently rated as one of the world's most popular programming languages. Python
is fairly easy to learn, so if you are starting to learn any programming language then Python
could be your great choice. Today various Schools, Colleges and Universities are teaching
Python as their primary programming language. There are many other good reasons which
makes Python as the top choice of any programmer:

 Python is Open Source which means its available free of cost.


 Python is simple and so easy to learn
 Python is versatile and can be used to create many different things.
 Python has powerful development libraries include AI, ML etc.
 Python is much in demand and ensures high salary

Python is a MUST for students and working professionals to become a great Software Engineer

specially when they are working in Web Development Domain. I will list down some of the key
advantages of learning Python:

 Python is Interpreted − Python is processed at runtime by the interpreter. You do not


need to compile your program before executing it. This is similar to PERL and PHP.
 Python is Interactive − You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
 Python is Object-Oriented − Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
 Python is a Beginner's Language − Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from simple
text processing to WWW browsers to games.

2
Python Online Compiler/Interpreter
We have provided Python Online Compiler/Interpreter which helps you
to Edit and Execute the code directly from your browser. Try to click the icon to run the
following Python code to print conventional "Hello, World!".

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

# This is my first Python program.


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

print ("Hello, World!");

Careers with Python


If you know Python nicely, then you have a great career ahead. Here are just a few of the career
options where Python is a key skill:

 Game developer
 Web designer
 Python developer
 Full-stack developer
 Machine learning engineer
 Data scientist
 Data analyst
 Data engineer
 DevOps engineer
 Software engineer
 Many more other roles

Characteristics of Python
Following are important characteristics of Python Programming −

 It supports functional and structured programming methods as well as OOP.


 It can be used as a scripting language or can be compiled to byte-code for building large
applications.
 It provides very high-level dynamic data types and supports dynamic type checking.
 It supports automatic garbage collection.
 It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

3
Applications of Python
The latest release of Python is 3.x. As mentioned before, Python is one of the most widely used
language over the web. I'm going to list few of them here:

 Easy-to-learn − Python has few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the language quickly.
 Easy-to-read − Python code is more clearly defined and visible to the eyes.
 Easy-to-maintain − Python's source code is fairly easy-to-maintain.
 A broad standard library − Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, and Macintosh.
 Interactive Mode − Python has support for an interactive mode which allows interactive
testing and debugging of snippets of code.
 Portable − Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
 Extendable − You can add low-level modules to the Python interpreter. These modules
enable programmers to add to or customize their tools to be more efficient.
 Databases − Python provides interfaces to all major commercial databases.
 GUI Programming − Python supports GUI applications that can be created and ported
to many system calls, libraries and windows systems, such as Windows MFC, Macintosh,
and the X Window system of Unix.
 Scalable − Python provides a better structure and support for large programs than shell
scripting.

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.

Prerequisites
Although it is a beginners 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.

4
Python History and Versions
o Python laid its foundation in the late 1980s.
o The implementation of Python was started in December 1989 by Guido Van Rossum at
CWI in Netherland.
o In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to
alt.sources.
o In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.
o Python 2.0 added new features such as list comprehensions, garbage collection systems.
o On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to
rectify the fundamental flaw of the language.
o ABC programming language is said to be the predecessor of Python language, which was
capable of Exception Handling and interfacing with the Amoeba Operating System.
o The following programming languages influence Python:
o ABC language.
o Modula-3

Why the Name Python?


There is a fact behind choosing the name Python. Guido van Rossum was reading the script of a
popular BBC comedy series "Monty Python's Flying Circus". It was late on-air 1970s.

Van Rossum wanted to select a name which unique, sort, and little-bit mysterious. So he decided
to select naming Python after the "Monty Python's Flying Circus" for their newly created
programming language.

The comedy series was creative and well random. It talks about everything. Thus it is slow and
unpredictable, which made it very interesting.

Python is also versatile and widely used in every technical field, such as Machine
Learning, Artificial Intelligence, Web Development, Mobile Application, Desktop Application,
Scientific Calculation, etc.

Python Version List


Python programming language is being updated regularly with new features and supports. There
are lots of update in Python versions, started from 1994 to current release.

5
A list of Python versions with its released date is given below.

Python Version Released Date

Python 1.0 January 1994

Python 1.5 December 31, 1997

Python 1.6 September 5, 2000

Python 2.0 October 16, 2000

Python 2.1 April 17, 2001

Python 2.2 December 21, 2001

Python 2.3 July 29, 2003

Python 2.4 November 30, 2004

Python 2.5 September 19, 2006

Python 2.6 October 1, 2008

Python 2.7 July 3, 2010

Python 3.0 December 3, 2008

Python 3.1 June 27, 2009

Python 3.2 February 20, 2011

Python 3.3 September 29, 2012

Python 3.4 March 16, 2014

Python 3.5 September 13, 2015

Python 3.6 December 23, 2016

Python 3.7 June 27, 2018

Python 3.8 October 14, 2019

6
Tips to Keep in Mind While Learning Python
The most common question asked by the beginners - "What is the best way to learn
Python"? It is the initial and relevant question because first step in learning any programming
language is to know how to learn.

The proper way of learning will help us to learn fast and become a good Python developer.

In this section, we will discuss various tips that we should keep in mind while learning Python.

1. Make it Clear Why We Want to Learn


The goal should be clear before learning the Python. Python is an easy, a vast language as well.
It includes numbers of libraries, modules, in-built functions and data structures. If the goal is
unclear then it will be a boring and monotonous journey of learning Python. Without any clear
goal, you perhaps won't make it done.

So, first figure out the motivation behind learning, which can anything be such as knowing
something new, develop projects using Python, switch to Python, etc. Below are the general
areas where Python is widely used. Pick any of them.

o Data Analysis and Processing


o Artificial Intelligence
o Games
o Hardware/Sensor/Robots
o Desktop Applications

Choose any one or two areas according to your interest and start the journey towards learning
Python.

2. Learn the Basic Syntax


It is the most essential and basic step to learn the syntax of the Python programming language.
We have to learn the basic syntax before dive deeper into learning it. As we have discussed in
our earlier tutorial, Python is easy to learn and has a simple syntax. It doesn't use semicolon and
brackets. Its syntax is like the English language.

So it will take minimum amount of time to learning its syntax. Once we get its syntax properly,
further learning will be easier and quicker getting to work on projects.

Note - Learn Python 3, not Python 2.7, because the industry no longer uses it. Our Python tutorial is
based on its latest version Python 3.

7
3. Write Code by Own
Writing the code is the most effective and robust way to learn Python. First, try to write code on
paper and run in mind (Dry Run) then move to the system. Writing code on paper will help us
get familiar quickly with the syntax and the concept store in the deep memory. While writing the
code, try to use proper functions and suitable variables names.

There are many editors available for Python programming which highlights the syntax related
issue automatically. So we don't need to pay lot of attention of these mistakes.

4. Keep Practicing
The next important step is to do the practice. It needs to implementing the Python concepts
through the code. We should be consistence to our daily coding practice.

Consistency is the key of success in any aspect of life not only in programming. Writing code
daily will help to develop muscle memory.

We can do the problem exercise of related concepts or solve at least 2 or 3 problems of Python. It
may seem hard but muscle memory plays large part in programing. It will take us ahead from
those who believe only the reading concept of Python is sufficient.

5. Make Notes as Needed


Creating notes by own is an excellent method to learn the concepts and syntax of Python. It will
establish stability and focus that helps you become a Python developer. Make brief and concise
notes with relevant information and include appropriate examples of the subject concerned.

Maintain own notes are also helped to learn fast. A study published in Psychological Science that
-

The students who were taking longhand notes in the studies were forced to be more selective —
because you can't write as fast as you can type.

6. Discuss Concepts with Other


Coding seems to be solitary activity, but we can enhance our skills by interacting with the others.
We should discuss our doubts to the expert or friends who are learning Python. This habit will
help to get additional information, tips and tricks, and solution of coding problems. One of the
best advantages of Python, it has a great community. Therefore, we can also learn from
passionate Python enthusiasts.

8
7. Do small Projects
After understanding Python's basic concept, a beginner should try to work on small projects. It
will help to understand Python more deeply and become more component in it. Theoretical
knowledge is not enough to get command over the Python language. These projects can be
anything as long as they teach you something. You can start with the small projects such as
calculator app, a tic-toc-toe game, an alarm clock app, a to-do list, student or customer
management system, etc.

Once you get handy with a small project, you can easily shift toward your interesting domain
(Machine Learning, Web Development, etc.).

8. Teach Others
There is a famous saying that "If you want to learn something then you should teach other".
It is also true in case of learning Python. Share your information to other students via creating
blog posts, recording videos or taking classes in local training center. It will help us to enhance
the understanding of Python and explore the unseen loopholes in your knowledge. If you don't
want to do all these, join the online forum and post your answers on Python related questions.

9. Explore Libraries and Frameworks


Python consists of vast libraries and various frameworks. After getting familiar with Python's
basic concepts, the next step is to explore the Python libraries. Libraries are essential to work
with the domain specific projects. In the following section, we describe the brief introduction of
the main libraries.

o TensorFlow - It is an artificial intelligence library which allows us to create large scale


AI based projects.
o Django - It is an open source framework that allows us to develop web applications. It is
easy, flexible, and simple to manage.
o Flask - It is also an open source web framework. It is used to develop lightweight web
applications.
o Pandas - It is a Python library which is used to perform scientific computations.
o Keras - It is an open source library, which is used to work around the neural network.

There are many libraries in Python. Above, we have mentioned a few of them.

9
10. Contribute to Open Source
As we know, Python is an open source language that means it is freely available for everyone.
We can also contribute to Python online community to enhance our knowledge. Contributing to
open source projects is the best way to explore own knowledge. We also receive the feedback,
comments or suggestions for work that we submitted. The feedback will enable the best practices
for Python programming and help us to become a good Python developer.

Usage of Python
Python is a general purpose, open source, high-level programming language and also provides
number of libraries and frameworks. Python has gained popularity because of its simplicity, easy
syntax and user-friendly environment. The usage of Python as follows.

o Desktop Applications
o Web Applications
o Data Science
o Artificial Intelligence
o Machine Learning
o Scientific Computing
o Robotics
o Internet of Things (IoT)
o Gaming
o Mobile Apps
o Data Analysis and Preprocessing

10
NEED OF PYTHON PROGRAMMING

Python is an object-oriented and open-source language developed in the 1980s by Dutchman


Guido van Rossum. Tech Giants like Cisco, IBM, Mozilla, Google, Quora, Hewlett-Packard,
Dropbox, and Qualcomm are using this language owing to its simplicity and elegance. Most
developers prefer Python over the plethora of programming languages out there because of its
emphasis on readability and efficiency. There are several reasons why you should
consider Python training. A course in Python can provide numerous benefits to the users.
Following are the major features and applications of Python that has influenced more and more
people to learn Python and gain certification.
1. Data Science: Python is the preferred programming language of most data scientists. Be it
IT ops, software development or marketing, currently every job makes use of data and depends
on it to drive their operations. With the release of ‘Numpy‘ and ‘Pandas’, Python rose to
prominence in the world of data. Python also handles statistical, tabular and matrix data and
also visualizes it with libraries like ‘Matplotlib’ and ‘Seaborn‘.
Moreover, in the data science arena, python job postings outnumber all others. This indicates
the fact that the skills you gain with Python will directly transfer to developing your analytic
skills.
2. Easy to Learn: Python is an easy language to master. This is chiefly because of its
resemblance to the English language. Python’s syntax is characterized by very few rules and
special cases. It’s safe to say that in Python the focus is on what you want to do with the code,
not on language intricacies. Anybody can master Python easily. With practice, newbies can
build a basic game in mere days using python. Another attractive aspect of this programming
language is its efficiency and readability.
3. Cross-Platform and Open Source: It’s been more than 20 years since this language has
been running cross-platform and open source. Be it Linux, Windows or MacOS, Python code
works on every platform. Another remarkable thing about Python is that it’s supported by
decades of bug-squashing and kink-straightening which ensures that its code works as intended
whenever the user runs it.
4. Versatile Language and Platform: Python remains very relevant today as it can be used in
any operations scenario or software development, be it in managing local and cloud
infrastructure, working against a SQL database, developing a custom function for Hive & Pig,
supporting object-oriented design or even developing a small tool for the user.
5. Vast Libraries: Python is supported by PyPI which has 85,000+ python scripts and
modules accessible to the user. These modules provide pre-packaged functionality available to
the users in their local Python environment. It can solve diverse problems such as executing
advanced data analytics like developing REStful web services or sentiment analysis and
establishing computer vision.
6. Flexibility: Python has several powerful applications integrated with other programming
languages. Details about these are given as follows:

11
 .Net and C# compatible: IronPython
 A version with C: CPython
 Python combined with Ruby: RubyPython
 Python integrated with Java: Jython
 Python written with Objective C toolkits: PyObjc
7. High Salary: The salary of Python engineers is comparatively higher as compared to others
in the industry. In the United States, a Python developer earns an average of $116,028 per year.
8. Scripting and Automation: What most people don’t know about Python is that it can be
used as a scripting language. In scripting, the code is written in script form and gets executed.
So the code is read and interpreted by the machine and errors are checked during runtime.
After the code is checked, it can be used many times. It is also possible to automate specific
tasks in a problem by automation.
9. Artificial Intelligence: Without any dispute, Artificial intelligence is going to lead the
future IT. Python’s libraries such as Keras and TensorFlow enables machine learning
functionality. Also, libraries like OpenCV aids in computer vision or image recognition.
10. Computer Graphics: Python can be employed in small, large, online or offline projects. It
is used to develop GUI and desktop applications. It’s ‘Tkinter’ library enables simple and
rapid application development. This programming language is also used in game development
where the logic is written using a module ‘pygame’ which can also run on android devices.
11. Testing Framework: This language is an excellent tool for validating the products or ideas
for established enterprises. Python has numerous built-in testing frameworks that deal with
debugging and rapid workflows. Its tools and modules such as Selenium and Splinter work to
make things easier. Python also supports cross-platform and cross-browser testing with
frameworks like PyTest and Robot framework.
12. Web Development: Python’s different frameworks support website development. Python
has an array of frameworks for developing websites. Popular frameworks such as Django,
Flask, and Pylons are characterized by faster and stable code; this is because they are written in
Python.

FEATURES APPLICATIONS:
Features of Python:
Python is a High-level language. The following Features of Python listed below:
Simple : Python is a simple and small programming language. Reading a program of
python language feels almost like reading simple English. This is the main fact the
greatest strength of python which allows the programmer to concentrate on the solution
to the problem rather than the language itself.
Open Source: Python is an open-source software. Anyone can freely distribute it, read
the source code, and edit it easily.

12
High-level Language: When writing programs in python, the programmers don’t have to
worry about the low-level details like managing the memory used by the program. Python
is a High-level language that needed to concentrate on writing solutions to problems.
Interactive: Python programs work in an interactive mode which allows us interactive
testing and debugging of a piece of code. Most Programmers can easily interact with the
interpreter directly.
Object-Oriented: Python supports object-oriented as well as procedure-oriented
programming language. In Python, the OOP technique encapsulates data and
functionalities within objects.
Dynamic: Python executes dynamically, programs written in python can be copied.
Python used for the flexible development of applications.
Secure: Python language environment is much more secure than other languages like
C++ and Java. In Python, Modules can distribute to prevent altering the source code,
Apart from this, additional security checks can easily add to implement additional
security features.
Interpreted: Python is processed at run-time by the interpreter. So, there is no need to
compile a program before executing it. You can easily run the program. Generally,
Python converts the source code into an intermediate code that says called Bytecode.
Then it translated into the native language of your computer so that it can be executed.
Multi-threaded: Python supports multi-threading which is executing more than one
process of a program simultaneously. So, it allows programmers to perform process
management tasks.
Garbage Collection: Python run-time environment handles garbage collection of all
python objects.
Portable: Python is a portable language and the programs behave the same on a wide
variety of hardware platforms it has the same interface on all platforms. The programs
work on any operating system like Linux, Windows, MAC, Solaris etc.

Applications of Python:
Python is a high-level programming language that used to develop a wide range of
applications including image processing, text processing, enterprise-level applications,
web etc. The features and applications of python:

1. Web-Development: Python is easily extensible one that provides good integration


with databases and another web standard material. So, Python is a popular language for
web development.

13
Example : World Best Search engine Google has been built using Python, World Best
Video Sharing site YouTube developed using Python, The front page of
internet reddit written in Python.
2. Embedded Scripting Language: Python is used as an embedded scripting language
for various types of testing, building, deployment, monitoring frameworks, scientific
apps, etc.
3. Image Processing: Python is used to make 2D imaging software such as GIMP, Paint
Shop Pro, etc.
Python also used in 3D to make 3D animation software packages such as 3Ds Max,
Maya, Blender, etc.
4. GUI-Based Applications: Python has a simple syntax, rich text processing, modular
architecture and the ability to work on multiple operating systems makes Python a
preferred choice for developers. Python is a GUI-based application so, it has various GUI
tool-kits are available like PyQt, wxPython, PyGtk. This tool kit helps developers to
create high function Graphical User Interface (GUI).

Python Keywords:
and assert break class continue def del elif else except

exec finally for from global if import in is lambda

not or pass print raise return try while with yield

14
Python - Environment Setup
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. Let's
understand how to set up our Python environment.

 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

Local Environment Setup


Open a terminal window and type "python" to find out if it is already installed and which version
is installed. If Python is already installed then you will get a message something like as follows:

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

>>>

Getting & Installing 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/

15
You can download Python documentation from https://www.python.org/doc/. The
documentation is available in HTML, PDF, and PostScript formats.

Python distribution is available for a wide variety of platforms. You need to download only the
binary code applicable for your platform and install Python.

If the binary code for your platform is not available, you need a C compiler to compile the source
code manually. Compiling the source code offers more flexibility in terms of choice of features
that you require in your installation.

Here is a quick overview of installing Python on various platforms −

Install Python on Ubuntu Linux


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

$ python3.11 --version

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

$ sudo apt update

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

$ sudo apt-get install software-properties-common


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

Update the package list again.

$ sudo apt update

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

$ sudo apt-get install python3.11

Check whether it has been properly installed.

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

16
>>> print ("Hello World")
Hello World

>>>

Install Python on other Linux


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

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


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

Now issue the following commands:

$ run ./configure script


$ make
$ make install

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


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

Using Yum Command

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

$ sudo yum install python3

Install Python on Windows


It should be noted that Python's version 3.10 onwards cannot be installed on Windows 7 or
earlier operating systems.

The recommended way to install Python is to use the official installer. A link to the latest stable
version is given on the home page itself. It is also found
at https://www.python.org/downloads/windows/.

You can find embeddable packages and installers for 32 as well as 64-bit architecture.

17
Let us download 64-bit Windows installer −

(https://www.python.org/ftp/python/3.11.2/python-3.11.2-amd64.exe)

Double click on 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.

18
Accept defaults for rest of the steps in this installation wizard to complete the installation.

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

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.

19
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/.
 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 several years out of date.
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.

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.

20
Setting up PATH

Programs and other executable files can be in many directories, so operating systems provide a
search path that lists the directories that the OS searches for executables.

The path is stored in an environment variable, which is a named string maintained by the
operating system. This variable contains information available to the command shell and other
programs.

The path variable is named as PATH in Unix or Path in Windows (Unix is case sensitive;
Windows is not).

In Mac OS, the installer handles the path details. To invoke the Python interpreter from any
particular directory, you must add the Python directory to your path.

Setting path at Unix/Linux

To add the Python directory to the path for a particular session in Unix −

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

Setting path at Windows


To add the Python directory to the path for a particular session in Windows −

At the command prompt − type path %path%;C:\Python and press Enter.

Note − C:\Python is the path of the Python directory

Python Environment Variables

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

Sr.No. Variable & Description

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

21
PYTHONSTARTUP
2 It contains the path of an initialization file containing Python source code. It is
executed every time you start the interpreter. It is named as .pythonrc.py in
Unix and it contains commands that load utilities or modify PYTHONPATH.

PYTHONCASEOK
3 It is used in Windows to instruct Python to find the first case-insensitive match
in an import statement. Set this variable to any value to activate it.

PYTHONHOME
4 It is an alternative module search path. It is usually embedded in the
PYTHONSTARTUP or PYTHONPATH directories to make switching
module libraries easy.

Running Python
There are three different ways to start Python −

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

Enter python the command line.

Start coding right away in the interactive interpreter.

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

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

Sr.No. Option & Description

1 -d
It provides debug output.

2 -O
It generates optimized bytecode (resulting in .pyo files).

22
3 -S
Do not run import site to look for Python paths on startup.

4 -v
verbose output (detailed trace on import statements).

-X
5 disable class-based built-in exceptions (just use strings); obsolete starting with
version 1.6.

6 -c cmd
run Python script sent in as cmd string

7 file
run Python script from given file

Script from the Command-line


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

$python script.py # Unix/Linux


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

Note − Be sure the file permission mode allows execution.

Integrated Development Environment


You can run Python from a Graphical User Interface (GUI) environment as well, if you have a
GUI application on your system that supports Python.

 Unix − IDLE is the very first Unix IDE for Python.


 Windows − PythonWin is the first Windows interface for Python and is an IDE with a
GUI.
 Macintosh − The Macintosh version of Python along with the IDLE IDE is available
from the main website, downloadable as either MacBinary or BinHex'd files.

If you are not able to set up the environment properly, then you can take help from your system
admin. Make sure the Python environment is properly set up and working perfectly fine.

23
BASIC SYNTAX OF PYTHON PROGRAMMING
Here's a basic overview of Python's syntax:

 Comments: Comments start with the # character and are used to add explanations or
notes to your code. They are ignored by the interpreter.

Python Copy code

# This is a comment

 Variables: Variables are used to store data. You don't need to declare a variable's type
explicitly; Python infers it automatically.

Python Copy code

x = 10 # Integer

name = "John" # String

is_valid = True # Boolean

 Print: You can use the print() function to display data on the screen.

Python Copy code

print("Hello, World!")

 Indentation: Python uses indentation (whitespace) to define blocks of code. It's


important to maintain consistent indentation.

Python Copy code

if x > 5:

print("x is greater than 5")

else:

print("x is not greater than 5")

24
 Conditional Statements: Python uses if, elif (else if), and else for conditional branching.

Python Copy code

if condition:

# Code to execute if the condition is True

elif another_condition:

# Code to execute if another_condition is True

else:

# Code to execute if neither condition is True

 Loops: Python provides for and while loops for iterative operations.

Python Copy code

for i in range(5):

print(i)

while x > 0:

print(x)

x -= 1

 Data Structures: Python includes various data structures, such as lists, tuples,
dictionaries, and sets.

Python Copy code

my_list = [1, 2, 3]

my_tuple = (1, 2, 3)

my_dict = {"name": "John", "age": 30}

my_set = {1, 2, 3}

25
 Functions: Functions are defined using the def keyword.

Python Copy code

def greet(name):

print(f"Hello, {name}!")

greet("Alice")

 Lists: Lists are ordered collections of items.

Python Copy code

fruits = ["apple", "banana", "cherry"]

 Dictionaries: Dictionaries are collections of key-value pairs.

Python Copy code

person = {"name": "John", "age": 30}

 Strings: Python provides various string manipulation functions.

Python Copy code

text = "Hello, World!"

substring = text[0:5] # Slicing

 Classes and Objects: You can create classes and objects for object-oriented
programming.

Python Copy code

class Person:

def __init__(self, name, age):

self.name = name

self.age = age

person = Person("John", 30)

26
These are some of the fundamental elements of Python syntax. Python is a versatile language
used in web development, data analysis, machine learning, and more. Learning Python involves
exploring these concepts in more detail and building practical programs.

VARIABLES
What are Python Variables?

Python variables are the reserved memory locations used to store values with in 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.

Understanding Memory Address

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 will 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
>>> 18

27
18
>>> id(18)
140714055169352

Once the data is stored in the memory, it should be accessed repeatedly for performing a certain
process. Obviously, fetching the data from its ID is cumbersome. High level languages like
Python make it possible to give a suitable alias or a label to refer to the memory location.

In the above example, let us label the location of May as month, and location in which 18 is
stored as age. Python uses the assignment operator (=) to bind an object with the label.

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

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

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

The label is an identifier. It is usually called as a variable. A Python variable is a symbolic name
that is a reference or pointer to an object.

Declaring Python Variables


Python variables do not need explicit declaration to reserve memory space or you can say to
create a variable. A Python variable is created automatically when you assign a value to it. The
equal sign (=) is used to assign values to variables.

The operand to the left of the = operator is the name of the variable and the operand to the right
of the = operator is the value stored in the variable. For example −

counter = 100 # Creates an integer variable


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

28
Printing Python Variables

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

counter = 100 # Creates an integer variable


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

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

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

100
1000.0
Zara Ali

Deleting Python Variables


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

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

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

del var
del var_a, var_b

Example

Following examples 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)

29
del counter
print (counter)

This will produce the following result:

100
Traceback (most recent call last):
File "main.py", line 7, in <module>
print (counter)
NameError: name 'counter' is not defined

Python Variables - Multiple Assignment


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

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

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

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

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

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

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

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


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

Let's try few examples in script mode: −

30
a = b = c = 100

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

This produces the following result:

100
100
100

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

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

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

This produces the following result:

1
2
Zara Ali

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

Python Variables - Naming Convention


Every Python variable should have a unique name like a, b, c. A variable name can be
meaningful like color, age, name etc. There are certain rules which should be taken care while
naming a Python variable:

 A variable name must start with a letter or the underscore character


 A variable name cannot start with a number or any special character like $, (, * % etc.
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )

31
 Python variable names are case-sensitive which means Name and NAME are two
different variables in Python.
 Python reserved keywords cannot be used naming the variable.

If the name of variable contains multiple words, we should use these naming patterns −

 Camel case − First letter is a lowercase, but first letter of each subsequent word is in
uppercase. For example: kmPerHour, pricePerLitre
 Pascal case − First letter of each word is in uppercase. For example: KmPerHour,
PricePerLitre
 Snake case − Use single underscore (_) character to separate words. For example:
km_per_hour, price_per_litre

Example

Following are valid Python variable names:

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

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

This will produce the following result:

100
100
Zara
Nuha
20
100000

Example
32
Following are invalid Python variable names:

1counter = 100
$_count = 100
zara-salary = 100000

print (1counter)
print ($count)
print (zara-salary)

This will produce the following result:

File "main.py", line 3


1counter = 100
^
SyntaxError: invalid syntax

Example

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

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

Use of variables is especially advantageous when writing scripts or programs. Following script
also uses the above variables.

#! /usr/bin/python3

width = 10
height = 20

33
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

Constants in Python

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

The naming convention using all-caps is sometimes referred to as screaming snake case - where
the all-caps (screaming) and the underscores (snakes).

Python vs C/C++ Variables

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

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

34
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 remains unreferred.

Python's garbage collector mechanism releases the memory occupied by any unreferred object.

Python's identity operator is returns True if both the operands have same id() value.

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

35
Python - Data Types
Computer is a data processing device. Computer stores the data in its memory and
processes it as per the given program. Data is a representation of facts about a certain
object.

Some examples of data −

Data of students − name, gender, class, marks, age, fee etc.

Data of books in library − title, author, publisher, price, pages, year of publication etc.

Data of employees in an office − name, designation, salary, department, branch, etc.

Data type represents a kind of value and determines what operations can be done
on it. Numeric, non-numeric and Boolean (true/false) data are the most obvious data
types. However, each programming language has its own classification largely reflecting
its programming philosophy.

Python Data Types

Python Data Types are used to define the type of a variable. It defines what type
of data we are going to store in a variable. The data stored in memory can be of many
types. For example, a person's age is stored as a numeric value and his or her address is
stored as alphanumeric characters.

 Python has various built-in data types which we will discuss with in this tutorial:

Numeric - int, float, complex

String - str

Sequence - list, tuple, range

Binary - bytes, bytearray, memoryview

Mapping - dict

36
Boolean - bool

Set - set, frozenset

None - NoneType

data_types

Python Numeric Data Type

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

var1 = 1 # int data type

var2 = True # bool data type

var3 = 10.023 # float data type

var4 = 10+3j # complex data type

Python supports four different numerical types and each of them have built-in classes in
Python library, called int, bool, float and complex respectively −

int (signed integers)

bool (subtype of integers.)

float (floating point real values)

complex (complex numbers)

Python's standard library has a built-in function type(), which returns the class of the
given object. Here, it is used to check the type of an integer and floating point number.

>>> type(123)

<class 'int'>

>>> type(9.99)

37
<class 'float'>

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

A Boolean number has only two possible values, as represented by the keywords, True
and False. They correspond to integer 1 and 0 respectively.

>>> type (True)

<class 'bool'>

>>> type(False)

<class 'bool'>

Examples

Here are some examples of numbers −

int bool float complex


10 True 0.0 3.14j
0O777 False 15.20 45.j
-786 -21.9 9.322e-36j
080 32.3+e18 .876j
0x17 -90. -.6545+0J
-0x260 -32.54e100 3e+26J
0x69 70.2-E12 4.53e-7j

38
Example

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

# integer variable.

a=100

print("The type of variable having value", a, " is ", type(a))

# boolean variable.

b=True

print("The type of variable having value", b, " is ", type(b))

# float variable.

c=20.345

print("The type of variable having value", c, " is ", type(c))

# complex variable.

d=10+3j

print("The type of variable having value", d, " is ", type(d))

Python Sequence Data Type

Sequence is a collection data type. It is an ordered collection of items. Items in the


sequence have a positional index starting with 0. It is conceptually similar to an array in
C or C++. There are following three sequence data types defined in Python.

String Data Type

List Data Type

Tuple Data Type

39
Python sequences are bounded and iterable - Whenever we say an iterable in Python, it
means a sequence data type (for example, a list).

Python String Data Type

Python string is a sequence of one or more Unicode characters, enclosed in single,


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

>>> 'TutorialsPoint'

'TutorialsPoint'

>>> "TutorialsPoint"

'TutorialsPoint'

>>> '''TutorialsPoint'''

'TutorialsPoint'

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

>>> type("Welcome To TutorialsPoint")

<class 'str'>

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


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

40
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator in Python. For example −

str = 'Hello World!'

print (str) # Prints complete string

print (str[0]) # Prints first character of the string

print (str[2:5]) # Prints characters starting from 3rd to 5th

print (str[2:]) # Prints string starting from 3rd character

print (str * 2) # Prints string two times

print (str + "TEST") # Prints concatenated string

This will produce the following result −

Hello World!

llo

llo World!

Hello World!Hello World!

Hello World!TEST

Python List Data Type

Python Lists are the most versatile compound data types. A Python list contains items
separated by commas and enclosed within square brackets ([]). To some extent, Python
lists are similar to arrays in C. One difference between them is that all the items
belonging to a Python list can be of different data type where as C array can store
elements related to a particular data type.

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

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

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

<class 'list'>

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

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

A list can have items which are simple numbers, strings, tuple, dictionary, set or object of
user defined class also.

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. For example −

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

tinylist = [123, 'john']

print (list) # Prints complete list

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

print (list[1:3]) # Prints elements starting from 2nd till 3rd

print (list[2:]) # Prints elements starting from 3rd element

print (tinylist * 2) # Prints list two times

print (list + tinylist) # Prints concatenated lists

42
This produce the following result −

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

abcd

[786, 2.23]

[2.23, 'john', 70.2]

[123, 'john', 123, 'john']

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

Python Tuple Data Type

Python tuple is another sequence data type that is similar to a list. A Python tuple consists
of a number of values separated by commas. Unlike lists, however, tuples are enclosed
within parentheses (...).

A tuple is also a sequence, hence each item in the tuple has an index referring to its
position in the collection. The index starts from 0.

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

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

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

<class 'tuple'>

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

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

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

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

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

The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] )
and their elements and size can be changed .ie lists are mutable, while tuples are enclosed
in parentheses ( ( ) ) and cannot be updated (immutable). Tuples can be thought of as
read-only lists. For example −

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

tinytuple = (123, 'john')

print (tuple) # Prints the complete tuple

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

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

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

print (tinytuple * 2) # Prints the contents of the tuple twice

print (tuple + tinytuple) # Prints concatenated tuples

This produce the following result −

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

abcd

(786, 2.23)

(2.23, 'john', 70.2)

(123, 'john', 123, 'john')

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

44
The following code is invalid with tuple, because we attempted to update a tuple, which
is not allowed. Similar case is possible with lists −

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

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

tuple[2] = 1000 # Invalid syntax with tuple

list[2] = 1000 # Valid syntax with list

Python Ranges Function

Python range() is an in-built function in Python which returns a sequence of numbers


starting from 0 and increments to 1 until it reaches a specified number.

We use range() function with for and while loop to generate a sequence of numbers.
Following is the syntax of the function:

range(start, stop, step)

Here is the description of the parameters used:

start: Integer number to specify starting position, (Its optional, Default: 0)

stop: Integer number to specify starting position (It's mandatory)

step: Integer number to specify increment, (Its optional, Default: 1)

Examples

Following is a program which uses for loop to print number from 0 to 4 −

for i in range(5):

print(i)

45
This produce the following result −

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

for i in range(1, 5):

print(i)This produce the following result −

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

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

print(i)

This produce the following result −

46
Python Dictionary Data Type

Python dictionaries are kind of hash table type. A dictionary key can be almost any
Python type, but are usually numbers or strings. Values, on the other hand, can be any
arbitrary Python object.

Python dictionary is like associative arrays or hashes found in Perl and consist of
key:value pairs. The pairs are separated by comma and put inside curly brackets {}. To
establish mapping between key and value, the semicolon':' symbol is put between the
two.

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

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

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

<class 'dict'>

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

dict = {}

dict['one'] = "This is one"

dict[2] = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

print (dict['one']) # Prints value for 'one' key

print (dict[2]) # Prints value for 2 key

print (tinydict) # Prints complete dictionary

print (tinydict.keys()) # Prints all the keys

47
print (tinydict.values()) # Prints all the values

This produce the following result −

This is one

This is two

{'dept': 'sales', 'code': 6734, 'name': 'john'}

['dept', 'code', 'name']

['sales', 6734, 'john']

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

Python Set Data Type

Set is a Python implementation of set as defined in Mathematics. A set in Python is a


collection, but is not an indexed or ordered collection as string, list or tuple. An object
cannot appear more than once in a set, whereas in List and Tuple, same object can appear
more than once.

Comma separated items in a set are put inside curly brackets or braces {}. Items in the set
collection can be of different data types.

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

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

Note that items in the set collection may not follow the same order in which they are
entered. The position of items is optimized by Python to perform operations over set as
defined in mathematics.

48
Python’s Set is an object of built-in set class, as can be checked with the type()
function.

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

<class 'set'>

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

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

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: unhashable type: 'list'

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


in computer's memory. Only immutable objects are hashable.

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

Python Boolean Data Types

Python boolean type is one of built-in data types which represents one of the two values
either True or False. Python bool() function allows you to evaluate the value of any
expression and returns either True or False based on the expression.

Examples

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

49
a = True

# display the value of a

print(a)

# display the data type of a

print(type(a))

This produce the following result −

true

<class 'bool'>

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

# Returns false as a is not equal to b

a=2

b=4

print(bool(a==b))

# Following also prints the same

print(a==b)

# Returns False as a is None

a = None

print(bool(a))

# Returns false as a is an empty sequence

50
a = ()

print(bool(a))

# Returns false as a is 0

a = 0.0

print(bool(a))

# Returns false as a is 10

a = 10

print(bool(a))

This produce the following result −

False

False

False

False

False

True

Python Keywords
Every scripting language has designated words or keywords, with particular definitions and
usage guidelines. Python is no exception. The fundamental constituent elements of any Python
program are Python keywords.

This tutorial will give you a basic overview of all Python keywords and a detailed discussion of
some important keywords that are frequently used.

51
Introducing Python Keywords
Python keywords are unique words reserved with defined meanings and functions that we can
only apply for those functions. You'll never need to import any keyword into your program
because they're permanently present.

Python's built-in methods and classes are not the same as the keywords. Built-in methods and
classes are constantly present; however, they are not as limited in their application as keywords.

Assigning a particular meaning to Python keywords means you can't use them for other purposes
in our code. You'll get a message of SyntaxError if you attempt to do the same. If you attempt to
assign anything to a built-in method or type, you will not receive a SyntaxError message;
however, it is still not a smart idea.

Python contains thirty-five keywords in the most recent version, i.e., Python 3.8. Here we have
shown a complete list of Python keywords for the reader's reference.

False await else import pass

None break except in raise

True class finally is return

and continue for lambda try

as def from nonlocal while

assert del global not with

async elif if or yield

In distinct versions of Python, the preceding keywords might be changed. Some extras may be
introduced, while others may be deleted. By writing the following statement into the coding
window, you can anytime retrieve the collection of keywords in the version you are working on.

Code

# Python program to demonstrate the application of iskeyword()


# importing keyword library which has lists
import keyword
# displaying the complete list using "kwlist()."
print("The set of keywords in this version is: ")
print( keyword.kwlist )

52
Output:

The set of keywords in this version is :


['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except',
'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while',
'with', 'yield']

By calling help(), you can retrieve a list of currently offered keywords:

Code

help("keywords")

How to Identify Python Keywords


Python's keyword collection has evolved as new versions were introduced. The await and async
keywords, for instance, were not introduced till Python 3.7. Also, in Python 2.7, the words print
and exec constituted keywords; however, in Python 3+, they were changed into built-in methods
and are no longer part of the set of keywords. In the paragraphs below, you'll discover numerous
methods for determining whether a particular word in Python is a keyword or not.

Write Code on a Syntax Highlighting IDE


There are plenty of excellent Python IDEs available. They'll all highlight keywords to set them
apart from the rest of the terms in the code. This facility will assist you in immediately
identifying Python keywords during coding so that you do not misuse them.

Verify Keywords with Script in a REPL


There are several ways to detect acceptable Python keywords plus know further regarding them
in the Python REPL.

Look for a SyntaxError


Lastly, if you receive a SyntaxError when attempting to allocate to it, name a method with it, or
do anything else with that, and it isn't permitted, it's probably a keyword. This one is somewhat
more difficult to see, but it is still a technique for Python to tell you if you're misusing a
keyword.

Python Keywords and Their Usage


The following sections categorize Python keywords under the headings based on their frequency
of use. The first category, for instance, includes all keywords utilized as values, whereas the next
group includes keywords employed as operators. These classifications will aid in understanding

53
how keywords are employed and will assist you in arranging the huge collection of Python
keywords.

o A few terms mentioned in the segment following may be unfamiliar to you. They're
explained here, and you must understand what they mean before moving on:
o The Boolean assessment of a variable is referred to as truthfulness. A value's truthfulness
reveals if the value of the variable is true or false.

In the Boolean paradigm, truth refers to any variable that evaluates to true. Pass an item as an
input to bool() to see if it is true. If True is returned, the value of the item is true. Strings and lists
which are not empty, non-zero numbers, and many other objects are illustrations of true values.

False refers to any item in a Boolean expression that returns false. Pass an item as an input to
bool() to see if it is false. If False is returned, the value of the item is false. Examples of false
values are " ", 0, { }, and [ ].

Value Keywords: True, False, None


Three Python keywords are employed as values in this example. These are singular values,
which we can reuse indefinitely and every time correspond to the same entity. These values will
most probably be seen and used frequently.

The Keywords True and False

These keywords are typed in lowercase in conventional computer languages (true and false);
however, they are typed in uppercase in Python every time. In Python script, the True Python
keyword represents the Boolean true state. False is a keyword equivalent to True, except it has
the negative Boolean state of false.

True and False are those keywords that can be allocated to variables or parameters and are
compared directly.

Code

print( 4 == 4 )
print( 6 > 9 )
print( True or False )
print( 9 <= 28 )
print( 6 > 9 )
print( True and False )

Output:

54
True
False
True
True
False
False

Because the first, third, and fourth statements are true, the interpreter gives True for those and
False for other statements. True and False are the equivalent in Python as 1 & 0. We can use the
accompanying illustration to support this claim:

Code

print( True == 3 )
print( False == 0 )
print( True + True + True)

Output:

False
True
3

The None Keyword

None is a Python keyword that means "nothing." None is known as nil, null, or undefined in
different computer languages.

If a function does not have a return clause, it will give None as the default output:

Code

print( None == 0 )
print( None == " " )
print( None == False )
A = None
B = None
print( A == B )

Output:

False
False
False
True

55
If a no_return_function returns nothing, it will simply return a None value. None is delivered by
functions that do not meet a return expression in the program flow. Consider the following
scenario:

Code

def no_return_function():
num1 = 10
num2 = 20
addition = num1 + num2
number = no_return_function()
print( number )

Output:

This program has a function with_return that performs multiple operations and contains a return
expression. As a result, if we display a number, we get None, which is given by default when
there is no return statement. Here's an example showing this:

Code

def with_return( num ):


if num % 4 == 0:
return False

number = with_return( 67 )
print( number )

Output:

Operator Keywords: and, or, not, in, is


Several Python keywords are employed as operators to perform mathematical operations. In
many other computer languages, these operators are represented by characters such as &, |, and!.
All of these are keyword operations in Python:

Mathematical Operations in Other Python


Operations Languages Keyword

AND, ∧ && and

56
OR, ∨ || or

NOT, ¬ ! not

CONTAINS, ∈ in

IDENTITY === is

Writers created Python programming with clarity in mind. As a result, many operators in other
computer languages that employ characters in Python are English words called keywords.

The and Keyword

The Python keyword and determines whether both the left-hand side and right-hand side
operands and are true or false. The outcome will be True if both components are true. If one is
false, the outcome will also be False:

Truth table for and

X Y X and Y

True True True

False True False

True False False

False False False

<component1> and <component2>

It's worth noting that the outcomes of an and statement aren't always True or False. Due to and's
peculiar behavior, this is the case. Instead of processing the inputs to corresponding Boolean
values, it just gives <component1> if it is false or <component2> if it is true. The outputs of a
and expression could be utilized with a conditional if clause or provided to bool() to acquire an
obvious True or False answer.

The or Keyword

The or keyword in Python is utilized to check if, at minimum, 1 of the inputs is true. If the first
argument is true, the or operation yields it; otherwise, the second argument is returned:

<component1> or <component2>

57
Similarly to the and keyword, the or keyword does not change its inputs to corresponding
Boolean values. Instead, the outcomes are determined based on whether they are true or false.

Truth table for or

X Y X or Y

True True True

True False True

False True True

False False False

The not Keyword

The not keyword in Python is utilized to acquire a variable's contrary Boolean value:

The not keyword is employed to switch the Boolean interpretation or outcome in conditional
sentences or other Boolean equations. Not, unlike and, and or, determines the specific Boolean
state, True or False, afterward returns the inverse.

Truth Table for not

X not X

True False

False True

Code

False and True


False or True
not True

Output:

False
True
False

58
The in Keyword

The in keyword of Python is a robust confinement checker, also known as a membership


operator. If you provide it an element to seek and a container or series to seek into, it will give
True or False, depending on if that given element was located in the given container:

<an_element> in <a_container>

Testing for a certain character in a string is a nice illustration of how to use the in keyword:

Code

container = "Javatpoint"
print( "p" in container )
print( "P" in container )

Output:

True
False

Lists, dictionaries, tuples, strings, or any data type with the method __contains__(), or we can
iterate over it will work with the in keyword.

The is Keyword

In Python, it's used to check the identification of objects. The == operation is used to determine
whether two arguments are identical. It also determines whether two arguments relate to the
unique object.

When the objects are the same, it gives True; otherwise, it gives False.

Code

print( True is True )

print( False is True )


print( None is not None )
print( (9 + 5) is (7 * 2) )

Output:

True
False
False

59
True

True, False, and None are all the same in Python since there is just one version.

Code

print( [] == [] )
print( [] is [] )
print( {} == {} )
print( {} is {} )

Output:

True
False
True
False

A blank dictionary or list is the same as another blank one. However, they aren't identical entities
because they are stored independently in memory. This is because both the list and the dictionary
are changeable.

Code

print( '' == '' )


print( '' is '' )

Output:

True
True

Strings and tuples, unlike lists and dictionaries, are unchangeable. As a result, two equal strings
or tuples are also identical. They're both referring to the unique memory region.

The nonlocal Keyword


Nonlocal keyword usage is fairly analogous to global keyword usage. The keyword nonlocal is
designed to indicate that a variable within a function that is inside a function, i.e., a nested
function is just not local to it, implying that it is located in the outer function. We must define a
non-local parameter with nonlocal if we ever need to change its value under a nested function.
Otherwise, the nested function creates a local variable using that title. The example below will
assist us in clarifying this.

Code

60
def the_outer_function():
var = 10
def the_inner_function():
nonlocal var
var = 14
print("The value inside the inner function: ", var)
the_inner_function()
print("The value inside the outer function: ", var)

the_outer_function()

Output:

The value inside the inner function: 14


The value inside the outer function: 14

the_inner_function() is placed inside the_outer_function in this case.

The the_outer_function has a variable named var. Var is not a global variable, as you may have
noticed. As a result, if we wish to change it inside the the_inner_function(), we should declare it
using nonlocal.As a result, the variable was effectively updated within the nested
the_inner_function, as evidenced by the results. The following is what happens if you don't use
the nonlocal keyword:

Code

def the_outer_function():
var = 10
def the_inner_function():
var = 14
print("Value inside the inner function: ", var)
the_inner_function()
print("Value inside the outer function: ", var)

the_outer_function()

Output:

Value inside the inner function: 14


Value inside the outer function: 10

61
Iteration Keywords: for, while, break, continue
The iterative process and looping are essential programming fundamentals. To generate and
operate with loops, Python has multiple keywords. These would be utilized and observed in
almost every Python program. Knowing how to use them correctly can assist you in becoming a
better Python developer.

The for Keyword

The for loop is by far the most popular loop in Python. It's built by blending two Python
keywords. They are for and in, as previously explained.

The while Keyword

Python's while loop employs the term while and functions similarly to other computer languages'
while loops. The block after the while phrase will be repeated repeatedly until the condition
following the while keyword is false.

The break Keyword

If you want to quickly break out of a loop, employ the break keyword. We can use this keyword
in both for and while loops.

The continue Keyword

You can use the continue Python keyword if you wish to jump to the subsequent loop iteration.
The continue keyword, as in many other computer languages, enables you to quit performing the
present loop iteration and go on to the subsequent one.

Code

# Program to show the use of keywords for, while, break, continue


for i in range(15):

print( i + 4, end = " ")

# breaking the loop when i = 9


if i == 9:
break
print()

# looping from 1 to 15

62
i = 0 # initial condition
while i < 15:

# When i has value 9, loop will jump to next iteration using continue. It will not print
if i == 9:
i += 3
continue
else:
# when i is not equal to 9, adding 2 and printing the value
print( i + 2, end = " ")

i += 1

Output:

4 5 6 7 8 9 10 11 12 13
2 3 4 5 6 7 8 9 10 14 15 16

Exception Handling Keywords - try, except, raise, finally, and assert


try: This keyword is designed to handle exceptions and is used in conjunction with the keyword
except to handle problems in the program. When there is some kind of error, the program inside
the "try" block is verified, but the code in that block is not executed.

except: As previously stated, this operates in conjunction with "try" to handle exceptions.

finally: Whatever the outcome of the "try" section, the "finally" box is implemented every time.

raise: The raise keyword could be used to specifically raise an exception.

assert: This method is used to help in troubleshooting. Often used to ensure that code is correct.
Nothing occurs if an expression is interpreted as true; however, if it is false, "AssertionError" is
raised. An output with the error, followed by a comma, can also be printed.

Code

# initializing the numbers


var1 = 4
var2 = 0

63
# Exception raised in the try section
try:
d = var1 // var2 # this will raise a "divide by zero" exception.
print( d )
# this section will handle exception raised in try block
except ZeroDivisionError:
print("We cannot divide by zero")
finally:
# If exception is raised or not, this block will be executed every time
print("This is inside finally block")
# by using assert keyword we will check if var2 is 0
print ("The value of var1 / var2 is : ")
assert var2 != 0, "Divide by 0 error"
print (var1 / var2)

Output:

We cannot divide by zero


This is inside finally block
The value of var1 / var2 is :
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
Input In [44], in ()
15 # by using assert keyword we will check if var2 is 0
16 print ("The value of var1 / var2 is : ")
---> 17 assert var2 != 0, "Divide by 0 error"
18 print (var1 / var2)

AssertionError: Divide by 0 error

The pass Keyword


In Python, a null sentence is called a pass. It serves as a stand-in for something else. When it is
run, nothing occurs.

Let's say we possess a function that has not been coded yet however we wish to do so in the long
term. If we write just this in the middle of code,

Code

def function_pass( arguments ):

Output:
64
def function_pass( arguments ):
^
IndentationError: expected an indented block after function definition on line 1

as shown, IndentationError will be thrown. Rather, we use the pass command to create a blank
container.

Code

def function_pass( arguments ):


pass

We can use the pass keyword to create an empty class too.

Code

class passed_class:
pass

The return Keyword


The return expression is used to leave a function and generate a result.

The None keyword is returned by default if we don't specifically return a value. The
accompanying example demonstrates this.

Code

def func_with_return():
var = 13
return var
def func_with_no_return():
var = 10

print( func_with_return() )
print( func_with_no_return() )

Output:

13
None

65
The del Keyword
The del keyword is used to remove any reference to an object. In Python, every entity is an
object. We can use the del command to remove a variable reference.

Code

var1 = var2 = 5
del var1
print( var2 )
print( var1 )

Output:

5
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [42], in ()
2 del var1
3 print( var2 )
----> 4 print( var1 )

NameError: name 'var1' is not defined

We can notice that the variable var1's reference has been removed. As a result, it's no longer
recognized. However, var2 still exists.

Deleting entries from a collection like a list or a dictionary is also possible with del:

Code

list_ = ['A','B','C']
del list_[2]
print(list_)

Output:

['A', 'B']

66
Input and Output in Python
Sometimes a developer might want to take user input at some point in the program. To do
this Python provides an input() function.

Syntax:

input('prompt')

where prompt is an optional string that is displayed on the string at the time of taking
input.

Example 1: Python get user input with a message

# Taking input from the user

name = input("Enter your name: ")

# Output

print("Hello, " + name)

print(type(name))

Output:

Enter your name: GFG

Hello, GFG

<class 'str'>

Note: Python takes all the input as a string input by default. To convert it to any other
data type we have to convert the input explicitly. For example, to convert the input to int
or float we have to use the int() and float() method respectively.

67
Example 2: Integer input in Python

# Taking input from the user as integer

num = int(input("Enter a number: "))

add = num + 1

# Output

print(add)

Output:

Enter a number: 25

26

How to take Multiple Inputs in Python :

we can take multiple inputs of the same data type at a time in python, using map()
method in python.

a, b, c = map(int, input("Enter the Numbers : ").split())

print("The Numbers are : ",end = " ")

print(a, b, c)

Output :

Enter the Numbers : 2 3 4

The Numbers are : 2 3 4

How take inputs for the Sequence Data Types like List, Set, Tuple, etc.

In the case of List and Set the input can be taken from the user in two ways.

68
Taking List/Set elements one by one by using the append()/add() methods.

Using map() and list() / set() methods.

Taking List/Set elements one by one

Take the elements of the List/Set one by one and use the append() method in the case of
List, and add() method in the case of a Set, to add the elements to the List / Set.

List = list()

Set = set()

l = int(input("Enter the size of the List : "))

s = int(input("Enter the size of the Set : "))

print("Enter the List elements : ")

for i in range(0, l):

List.append(int(input()))

print("Enter the Set elements : ")

for i in range(0, s):

Set.add(int(input()))

print(List)

print(Set)

Output :Enter the size of the List : 4

Enter the size of the Set : 3

69
Enter the List elements :

Enter the Set elements :

[9, 0, 1, 3]

{9, 2, 1}

Using map() and list() / set() Methods

List = list(map(int, input("Enter List elements : ").split()))

Set = set(map(int, input("Enter the Set elements :").split()))

print(List)

print(Set)

Output :

Enter List elements : 3 4 8 9 0 11

Enter the Set elements :34 88 230 234 123

[3, 4, 8, 9, 0, 11]

70
{34, 230, 234, 88, 123}

Taking Input for Tuple

We know that tuples are immutable, there are no methods available to add elements to
tuples. To add a new element to a tuple, first type cast the tuple to the list, later append
the element to the list, and again type cast list back to a tuple.

T = (2, 3, 4, 5, 6)

print("Tuple before adding new element")

print(T)

L = list(T)

L.append(int(input("Enter the new element : ")))

T = tuple(L)

print("Tuple After adding the new element")

print(T)

Output :

Tuple before adding new element

(2, 3, 4, 5, 6)

Enter the new element : 35

Tuple After adding the new element

(2, 3, 4, 5, 6, 35)

 How to Display Output in Python

Python provides the print() function to display output to the standard output devices.

71
Syntax: print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)

Parameters:

value(s) : Any value, and as many as you like. Will be converted to string before printed

sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than
one.Default :’ ‘

end=’end’: (Optional) Specify what to print at the end.Default : ‘\n’

file : (Optional) An object with a write method. Default :sys.stdout

flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered


(False). Default: False

Returns: It returns output to the screen.

Example: Python Print Output

# Python program to demonstrate

# print() method

print("GFG")

# code for disabling the softspace feature

print('G', 'F', 'G')

Output

GFG

GFG

In the above example, we can see that in the case of the 2nd print statement there is a
space between every letter and the print statement always add a new line character at the

72
end of the string. This is because after every character the sep parameter is printed and at
the end of the string the end parameter is printed. Let’s try to change this sep and end
parameter.

Example: Python Print output with custom sep and end parameter

# Python program to demonstrate

# print() method

print("GFG", end = "@")

# code for disabling the softspace feature

print('G', 'F', 'G', sep="#")

Output

GFG@G#F#G

Formatting Output

Formatting output in Python can be done in many ways. Let’s discuss them below

Using formatted string literals

We can use formatted string literals, by starting a string with f or F before opening
quotation marks or triple quotation marks. In this string, we can write Python expressions
between { and } that can refer to a variable or any literal value.

Example: Python String formatting using F string

# Declaring a variable

name = "Gfg"

# Output

73
print(f'Hello {name}! How are you?')

Output:

Hello Gfg! How are you?

Using format()

We can also use format() function to format our output to make it look presentable. The
curly braces { } work as placeholders. We can specify the order in which variables occur
in the output.

Example: Python string formatting using format() function

# Initializing variables

a = 20

b = 10

# addition

sum = a + b

# subtraction

sub = a- b

# Output

print('The value of a is {} and b is {}'.format(a,b))

print('{2} is the sum of {0} and {1}'.format(a,b,sum))

print('{sub_value} is the subtraction of {value_a} and {value_b}'.format(value_a = a ,


value_b = b, sub_value = sub))

Output:

74
The value of a is 20 and b is 10

30 is the sum of 20 and 10

10 is the subtraction of 20 and 10

Using % Operator

We can use ‘%’ operator. % values are replaced with zero or more value of elements. The
formatting using % is similar to that of ‘printf’ in the C programming language.

%d – integer

%f – float

%s – string

%x – hexadecimal

%o – octal

Example:

# Taking input from the user

num = int(input("Enter a value: "))

add = num + 5

# Output

print("The sum is %d" %add)

Output:

Enter a value: 50

The sum is 55

75
Indentation in Python
Indentation is a very important concept of Python because without properly indenting the
Python code, you will end up seeing IndentationError and the code will not get compiled.

Python Indentation

Python indentation refers to adding white space before a statement to a particular block of
code. In another word, all the statements with the same space to the right, belong to
the same code block.Indentation-python

Example of Python Indentation

Statement (line 1), if condition (line 2), and statement (last line) belongs to the same
block which means that after statement 1, if condition will be executed. and suppose the
if condition becomes False then the Python will jump to the last statement for execution.

The nested if-else belongs to block 2 which means that if nested if becomes False, then
Python will execute the statements inside the else condition.

Statements inside nested if-else belong to block 3 and only one statement will be
executed depending on the if-else condition.

Python indentation is a way of telling a Python interpreter that the group of statements
belongs to a particular block of code. A block is a combination of all these statements.
Block can be regarded as the grouping of statements for a specific purpose. Most
programming languages like C, C++, and Java use braces { } to define a block of code.
Python uses indentation to highlight the blocks of code. Whitespace is used for
indentation in Python. All statements with the same distance to the right belong to the
same block of code. If a block has to be more deeply nested, it is simply indented further
to the right. You can understand it better by looking at the following lines of code.

Example 1

The lines print(‘Logging on to geeksforgeeks…’) and print(‘retype the URL.’) are two
separate code blocks. The two blocks of code in our example if-statement are both

76
indented four spaces. The final print(‘All set!’) is not indented, so it does not belong to
the else block.

# Python program showing

# indentation

site = 'gfg'

if site == 'gfg':

print('Logging on to geeksforgeeks...')

else:

print('retype the URL.')

print('All set !')

Output:

Logging on to geeksforgeeks...

All set !

Example 2

To indicate a block of code in Python, you must indent each line of the block by the same
whitespace. The two lines of code in the while loop are both indented four spaces. It is
required for indicating what block of code a statement belongs to. For example, j=1 and
while(j<=5): is not indented, and so it is not within the Python while block. So, Python
code structures by indentation.

j=1

while(j<= 5):

print(j)

77
j=j+1

Output:

Note: Python uses 4 spaces as indentation by default. However, the number of spaces is
up to you, but a minimum of 1 space has to be used.

SCRIPT STRUCTURE
Python is a high-level, interpreted programming language that is easy to learn and use. It
has a simple and easy-to-understand syntax that emphasizes readability and reduces the
cost of program maintenance. The basic structure of a Python program consists of the
following components:

Comments: Comments are used to explain the purpose of the code or to make notes for
other programmers. They start with a ‘#’ symbol and are ignored by the interpreter.

Import Statements: Import statements are used to import modules or libraries into the
program. These modules contain predefined functions that can be used to accomplish
tasks.

Variables: Variables are used to store data in memory for later use. In Python, variables
do not need to be declared with a specific type.

Data Types: Python supports several built-in data types including integers, floats,
strings, booleans, and lists.

78
Operators: Operators are used to perform operations on variables and data. Python
supports arithmetic, comparison, and logical operators.

Control Structures: Control structures are used to control the flow of a program. Python
supports if-else statements, for loops, and while loops.

Functions: Functions are used to group a set of related statements together and give them
a name. They can be reused throughout a program.

Classes: Classes are used to define objects that have specific attributes and methods.
They are used to create more complex data structures and encapsulate code.

Exceptions: Exceptions are used to handle errors that may occur during the execution of
a program.

Overall, the basic structure of a Python program consists of these components working
together to accomplish a specific task or solve a particular problem.

Here’s an example of a simple Python program that demonstrates the basic structure of
Python:

# This is a comment

import random # Importing a module

# Defining variables

x = 10

y = "Hello, World!"

z = True

# Performing arithmetic operation

result = x + 5

# Using if-else statement

79
if z:

print(y)

else:

print(result)

# Defining a function

def greet(name):

print("Hello, " + name + "!")

# Using the function

greet("Alice")

In this example, we start with a comment that explains the purpose of the code. Then, we
import the random module to generate random numbers later in the program.

Next, we define three variables with different data types: x is an integer, y is a string, and
z is a boolean. We then perform an arithmetic operation on x and store the result in the
result variable.

We use an if-else statement to check the value of z. If z is True, we print the string stored
in y, otherwise, we print the value of result.

Finally, we define a function called greet() that takes a parameter called name and prints
a greeting message. We call the function with the argument "Alice" to print "Hello,
Alice!" to the console.

80
RUNNING PYTHON SCRIPTS
Python is a well-known high-level programming language. The Python script is basically
a file containing code written in Python. The file containing Python script has the
extension ‘.py’ or can also have the extension ‘.pyw’ if it is being run on a Windows
machine. In this article, we will learn how to run a Python program. To run a Python
script, we need a Python interpreter that needs to be downloaded and installed.

Different ways to run Python Script

Here are the ways using which we can run a Python script.

Interactive Mode

Command Line

Text Editor (VS Code)

IDE (PyCharm)

Here is a simple Python script to print ‘Hello World!’.

print('Hello World!')

Here, the print() function is to print out any text written within the parenthesis. We can
write the text that we want to be printed using either a single quote as shown in the above
script or a double quote.

If you are coming from any other language then you will also notice that there is no
semicolon at the end of the statement as, with Python, you do not need to specify a
semicolon at the end of the line. And also we don’t need to include or import any files to
run a simple Python script.

There are various ways to run a Python script but before going toward the different ways
to run a Python script, we first have to check whether a Python interpreter is installed on
the system or not. So in Windows, open ‘cmd’ (Command Prompt) and type the
following command.

81
python -V

This command will give the version number of the Python interpreter installed or will
display an error if otherwise.

How to Run Python Script Interactively

In Python Interactive Mode, you can run your script line by line in a sequence. To enter
an interactive mode, you will have to open Command Prompt on your Windows machine
and type ‘python’ and press Enter.

Example1: Run the following line in the interactive mode:

print('Hello World !')

Output:

82
Example 2: Run the following lines one by one in the interactive mode.

name = "Aakash"

print("My name is " + name)

Output:

Example 3: Run the following line one by one in the interactive mode.

a=1

b=3

if a > b:

print("a is Greater")

else:

print("b is Greater")

83
Output:

Note: To exit from this mode, press ‘Ctrl+Z’ and then press ‘Enter’ or type ‘exit()’ and
then press Enter.

How to Run Python Script by the Command Line

To run a Python script store in a ‘.py’ file in the command line, we have to write ‘python’
keyword before the file name in the command prompt.

python hello.py

You can write your own file name in place of ‘hello.py’.

Output:

84
Running Python Scripts using a Text Editor

To run Python script on a text editor like VS Code (Visual Studio Code) then you will
have to do the following:

Go to the extension section or press ‘Ctrl+Shift+X’ on Windows, then search and install
the extension named ‘Python’ and ‘Code Runner’. Restart your vs code after that.

Now, create a new file with the name ‘hello.py’ and write the below code in it:

print('Hello World!')

Then, right-click anywhere in the text area and select the option that says ‘Run Code’ or
press ‘Ctrl+Alt+N’ to run the code.

Output:

Running Python Scripts using an IDE

To run Python script on an IDE (Integrated Development Environment) like PyCharm,


you will have to do the following:

Create a new project.

Give a name to that project as ‘GfG’ and click on Create.

Select the root directory with the project name we specified in the last step. Right-click
on it, go to New, anto, and click on the ‘Python file’ option. Then give the name of the
file as ‘hello’ (you can specify any name as per your project requirement). This will
create a ‘hello.py’ file in the project root directory.

85
Note: You don’t have to specify the extension as it will take it automatically.

Now write the below Python script to print the message:

print('Hello World !')

To run this Python script, Right click and select the ‘Run File in Python Console’ option.
This will open a console box at the bottom and show the output there. We can also run
using the Green Play Button at the top right corner of the IDE.

Output:

86

You might also like