Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Ds Python Unit-I

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

PYTHON PROGRAMMING FOR DATA ANALYSIS

Unit-I
Data Analysis
Data analysis is the process of inspecting, collecting , cleaning, transforming,
and modeling data using various statistical and logical methods and techniques to
discover useful information .

Data Analytics
Data analytics is the process of exploring and analyzing large datasets to find
hidden patterns, unseen trends, discover correlations, and derive valuable insights to
make business predictions. It improves the speed and efficiency of your business.

Difference between Data Analytics and Data Analysis


Data Analytics Data Analysis

It is described as a traditional
1. It is described as a particularized form of analytics.
form of analytics.

To process data, firstly raw data is defined in a


It includes collection of data and
meaningful manner, then data cleaning and
2. then the inspection of data is
conversion is done to get meaningful information
done.
from raw data.

It supports decision making by It analyzes the data by focusing on insights into


3.
analyzing business data. business data.

Descriptive analysis cannot be


4. A Descriptive analysis can be performed on this.
performed on this.

It does not deal with inferential


5. It supports inferential analysis.
analysis.

Python Introduction
Python is a very powerful high-level, general-purpose, object-oriented
programming language created by Guido van Rossum in 1989.

Python is very popular for developers and professionals because, it has a rich set of
supporting libraries, and addon modules. It is a cross-platform(platform-independent)
language and runs on all major operating systems including Windows, Linux, and
Macintosh. Python comes with a powerful and easy to-use graphical user interface
(GUI) toolkit that makes the task of developing GUI applications.

The Python programming language was conceived in the late 1980s, and its
implementation was started in December 1989 by Guido van Rossum at CWI(Centrum
Wiskunde & Informatica) in the Netherlands as a successor of ABC programming
language. Python was published in 1991.
Python Versions and Release Dates

Release dates for the major versions

 Python 1.0 - January 1994


 Python 2.0 - October 16, 2000
 Python 3.0 - December 3, 2008
 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 Oct 14, 2019
 Python 3.9 Oct 5, 2020
 Python 3.10 Oct. 04, 2021
 Python 3.11.0, Oct 24, 2022

Latest version of Python : Python 3.11.5 Aug 24, 2023

Features of Python

1) Easy to Learn and Use


Python is easy to learn as compared to other programming languages. Its
syntax is straightforward. There is no use of the semicolon or curly-bracket, the
indentation defines the code block.

2) Expressive Language
Python can perform complex tasks using a few lines of code.
3) Interpreted Language
Python is an interpreted language; it means the Python program is executed
one line at a time. The interpreted language 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.

5) Free and Open Source


Python is freely available for everyone. It is freely available on its official
website www.python.org.

6) Object-Oriented Language
Python supports object-oriented language.It supports
object-oriented concepts inheritance, polymorphism, encapsulation, etc.

7) Large Standard Library


It provides a vast range of libraries for the various fields such as machine
learning, web developing, and also for the scripting.

8) GUI Programming Support


Graphical User Interface is used for the developing Desktop applications and
the web applications.

9) Integrated
Python can be integrated with other languages,
like C, C++, and Java.

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

Why Python is used for Data science/Data Analysis


Python is open source, interpreted, high level language and provides great approach
for object-oriented programming. It is one of the best language used by data
scientist for various data science projects/applications. Python provide great
functionality to deal with mathematics, statistics and scientific functions. It provides
great libraries to deals with data science applications.

Python library
A Python library is a collection of related modules. these libraries can be used
repeatedly in different programs. It makes Python Programming simpler and
convenient for the programmer. As we don't need to write the same code again and
again for different programs.

Essential Python Libraries for DataScience


Python has interactive libraries for data processing, data modeling, data visualization
and machine learning.These libraries are

1. NumPy
NumPy is a popular open-source library for data processing and modeling, that is
widely used in data science, machine learning, and deep learning. NumPy introduces
objects for multidimensional arrays and matrices.

2. Pandas
Pandas is an open-source library for data cleaning and processing. Pandas
specializes in manipulating numerical tables and time series, which are common
data forms in data science.

3. SciPy
Scipy stands for Scientific Python. SciPy is an open-source library for data
processing and modeling for scientific applications. It is useful in solving
many mathematical equations and algorithms.

4. TensorFlow
Tensor Flow is a free and open-source software library for machine learning and
artificial intelligence. Tensor Flow is a library for high-performance numerical
computations. It’s used across various scientific fields.

