0% found this document useful (0 votes)
1 views76 pages

Introduction To Python

Uploaded by

ratnaveni2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views76 pages

Introduction To Python

Uploaded by

ratnaveni2006
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Programming Language

INTRODUCTION TO PYTHON:
python is a widely used programming language that offers several
unique features and advantages compared to languages like Java and C+
+. .
In the late 1980s, Guido van Rossum dreamed of developing Python.
The first version of Python 0.9.0 was released in 1991. Since its
release, Python started gaining popularity. According to reports, Python is
now the most popular programming language among developers because
of its high demands in the tech realm.

What is Python
Python is a general-purpose, dynamically typed, high-level, compiled and
interpreted, garbage-collected, and purely object-oriented programming
language that supports procedural, object-oriented, and functional
programming.

Why We learn Python?


Python provides many useful features to the programmer. These features
make it the most popular and widely used language. We have listed below
few-essential features of Python.
o Easy to use and Learn: Python has a simple and easy-to-understand
syntax, unlike traditional languages like C, C++, Java, etc., making it easy
for beginners to learn.
o Expressive Language: It allows programmers to express complex
concepts in just a few lines of code or reduces Developer's Time.
o Interpreted Language: Python does not require compilation, allowing
rapid development and testing. It uses Interpreter instead of Compiler.
o Object-Oriented Language: It supports object-oriented programming,
making writing reusable and modular code easy.
o Open-Source Language: Python is open-source and free to use,
distribute and modify.
o Extensible: Python can be extended with modules written in C, C++, or
other languages.
o Learn Standard Library: Python's standard library contains many
modules and functions that can be used for various tasks, such as string
manipulation, web programming, and more.
o GUI Programming Support: Python provides several GUI frameworks,
such as Tkinter and PyQt, allowing developers to create desktop
applications easily.
o Integrated: Python can easily integrate with other languages and
technologies, such as C/C++, Java, and . NET.
o Embeddable: Python code can be embedded into other applications as a
scripting language.
o Dynamic Memory Allocation: Python automatically manages memory
allocation, making it easier for developers to write complex programs
without worrying about memory management.
o Wide Range of Libraries and Frameworks: Python has a vast
collection of libraries and frameworks, such as NumPy, Pandas, Django,
and Flask, that can be used to solve a wide range of problems.
o Versatility: Python is a universal language in various domains such as
web development, machine learning, data analysis, scientific computing,
and more.
o Large Community: Python has a vast and active community of
developers contributing to its development and offering support. This
makes it easy for beginners to get help and learn from experienced
developers.
o Career Opportunities: Python is a highly popular language in the job
market. Learning Python can open up several career opportunities in data
science, artificial intelligence, web development, and more.
o High Demand: With the growing demand for automation and digital
transformation, the need for Python developers is rising. Many industries
seek skilled Python developers to help build their digital infrastructure.
o Increased Productivity: Python has a simple syntax and powerful
libraries that can help developers write code faster and more efficiently.
This can increase productivity and save time for developers and
organizations.
o Big Data and Machine Learning: Python has become the go-to
language for big data and machine learning. Python has become popular
among data scientists and machine learning engineers with libraries
like NumPy, Pandas, Scikit-learn, TensorFlow, and more.

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

Python Applications
1) Web Applications
We can use Python to develop web applications. It provides libraries to
handle internet protocols such as HTML and XML, JSON, Email processing,
request, beautifulSoup, Feedparser, etc. One of Python web-framework
named Django is used on Instagram. Python provides many useful
frameworks, and these are given below:

ADVERTISEMENT

o Django and Pyramid framework(Use for heavy applications)


o Flask and Bottle (Micro-framework)
o Plone and Django CMS (Advance Content management)

2) Desktop GUI Applications


The GUI stands for the Graphical User Interface, which provides a smooth
interaction to any application. Python provides a Tk GUI library to
develop a user interface. Some popular GUI libraries are given below.

o Tkinter or Tk
o wxWidgetM
o Kivy (used for writing multitouch applications )
o PyQt or Pyside

3) Console-based Application
Console-based applications run from the command-line or shell. These
applications are computer program which are used commands to execute.
This kind of application was more popular in the old generation of
computers. Python can develop this kind of application very effectively. It
is famous for having REPL, which means the Read-Eval-Print Loop that
makes it the most suitable language for the command-line applications.

Python provides many free library or module which helps to build the
command-line apps. The necessary IO libraries are used to read and
write. It helps to parse argument and create console help text out-of-the-
box. There are also advance libraries that can develop independent
console apps.

4) Software Development
Python is useful for the software development process. It works as a
support language and can be used to build control and management,
testing, etc.

o SCons is used to build control.


o Buildbot and Apache Gumps are used for automated continuous
compilation and testing.
o Round or Trac for bug tracking and project management.

5) Scientific and Numeric


This is the era of Artificial intelligence where the machine can perform the
task the same as the human. Python language is the most suitable
language for Artificial intelligence or machine learning. It consists of many
scientific and mathematical libraries, which makes easy to solve complex
calculations.

Implementing machine learning algorithms require complex mathematical


calculation. Python has many libraries for scientific and numeric such as
Numpy, Pandas, Scipy, Scikit-learn, etc. If you have some basic
knowledge of Python, you need to import libraries on the top of the code.
Few popular frameworks of machine libraries are given below.

o SciPy
o Scikit-learn
o NumPy
o Pandas
o Matplotlib

6) Business Applications
Business Applications differ from standard applications. E-commerce and
ERP are an example of a business application. This kind of application
requires extensively, scalability and readability, and Python provides all
these features.

ADVERTISEMENT

Oddo is an example of the all-in-one Python-based application which


offers a range of business applications. Python provides
a Tryton platform which is used to develop the business application.

7) Audio or Video-based Applications


Python is flexible to perform multiple tasks and can be used to create
multimedia applications. Some multimedia applications which are made
by using Python are TimPlayer, cplay, etc. The few multimedia libraries
are given below.

o Gstreamer
o Pyglet
o QT Phonon

8) 3D CAD Applications
The CAD (Computer-aided design) is used to design engineering related
architecture. It is used to develop the 3D representation of a part of a
system. Python can create a 3D CAD application by using the following
functionalities.

o Fandango (Popular )
o CAMVOX
o HeeksCNC
o AnyCAD
o RCAM

9) Enterprise Applications
Python can be used to create applications that can be used within an
Enterprise or an Organization. Some real-time applications are OpenERP,
Tryton, Picalo, etc.

10) Image Processing Application


Python contains many libraries that are used to work with the image. The
image can be manipulated according to our requirements. Some libraries
of image processing are given below.

o OpenCV
o Pillow
o SimpleITK

Installation of PYTHON on Windows


Visit the link [Link] to download the latest release
of Python. In this process, we will install Python 3.11.3 on our Windows
operating system. When we click on the above link, it will bring us the
following page.
Step - 1: Select the Python's version to download.

Click on the download button to download the exe file of Python.


If in case you want to download the specific version of Python. Then, you
can scroll down further below to see different versions from 2 and 3
respectively. Click on download button right next to the version number
you want to download.
Step - 2: Click on the Install Now
ADVERTISEMENT

Double-click the executable file, which is downloaded.

The following window will open. Click on the Add Path check box, it will set
the Python path automatically.
Now, Select Customize installation and proceed. We can also click on the
customize installation to choose desired location and features. Other
important thing is install launcher for the all user must be checked.
Here, under the advanced options, click on the checkboxes of " Install
Python 3.11 for all users ", which is previously not checked in. This will
checks the other option " Precompile standard library " automatically. And
the location of the installation will also be changed. We can change it
later, so we leave the install location default. Then, click on the install
button to finally install.

Step - 3 Installation in Process/progress


The set up is in progress. All the python libraries, packages, and other
python default files will be installed in our system. Once the installation is
successful, the following page will appear saying " Setup was successful ".
Step - 4: Verifying the Python Installation
ADVERTISEMENT

To verify whether the python is installed or not in our system, we have to


do the following.
o Go to "Start" button, and search " cmd ".
o Then type, " python - - version ".
o If python is successfully installed, then we can see the version of the
python installed.
o If not installed, then it will print the error as " 'python' is not recognized
as an internal or external command, operable program or batch
file. ".

We are ready to work with the Python.


Step - 5: Opening idle
Now, to work on our first python program, we will go the interactive
interpreter prompt(idle). To open this, go to "Start" and type idle. Then,
click on open to start working on idle.
First Python Program
In this Section, we will discuss the basic syntax of Python, we will run a
simple program to print Hello World on the console.
Python provides us the two ways to run a program:
ADVERTISEMENT

o Using Interactive interpreter prompt


o Using a script file

Let's discuss each one of them in detail.

Interactive interpreter/command prompt


