Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
98 views

Unit 1 Python Programming Basics

This document provides an overview of Python programming. It discusses that Python is a general purpose, high-level, interpreted programming language that supports object-oriented, imperative and functional programming. It notes that Python is easy to learn, powerful, versatile and can be used for web, enterprise and other applications. The document also provides a brief history of Python and its versions.

Uploaded by

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

Unit 1 Python Programming Basics

This document provides an overview of Python programming. It discusses that Python is a general purpose, high-level, interpreted programming language that supports object-oriented, imperative and functional programming. It notes that Python is easy to learn, powerful, versatile and can be used for web, enterprise and other applications. The document also provides a brief history of Python and its versions.

Uploaded by

Prafful Jain
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

BCA Semester 6th

BCA614 Python Programming


Unit I Basics of Python Programming

Python provides basic and advanced concepts of Python. Python is a simple, general purpose,
high level, and object-oriented programming language.

Python is an interpreted scripting language also. Guido Van Rossum is known as the founder
of Python programming.

What is Python
Python is a general purpose, dynamic, high-level, and interpreted programming language.
It supports Object Oriented programming approach to develop applications. It is simple and
easy to learn and provides lots of high-level data structures.

Python is easy to learn yet powerful and versatile scripting language, which makes it attractive
for Application Development.

Python's syntax and dynamic typing with its interpreted nature make it an ideal language for
scripting and rapid application development.

Python supports multiple programming pattern, including object-oriented, imperative, and


functional or procedural programming styles.

Python is not intended to work in a particular area, such as web programming. That is why it
is known as multipurpose programming language because it can be used with web, enterprise,
3D CAD, etc.

We don't need to use data types to declare variable because it is dynamically typed so we can
write a=10 to assign an integer value in an integer variable.

Python makes the development and debugging fast because there is no compilation step
included in Python development, and edit-test-debug cycle is very fast.

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?


o There is a fact behind choosing the name Python
o Guido van Rossum was reading the script of a popular BBC comedy series "Monty
Python's Flying Circus". It was late on-air 1970s.
o 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.
o The comedy series was creative and well random. It talks about everything. Thus it is
slow and unpredictable, which made it very interesting.
o 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

o 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.
o 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 2 vs. Python 3


In most of the programming languages, whenever a new version releases, it supports the
features and syntax of the existing version of the language, therefore, it is easier for the projects
to switch in the newer version. However, in the case of Python, the two versions Python 2 and
Python 3 are very much different from each other.

A list of differences between Python 2 and Python 3 are given below:

1. Python 2 uses print as a statement and used as print "something" to print some string
on the console. On the other hand, Python 3 uses print as a function and used as
print("something") to print something on the console.
2. Python 2 uses the function raw_input() to accept the user's input. It returns the string
representing the value, which is typed by the user. To convert it into the integer, we
need to use the int() function in Python. On the other hand, Python 3 uses input()
function which automatically interpreted the type of input entered by the user. However,
we can cast this value to any type by using primitive functions (int(), str(), etc.).
3. In Python 2, the implicit string type is ASCII, whereas, in Python 3, the implicit string
type is Unicode.
4. Python 3 doesn't contain the xrange() function of Python 2. The xrange() is the variant
of range() function which returns a xrange object that works similar to Java iterator.
The range() returns a list for example the function range(0,3) contains 0, 1, 2.
5. There is also a small change made in Exception handling in Python 3. It defines a
keyword as which is necessary to be used. We will discuss it in Exception handling
section of Python programming tutorial.

Python Features
Python provides many useful features which make it popular and valuable from the other
programming languages. It supports object-oriented programming, procedural programming
approaches and provides dynamic memory allocation. We have listed below a few essential
features.

1) Easy to Learn and Use


Python is easy to learn as compared to other programming languages. Its syntax is
straightforward and much the same as the English language. There is no use of the semicolon
or curly-bracket, the indentation defines the code block. It is the recommended programming
language for beginners.

2) Expressive Language
Python can perform complex tasks using a few lines of code. A simple example, the hello world
program you simply type print("Hello World"). It will take only one line to execute, while
Java or C takes multiple lines.

3) Interpreted Language
Python is an interpreted language; it means the Python program is executed one line at a time.
The advantage of being interpreted language, it makes debugging easy and portable.

4) Cross-platform Language

Python can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh,
etc. So, we can say that Python is a portable language. It enables programmers to develop the
software for several competing platforms by writing a program only once.

5) Free and Open Source


Python is freely available for everyone. It is freely available on its official
website www.python.org. It has a large community across the world that is dedicatedly
working towards make new python modules and functions. Anyone can contribute to the
Python community. The open-source means, "Anyone can download its source code without
paying any penny."
6) Object-Oriented Language
Python supports object-oriented language and concepts of classes and objects come into
existence. It supports inheritance, polymorphism, and encapsulation, etc. The object-oriented
procedure helps to programmer to write reusable code and develop applications in less code.