5.Matplotlib
Matplotlib is an extensive library for creating fixed, interactive, and animated
Python visualizations. Matplotlib is designed to be as functional as MATLAB, with the
additional benefit of being able to use Python. It also free and open source Library.

6.SQLite3
Python programming language provides a library for database operations. Python
SQLite3 module is used to integrate the SQLite database with Python. It is mainly used
for database operations using sql queries. There is no need to install this Library
separately as it comes along with Python after the 2.5x version.
7.Scikit-learn
Scikit-learn (Sklearn) is the most useful and robust library for machine learning in
Python. It provides a selection of efficient tools for machine learning and statistical
modeling including classification, regression and clustering.

8.Statsmodels
statsmodels is a Python Library that provides a complement for statistical
computations including descriptive statistics ,estimation and inference for statistical
models.

Python Language Basics


Interacting with Python
In python standard distribution There are two ways to
work with Python :
1. Command Line Mode (Interactive Mode)
2. IDLE mode(Script Mode)

Command Line Mode


On selecting the Python Command Line, you see the Python Command Line
window displaying the Python prompt (>>>), as shown in Figure

Python Command Line window.


In command line mode, you type Python instructions one line
at a time.

IDLE (Integrated DeveLopment Environment)


Python IDLE comes with the standard Python distribution. IDLE combines an
interactive interpreter with code editing and debugging tools. The Python IDLE
Shell window as shown in Figure.
Python Shell window.

Character set:
Any Programming language is required to represent its characters with the
help of character set. An ASCII character set is used to represent characters up to
3rd generation languages(c/c++). An ASCII character set supports 8 bit characters.
The number of characters that can be represented by this coding system is limited
to 256 only. In order to extend ASCII coding system, an universal coding system
(UNICODE) is introduced. Python adapted this coding system for representing its
characters.
Note: There are 65536(0 to 65535) characters are available
in UNICODE character set.

Keywords
Keywords are the reserved words in Python. There are 35 keywords in
Python 3.10 This number can vary in different versions of Python.

Keywords in Python3.10 programming language


'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'
Note: you can always get the list of keywords in your current version by typing
the following in the prompt.
>>> import keyword
>>>keyword.kwlist
>>>len(keyword.kwlist)
Running Python as a calculator

Eg:
>>> 2*10
20
>>> 3+4+9
16
>>> 2**3
8

Data Types in Python

Python has a rich set of fundamental data types. The operations on an object
depends on its data type.

The list of data types are as follows:


Integers:
Integers are 32 bits long, and their range is from

–2147483648 to 2147483647

Long Integers:
It has unlimited, subject to the memory limitations of the computer.

Floating Point Numbers:


Floating-point numbers are also known as double-precision
numbers(used 64 bits)

Strings:
Sequences of Unicode characters. A string can be defined either Single quotes
(or) double quotesor (or) triple quotes. By using triple quotes we can write
multi-line strings.

Boolean:
It can hold only one of two possible values: True or False.

Complex Number:
A complex number has a real and an imaginary component, both represented
by float types in Python. For instance, 2+3j is a complex number, where 3j is the
imaginary component and is
equal to √-9 (√9 × √−1 = 3i or 3j)
Eg1:
>>> complex(2,3)
(2+3j)

Finding Data Types


To find the data type of the specified object, we use the type() function, which
returns the data type of the object passed to it.
Syntax:
type(value/object)
eg:
>>> type(10)
<class 'int'>

>>> type(10.0)
<class 'float'>

>>> type(‘abc’)
<class 'str'>

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

>>> type(2+3j)
<class 'complex'>

Variables
Variables are used for storing data in a program. Therefore, by assigning
different data types to variables(you can store numbers, strings,etc.).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.

Rules for creating variable names(Identifiers)


1. Identifiers can be a combination of alphabets in lowercase
(a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore ( _ ).
2. An identifier cannot start with a digit. identifier must start with an Alphabet
or an underscore
3. Keywords cannot be used as identifiers.
4. Identifier can be of any length.

For example
A = 10
value = 10.0
st_value="Hello World!"

You can see in the preceding examples the variable can be a single character or a
word or words connected with underscores.

Multiple Assignment
1) Python allows you to assign a single value to several variables.
For example
a=b=c=1
Here, an integer value 1 is assigned all the three variables.