Python provides us the feature to execute the Python statement one by
one at the interactive prompt. It is preferable in the case where we are
concerned about the output of each line of our Python program.
To open the interactive mode, open the terminal (or command prompt)
and type python (python3 in case if you have Python2 and Python3 both
installed on your system).
It will open the following prompt where we can execute the Python
statement and check their impact on the console.
After writing the print statement, press the Enter key.

Here, we get the message "Hello World !" printed on the console.

Using a script file (Script Mode


Programming)
The interpreter prompt is best to run the single-line statements of the
code. However, we cannot write the code every-time on the terminal. It is
not suitable to write multiple lines of code.
Using the script mode, we can write multiple lines code into a file which
can be executed later. For this purpose, we need to open an editor like
notepad, create a file named and save it
with [Link] extension, which stands for "Python". Now, we
will implement the above example using the script mode.
ADVERTISEMENT

1. print ("hello world"); #here, we have used print() function to print the message
on the console.
To run this file named as [Link], we need to run the following command
on the terminal.

Step - 1: Open the Python interactive shell, and click "File" then
choose "New", it will open a new blank script in which we can write our
code.

Step -2: Now, write the code and press "Ctrl+S" to save the file.
Step - 3: After saving the code, we can run it by clicking "Run" or "Run
Module". It will display the output to the shell.

The output will be shown as follows.


Step - 4: Apart from that, we can also run the file using the operating
system terminal. But, we should be aware of the path of the directory
where we have saved our file.
o Open the command line prompt and navigate to the directory.

o We need to type the python keyword, followed by the file name and hit
enter to run the Python file.
Multi-line Statements
Multi-line statements are written into the notepad like an editor and saved
it with .py extension. In the following example, we have defined the
execution of the multiple code lines using the Python script.
ADVERTISEMENT

Code:
1. name = "Andrew Venis"
2. branch = "Computer Science"
3. age = "25"
4. print("My name is: ", name, )
5. print("My age is: ", age)
Script File:
Pros and Cons of Script Mode
Advantages of running code in script mode.
ADVERTISEMENT

o We can run multiple lines of code.


o Debugging is easy in script mode.
o It is appropriate for beginners and also for experts.

Disadvantages of the script mode.


o We have to save the code every time if we make any change in the code.
o It can be tedious when we run a single or a few lines of code.

Python Variables
A variable is the name given to a memory location. A value-holding
Python variable is also known as an identifier.
Since Python is an infer language that is smart enough to determine the
type of a variable, we do not need to specify its type in Python.
Variable names must begin with a letter or an underscore, but they can
be a group of both letters and digits.
The name of the variable should be written in lowercase. Both Rahul and
rahul are distinct variables.

Identifier /VARIABLE Naming


Identifiers are things like variables. An Identifier is utilized to recognize
the literals utilized in the program. The standards to name an identifier
are given underneath.
o The variable's first character must be an underscore or alphabet (_).
o Every one of the characters with the exception of the main person might
be a letter set of lower-case(a-z), capitalized (A-Z), highlight, or digit (0-9).
o White space and special characters (!, @, #, %, etc.) are not allowed in
the identifier name. ^, &, *).
o Identifier name should not be like any watchword characterized in the
language.
o Names of identifiers are case-sensitive; for instance, my name, and
MyName isn't something very similar.
o Examples of valid identifiers: a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.

Declaring Variable and Assigning Values


o Python doesn't tie us to pronounce a variable prior to involving it in the
application. It permits us to make a variable at the necessary time.
o In Python, we don't have to explicitly declare variables. The variable is
declared automatically whenever a value is added to it.
o The equal (=) operator is utilized to assign worth to a variable.

Object References
When we declare a variable, it is necessary to comprehend how the
Python interpreter works. Compared to a lot of other programming
languages, the procedure for dealing with variables is a little different.
Python is the exceptionally object-arranged programming language;
Because of this, every data item is a part of a particular class. Think about
the accompanying model.
1. print("John")
Output:
John
The Python object makes a integer object and shows it to the control
center. We have created a string object in the print statement above.
Make use of the built-in type() function in Python to determine its type.
1. type("John")
Output:
<class 'str'>
In Python, factors are an symbolic name that is a reference or pointer to
an item. The factors are utilized to indicate objects by that name.
Let's understand the following example
1. a = 50

In the above, the variable a refers to an integer object.


Suppose we assign the integer value 50 to a new variable b.
1. a = 50
2. b = a

The variable b refers to the same object that a points to because Python does
not create another object.
Let's assign the new value to b. Now both variables will refer to the
different objects.
1. a = 50
2. b =100

Python manages memory efficiently if we assign the same variable to two


different values.

Object Identity
Every object created in Python has a unique identifier. Python gives the
dependable that no two items will have a similar identifier. The object
identifier is identified using the built-in id() function. consider about the
accompanying model.
1. a = 50
2. b=a
3. print(id(a))
4. print(id(b))
5. # Reassigned variable a
6. a = 500
7. print(id(a))
Output:
140734982691168
140734982691168
2822056960944
We assigned the b = a, an and b both highlight a similar item. The id()
function that we used to check returned the same number. We reassign a
to 500; The new object identifier was then mentioned.

Variable Names.
Rules for Naming Python Variables
1. Constant and variable names should have a combination of letters in lowercase (a
to z) or uppercase (A to Z) or digits (0 to 9) or an underscore (_). For example:
snake_case

MACRO_CASE
camelCase

CapWords

2. Create a name that makes sense. For example, vowel makes more sense than v.
3. If you want to create a variable name having two words, use underscore to
separate them. For example:

my_name

current_salary

5. Python is case-sensitive. So num and Num are different variables. For example,
var num = 5

var Num = 55

print(num) # 5

print(Num) # 55

6. Avoid using keywords like if, True, class, etc. as variable names.

Variable names can be any length can have capitalized, lowercase


(start to finish, a to z), the digit (0-9), and highlight character(_).
Example.
1. name = "Devansh"
2. age = 20
3. marks = 80.50

4. print(name)
5. print(age)
6. print(marks)
Output:
Devansh
20
80.5
Consider the following valid variables name.
1. name = "A"
2. Name = "B"
3. naMe = "C"
4. NAME = "D"
5. n_a_m_e = "E"
6. _name = "F"
7. name_ = "G"
8. _name_ = "H"
9. na56me = "I"
10.
[Link](name,Name,naMe,NAME,n_a_m_e, NAME, n_a_m_e, _name, name_,_name,
na56me)
Output:
A B C D E D E F G F I
We have declared a few valid variable names in the preceding example,
such as name, _name_, and so on. However, this is not recommended
because it may cause confusion when we attempt to read code. To make
the code easier to read, the name of the variable ought to be descriptive.
The multi-word keywords can be created by the following method.
o Camel Case - In the camel case, each word or abbreviation in the middle
of begins with a capital letter. There is no intervention of whitespace. For
example - nameOfStudent, valueOfVaraible, etc.
o Pascal Case - It is the same as the Camel Case, but here the first word is
also capital. For example - NameOfStudent, etc.
o Snake Case - In the snake case, Words are separated by the underscore.
For example - name_of_student, etc.

Multiple Assignment
Multiple assignments, also known as assigning values to multiple
variables in a single statement, is a feature of Python.
We can apply different tasks in two ways, either by relegating a solitary
worth to various factors or doling out numerous qualities to different
factors. Take a look at the following example.
1. Assigning single value to multiple variables
Eg:
1. x=y=z=50
2. print(x)
3. print(y)
4. print(z)
Output:
50
50
50
2. Assigning multiple values to multiple variables:
Eg:
1. a,b,c=5,10,15
2. print a
3. print b
4. print c
Output:
5
10
15
The values will be assigned in the order in which variables appear.

Python Variable Types

There are two types of variables in Python - Local variable and Global
variable. Let's understand the following variables.

Local Variable
The variables that are declared within the function and have scope within
the function are known as local variables. Let's examine the following
illustration.
Example -
1. # Declaring a function
2. def add():
3. # Defining local variables. They has scope only within a function
4. a = 20
5. b = 30
6. c=a+b
7. print("The sum is:", c)
8.
9. # Calling a function
[Link]()
Output:
The sum is: 50
Explanation:
We declared the function add() and assigned a few variables to it in the
code above. These factors will be alluded to as the neighborhood factors
which have scope just inside the capability. We get the error that follows
if we attempt to use them outside of the function.
1. add()
2. # Accessing local variable outside the function
3. print(a)
Output:
The sum is: 50
print(a)
NameError: name 'a' is not defined
We tried to use local variable outside their scope; it threw
the NameError.