7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and thus it can
be used further in our Python code. It converts the program into byte code, and any platform
can use that byte code.

8) Large Standard Library


It provides a vast range of libraries for the various fields such as machine learning, web
developer, and also for the scripting. There are various machine learning libraries, such as
Tensor flow, Pandas, Numpy, Keras, and Pytorch, etc. Django, flask, pyramids are the popular
framework for Python web development.

9) GUI Programming Support


Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter, Kivy
are the libraries which are used for developing the web application.

10) Integrated
It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code line
by line like C,C++ Java. It makes easy to debug the code.

11. Embeddable
The code of the other programming language can use in the Python source code. We can use
Python source code in another programming language as well. It can embed other language
into our code.

12. Dynamic Memory Allocation


In Python, we don't need to specify the data-type of the variable. When we assign some value
to the variable, it automatically allocates the memory to the variable at run time. Suppose we
are assigned integer value 15 to x, then we don't need to write int x = 15. Just write x = 15.

Python Applications
Python is known for its general-purpose nature that makes it applicable in almost every domain
of software development. Python makes its presence in every emerging field. It is the fastest-
growing programming language and can develop any application.

Here, we are specifying application areas where Python can be applied.


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. Python provides many
useful frameworks, and these are given below:

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.

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

In this topic, we have described all types of applications where Python plays an essential role
in the development of these applications. In the next tutorial, we will learn more concepts about
Python.
How to Install Python (Environment Set-up)
In order to become Python developer, the first step is to learn how to install or update Python
on a local machine or computer.

Installation on Windows

Visit the link https://www.python.org/downloads/ to download the latest release of Python. In


this process, we will install Python 3.8.6 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.

Step - 2: Click on the Install Now

Double-click the executable file, which is downloaded; Select Customize installation and
proceed. Click on the Add Path check box, it will set the Python path automatically.

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.

Step - 3 Installation in Process


Now, try to run python on the command prompt. Type the command python -version in case
of python3.

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:

o Using Interactive interpreter prompt


o Using a script file

Let's discuss each one of them in detail.

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

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 .py extension, which stands for "Python". Now, we will implement the above example
using the script mode.
Python Variables
Variable is a name that is used to refer to memory location. Python variable is also known as
an identifier and used to hold value.

In Python, we don't need to specify the type of variable because Python is a infer language and
smart enough to get variable type.

Variable names can be a group of both the letters and digits, but they have to begin with a letter
or an underscore.

It is recommended to use lowercase letters for the variable name. Rahul and rahul both are two
different variables.

Identifier Naming
Variables are the example of identifiers. An Identifier is used to identify the literals used in the
program. The rules to name an identifier are given below.

o The first character of the variable must be an alphabet or underscore ( _ ).


o All the characters except the first character may be an alphabet of lower-case (a-z),
upper-case (A-Z), underscore, or digit (0-9).
o Identifier name must not contain any white-space, or special character (!, @, #, %, ^,
&, *).
o Identifier name must not be similar to any keyword defined in the language.
o Identifier names are case sensitive; for example, myname, and MyName is not the
same.
o Examples of valid identifiers: a123, _n, n_9, etc.
Declaring Variable and Assigning Values
Python does not bind us to declare a variable before using it in the application. It allows us to
create a variable at the required time.

We don't need to declare explicitly variable in Python. When we assign any value to the
variable, that variable is declared automatically.

The equal (=) operator is used to assign value to a variable.

o Examples of invalid identifiers: 1a, n%4, n 9, etc.

Object References
It is necessary to understand how the Python interpreter works when we declare a variable. The
process of treating variables is somewhat different from many other programming languages.

Python is the highly object-oriented programming language; that's why every data item belongs
to a specific type of class. Consider the following example.

print("ABC")

output

ABC

The Python object creates an integer object and displays it to the console. In the above print
statement, we have created a string object. Let's check the type of it using the Python built-
in type() function.

type("ABC")

Output:

<class 'str'>

In Python, variables are a symbolic name that is a reference or pointer to an object. The
variables are used to denote objects by that name.

Let's understand the following example

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

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

a = 50

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.

a = 50

b =100

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

Object Identity
In Python, every created object identifies uniquely in Python. Python provides the guaranteed
that no two objects will have the same identifier. The built-in id() function, is used to identify
the object identifier. Consider the following example.

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:

3065075101520
3065075101520
3065117318480
We assigned the b = a, a and b both point to the same object. When we checked by
the id() function it returned the same number. We reassign a to 500; then it referred to the new
object identifier.

Variable Names
We have already discussed how to declare the valid variable. Variable names can be any length
can have uppercase, lowercase (A to Z, a to z), the digit (0-9), and underscore character(_).
Consider the following example of valid variables names.
1. name = "Rajiv"
2. age = 20
3. marks = 80.50
4. print(name)
5. print(age)
6. print(marks)