2)For example –
a,b,c=1,2,'Hello'
Here, two integer values 1 and 2 are assigned to variables a and b respectively,
and a string "Hello" is assigned to the variable c.

Python Input and Output


Python provides no. of built-in functions for I/O operations. Some of the
functions like input() and print() are widely used for standard input and output
operations . Let us see the output section first.
Python Output Using print() function
The 'print' function is used to print data to the standard output device(monitor) .
Syntax:
print(objects, sep=' ', end='\n')

 Here, objects are the value(s) to be printed. Objects are separated by


comma.
 The ‘sep’ is used to display separator between the values. Default is a
space character.
 After all values are printed, ‘end’ is printed. Default is a new line.
eg:
print('Welcome')
Output: Welcome

a=5
print('The value of a is', a)
Output: The value of a is 5

print(1,2,3,4,5)
Output: 1 2 3 4 5

print(1,2,3,4,5,sep='*')
Output: 1*2*3*4*5

print(1,2,3,4,5,sep='#',end='$')
Output: 1#2#3#4#5$

Comments:
Un executable lines in a program are called as comment lines. Comments lines
are for documentation purposes and these lines are ignored by the interpreter.

# - Single line comment

’’’
---------------------
--------------------- Multi line comment
----------------------
’’’
Writing Python Programs(Scripts)
We can write Python programs either through IDLE’s built-in editor or through
any editor. We will be using python IDLE’s editor for writing programs. We can
launch IDLE and then select the File > NewFile option to open IDLE’s built-in
editor and write the following small program.
Note: Python script(program) extension is .py
test.py
# This is First program
print ("Hello World!")
print ("Welcome to Python Programming")

Running Python Programs from the IDLE’s editor


We can run the program from IDLE editor by pressing the F5 function key (or)
from the editor’s Run menu: select Run Module. The output appears in the IDLE
interactive shell window.

P1.py
eno = 100 # An integer assignment
ename = "HHHH" # A string assignment
salary = 20000.00 # A floating point assignment
print("Employ Number :",eno)
print("Employ Name :", ename)
print("Salary :",salary)

Format strings
We can use format strings in print() function like printf() style used in ‘C’
language.
The list of format Strings

eg1:
C Language
int n=10;
printf("value of n = %d",n);

python
n=10
print("value of n = %d"%n)

eg2:
>>> m=10;n=20

>>> print("m = %d and n = %d"%(m,n))


output: m = 10 and n = 20

prg: Emp.py
eno=100
ename='HHHH'
grade='A'
salary=20000.00
print ("Employ Number :%d"%eno)
print ("Employ Name :%s"%ename)
print ("Grade :%c"%grade)
print ("salary :%.2f"%salary)

Escape Sequences
Python uses some backslash characters in output functions for formatting the
output. These characters are called as Escape sequence characters. In these
characters it consists of two characters ,But it is treated as a single character

Eg:
print('Hello \n Welcome to Python Programming')
print('Name\tEmail Address\tContact Number')

python Input
We want to take the input from the user, We use input() function.
Syntax :
input([prompt])

where prompt is the string we wish to display on the screen. It is


an optional.

Note: input function return only string value.

>>> num = input('Enter any number: ')


Enter any number: 10
>>> num
'10'
Here, we can see that the entered value 10 is a string, not a number.

Type conversion (or) Type casting in Python


Sometimes it is necessary to convert values from one type to another. The
process of converting from one type to another type is called as type casting or
type conversion.
To convert one type to another Python supplies several built-in functions. these
functions are
1)float(x) :
This function converts string type to a floating point number

2) int(x)
This function converts string type to integer.

Program
Conv1.py

s=input("Enter any string :")


f=float(s)
print("After converting to float :",f)
n=int(s)
print("After converting to integer :",n)

3. ord(x) :
converts a character to integer(Unicode value).

4.chr(x) :
Converts an integer(Unicode value) to a character

5. str(x) :
Converts integer (or) float into a string.

6.complex(real,imag) :
Converts real numbers to complex number

Eg(Unicode values):
A to Z 65 to 90
a to z 97 to 122
0 to 9 48 to 57
Esc 27
Backspace 8
Enter 13
SpaceBar 32
Tab 9
etc.

program
Conv2.py

c = ord('A')
print ("After converting character to integer :",c)
c = chr(65)
print ("After converting integer to character :",c)
c = str(123)
print ("After converting integer to string :",c)
c = complex(1,2)
print ("After converting integers to complex number :",c)