Global Variables
Global variables can be utilized all through the program, and its extension
is in the whole program. Global variables can be used inside or outside
the function.
By default, a variable declared outside of the function serves as the global
variable. Python gives the worldwide catchphrase to utilize worldwide
variable inside the capability. The function treats it as a local variable if
we don't use the global keyword. Let's examine the following illustration.
Example -
1. # Declare a variable and initialize it
2. x = 101
3.
4. # Global variable in function
5. def mainFunction():
6. # printing a global variable
7. global x
8. print(x)
9. # modifying a global variable
10. x = 'Welcome To Javatpoint'
11. print(x)
12.
[Link]()
[Link](x)
Output:
101
Welcome To Javatpoint
Welcome To Javatpoint
Explanation:
In the above code, we declare a global variable x and give out a value to
it. We then created a function and used the global keyword to access the
declared variable within the function. We can now alter its value. After
that, we gave the variable x a new string value and then called the
function and printed x, which displayed the new value.
=

Delete a variable
We can delete the variable using the del keyword. The syntax is given
below.
Syntax -
1. del <variable_name>
In the following example, we create a variable x and assign value to it. We
deleted variable x, and print it, we get the error "variable x is not
defined". The variable x will no longer use in future.
Example -
1. # Assigning a value to x
2. x=6
3. print(x)
4. # deleting a variable.
5. del x
6. print(x)
Output:
6
Traceback (most recent call last):
File "C:/Users/DEVANSH SHARMA/PycharmProjects/Hello/[Link]",
line 389, in
print(x)
NameError: name 'x' is not defined

Maximum Possible Value of an Integer in


Python
Python, to the other programming languages, does not support long int or
float data types. It uses the int data type to handle all integer values. The
query arises here. In Python, what is the maximum value that the variable
can hold? Take a look at the following example.
Example -
1. # A Python program to display that we can store
2. # large numbers in Python
3.
4. a = 10000000000000000000000000000000000000000000
5. a=a+1
6. print(type(a))
7. print (a)
Output:
<class 'int'>
10000000000000000000000000000000000000000001
As we can find in the above model, we assigned a large whole number
worth to variable x and really look at its sort. It printed class <int> not
long int. As a result, the number of bits is not limited, and we are free to
use all of our memory.
There is no special data type for storing larger numbers in Python.
We can print numerous factors inside the single print explanation. The
examples of single and multiple printing values are provided below.
Example - 1 (Printing Single Variable)
1. # printing single value
2. a = 5
3. print(a)
4. print((a))
Output:
5
5
Example - 2 (Printing Multiple Variables)
1. a=5
2. b=6
3. # printing multiple variables
4. print(a,b)
5. # separate the variables by the comma
6. Print(1, 2, 3, 4, 5, 6, 7, 8)
Output:
5 6
1 2 3 4 5 6 7 8

Python Data Types


Every value has a datatype, and variables can hold values. Python is a powerfully composed
language; consequently, we don't have to characterize the sort of variable while announcing
it. The interpreter binds the value implicitly to its type.
1. a = 5
We did not specify the type of the variable a, which has the value five from an integer. The
Python interpreter will automatically interpret the variable as an integer.
We can verify the type of the program-used variable thanks to Python. The type() function in
Python returns the type of the passed variable.
Consider the following illustration when defining and verifying the values of various data
types.
1. a=10
2. b="Hi Python"
3. c = 10.5
4. print(type(a))
5. print(type(b))
6. print(type(c))
Output:
<type 'int'>
<type 'str'>
<type 'float'>
Standard data types
A variable can contain a variety of values. On the other hand, a person's id must be stored as
an integer, while their name must be stored as a string.
The storage method for each of the standard data types that Python provides is specified by
Python. The following is a list of the Python-defined data types.
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary

The data types will be briefly discussed in this tutorial section. We will talk about every
single one of them exhaustively later in this instructional exercise.

Numbers
Numeric values are stored in numbers. The whole number, float, and complex qualities have
a place with a Python Numbers datatype. Python offers the type() function to determine a
variable's data type. The instance () capability is utilized to check whether an item has a place
with a specific class.
When a number is assigned to a variable, Python generates Number objects. For instance,
1. a=5
2. print("The type of a", type(a))
3.
4. b = 40.5
5. print("The type of b", type(b))
6.
7. c = 1+3j
8. print("The type of c", type(c))
9. print(" c is a complex number", isinstance(1+3j,complex))
Output:
The type of a <class 'int'>
The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True
Python supports three kinds of numerical data.
ADVERTISEMENT

o Int: Whole number worth can be any length, like numbers 10, 2, 29, - 20,
- 150, and so on. An integer can be any length you want in Python. Its
worth has a place with int.
o Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can
be accurate to within 15 decimal places.
o Complex: An intricate number contains an arranged pair, i.e., x + iy,
where x and y signify the genuine and non-existent parts separately. The
complex numbers like 2.14j, 2.0 + 2.3j, etc.

Sequence Type
String

The sequence of characters in the quotation marks can be used to describe the string. A string
can be defined in Python using single, double, or triple quotes.
String dealing with Python is a direct undertaking since Python gives worked-in capabilities
and administrators to perform tasks in the string.
When dealing with strings, the operation "hello"+" python" returns "hello python," and the
operator + is used to combine two strings.
Because the operation "Python" *2 returns "Python," the operator * is referred to as a
repetition operator.
The Python string is demonstrated in the following example.
Example - 1
1. str = "string using double quotes"
2. print(str)
3. s = '''''A multiline
4. string'''
5. print(s)
Output:
string using double quotes
A multiline
string
Look at the following illustration of string handling.
Example - 2
1. str1 = 'hello javatpoint' #string str1
2. str2 = ' how are you' #string str2
3. print (str1[0:2]) #printing first two character using slice operator
4. print (str1[4]) #printing 4th character of the string
5. print (str1*2) #printing the string twice
6. print (str1 + str2) #printing the concatenation of str1 and str2
Output:
he
o
hello javatpointhello javatpoint
hello javatpoint how are you

List

Lists in Python are like arrays in C, but lists can contain data of different types. The things
put away in the rundown are isolated with a comma (,) and encased inside square sections [].
To gain access to the list's data, we can use slice [:] operators. Like how they worked with
strings, the list is handled by the concatenation operator (+) and the repetition operator (*).
Look at the following example.
Example:
1. list1 = [1, "hi", "Python", 2]
2. #Checking type of given list
3. print(type(list1))
4.
5. #Printing the list1
6. print (list1)
7.
8. # List slicing
9. print (list1[3:])
10.
11. # List slicing
12. print (list1[0:2])
13.
14. # List Concatenation using + operator
15. print (list1 + list1)
16.
17. # List repetition using * operator
18. print (list1 * 3)
Output:
[1, 'hi', 'Python', 2]
[2]
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]

Tuple
In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of items from
various data types. A parenthetical space () separates the tuple's components from one
another.
Because we cannot alter the size or value of the items in a tuple, it is a read-only data
structure.
Let's look at a straightforward tuple in action.
Example:
1. tup = ("hi", "Python", 2)
2. # Checking type of tup
3. print (type(tup))
4.
5. #Printing the tuple
6. print (tup)
7.
8. # Tuple slicing
9. print (tup[1:])
10. print (tup[0:1])
11.
12. # Tuple concatenation using + operator
13. print (tup + tup)
14.
15. # Tuple repatation using * operator
16. print (tup * 3)
17.
18. # Adding value to tup. It will throw an error.
19. t[2] = "hi"
Output:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
Traceback (most recent call last):
File "[Link]", line 14, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment

Dictionary
A dictionary is a key-value pair set arranged in any order. It stores a specific value for each
key, like an associative array or a hash table. Value is any Python object, while the key can
hold any primitive data type.
The comma (,) and the curly braces are used to separate the items in the dictionary.
Look at the following example.
ADVERTISEMENT

1. d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}


2.
3. # Printing dictionary
4. print (d)
5.
6. # Accesing value using keys
7. print("1st name is "+d[1])
8. print("2nd name is "+ d[4])
9.
10. print ([Link]())
11. print ([Link]())
Output:
1st name is Jimmy
2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])

Boolean
True and False are the two default values for the Boolean type. These qualities are utilized to
decide the given assertion valid or misleading. The class book indicates this. False can be
represented by the 0 or the letter "F," while true can be represented by any value that is not
zero.
Look at the following example.
1. # Python program to check the boolean type
2. print(type(True))
3. print(type(False))
4. print(false)
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined

Set
The data type's unordered collection is Python Set. It is iterable, mutable(can change after
creation), and has remarkable components. The elements of a set have no set order; It might
return the element's altered sequence. Either a sequence of elements is passed through the
curly braces and separated by a comma to create the set or the built-in function set() is used
to create the set. It can contain different kinds of values.
Look at the following example.
1. # Creating Empty set
2. set1 = set()
3.
4. set2 = {'James', 2, 3,'Python'}
5.
6. #Printing Set value
7. print(set2)
8.
9. # Adding element to the set
10.
11. [Link](10)
12. print(set2)
13.
14. #Removing element from the set
15. [Link](2)
16. print(set2)
Output:
{3, 'Python', 'James', 2}
{'Python', 'James', 3, 2, 10}
{'Python', 'James', 3, 10}

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.

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 retur