Output:

Rajiv
20
80.5

The multi-word variables 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
Python allows us to assign a value to multiple variables in a single statement, which is also
known as multiple assignments.

We can apply multiple assignments in two ways, either by assigning a single value to multiple
variables or assigning multiple values to multiple variables. Consider 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

Local variables are the variables that declared inside the function and have scope within the
function. Let's understand the following example.

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. # Calling a function
9. add()

Output:

The sum is: 50


Global Variables

Global variables can be used throughout the program, and its scope is in the entire program.
We can use global variables inside or outside the function.

A variable declared outside the function is the global variable by default. Python provides
the global keyword to use global variable inside the function. If we don't use
the global keyword, the function treats it as a local variable. Let's understand the following
example.

Example –
1. # Declare a variable and initialize it
2. x = 101
3. # Global variable in function
4. def mainFunction():
5. # printing a global variable
6. global x
7. print(x)
8. # modifying a global variable
9. x = 'Welcome To Python'
10. print(x)
11. mainFunction()
12. print(x)

Output:

101
Welcome To Python
Welcome To Python
Python Data Types
Variables can hold values, and every value has a data-type. Python is a dynamically typed
language; hence we do not need to define the type of the variable while declaring it. The
interpreter implicitly binds the value with its type.

a=5

The variable a holds integer value five and we did not define its type. Python interpreter will
automatically interpret variables a as an integer type.

Python enables us to check the type of the variable used in the program. Python provides us
the type() function, which returns the type of the variable passed.

Consider the following example to define the values of different data types and checking its
type.

1. a=10
2. b="Hi Python"
3. c = 10.5
4. print(type(a))
5. print(type(b))
6. print(type(c))

Standard data types


A variable can hold different types of values. For example, a person's name must be stored as
a string whereas its id must be stored as an integer.

Python provides various standard data types that define the storage method on each of them.
The data types defined in Python are given below.

1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
Numbers
Number stores numeric values. The integer, float, and complex values belong to a Python
Numbers data-type. Python provides the type() function to know the data-type of the variable.
Similarly, the isinstance() function is used to check an object belongs to a particular class.

Python creates Number objects when a number is assigned to a variable. For example;

1. a = 5
2. print("The type of a", type(a))
3. b = 40.5
4. print("The type of b", type(b))
5. c = 1+3j
6. print("The type of c", type(c))
7. 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 types of numeric data.


1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python
has no restriction on the length of an integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is
accurate upto 15 decimal points.
3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote
the real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j,
etc.

Sequence Type
String
The string can be defined as the sequence of characters represented in the quotation marks. In
Python, we can use single, double, or triple quotes to define a string. String handling in
Python is a straightforward task since Python provides built-in functions and operators to
perform operations in the string. In the case of string handling, the operator + is used to
concatenate two strings as the operation "hello"+" python" returns "hello python". mutable(can
modify after creation) . String is immutable(can’t modify after creation)

The operator * is known as a repetition operator as the operation "Python" *2 returns 'Python
Python'.

The following example illustrates the string in Python.

Example – 1
str = "string using double quotes"
print(str)
s = '''''A multiline
string'''
print(s)

Output:

string using double quotes


A multiline
string
Consider the following example of string handling.
Example – 2
str1 = 'hello python' #string str1
str2 = ' how are you' #string str2
print (str1[0:2]) #printing first two character using slice operator
print (str1[4]) #printing 4th character of the string
print (str1*2) #printing the string twice
print (str1 + str2) #printing the concatenation of str1 and str2
Output:
he
o
hello pythonhello python
hello python how are you

List
Python Lists are similar to arrays in C. However, the list can contain data of different types.
The items stored in the list are separated with a comma (,) and enclosed within square brackets
[].We can use slice [:] operators to access the data of the list. The concatenation operator (+)
and repetition operator (*) works with the list in the same way as they were working with the
strings. List is mutable (can modify after creation)

Consider the following example.

list1 = [1, "hi", "Python", 2]


#Checking type of given list
print(type(list1))
#Printing the list1
print (list1)
# List slicing
print (list1[3:])
# List slicing
print (list1[0:2])
# List Concatenation using + operator
print (list1 + list1)
# List repetation using * operator
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
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the
items of different data types. The items of the tuple are separated with a comma (,) and enclosed
in parentheses (). Tuple is immutable (can’t modify after creation).
A tuple is a read-only data structure as we can't modify the size and value of the items of
a tuple.

Let's see a simple example of the tuple.

tup = ("hi", "Python", 2)


# Checking type of tup
print (type(tup))
#Printing the tuple
print (tup)
# Tuple slicing
print (tup[1:])
print (tup[0:1])
# Tuple concatenation using + operator
print (tup + tup)
# Tuple repatation using * operator
print (tup * 3)
# Adding value to tup. It will throw an error.
tup[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)