Python Indentation
Most of the programming languages like C, C++and Java use curly braces { } to
define a block of code.
Python uses whitespace indentation to define blocks rather than curly
braces . A code block (body of a function, loop etc.) starts with indentation and
ends with un-indentation line.

Python Operators
Operator :
Operator is special symbol in Python and it performs a particular
operation.
Operand :
The value on which the operator acts is called as operand.

Python has a number of operators which are classified below.


1)Arithmetic operators
2)Relational operators
3)Logical operators
4)Bitwise operators
5)Assignment operators
6)Special operators
a. Identity operator b. Membership operator

Arithmetic operators
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication etc.
Ari.py
print('Enter any two Numbers ')
a=int(input())
b=int(input())
print('Addition :',a+b)
print('Subtraction :',a-b)
print('Multiplication :',a*b)
print('Division :',a/b)
print('Modulus :',a%b)
print('Floor Division :',a//b)
print('Exponent :',a**b)

round()
Python provides an inbuilt function round() ,which rounds precision digits of
floating point number.
Syntax:
round(floating number, no of precision digits)
>>>round(10.639 , 2)
10.64
>>> round(10/3,2)
3.33
>>> n=10.3159
>>> n
10.3159
>>> round(n,2)
10.32

2)Relational operators
These are used to test the relation between 2 values or 2 expressions.
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to

Logical operators :
These are used to combine the result of 2 or more expressions.
and Logical AND
or Logical OR
not Logical NOT

Exp1 Exp2 Exp1 and Exp2 Exp1 or Exp2


-----------------------------------------------------------------------
True True True True
True False False True
False True False True
False False False False

If Exp=True -> not Exp=False


If Exp=False -> not Exp=True

Bit-wise Operators :
These operators are used for manipulation of data at bit level.
Bit-wise logical operators :
These are used for bit-wise logical decision making.
& Bit-wise logical AND

Bit-wise logical OR

^ Bit-wise logical XOR

B1 B2 B1 & B2 B1 B2 B1 ^ B2
------------------------------------------------------------------
1 1 1 1 0
1 0 0 1 1
0 1 0 1 1
0 0 0 0 0

Eg : int a=5,b=6;
a=5 - 1 0 1
b=6 - 1 1 0

1 0 1
1 1 0
----------------------
a&b : 1 0 0 =4
----------------------

1 0 1
1 1 0
----------------------
a|b : 1 1 1 =7
----------------------

1 0 1
1 1 0
----------------------
a^b : 0 1 1 =3
----------------------

Bit1.py
print('Enter any two Numbers ')
a=int(input())
b=int(input())
print('a & b :',a&b)
print('a | b :',a|b)
print('a ^ b :',a^b)

Bit-wise shift operartor :


The shift operations take binary patterns and shift the bits to the left or right.

<< - left Shift


>> - Right Shift
Eg :
a=4
a=4 -> 1 0 0 (binary form)
b=a<<2; means value of a is to be left shifted by 2 bits and store it in b.

then the value of b :-


1 0 0 0 0 = 2 power 4 = 16

a=4 -> 1 0 0 (binary form)


c=a>>1; means a is to be right shifted by 1 bit and store it in c.
then the value of c :-
1 0 = 2 power 1 = 2

Bit2.py
a=4
b=a<<2
c=a>>1
print('a :',a)
print('b :',b)
print('c :',c)

Assignment Operators :
These operators are used to assign values to variables.
Simple assignment :
=
compound assignment
+=
-=
*=
/=
//=
%=
**=

n=10, if we want to add 5 to n then we will give


n=n+5
(or)
n+=5 which is compound assignment.

Eg:
>>> n=10
>>> n
10
>>> n+=5
>>> n
15

Special operators
Python language offers two types of special operators. They are
1.identity operators
2.membership operators
Identity operators
‘is’ and ‘is not’ are the identity operators in Python. They are used to check two
values or variables.

is - True if the operands are identical


is not - True if the operands are not identical

eg:
>>> a=10
>>> b=10
>>> c=20
>>> a is b
True
>>> a is not c
True

Membership operators
‘in’ and ‘not in’ are the membership operators in Python.
They are used to test whether a value or variable is found in a sequence(string,
list, tuple,set,Etc.).