n

and continu for lambda try


e

as def from nonloca while


l

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
1. # Python program to demonstrate the application of iskeyword()
2. # importing keyword library which has lists
3. import keyword
4.
5. # displaying the complete list using "kwlist()."
6. print("The set of keywords in this version is: ")
7. print( [Link] )
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:

A Boolean literal can have any of the two values: True or False.
Example - Boolean Literals
1. x = (1 == True)
2. y = (2 == False)
3. z = (3 == True)
4. a = True + 10
5. b = False + 10
6.
7. print("x is", x)
8. print("y is", y)
9. print("z is", z)
[Link]("a:", a)
[Link]("b:", b)
Output:
x is True
y is False
z is False
a: 11
b: 10

IV. Special literals.


Python contains one special literal i.e., None.
None is used to specify to that field that is not created. It is also used for
the end of lists in Python.
Example - Special Literals
1. val1=10
2. val2=None
3. print(val1)
4. print(val2)
Output:
10
None

V. Literal Collections.
Python provides the four types of literal collection such as List literals,
Tuple literals, Dict literals, and Set literals.

List:
o List contains items of different data types. Lists are mutable i.e.,
modifiable.
o The values stored in List are separated by comma(,) and enclosed within
square brackets([]). We can store different types of data in a List.

Example - List literals


1. list=['John',678,20.4,'Peter']
2. list1=[456,'Andrew']
3. print(list)
4. print(list + list1)
Output:
['John', 678, 20.4, 'Peter']
['John', 678, 20.4, 'Peter', 456, 'Andrew']
Dictionary:
o Python dictionary stores the data in the key-value pair.
o It is enclosed by curly-braces {} and each pair is separated by the
commas(,).

Example
1. dict = {'name': 'Pater', 'Age':18,'Roll_nu':101}
2. print(dict)
Output:
{'name': 'Pater', 'Age': 18, 'Roll_nu': 101}
Tuple:
o Python tuple is a collection of different data-type. It is immutable which
means it cannot be modified after creation.
o It is enclosed by the parentheses () and each element is separated by the
comma(,).

Example
1. tup = (10,20,"Dev",[2,3,4])
2. print(tup)
Output:
(10, 20, 'Dev', [2, 3, 4])
Set:
o Python set is the collection of the unordered dataset.
o It is enclosed by the {} and each element is separated by the comma(,).

Example: - Set Literals


1. set = {'apple','grapes','guava','papaya'}
2. print(set)
Output:
{'guava', 'apple', 'papaya', 'grapes'}

Python Operators
Introduction:
In this article, we are discussing Python Operators. The operator is a
symbol that performs a specific operation between two operands,
according to one definition. Operators serve as the foundation upon which
logic is constructed in a program in a particular programming language. In
every programming language, some operators perform several tasks.
Same as other languages, Python also has some operators, and these are
given below -
ADVERTISEMENT

o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
o Arithmetic Operators

Arithmetic Operators
Arithmetic operators used between two operands for a particular
operation. There are many arithmetic operators. It includes the exponent
(**) operator as well as the + (addition), - (subtraction), *
(multiplication), / (divide), % (reminder), and // (floor division) operators.
Consider the following table for a detailed explanation of arithmetic
operators.

Operator Description

+ (Addition) It is used to add two operands. For example, if a = 10, b = 10 => a+b = 20

- It is used to subtract the second operand from the first operand. If the first op
(Subtraction) than the second operand, the value results negative. For example, if a = 20, b
= 15

/ (divide) It returns the quotient after dividing the first operand by the second operand.
if a = 20, b = 10 => a/b = 2.0

* It is used to multiply one operand with the other. For example, if a = 20, b = 4
(Multiplicatio 80
n)

% (reminder) It returns the reminder after dividing the first operand by the second operand.
if a = 20, b = 10 => a%b = 0

** (Exponent) As it calculates the first operand's power to the second operand, it is an expone

// (Floor It provides the quotient's floor value, which is obtained by dividing the two ope
division)