TypeError: 'tuple' object does not support item assignment

Dictionary
Dictionary is an unordered set of a key-value pair of items. It is like an associative array or a
hash table where each key stores a specific value. Key can hold any primitive data type,
whereas value is an arbitrary Python object. Dictionary is mutable (can modify after creation)

The items in the dictionary are separated with the comma (,) and enclosed in the curly braces
{}.

Consider the following example.

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


# Printing dictionary
print (d)
# Accesing value using keys
print("1st name is "+d[1])
print("2nd name is "+ d[4])
print (d.keys())
print (d.values())

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
Boolean type provides two built-in values, True and False. These values are used to determine
the given statement true or false. It denotes by the class bool. True can be represented by any
non-zero value or 'T' whereas false can be represented by the 0 or 'F'. Consider the following
example.

# Python program to check the boolean type


print(type(True))
print(type(False))
print(false)

Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined

Set
Python Set is the unordered collection of the data type. It is iterable, mutable(can modify after
creation), and has unique elements. In set, the order of the elements is undefined; it may return
the changed sequence of the element. The set is created by using a built-in function set(), or a
sequence of elements is passed in the curly braces and separated by the comma. It can contain
various types of values. Consider the following example.

# Creating Empty set


set1 = set()
set2 = {'James', 2, 3,'Python'}
#Printing Set value
print(set2)
# Adding element to the set
set2.add(10)
print(set2)
#Removing element from the set
set2.remove(2)
print(set2)

Output:

{3, 'Python', 'James', 2}


{'Python', 'James', 3, 2, 10}
{'Python', 'James', 3, 10}

Python Keywords
Python Keywords are special reserved words that convey a special meaning to the
compiler/interpreter. Each keyword has a special meaning and a specific operation. These
keywords can't be used as a variable. Following is the List of Python Keywords.

True False None and as

asset def class continue break

else finally elif del except

global for if from import

raise try or return pass

nonlocal in not is lambda

Consider the following explanation of keywords.

1. True - It represents the Boolean true, if the given condition is true, then it returns
"True". Non-zero values are treated as true.
2. False - It represents the Boolean false; if the given condition is false, then it returns
"False". Zero value is treated as false
3. None - It denotes the null value or void. An empty list or Zero can't be treated as None.
4. and - It is a logical operator. It is used to check the multiple conditions. It returns true
if both conditions are true.
5. or - It is a logical operator in Python. It returns true if one of the conditions is true.
6. not - It is a logical operator and inverts the truth value.
7. def - This keyword is used to declare the function in Python.
8. class - It is used to represents the class in Python. The class is the blueprint of the
objects. It is the collection of the variable and methods.
9. continue - It is used to stop the execution of the current iteration.
10. break - It is used to terminate the loop execution and control transfer to the end of
the loop.
11. If - It is used to represent the conditional statement. The execution of a particular block
is decided by if statement.
12. else - The else statement is used with the if statement. When if statement returns false,
then else block is executed.
13. elif - This Keyword is used to check the multiple conditions. It is short for else-if. If the
previous condition is false, then check until the true condition is found.
14. del - It is used to delete the reference of the object.
15. try, except - The try-except is used to handle the exceptions. The exceptions are run-
time errors.
16. raise - The raise keyword is used to through the exception forcefully.
17. finally - The finally keyword is used to create a block of code that will always be
executed no matter the else block raises an error or not.
18. for, while - Both keywords are used for iteration. The for keyword is used to iterate
over the sequences (list, tuple, dictionary, string). A while loop is executed until the
condition returns false.
19. import - The import keyword is used to import modules in the current Python script.
The module contains a runnable Python code.
20. from - This keyword is used to import the specific function or attributes in the current
Python script.
21. as - It is used to create a name alias. It provides the user-define name while importing
a module.
22. pass - The pass keyword is used to execute nothing or create a placeholder for future
code. If we declare an empty class or function, it will through an error, so we use the
pass keyword to declare an empty class or function.
Example:

class my_class:
pass
def my_func():
pass
23. return - The return keyword is used to return the result value or none to called
function.
24. is - This keyword is used to check if the two-variable refers to the same object. It returns
the true if they refer to the same object otherwise false. Consider the following
example.

Example

x=5
y=5
a = []
b = []
print(x is y)
print(a is b)

25. global - The global keyword is used to create a global variable inside the function. Any
function can access the global.

Python Operators
The operator can be defined as a symbol which is responsible for a particular operation between
two operands. Operators are the pillars of a program on which the logic is built in a specific
programming language. Python provides a variety of operators, which are described as follows.

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

Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations between two operands. It
includes + (addition), - (subtraction), *(multiplication), /(divide), %(reminder), //(floor
division), and exponent (**) 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 = 20, b = 10 => a+b =
30

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

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