in - True if value/variable is found in the sequence


not in - True if value/variable is not found in the sequence
eg:

>>> st='abcd'
>>> 'a' in st
True
>>> 'k' not in st
True
>>> x='a'
>>> x in st
True
>>> "WEL" in "WELCOME"
True
>>> "WCE" in "WELCOME"
False
Control Flow Statements :

Conditional control statments

1.Simple if statement
It is a Conditional control statement in Python
The general form of the if statement is:

if condition :
block

• The reserved word if begins a if statement.


• The condition is a Boolean expression . A colon (:) must
follow the condition.
• The block is a block of one or more statements to be executed
if the condition is true.

- To find maximum value of given 2 values using simple if


If.py
print ("Enter any two values")
a=int(input())
b=int(input())
max=a
if max < b :
max=b
print("Maximum value :",max)

- To find maximum value of given 3 values using simple if

print("Enter any 3 values")


a=int(input())
b=int(input())
c=int(input())
max=a
if max < b :
max=b
if max < c:
max=c
print("Maximum value :",max)

2. if-else statement
It is an extension of simple if statement.

The general form of an if-else statement is

if condition :
if block
else :
else block

The condition is a Boolean expression, if it is true then if block will be executed


otherwise else block will be executed.

- To find maximum value of given two values using if-else


If-else.py
print ("Enter any two values")
a=int(input())
b=int(input())

if a> b :
max=a
else :
max=b
print("Maximum value :",max)

- To check whether the given number is even or odd


if-else1.py
n=int(input("Enter any Number :"))
if n%2==0 :
print("Given Number is Even")
else :
print("Given Number is Odd")
3. Nested if statement :
Using a if statement within another if is called as nested if. If a series of
decisions are involved, we use nested if statement.

Form : 1
if condition-1 :
if condition-2 :
………….
………..
if condition-n :
Statements

Form : 2
if condition-1 :
if condition-2 :
Statement-1
else :
Statement-2
else :
if condition-3 :
Statement-3
else :
Statement-4

To find maximum of three values using nested if


Nest-if.py

print("Enter any 3 values ")


a=int(input())
b=int(input())
c=int(input())
if a>b :
if a>c :
max=a
else :
max=c
else :
if b>c :
max=b
else :
max=c
print("Maximum value :",max)

4. if-elif-else statement
This statement is also used for a series of decisions are involved.

Syntax:
if condition-1 :
statements-1
elif condition-2 :
statements-2
………………….
………………….
elif condition-n:
statements-n
else :
else block - statements

In this statement, the conditions are evaluated from top to bottom, if the
condition is true then the statements associated that block is executed and the
control transfers to the next statement. Otherwise when all conditions are false then
the final else block statements will be executed.

- Find maximum of 3 values using if-elif-else


If-elif.py
print("Enter any 3 values ")
a=int(input())
b=int(input())
c=int(input())
if a>b and a>c :
max=a
elif b>c :
max=b
else :
max=c
print("Maximum value :",max)
Loop control statements :
loop:
The process of repeatedly executing a block of statement up to specified
number of times is called as loop.
Python supports 2 types of looping statements. They are :
1) while loop
2) for loop

While loop
It is a conditional controlled loop statement in python.

Syntax:
while condition :
statements

In this loop first the condition will be evaluated. If it is true, then the
statement block will be executed. After the execution of statements, the condition
will be evaluated once again, if it is true then the statement block will be executed
once again. This process of repeated execution continues until the condition
becomes false.

#Write a program To Display natural numbers from 1 to given number

n=int(input("Enter any Number :"))


print("Natural number from 1 to",n)
i=1
while i<=n :
print(i,end='\t')
i=i+1

#To Display Even and Odd numbers from 1 to given number


n=int(input("Enter any Number :"))
print("\nEven number from 1 to",n)
i=1
while i<=n :
if i%2==0 :
print(i,end='\t')
i=i+1
print("\n\nOdd number from 1 to",n)
i=1
while i<=n :
if i%2!=0 :
print(i,end='\t')
i=i+1

#To Display factors of given number


n=int(input("Enter any Number :"))
print("Factors of ",n)
i=1
while i<=n :
if n%i==0 :
print(i,end='\t')
i=i+1

#To check whether the given number is prime or not

print("Enter any Number : ",end='')