Program Code:
Now we give code examples of arithmetic operators in Python. The code is
given below -
1. a = 32 # Initialize the value of a
2. b=6 # Initialize the value of b
3. print('Addition of two numbers:',a+b)
4. print('Subtraction of two numbers:',a-b)
5. print('Multiplication of two numbers:',a*b)
6. print('Division of two numbers:',a/b)
7. print('Reminder of two numbers:',a%b)
8. print('Exponent of two numbers:',a**b)
9. print('Floor division of two numbers:',a//b)
Output:
Now we compile the above code in Python, and after successful
compilation, we run it. Then the output is given below -
Addition of two numbers: 38
Subtraction of two numbers: 26
Multiplication of two numbers: 192
Division of two numbers: 5.333333333333333
Reminder of two numbers: 2
Exponent of two numbers: 1073741824
Floor division of two numbers: 5

Comparison operator
Comparison operators mainly use for comparison purposes. Comparison
operators compare the values of the two operands and return a true or
false Boolean value in accordance. The example of comparison operators
are ==, !=, <=, >=, >, <. In the below table, we explain the works of the
operators.

Operator Description

== If the value of two operands is equal, then the condition becomes true.

!= If the value of two operands is not equal, then the condition becomes true.

<= The condition is met if the first operand is smaller than or equal to the second ope

>= The condition is met if the first operand is greater than or equal to the second ope

> If the first operand is greater than the second operand, then the condition become

< If the first operand is less than the second operand, then the condition becomes tr

Program Code:
Now we give code examples of Comparison operators in Python. The code
is given below -
1. a = 32 # Initialize the value of a
2. b = 6 # Initialize the value of b
3. print('Two numbers are equal or not:',a==b)
4. print('Two numbers are not equal or not:',a!=b)
5. print('a is less than or equal to b:',a<=b)
6. print('a is greater than or equal to b:',a>=b)
7. print('a is greater b:',a>b)
8. print('a is less than b:',a<b)
Output:
Now we compile the above code in Python, and after successful
compilation, we run it. Then the output is given below -
Two numbers are equal or not: False
Two numbers are not equal or not: True
a is less than or equal to b: False
a is greater than or equal to b: True
a is greater b: True
a is less than b: False

Assignment Operators
Using the assignment operators, the right expression's value is assigned
to the left operand. There are some examples of assignment operators
like =, +=, -=, *=, %=, **=, //=. In the below table, we explain the works
of the operators.

Operato Description
r

= It assigns the value of the right expression to the left operand.

+= By multiplying the value of the right operand by the value of the left operand, the
receives a changed value. For example, if a = 10, b = 20 => a+ = b will be equal
and therefore, a = 30.

-= It decreases the value of the left operand by the value of the right operand and
modified value back to left operand. For example, if a = 20, b = 10 => a- = b will b
= a- b and therefore, a = 10.

*= It multiplies the value of the left operand by the value of the right operand and
modified value back to then the left operand. For example, if a = 10, b = 20 => a
equal to a = a* b and therefore, a = 200.

%= It divides the value of the left operand by the value of the right operand and
reminder back to the left operand. For example, if a = 20, b = 10 => a % = b will b
= a % b and therefore, a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign 4**2 = 1

//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign 4//3 = 1

Program Code:
Now we give code examples of Assignment operators in Python. The code
is given below -
1. a = 32 # Initialize the value of a
2. b=6 # Initialize the value of b
3. print('a=b:', a==b)
4. print('a+=b:', a+b)
5. print('a-=b:', a-b)
6. print('a*=b:', a*b)
7. print('a%=b:', a%b)
8. print('a**=b:', a**b)
9. print('a//=b:', a//b)
Output:
Now we compile the above code in Python, and after successful
compilation, we run it. Then the output is given below -
a=b: False
a+=b: 38
a-=b: 26
a*=b: 192
a%=b: 2
a**=b: 1073741824
a//=b: 5

Bitwise Operators
The two operands' values are processed bit by bit by the bitwise
operators. The examples of Bitwise operators are bitwise OR (|), bitwise
AND (&), bitwise XOR (^), negation (~), Left shift (<<), and Right shift
(>>). Consider the case below.
For example,
1. if a = 7
2. b=6
3. then, binary (a) = 0111
4. binary (b) = 0110
5.
6. hence, a & b = 0011
7. a | b = 0111
8. a ^ b = 0100
9. ~ a = 1000
[Link], Binary of x = 0101
11. Binary of y = 1000
[Link] OR = 1101
13.8 4 2 1
14.1 1 0 1 = 8 + 4 + 1 = 13
15.
[Link] AND = 0000
17.0000 = 0
18.
[Link] XOR = 1101
20.8 4 2 1
21.1 1 0 1 = 8 + 4 + 1 = 13
[Link] of x = ~x = (-x) - 1 = (-5) - 1 = -6
23.~x = -6
In the below table, we are explaining the works of the bitwise operators.

Operator Description

& (binary A 1 is copied to the result if both bits in two operands at the same location are
and) copied.

| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit will

^ (binary If the two bits are different, the outcome bit will be 1, else it will be 0.
xor)

~ (negation) The operand's bits are calculated as their negations, so if one bit is 0, the next
and vice versa.

<< (left The number of bits in the right operand is multiplied by the leftward shift of the
shift) left operand.

>> (right The left operand is moved right by the number of bits present in the right operand
shift)

Program Code:
Now we give code examples of Bitwise operators in Python. The code is
given below -
1. a=5 # initialize the value of a
2. b=6 # initialize the value of b
3. print('a&b:', a&b)
4. print('a|b:', a|b)
5. print('a^b:', a^b)
6. print('~a:', ~a)
7. print('a<<b:', a<<b)
8. print('a>>b:', a>>b)
Output:
Now we compile the above code in Python, and after successful
compilation, we run it. Then the output is given below -
a&b: 4
a|b: 7
a^b: 3
~a: -6
a<>b: 0

Logical Operators
The assessment of expressions to make decisions typically uses logical
operators. The examples of logical operators are and, or, and not. In the
case of logical AND, if the first one is 0, it does not depend upon the
second one. In the case of logical OR, if the first one is 1, it does not
depend on the second one. Python supports the following logical
operators. In the below table, we explain the works of the logical
operators.

Operato Description
r

and The condition will also be true if the expression is true. If the two expressions a a
same, then a and b must both be true.

or The condition will be true if one of the phrases is true. If a and b are the two express
or b must be true if and is true and b is false.

not If an expression a is true, then not (a) will be false and vice versa.

Program Code:
Now we give code examples of arithmetic operators in Python. The code is
given below -
1. a=5 # initialize the value of a
2. print(Is this statement true?:',a > 3 and a < 5)
3. print('Any one statement is true?:',a > 3 or a < 5)
4. print('Each statement is true then return False and vice-versa:',(not(a > 3 and
a < 5)))
Output:
Now we give code examples of Bitwise operators in Python. The code is
given below -
Is this statement true?: False
Any one statement is true?: True
Each statement is true then return False and vice-versa: True

Membership Operators
The membership of a value inside a Python data structure can be verified
using Python membership operators. The result is true if the value is in
the data structure; otherwise, it returns false.

Operator Description

in If the first operand cannot be found in the second operand, it is evaluated to be tru
or dictionary).

not in If the first operand is not present in the second operand, the evaluation is true (
dictionary).

Program Code:
Now we give code examples of Membership operators in Python. The code
is given below -
1. x = ["Rose", "Lotus"]
2. print(' Is value Present?', "Rose" in x)
3. print(' Is value not Present?', "Riya" not in x)
Output:
Now we compile the above code in Python, and after successful
compilation, we run it. Then the output is given below -
Is value Present? True
Is value not Present? True

Identity Operators
Operator Description

is If the references on both sides point to the same object, it is determined to be true

is not If the references on both sides do not point at the same object, it is determined to

Program Code:
Now we give code examples of Identity operators in Python. The code is
given below -
1. a = ["Rose", "Lotus"]
2. b = ["Rose", "Lotus"]
3. c = a
4. print(a is c)
5. print(a is not c)
6. print(a is b)
7. print(a is not b)
8. print(a == b)
9. print(a != b)
Output:
Now we compile the above code in python, and after successful
compilation, we run it. Then the output is given below -
True
False
False
True
True
False

Operator Precedence
The order in which the operators are examined is crucial to understand
since it tells us which operator needs to be considered first. Below is a list
of the Python operators' precedence tables.

Operator Description

** Overall other operators employed in the expression, the


exponent operator is given precedence.

~+- the minus, unary plus, and negation.

* / % // the division of the floor, the modules, the division, and the
multiplication.

+- Binary plus, and minus

>> << Left shift. and right shift

& Binary and.

^| Binary xor, and or

<= < > >= Comparison operators (less than, less than equal to, greater
than, greater then equal to).
<> == != Equality operators.

= %= /= //= -= Assignment operators


+=
*= **=

is is not Identity operators

in not in Membership operators

not or and Logical operators

Comments can be used to explain Python code.

Comments can be used to make the code more readable.

Comments can be used to prevent execution when testing code.

Creating a Comments in PYTHON


Comments starts with a #, and Python will ignore them:

Example
#This is a comment
print("Hello, World!")
OUTPUT
Hello, World!

Comments can be placed at the end of a line, and Python will ignore the rest
of the line:

Example
print("Hello, World!") #This is a comment

OUTPUT
Hello, World!

A comment does not have to be text that explains the code, it can also be
used to prevent Python from executing code:

Example
#print("Hello, World!")
print("Cheers, Mate!")

OUTPUT

Cheers, Mate!

Multiline Comments
Python does not really have a syntax for multiline comments.

To add a multiline comment you could insert a # for each line:

Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")
OUTPUT:
Hello, World!

Or, not quite as intended, you can use a multiline string.

Since Python will ignore string literals that are not assigned to a variable, you
can add a multiline string (triple quotes) in your code, and place your
comment inside it:

Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
OUTPUT:
Hello, World!

Python If-else statements


Decision making is the most important aspect of almost all the
programming languages. As the name implies, decision making allows us
to run a particular block of code for a particular decision. Here, the
decisions are made on the validity of the particular conditions. Condition
checking is the backbone of decision making.
In python, decision making is performed by the following statements.

Statement Description

If Statement The if statement is used to test a specific condition. If the condition is


true, a block of code (if-block) will be executed.

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

Nested if Nested if statements enable us to use if ? else statement inside an outer


Statement if statement.

Indentation in Python
For the ease of programming and to achieve simplicity, python doesn't
allow the use of parentheses for the block level code. In Python,
indentation is used to declare a block. If two statements are at the same
indentation level, then they are the part of the same block.
Generally, four spaces are given to indent the statements which are a
typical amount of indentation in python.
Indentation is the most used part of the python language since it declares
the block of code. All the statements of one block are intended at the
same level indentation. We will see how the actual indentation takes
place in decision making and other stuff in python.

*CONTROL STATEMENTS IN PYTHON*


The if statement
The if statement is used to test a particular condition and if the condition
is true, it executes a block of code known as if-block. The condition of if
statement can be any valid logical expression which can be either
evaluated to true or false.

The syntax of the if-statement is given below.


1. if expression:
2. statement

Example 1
1. # Simple Python program to understand the if statement
2. num = int(input("enter the number:"))
3. # Here, we are taking an integer num and taking input dynamically
4. if num%2 == 0:
5. # Here, we are checking the condition. If the condition is true, we will enter the
block
6. print("The Given number is an even number")
Output:
enter the number: 10
The Given number is an even number

Example 2 : Program to print the largest of the three


numbers.
1. # Simple Python Program to print the largest of the three numbers.
2. a = int (input("Enter a: "));
3. b = int (input("Enter b: "));
4. c = int (input("Enter c: "));
5. if a>b and a>c:
6. # Here, we are checking the condition. If the condition is true, we will enter the block

7. print ("From the above three numbers given a is largest");


8. if b>a and b>c:
9. # Here, we are checking the condition. If the condition is true, we will enter the block

10. print ("From the above three numbers given b is largest");


[Link] c>a and c>b:
12.# Here, we are checking the condition. If the condition is true, we will enter the block

13. print ("From the above three numbers given c is largest");


Output:
Enter a: 100
Enter b: 120
Enter c: 130
From the above three numbers given c is largest

The if-else statement


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

If the condition is true, then the if-block is executed. Otherwise, the else-
block is executed.
The syntax of the if-else statement is given below.
1. if condition:
2. #block of statements
3. else:
4. #another block of statements (else-block)

Example 1 : Program to check whether a person is


eligible to vote or not.
5.
1. # Simple Python Program to check whether a person is eligible to vote or not.
2. age = int (input("Enter your age: "))
3. # Here, we are taking an integer num and taking input dynamically
4. if age>=18:
5. # Here, we are checking the condition. If the condition is true, we will enter th
e block
6. print("You are eligible to vote !!");
7. else:
8. print("Sorry! you have to wait !!");
Output:
Enter your age: 90
You are eligible to vote !!
Example 2: Program to check whether a number is
even or not.

1. # Simple Python Program to check whether a number is even or not.


2. num = int(input("enter the number:"))
3. # Here, we are taking an integer num and taking input dynamically
4. if num%2 == 0:
5. # Here, we are checking the condition. If the condition is true, we will enter the bloc
k
6. print("The Given number is an even number")
7. else:
8. print("The Given Number is an odd number")
Output:
enter the number: 10
The Given number is even number

The elif statement


1. if expression 1:
2. # block of statements
3.
4. elif expression 2:
5. # block of statements
6.
7. elif expression 3:
8. # block of statements
9.
[Link]:
11. # block of statements
The elif statement enables us to check multiple conditions and execute
the specific block of statements depending upon the true condition
among them. We can have any number of elif statements in our program
depending upon our need. However, using elif is optional.
The elif statement works like an if-else-if ladder statement in C. It must be
succeeded by an if statement.
The syntax of the elif statement is given below.

Example 1

1. # Simple Python program to understand elif statement


2. number = int(input("Enter the number?"))
3. # Here, we are taking an integer number and taking input dynamically
4. if number==10:
5. # Here, we are checking the condition. If the condition is true, we will enter t
he block
6. print("The given number is equals to 10")
7. elif number==50:
8. # Here, we are checking the condition. If the condition is true, we will enter t
he block
9. print("The given number is equal to 50");
[Link] number==100:
11.# Here, we are checking the condition. If the condition is true, we will enter t
he block
12. print("The given number is equal to 100");
[Link]:
14. print("The given number is not equal to 10, 50 or 100");
Output:
Enter the number?15
The given number is not equal to 10, 50 or 100

Example 2
1. # Simple Python program to understand elif statement
2. marks = int(input("Enter marks? "))
3. # Here, we are taking an integer marks and taking input dynamically
4. if marks > 85 and marks <= 100:
5. # Here, we are checking the condition. If the condition is true, we will enter the
block
6. print("Congrats ! you scored grade A ...")
7. elif marks > 60 and marks <= 85:
8. # Here, we are checking the condition. If the condition is true, we will enter the
block
9. print("You scored grade B + ...")
[Link] marks > 40 and marks <= 60:
11.# Here, we are checking the condition. If the condition is true, we will enter the
block
12. print("You scored grade B ...")
[Link] (marks > 30 and marks <= 40):
14.# Here, we are checking the condition. If the condition is true, we will enter the
block
15. print("You scored grade C ...")
[Link]:
17. print("Sorry you are fail ?")
Output:
Enter the marks? 89
Congrats ! you scored grade A ...
As long as the string is not assigned to a variable, Python will read the code,
but then ignore it, and you have made a multiline comment.

Python Loops
The following loops are available in Python to fulfil the looping needs.
Python offers 3 choices for running the loops. The basic functionality of all
the techniques is the same, although the syntax and the amount of time
required for checking the condition differ.
We can run a single statement or set of statements repeatedly using a
loop command.
The following sorts of loops are available in the Python programming
language.

[Link]. Name of the Loop Type & Description


loop

1 While loop Repeats a statement or group of statements while a given conditio


tests the condition before executing the loop body.

2 For loop This type of loop executes a code block multiple times and abbrevia
that manages the loop variable.

3 Nested loops We can iterate a loop inside another loop.


Loop Control Statements
Statements used to control loops and change the course of iteration are
called control statements. All the objects produced within the local scope
of the loop are deleted when execution is completed.
Python provides the following control statements. We will discuss them
later in detail.
Let us quickly go over the definitions of these loop control statements.

[Link]. Name of the Description


control statement

1 Break statement This command terminates the loop's execution and transfers th
control to the statement next to the loop.

2 Continue This command skips the current iteration of the loop. The
statement following the continue statement are not executed once
interpreter reaches the continue statement.

3 Pass statement The pass statement is used when a statement is syntactically ne


no code is to be executed.

The for Loop


Python's for loop is designed to repeatedly execute a code block while
iterating through a list, tuple, dictionary, or other iterable objects of
Python. The process of traversing a sequence is known as iteration.
Syntax of the for Loop
1. for value in sequence:
2. { code block }
In this case, the variable value is used to hold the value of every item
present in the sequence before the iteration begins until this particular
iteration is completed.
Loop iterates until the final item of the sequence are reached.
ADVERTISEMENT

Code
1. # Python program to show how the for loop works
2.
3. # Creating a sequence which is a tuple of numbers
4. numbers = [4, 2, 6, 7, 3, 5, 8, 10, 6, 1, 9, 2]
5.
6. # variable to store the square of the number
7. square = 0
8.
9. # Creating an empty list
[Link] = []
11.
12.# Creating a for loop
[Link] num in numbers:
14. square = num ** 2
15. [Link](square)
[Link]("The list of squares is", squares)
Output:
The list of squares is [16, 4, 36, 49, 9, 25, 64, 100, 36, 1,
81, 4]

Using else Statement with for Loop


As already said, a for loop executes the code block until the sequence
element is reached. The statement is written right after the for loop is
executed after the execution of the for loop is complete.
Only if the execution is complete does the else statement comes into
play. It won't be executed if we exit the loop or if an error is thrown.
Here is a code to better understand if-else statements.
Code
1. # Python program to show how if-else statements work
2.
3. string = "Python Loop"
4.
5. # Initiating a loop
6. for ch in a string:
7. # giving a condition in if block
8. if ch== "o":
9. print("If block")
10. # if condition is not satisfied then else block will be executed
11. else:
12. print(ch)
Output:
P
y
t
h
If block
n

L
If block
If block
p
Now similarly, using else with for loop.
Syntax:
1. for value in sequence:
2. # executes the statements until sequences are exhausted
3. else:
4. # executes these statements when for loop is completed
Code
1. # Python program to show how to use else statement with for loop
2.
3. # Creating a sequence
4. tuple_ = (3, 4, 6, 8, 9, 2, 3, 8, 9, 7)
5.
6. # Initiating the loop
7. for value in tuple_:
8. if value % 2 != 0:
9. print(value)
10.# giving an else statement
[Link]:
12. print("These are the odd numbers present in the tuple")
Output:
3
9
3
9
7
These are the odd numbers present in the tuple

The range() Function


With the help of the range() function, we may produce a series of
numbers. range(10) will produce values between 0 and 9. (10 numbers).
We can give specific start, stop, and step size values in the manner
range(start, stop, step size). If the step size is not specified, it defaults to
1.
Since it doesn't create every value it "contains" after we construct it, the
range object can be characterized as being "slow." It does provide in, len,
and __getitem__ actions, but it is not an iterator.
The example that follows will make this clear.
Code
1. # Python program to show the working of range() function
2.
3. print(range(15))
4.
5. print(list(range(15)))
6.
7. print(list(range(4, 9)))
8.
9. print(list(range(5, 25, 4)))
Output:
range(0, 15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
[4, 5, 6, 7, 8]
[5, 9, 13, 17, 21]
To iterate through a sequence of items, we can apply the range() method
in for loops. We can use indexing to iterate through the given sequence
by combining it with an iterable's len() function. Here's an illustration.
Code
1. # Python program to iterate over a sequence with the help of indexing
2.
3. tuple_ = ("Python", "Loops", "Sequence", "Condition", "Range")
4.
5. # iterating over tuple_ using range() function
6. for iterator in range(len(tuple_)):
7. print(tuple_[iterator].upper())
Output:
PYTHON
LOOPS
SEQUENCE
CONDITION
RANGE

While Loop
While loops are used in Python to iterate until a specified condition is met.
However, the statement in the program that follows the while loop is
executed once the condition changes to false.
Syntax of the while loop is:
1. while <condition>:
2. { code block }
All the coding statements that follow a structural command define a code
block. These statements are intended with the same number of spaces.
Python groups statements together with indentation.
Code
1. # Python program to show how to use a while loop
2. counter = 0
3. # Initiating the loop
4. while counter < 10: # giving the condition
5. counter = counter + 3
6.
7. print("Python Loops")
Output:
Python Loops
Python Loops
Python Loops
Python Loops

Using else Statement with while Loops


As discussed earlier in the for loop section, we can use the else statement
with the while loop also. It has the same syntax.
Code
1. #Python program to show how to use else statement with the while loop
2. counter = 0
3.
4. # Iterating through the while loop
5. while (counter < 10):
6. counter = counter + 3
7. print("Python Loops") # Executed untile condition is met
8. # Once the condition of while loop gives False this statement will be executed
9. else:
10. print("Code block inside the else statement")
Output:
Python Loops
Python Loops
Python Loops
Python Loops
Code block inside the else statement

Single statement while Block


The loop can be declared in a single statement, as seen below. This is
similar to the if-else block, where we can write the code block in a single
line.
Code
1. # Python program to show how to write a single statement while loop
2. counter = 0
3. while (count < 3): print("Python Loops")

Loop Control Statements


Now we will discuss the loop control statements in detail. We will see an
example of each control statement.
Continue Statement
It returns the control to the beginning of the loop.
Code
1. # Python program to show how the continue statement works
2.
3. # Initiating the loop
4. for string in "Python Loops":
5. if string == "o" or string == "p" or string == "t":
6. continue
7. print('Current Letter:', string)
Output:
Current Letter: P
Current Letter: y
Current Letter: h
Current Letter: n
Current Letter:
Current Letter: L
Current Letter: s

Break Statement
It stops the execution of the loop when the break statement is reached.
Code
1. # Python program to show how the break statement works
2.
3. # Initiating the loop
4. for string in "Python Loops":
5. if string == 'L':
6. break
7. print('Current Letter: ', string)
Output:
Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: h
Current Letter: o
Current Letter: n
Current Letter:

Pass Statement
Pass statements are used to create empty loops. Pass statement is also
employed for classes, functions, and empty control statements.
Code
1. # Python program to show how the pass statement works
2. for a string in "Python Loops":
3. pass
4. print( 'Last Letter:', string)
Output:
Last Letter: s

Python for loop


Python is a strong, universally applicable prearranging language planned
to be easy to comprehend and carry out. It is allowed to get to because it
is open-source. In this tutorial, we will learn how to use Python for loops,
one of the most fundamental looping instructions in Python programming.

Introduction to for Loop in Python


Python frequently uses the Loop to iterate over iterable objects like lists,
tuples, and strings. Crossing is the most common way of emphasizing
across a series, for loops are used when a section of code needs to be
repeated a certain number of times. The for-circle is typically utilized on
an iterable item, for example, a rundown or the in-fabricated range
capability. In Python, the for Statement runs the code block each time it
traverses a series of elements. On the other hand, the "while" Loop is
used when a condition needs to be verified after each repetition or when
a piece of code needs to be repeated indefinitely. The for Statement is
opposed to this Loop.

Syntax of for Loop


1. for value in range/sequence:
2. {loop body}
The value is the parameter that determines the element's value within
the iterable sequence on each iteration. When a sequence contains
expression statements, they are processed first. The first element in the
sequence is then assigned to the iterating variable iterating_variable.
From that point onward, the planned block is run. Each element in the
sequence is assigned to iterating_variable during the statement block
until the sequence as a whole is completed. Using indentation, the
contents of the Loop are distinguished from the remainder of the
program.

Example of Python for Loop


Code
1. # Code to find the sum of squares of each element of the list using for loop
2.
3. # creating the list of numbers
4. numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]
5.
6. # initializing a variable that will store the sum
7. sum_ = 0
8.
9. # using for loop to iterate over the list
[Link] num in numbers:
11.
12.sum_ = sum_ + num ** 2
13.
[Link]("The sum of squares is: ", sum_)
Output:
The sum of squares is: 774

The range() Function


Since the "range" capability shows up so habitually in for circles, we could
erroneously accept the reach as a part of the punctuation of for circle. It's
not: It is a built-in Python method that fulfills the requirement of providing
a series for the for expression to run over by following a particular pattern
(typically serial integers). Mainly, they can act straight on sequences, so
counting is unnecessary. This is a typical novice construct if they originate
from a language with distinct loop syntax:
Code
1. my_list = [3, 5, 6, 8, 4]
2. for iter_var in range( len( my_list ) ):
3. my_list.append(my_list[iter_var] + 2)
4. print( my_list )
Output:
[3, 5, 6, 8, 4, 5, 7, 8, 10, 6]

Iterating by Using Index of Sequence


Another method of iterating through every item is to use an index offset
within the sequence. Here's a simple illustration:
Code
ADVERTISEMENT

1. # Code to find the sum of squares of each element of the list using for loop
2.
3. # creating the list of numbers
4. numbers = [3, 5, 23, 6, 5, 1, 2, 9, 8]
5.
6. # initializing a variable that will store the sum
7. sum_ = 0
8.
9. # using for loop to iterate over list
[Link] num in range( len(numbers) ):
11.
12.sum_ = sum_ + numbers[num] ** 2
13.
[Link]("The sum of squares is: ", sum_)
Output:
The sum of squares is: 774
The len() worked in a technique that profits the complete number of
things in the rundown or tuple, and the implicit capability range(), which
returns the specific grouping to emphasize over, proved helpful here.

Using else Statement with for Loop


A loop expression and an else expression can be connected in Python.
After the circuit has finished iterating over the list, the else clause is
combined with a for Loop.
The following example demonstrates how to extract students' marks from
the record by combining a for expression with an otherwise statement.
Code
1. # code to print marks of a student from the record
2. student_name_1 = 'Itika'
3. student_name_2 = 'Parker'
4.
5.
6. # Creating a dictionary of records of the students
7. records = {'Itika': 90, 'Arshia': 92, 'Peter': 46}
8. def marks( student_name ):
9. for a_student in record: # for loop will iterate over the keys of the dictionary
10. if a_student == student_name:
11. return records[ a_student ]
12. break
13. else:
14. return f'There is no student of name {student_name} in the records'
15.
16.# giving the function marks() name of two students
[Link]( f"Marks of {student_name_1} are: ", marks( student_name_1 ) )
[Link]( f"Marks of {student_name_2} are: ", marks( student_name_2 ) )
Output:
Marks of Itika are: 90
Marks of Parker are: There is no student of name Parker in the records
Nested Loops
If we have a piece of content that we need to run various times and,
afterward, one more piece of content inside that script that we need to
run B several times, we utilize a "settled circle." While working with an
iterable in the rundowns, Python broadly uses these.
Code
1. import random
2. numbers = [ ]
3. for val in range(0, 11):
4. [Link]( [Link]( 0, 11 ) )
5. for num in range( 0, 11 ):
6. for i in numbers:
7. if num == i:
8. print( num, end = " " )
Output:
0 2 4 5 6 7 8 8 9 10

Python While Loops


In coding, loops are designed to execute a specified code block
repeatedly. We'll learn how to construct a while loop in Python, the syntax
of a while loop, loop controls like break and continue, and other exercises
in this tutorial.

Introduction of Python While Loop


In this article, we are discussing while loops in Python. The Python while
loop iteration of a code block is executed as long as the given Condition,
i.e., conditional_expression, is true.
If we don't know how many times we'll execute the iteration ahead of
time, we can write an indefinite loop.
Syntax of Python While Loop
Now, here we discuss the syntax of the Python while loop. The syntax is
given below -
1. Statement
2. while Condition:
3. Statement
The given condition, i.e., conditional_expression, is evaluated initially in
the Python while loop. Then, if the conditional expression gives a boolean
value True, the while loop statements are executed. The conditional
expression is verified again when the complete code block is executed.
This procedure repeatedly occurs until the conditional expression returns
the boolean value False.
ADVERTISEMENT

o The statements of the Python while loop are dictated by indentation.


o The code block begins when a statement is indented & ends with the very
first unindented statement.
o Any non-zero number in Python is interpreted as boolean True. False is
interpreted as None and 0.

Example
Program code 1:
Now we give code examples of while loops in Python for printing numbers
from 1 to 10. The code is given below -
1. i=1
2. while i<=10:
3. print(i, end=' ')
4. i+=1
Output:
Now we compile the above code in python, and after successful
compilation, we run it. Then the output is given below -
1 2 3 4 5 6 7 8 9 10
Program Code 2:
Now we give code examples of while loops in Python for Printing those
numbers divisible by either 5 or 7 within 1 to 50 using a while loop. The
code is given below -
1. i=1
2. while i<51:
3. if i%5 == 0 or i%7==0 :
4. print(i, end=' ')
5. i+=1
Output:
Now we compile the above code in python, and after successful
compilation, we run it. Then the output is given below -
5 7 10 14 15 20 21 25 28 30 35 40 42 45 49 50
Program Code:
Now we give code examples of while loops in Python, the sum of squares
of the first 15 natural numbers using a while loop. The code is given below
-
1. # Python program example to show the use of while loop
2.
3. num = 15
4.
5. # initializing summation and a counter for iteration
6. summation = 0
7. c = 1
8.
9. while c <= num: # specifying the condition of the loop
10. # begining the code block
11. summation = c**2 + summation
12. c = c + 1 # incrementing the counter
13.
14.# print the final sum
[Link]("The sum of squares is", summation)
Output:
Now we compile the above code in python, and after successful
compilation, we run it. Then the output is given below -
The sum of squares is 1240
Provided that our counter parameter i gives boolean true for the
condition, i less than or equal to num, the loop repeatedly executes the
code block i number of times.
Next is a crucial point (which is mostly forgotten). We have to increment
the counter parameter's value in the loop's statements. If we don't, our
while loop will execute itself indefinitely (a never-ending loop).
Finally, we print the result using the print statement.

Exercises of Python While Loop


Prime Numbers and Python While Loop
Using a while loop, we will construct a Python program to verify if the
given integer is a prime number or not.
Program Code:
Now we give code examples of while loops in Python for a number is
Prime number or not. The code is given below -
1. num = [34, 12, 54, 23, 75, 34, 11]
2.
3. def prime_number(number):
4. condition = 0
5. iteration = 2
6. while iteration <= number / 2:
7. if number % iteration == 0:
8. condition = 1
9. break
10. iteration = iteration + 1
11.
12. if condition == 0:
13. print(f"{number} is a PRIME number")
14. else:
15. print(f"{number} is not a PRIME number")
[Link] i in num:
17. prime_number(i)
Output:
Now we compile the above code in python, and after successful
compilation, we run it. Then the output is given below -
34 is not a PRIME number
12 is not a PRIME number
54 is not a PRIME number
23 is a PRIME number
75 is not a PRIME number
34 is not a PRIME number
11 is a PRIME number

2. Armstrong and Python While Loop


We will construct a Python program using a while loop to verify whether
the given integer is an Armstrong number.
ADVERTISEMENT

Program Code:
Now we give code examples of while loops in Python for a number is
Armstrong number or not. The code is given below -
1. n = int(input())
2. n1=str(n)
3. l=len(n1)
4. temp=n
5. s=0
6. while n!=0:
7. r=n%10
8. s=s+(r**1)
9. n=n//10
[Link] s==temp:
11. print("It is an Armstrong number")
[Link]:
13. print("It is not an Armstrong number ")
Output:
Now we compile the above code in python, and after successful
compilation, we run it. Then the output is given below -
342
It is not an Armstrong number

Multiplication Table using While Loop


In this example, we will use the while loop for printing the multiplication
table of a given number.
Program Code:
In this example, we will use the while loop for printing the multiplication
table of a given number. The code is given below -
1. num = 21
2. counter = 1
3. # we will use a while loop for iterating 10 times for the multiplication table
4. print("The Multiplication Table of: ", num)
5. while counter <= 10: # specifying the condition
6. ans = num * counter
7. print (num, 'x', counter, '=', ans)
8. counter += 1 # expression to increment the counter
Output:
Now we compile the above code in python, and after successful
compilation, we run it. Then the output is given below -
The Multiplication Table of: 21
21 x 1 = 21
21 x 2 = 42
21 x 3 = 63
21 x 4 = 84
21 x 5 = 105
21 x 6 = 126
21 x 7 = 147
21 x 8 = 168
21 x 9 = 189
21 x 10 = 210

Python break statement


The break is a keyword in python which is used to bring the program
control out of the loop. The break statement breaks the loops one by one,
i.e., in the case of nested loops, it breaks the inner loop first and then
proceeds to outer loops. In other words, we can say that break is used to
abort the current execution of the program and the control goes to the
next line after the loop.
The break is commonly used in the cases where we need to break the
loop for a given condition. The syntax of the break statement in Python is
given below.
Syntax:
1. #loop statements
2. break;
Example 1 : break statement with for loop
Code
1. # break statement example
2. my_list = [1, 2, 3, 4]
3. count = 1
4. for item in my_list:
5. if item == 4:
6. print("Item matched")
7. count += 1
8. break
9. print("Found at location", count)
Output:
Item matched
Found at location 2
In the above example, a list is iterated using a for loop. When the item is
matched with value 4, the break statement is executed, and the loop
terminates. Then the count is printed by locating the item.

Example 2 : Breaking out of a loop early


Code
1. # break statement example
2. my_str = "python"
3. for char in my_str:
4. if char == 'o':
5. break
6. print(char)
Output:
p
y
t
h
When the character is found in the list of characters, break starts
executing, and iterating stops immediately. Then the next line of the print
statement is printed.

Example 3: break statement with while loop


Code
ADVERTISEMENT

1. # break statement example


2. i = 0;
3. while 1:
4. print(i," ",end=""),
5. i=i+1;
6. if i == 10:
7. break;
8. print("came out of while loop");
Output:
0 1 2 3 4 5 6 7 8 9 came out of while loop
It is the same as the above programs. The while loop is initialised to True,
which is an infinite loop. When the value is 10 and the condition becomes
true, the break statement will be executed and jump to the later print
statement by terminating the while loop.

Example 4 : break statement with nested loops


Code
1. # break statement example
2. n = 2
3. while True:
4. i=1
5. while i <= 10:
6. print("%d X %d = %d\n" % (n, i, n * i))
7. i += 1
8. choice = int(input("Do you want to continue printing the table? Press 0 for no:
"))
9. if choice == 0:
10. print("Exiting the program...")
11. break
12. n += 1
[Link]("Program finished successfully.")
Output:
2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
Do you want to continue printing the table? Press 0 for no: 1
3 X 1 = 3
3 X 2 = 6
3 X 3 = 9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 X 7 = 21
3 X 8 = 24
3 X 9 = 27
3 X 10 = 30
Do you want to continue printing the table? Press 0 for no: 0
Exiting the program...
Program finished successfully.
There are two nested loops in the above program. Inner loop and outer
loop The inner loop is responsible for printing the multiplication table,
whereas the outer loop is responsible for incrementing the n value. When
the inner loop completes execution, the user will have to continue
printing. When 0 is entered, the break statement finally executes, and the
nested loop is terminated.

Python continue Statement


Python continue keyword is used to skip the remaining statements of the current loop and go
to the next iteration. In Python, loops repeat processes on their own in an efficient way.
However, there might be occasions when we wish to leave the current loop entirely, skip
iteration, or dismiss the condition controlling the loop.
We use Loop control statements in such cases. The continue keyword is a loop control
statement that allows us to change the loop's control. Both Python while and Python for loops
can leverage the continue statements.
Syntax:
1. continue

Python Continue Statements in for Loop


Printing numbers from 10 to 20 except 15 can be done using continue statement and for loop.
The following code is an example of the above scenario:
Code
1. # Python code to show example of continue statement
2.
3. # looping from 10 to 20
4. for iterator in range(10, 21):
5.
6. # If iterator is equals to 15, loop will continue to the next iteration
7. if iterator == 15:
8. continue
9. # otherwise printing the value of iterator
10. print( iterator )
Output:
10
11
12
13
14
16
17
18
19
20
Explanation: We will execute a loop from 10 to 20 and test the condition that the iterator
is equal to 15. If it equals 15, we'll employ the continue statement to skip to the following
iteration displaying any output; otherwise, the loop will print the result.

Python Continue Statements in while Loop


Code
1. # Creating a string
2. string = "JavaTpoint"
3. # initializing an iterator
4. iterator = 0
5.
6. # starting a while loop
7. while iterator < len(string):
8. # if loop is at letter a it will skip the remaining code and go to next iteration
9. if string[iterator] == 'a':
10. continue
11. # otherwise it will print the letter
12. print(string[ iterator ])
13. iterator += 1
Output:
J
v
T
p
o
i
n
t
Explanation: We will take a string "Javatpoint" and print each letter of
the string except "a". This time we will use Python while loop to do so.
Until the value of the iterator is less than the string's length, the while
loop will keep executing.
Python Pass Statement
In this tutorial, we will learn more about past statements. It is interpreted
as a placeholder for future functions, classes, loops, and other operations.

What is Python's Pass Statement?


The pass statement is also known as the null statement. The Python
mediator doesn't overlook a Remark, though a pass proclamation isn't. As
a result, these two Python keywords are distinct.
We can use the pass statement as a placeholder when unsure of the code
to provide. Therefore, the pass only needs to be placed on that line. The
pass might be utilized when we wish no code to be executed. We can
simply insert a pass in cases where empty code is prohibited, such as in
loops, functions, class definitions, and if-else statements.
Syntax
Backward Skip 10sPlay VideoForward Skip 10s
ADVERTISEMENT

1. Keyword:
2. pass
Ordinarily, we use it as a perspective for what's to come.
Let's say we have an if-else statement or loop that we want to fill in the
future but cannot. An empty body for the pass keyword would be
grammatically incorrect. A mistake would be shown by the Python
translator proposing to occupy the space. As a result, we use the pass
statement to create a code block that does nothing.
An Illustration of the Pass Statement
Code
1. # Python program to show how to use a pass statement in a for loop
2. '''''pass acts as a placeholder. We can fill this place later on'''
3. sequence = {"Python", "Pass", "Statement", "Placeholder"}
4. for value in sequence:
5. if value == "Pass":
6. pass # leaving an empty if block using the pass keyword
7. else:
8. print("Not reached pass keyword: ", value)
Output:
Not reached pass keyword: Python
Not reached pass keyword: Placeholder
Not reached pass keyword: Statement
The same thing is also possible to create an empty function or a class.
Code
1. # Python program to show how to create an empty function and an empty class
2.
3. # Empty function:
4. def empty():
5. pass
6.
7. # Empty class
8. class Empty:
9. pass

You might also like