* It is used to multiply one operand with the other. For example, if a = 20,
(Multiplication) b = 10 => a * b = 200

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

** (Exponent) It is an exponent operator represented as it calculates the first operand


power to the second operand.

// (Floor It gives the floor value of the quotient produced by dividing the two
division) operands.

Comparison operator
Comparison operators are used to comparing the value of the two operands and returns Boolean
true or false accordingly. The comparison operators are described in the following table.

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.

<= If the first operand is less than or equal to the second operand, then the
condition becomes true.

>= If the first operand is greater than or equal to the second operand, then the
condition becomes true.

> If the first operand is greater than the second operand, then the condition
becomes true.

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

Assignment Operators
The assignment operators are used to assign the value of the right expression to the left operand.
The assignment operators are described in the following table.

Operator Description

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

+= It increases the value of the left operand by the value of the right operand and
assigns the modified value back to left operand. For example, if a = 10, b = 20
=> a+ = b will be equal to a = a+ b and therefore, a = 30.

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

*= It multiplies the value of the left operand by the value of the right operand and
assigns the modified value back to then the left operand. For example, if a = 10,
b = 20 => a* = b will be 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
assigns the reminder back to the left operand. For example, if a = 20, b = 10 =>
a % = b will be equal to a = 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 = 16 to a.

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

Bitwise Operators
The bitwise operators perform bit by bit operation on the values of the two operands. Consider
the following example.

For example,

1. if a = 7
2. b=6
3. then, binary (a) = 0111
4. binary (b) = 0110
5. hence, a & b = 0011
6. a | b = 0111
7. a ^ b = 0100
8. ~ a = 1000

Operator Description

& (binary If both the bits at the same place in two operands are 1, then 1 is copied to
and) the result. Otherwise, 0 is copied.

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

^ (binary xor) The resulting bit will be 1 if both the bits are different; otherwise, the
resulting bit will be 0.
~ (negation) It calculates the negation of each bit of the operand, i.e., if the bit is 0, the
resulting bit will be 1 and vice versa.

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

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

Logical Operators
The logical operators are used primarily in the expression evaluation to make a decision.
Python supports the following logical operators.

Operator Description

and If both the expression are true, then the condition will be true. If a and b are the
two expressions, a → true, b → true => a and b → true.

or If one of the expressions is true, then the condition will be true. If a and b are
the two expressions, a → true, b → false => a or b → true.

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

Membership Operators
Python membership operators are used to check the membership of value inside a Python data
structure. If the value is present in the data structure, then the resulting value is true otherwise
it returns false.
Operator Description

in It is evaluated to be true if the first operand is found in the second operand (list,
tuple, or dictionary).

not in It is evaluated to be true if the first operand is not found in the second operand (list,
tuple, or dictionary).

Identity Operators
The identity operators are used to decide whether an element certain class or type.

Operator Description

is It is evaluated to be true if the reference present at both sides point to the same
object.

is not It is evaluated to be true if the reference present at both sides do not point to the
same object.

Operator Precedence
The precedence of the operators is essential to find out since it enables us to know which
operator should be evaluated first. The precedence table of the operators in Python is given
below.

Operator Description

** The exponent operator is given priority over all the others used in the
expression.

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

* / % // The multiplication, divide, modules, reminder, and floor division.


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

Python Comments
Python Comment is an essential tool for the programmers. Comments are generally used to
explain the code. We can easily understand the code if it has a proper explanation. A good
programmer must use the comments because in the future anyone wants to modify the code as
well as implement the new module; then, it can be done easily.