n=int(input())
count=0
i=1
while i<=n :
if n%i==0 :
count=count+1
i=i+1
if count==2 :
print("Given Number is Prime")
else :
print("Given Number is Not Prime")
#To calculate and display factorial of given number
n=int(input("Enter any Number :"))
fact=1
while n>=1 :
fact=fact*n
n=n-1
print("Factorial of Given Number :",fact)

#To calculate and display Reverse of given number


n=int(input("Enter any Number :"))
rev=0
while n>0 :
rev=(rev*10)+(n%10)
#n=int(n/10)
n=n//10
print("Reverse Number :",rev)

#To display Fibonacci series of first n terms


n=int(input("Enter No of Terms :"))
i,a,b,c=1,1,0,0
print("Fibonacci Series : ",end='')
while i<=n :
print(c,end="\t")
c=a+b
a=b
b=c
i=i+1

The range () Function


The range() function generates and returns a sequence of integers and is very
commonly used in for loop . There are 3 variations of the range() function,
depending on the number of parameters passed to it.

range(x):
Returns a list whose items are consecutive integers from 0 to x-1 .
range(x, y):
Returns a list whose items are consecutive integers from x to y-1 .

range(x, y, step):
Returns a list of integers from x to y-1 , and the difference between each
successive value is the value defined by step.

Note: When step is not specified, its default value is 1.

• range(10) -> 0,1,2,3,4,5,6,7,8,9


• range(1, 10) -> 1,2,3,4,5,6,7,8,9
• range(1, 10, 2) -> 1,3,5,7,9
• range(10, 0, -1) -> 10,9,8,7,6,5,4,3,2,1
• range(10, 0, -2) -> 10,8,6,4,2
• range(2, 11, 2) -> 2,4,6,8,10
• range(-5, 5) -> −5,−4,−3,−2,−1,0,1,2,3,4

The for Loop


The for loop iterates over a range of values. These values
can be a numeric range, or, elements of a data structure like a
string, list, tuple,etc.
Syntax:
for iterating_var in sequence :
statements

# To displays numbers from 1 to Given Number using for


loop

n=int(input("Enter any Number :"))


print("Natural Number from 1 to",n)
for i in range(1,n+1):
print (i,end='\t')

#To Display Even and Odd numbers from 1 to given number using for loop
n=int(input("Enter any Number : "))
print("\nEven number from 1 to",n)
for i in range(2,n+1,2):
print(i,end='\t')

print("\n\nOdd number from 1 to",n)


for i in range(1,n+1,2):
print(i,end='\t')

Unconditional control statements


1. The break statement
The break statement terminates and exits from the current loop.It is typically
used in an infinite loop.
Syntax:
break

Infinite Loop
An infinite loop is a loop that executes its block of statements repeatedly until
the user forces the loop to quit.

break.py
To display Numbers from 1 to given number,if the given number is greater than
20 it displays only 1 to 20 using break.

n=int(input("enter any Number :"))


k=1
while True :
print(k,end='\t')
k=k+1
if(k>20 or k > n ):
break

2. The continue Statement


The continue statement stops execution of the current iteration by skipping the
rest of the loop and continuing to execute the loop with the next iterative value.
Syntax:
continue

write a program to display numbers from 1 to 10 except for the values 4 and 7
using continue.

program
k=1
while k <=10 :
if k==4 or k==7:
k=k+1
continue
print (k,end=’\t’)
k=k+1

Output:
1 2 3 5 6 8 9 10

3. The pass Statement


The pass statement is used in Python to indicate an empty block of statements.
Syntax:
pass

write a program to display numbers from 1 to 10 except for the values 4 and 7
using pass

pass.py
k=1
while k <=10 :
if k==4 or k==7:
pass
else:
print (k,end='\t')
k+=1
Output:
1 2 3 5 6 8 9 10

IPython and Jupyter Notebook


IPython (Interactive Python) is a command shell for interactive computing in
multiple programming languages. It was created by Fernando Perez in 2001.

IPython provides the following features:


1. Interactive shells .
2. A browser-based notebook interface with support for
code, text, mathematical expressions, plots and other
media.
3. Support for interactive data visualization and use of GUI
toolkits.
4. Tools for parallel computing.

The IPython Notebook is also known as the Jupyter Notebook. It is an interactive


computing environment, in which you can combine code execution, rich text,
mathematics, plots and rich media. The Jupyter Notebook is a powerful tool for
developing and presenting data science projects.

You might also like