In the other programming language such as C++, It provides the // for single-lined comment
and /*.... */ for multiple-lined comment, but Python provides the single-lined Python comment.
To apply the comment in the code we use the hash(#) at the beginning of the statement or code.

Let's understand the following example.

# This is the print statement


print("Hello Python")
Here we have written comment over the print statement using the hash(#). It will not affect our
print statement.

Multiline Python Comment


We must use the hash(#) at the beginning of every line of code to apply the multiline Python
comment. Consider the following example.

1. # First line of the comment


2. # Second line of the comment
3. # Third line of the comment
Example:

1. # Variable a holds value 5


2. # Variable b holds value 10
3. # Variable c holds sum of a and b
4. # Print the result
5. a = 5
6. b = 10
7. c = a+b
8. print("The sum is:", c)
Output:

The sum is: 15

The above code is very readable even the absolute beginners can under that what is happening
in each line of the code. This is the advantage of using comments in code.

We can also use the triple quotes ('''''') for multiline comment. The triple quotes are also used
to string formatting. Consider the following example.

def intro():
"""
This function prints Hello Joseph
"""
print("Hi Joseph")
intro()
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 also provides
Statement 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 if


Statement statement.

Indentation in Python
For the ease of programming and to achieve simplicity, python doesn't allow the use of
parentheses for the block level code. In Python, indentation is used to declare a block. If two
statements are at the same indentation level, then they are the part of the same block.

Generally, four spaces are given to indent the statements which are a typical amount of
indentation in python.

Indentation is the most used part of the python language since it declares the block of code. All
the statements of one block are intended at the same level indentation. We will see how the
actual indentation takes place in decision making and other stuff in python.

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

1. if expression:
2. statement

Example 1
1. num = int(input("enter the number?"))
2. if num%2 == 0:
3. print("Number is even")

Output:

enter the number?10


Number is even

Example 2 : Program to print the largest of the three numbers.


1. a = int(input("Enter a? "));
2. b = int(input("Enter b? "));
3. c = int(input("Enter c? "));
4. if a>b and a>c:
5. print("a is largest");
6. if b>a and b>c:
7. print("b is largest");
8. if c>a and c>b:
9. print("c is largest");

Output:
Enter a? 100
Enter b? 120
Enter c? 130
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.

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.


1. age = int (input("Enter your age? "))
2. if age>=18:
3. print("You are eligible to vote !!");
4. else:
5. 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. num = int(input("enter the number?"))
2. if num%2 == 0:
3. print("Number is even...")
4. else:
5. print("Number is odd...")

Output:

enter the number?10


Number is even

The elif statement


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

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

The syntax of the elif statement is given below.

1. if expression 1:
2. # block of statements
3. elif expression 2:
4. # block of statements
5. elif expression 3:
6. # block of statements
7. else:
8. # block of statements

Example 1
1. number = int(input("Enter the number?"))
2. if number==10:
3. print("number is equals to 10")
4. elif number==50:
5. print("number is equal to 50");
6. elif number==100:
7. print("number is equal to 100");
8. else:
9. print("number is not equal to 10, 50 or 100");

Output:

Enter the number?15


number is not equal to 10, 50 or 100
Example 2
1. marks = int(input("Enter the marks? "))
2. if marks > 85 and marks <= 100:
3. print("Congrats ! you scored grade A ...")
4. elif marks > 60 and marks <= 85:
5. print("You scored grade B + ...")
6. elif marks > 40 and marks <= 60:
7. print("You scored grade B ...")
8. elif (marks > 30 and marks <= 40):
9. print("You scored grade C ...")
10. else:
11. print("Sorry you are fail ?")

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

For this purpose, the programming languages provide various types of loops which are capable
of repeating some specific code several numbers of times. Consider the following diagram to
understand the working of a loop statement.

Why we use loops in python?

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

1. It provides code re-usability.


2. Using loops, we do not need to write the same code again and again.
3. Using loops, we can traverse over the elements of data structures (array or linked lists).

There are the following loop statements in Python.

Loop Description
Statement

for loop The for loop is used in the case where we need to execute some part of the code
until the given condition is satisfied. The for loop is also called as a per-tested
loop. It is better to use for loop if the number of iteration is known in advance.

while loop The while loop is to be used in the scenario where we don't know the number
of iterations in advance. The block of statements is executed in the while loop
until the condition specified in the while loop is satisfied. It is also called a pre-
tested loop.

do-while loop The do-while loop continues until a given condition satisfies. It is also called
post tested loop. It is used when it is necessary to execute the loop at least once
(mostly menu driven programs).

Python for loop


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

The syntax of for loop in python is given below.

1. for iterating_var in sequence:


2. statement(s)
The for loop flowchart

For loop Using Sequence

Example-1: Iterating string using for loop

1. str = "Python"
2. for i in str:
3. print(i)

Output:

P
y
t
h
o
n

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

1. list = [1,2,3,4,5,6,7,8,9,10]
2. n = 5
3. for i in list:
4. c = n*i
5. print(c)
Output:

5
10
15
20
25
30
35
40
45
50

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

1. list = [10,30,23,43,65,12]
2. sum = 0
3. for i in list:
4. sum = sum+i
5. print("The sum is:",sum)
Output:

The sum is: 183

For loop Using range() function

The range() function


The range() function is used to generate the sequence of the numbers. If we pass the range(10),
it will generate the numbers from 0 to 9. The syntax of the range() function is given below.

Syntax:

1. range(start, stop, step size)


o The start represents the beginning of the iteration.
o The stop represents that the loop will iterate till stop-1. The range(1,5) will generate
numbers 1 to 4 iterations. It is optional.
o The step size is used to skip the specific numbers from the iteration. It is optional to
use. By default, the step size is 1. It is optional.

Consider the following examples:


Example-1: Program to print numbers in sequence.

1. for i in range(10):
2. print(i,end = ' ')

Output:

0123456789

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

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


2. for i in range(1,11):
3. c = n*i
4. print(n,"*",i,"=",c)

Output:

Enter the number 10


10 * 1 = 10
10 * 2 = 20
10 * 3 = 30
10 * 4 = 40
10 * 5 = 50
10 * 6 = 60
10 * 7 = 70
10 * 8 = 80
10 * 9 = 90
10 * 10 = 100
Example-3: Program to print even number using step size in range().

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


2. for i in range(2,n,2):
3. print(i)

Output:

Enter the number 20


2
4
6
8
10
12
14
16
18

We can also use the range() function with sequence of numbers. The len() function is
combined with range() function which iterate through a sequence using indexing. Consider the
following example.

1. list = ['Peter','Joseph','Ricky','Devansh']
2. for i in range(len(list)):
3. print("Hello",list[i])

Output:

Hello Peter
Hello Joseph
Hello Ricky
Hello Devansh

Nested for loop in python


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

Syntax

1. for iterating_var1 in sequence: #outer loop


2. for iterating_var2 in sequence: #inner loop
3. #block of statements
4. #Other statements

Example- 1: Nested for loop

# User input for number of rows


rows = int(input("Enter the rows:"))
# Outer loop will print number of rows
for i in range(0,rows+1):
# Inner loop will print number of Astrisk
for j in range(i):
print("*",end = '')
print()
Output:

Enter the rows:5


*
**
***
****
*****
Example-2: Program to number pyramid.
1. rows = int(input("Enter the rows"))
2. for i in range(0,rows+1):
3. for j in range(i):
4. print(i,end = '')
5. print()

Output:

1
22
333
4444
55555

Using else statement with for loop


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

Example 1

1. for i in range(0,5):
2. print(i)
3. else:
4. print("for loop completely exhausted, since there is no break.")

Output:

0
1
2
3
4
for loop completely exhausted, since there is no break.
The for loop completely exhausted, since there is no break.

Example 2

1. for i in range(0,5):
2. print(i)
3. break;
4. else:
5. print("for loop is exhausted");
6. print("The loop is broken due to break statement...came out of the loop")

In the above example, the loop is broken due to the break statement; therefore, the else
statement will not be executed. The statement present immediate next to else block will be
executed.

Output:

The loop is broken due to the break statement...came out of the loop.

Python While loop


The Python while loop allows a part of the code to be executed until the given condition returns
false. It is also known as a pre-tested loop.

It can be viewed as a repeating if statement. When we don't know the number of iterations then
the while loop is most effective to use.

The syntax is given below.

1. while expression:
2. statements

Here, the statements can be a single statement or a group of statements. The expression should
be any valid Python expression resulting in true or false. The true is any non-zero value and
false is 0.
Loop Control Statements
We can change the normal sequence of while loop's execution using the loop control statement.
When the while loop's execution is completed, all automatic objects defined in that scope are
demolished. Python offers the following control statement to use within the while loop.

1. Continue Statement - When the continue statement is encountered, the control transfer to
the beginning of the loop. Let's understand the following example.

Example:

# prints all letters except 'a' and 't'


i=0
str1 = 'python'
while i < len(str1):
if str1[i] == 'a' or str1[i] == 't':
i += 1
continue
print('Current Letter :', a[i])
i += 1

Output:

Current Letter : p
Current Letter : y
Current Letter : h
Current Letter : o
Current Letter : n

Break Statement - When the break statement is encountered, it brings control out of the
loop.

Example:

1. # The control transfer is transfered


2. # when break statement soon it sees t
3. i = 0
4. str1 = 'python'
5. while i < len(str1):
6. if str1[i] == 't':
7. i += 1
8. break
9. print('Current Letter :', str1[i])
10. i += 1

Output:

Current Letter : p
Current Letter : y

Pass Statement - The pass statement is used to declare the empty loop. It is also used to
define empty class, function, and control statement. Let's understand the following example.

Example -

1. # An empty loop
2. str1 = 'python'
3. i = 0
4. while i < len(str1):
5. i += 1
6. pass
7. print('Value of i :', i)

Output:

Value of i : 10
Example-1: Program to print 1 to 10 using while loop
1. i=1
2. #The while loop will iterate until condition becomes false.
3. while(i<=10):
4. print(i)
5. i=i+1

Output:

1
2
3
4
5
6
7
8
9
10
Example -2: Program to print table of given numbers.
1. i=1
2. number=0
3. b=9
4. number = int(input("Enter the number:"))
5. while i<=10:
6. print("%d X %d = %d \n"%(number,i,number*i))
7. i = i+1

Output:

Enter the number:10


10 X 1 = 10

10 X 2 = 20

10 X 3 = 30

10 X 4 = 40

10 X 5 = 50

10 X 6 = 60

10 X 7 = 70
10 X 8 = 80

10 X 9 = 90

10 X 10 = 100

Infinite while loop


If the condition is given in the while loop never becomes false, then the while loop will never
terminate, and it turns into the infinite while loop.

Any non-zero value in the while loop indicates an always-true condition, whereas zero
indicates the always-false condition. This type of approach is useful if we want our program to
run continuously in the loop without any disturbance.

Example 1
1. while (1):
2. print("Hi! we are inside the infinite while loop")

Output:

Hi! we are inside the infinite while loop


Hi! we are inside the infinite while loop
Example 2
1. var = 1
2. while(var != 2):
3. i = int(input("Enter the number:"))
4. print("Entered value is %d"%(i))

Output:

Enter the number:10


Entered value is 10
Enter the number:10
Entered value is 10
Enter the number:10
Entered value is 10
Infinite time

Using else with while loop


Python allows us to use the else statement with the while loop also. The else block is executed
when the condition given in the while statement becomes false. Like for loop, if the while loop
is broken using break statement, then the else block will not be executed, and the statement
present after else block will be executed. The else statement is optional to use with the while
loop. Consider the following example.
Example 1
1. terms = int(input("Enter the terms "))
2. # first two intial terms
3. a = 0
4. b = 1
5. count = 0
6. # check if the number of terms is Zero or negative
7. if (terms <= 0):
8. print("Please enter a valid integer")
9. elif (terms == 1):
10. print("Fibonacci sequence upto",terms,":")
11. print(a)
12. else:
13. print("Fibonacci sequence:")
14. while (count < terms) :
15. print(a, end = ' ')
16. c = a + b
17. # updating values
18. a = b
19. b = c
20. count += 1

Output:

Enter the terms 10


Fibonacci sequence:
0 1 1 2 3 5 8 13 21 34
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 is given below.

1. #loop statements
2. break;

Example 1

1. list =[1,2,3,4]
2. count = 1;
3. for i in list:
4. if i == 4:
5. print("item matched")
6. count = count + 1;
7. break
8. print("found at",count,"location");

Output:

item matched
found at 2 location

Example 2

1. str = "python"
2. for i in str:
3. if i == 'o':
4. break
5. print(i);

Output:

p
y
t
h

Example 3: break statement with while loop

1. i = 0;
2. while 1:
3. print(i," ",end=""),
4. i=i+1;
5. if i == 10:
6. break;
7. print("came out of while loop");

Output:

0 1 2 3 4 5 6 7 8 9 came out of while loop

Example 3
1. n=2
2. while 1:
3. i=1;
4. while i<=10:
5. print("%d X %d = %d\n"%(n,i,n*i));
6. i = i+1;
7. choice = int(input("Do you want to continue printing the table, press 0 for no?"))
8. if choice == 0:
9. break;
10. n=n+1

Output:

2X1=2

2X2=4

2X3=6

2X4=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

3X1=3

3X2=6

3X3=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


Python continue Statement
The continue statement in Python is used to bring the program control to the beginning of the
loop. The continue statement skips the remaining lines of code inside the loop and start with
the next iteration. It is mainly used for a particular condition inside the loop so that we can skip
some specific code for a particular condition. The continue statement in Python is used to bring
the program control to the beginning of the loop. The continue statement skips the remaining
lines of code inside the loop and start with the next iteration. It is mainly used for a particular
condition inside the loop so that we can skip some specific code for a particular condition.

Syntax

1. #loop statements
2. continue
3. #the code to be skipped

Flow Diagram

Consider the following examples.

Example 1

i=0
while(i < 10):
i = i+1
if(i == 5):
continue
print(i)

Output:

1
2
3
4
6
7
8
9
10

Observe the output of above code, the value 5 is skipped because we have provided the if
condition using with continue statement in while loop. When it matched with the given
condition then control transferred to the beginning of the while loop and it skipped the value 5
from the code.

Let's have a look at another example:

Example 2

1. str = "python"
2. for i in str:
3. if(i == 'T'):
4. continue
5. print(i)

Output:

p
y
t
h
o
n

Python Pass
In Python, the pass keyword is used to execute nothing; it means, when we don't want to
execute code, the pass can be used to execute empty. It is the same as the name refers to. It just
makes the control to pass by without executing any code. If we want to bypass any code pass
statement can be used.

It is beneficial when a statement is required syntactically, but we want we don't want to execute
or execute it later. The difference between the comments and pass is that, comments are entirely
ignored by the Python interpreter, where the pass statement is not ignored.

Suppose we have a loop, and we do not want to execute right this moment, but we will execute
in the future. Here we can use the pass.

Consider the following example.

Example - Pass statement

# pass is just a placeholder for


# we will added functionality later.
values = {'P', 'y', 't', 'h','o','n'}
for val in values:
pass

Example - 2:

for i in [1,2,3,4,5]:
if(i==4):
pass
print("This is pass block",i)
print(i)

Output:

1. 1
2. 2
3. 3
4. This is pass block 4
5. 4
6. 5

We can create empty class or function using the pass statement.

1. # Empty Function
2. def function_name(args):
3. pass
4. #Empty Class
5. class Python:
6. pass

You might also like