Python For Data Science
UNIT I
UNIT-1: Basics of Python
Features of python, literal constants-numbers, variables,
identifiers, data types, input operation, comments,
operators, operations on strings, other data types, type
conversion.
Selection or conditional branching statements-if, if else ,
nested if, if elif else, loops or iterative statements-while, for,
nested loops, break, continue, pass, else statement with
loops.
Introduction: Python is a widely used general-purpose, high level
programming language. It was created by Guido van Rossum in 1991
and further developed by the Python Software Foundation. It was
designed with an emphasis on code readability, and its syntax allows
programmers to express their concepts in fewer lines of code.
History:
Python was developed by Guido van Rossum in the late eighties
and early nineties at the National Research Institute for
Mathematics and Computer Science in the Netherlands.
Python is derived from many other languages, including ABC,
Modula-3, C, C++, Algol-68, SmallTalk, Unix shell, and other
scripting languages.
Guido Van Rossum published the first version of Python code
(version 0.9.0) at alt.sources in February 1991. This release
included already exception handling, functions, and the core
data types of list, dict, str and others. It was also object
oriented and had a module system.
Python version 1.0 was released in January 1994. The major
new features included in this release were the functional
programming tools lambda, map, filter and reduce, which Guido
Van Rossum never liked.
Six and a half years later in October 2000, Python 2.0 was
introduced. This release included list comprehensions, a full
garbage collector and it was supporting unicode.
Python flourished for another 8 years in the versions 2.x before
the next major release as Python 3.0 (also known as "Python
3000" and "Py3K") was released. Python 3 is not backwards
compatible with Python 2.x. The emphasis in Python 3 had been
on the removal of duplicate programming constructs and
modules, thus fulfilling or coming close to fulfilling the 13th law
of the Zen of Python: "There should be one -- and preferably
only one -- obvious way to do it."
Krishnaveni Degree College :: Narasaraopet Page No. : 1
Python For Data Science
UNIT I
Features of Python: Python's features include:
Easy-to-learn: Python has few keywords, simple structure, and a
clearly defined syntax. This allows to learn the language quickly.
Versatile: Python supports development of wide range of
applications ranging from simple text processing, WWW browsers,
games etc.
Free and Open Source: Downloading python and installing python is
free. Therefore, any one can freely distribute it, read the source
code, edit it and even use the code to write new free programs.
High-level Language: Python is a high level programming language,
so the programmers don’t have to worry about the low-level details
like managing memory used by program etc. They just need to
concentrate on the procedure to solve the problem.
Interactive: Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
Portable: Python can run on a wide variety of hardware platforms
and has the same interface on all platforms.
Object Oriented: Python supports object-oriented as well as
procedure-oriented programming. This language supports such
concepts as polymorphism, operation overloading and multiple
inheritance.
Interpreted: Python code is processed at runtime by python
Interpreter. Interpreted language has simpler execute cycle and also
works faster.
Extendable: As python is an open source software any one can add
low-level modules to the Python interpreter. These modules enable
programmers to add or to customize their tools to work more
efficiently.
Embeddable: Programmers can embed Python within their C, C++,
and java programs.
Secure: Python environment is secure from tampering. Modules can
be distributed to prevent altering the source code. Security checks
can be added to implement additional security features.
Robust: Python programmers cannot manipulate memory directly.
For every syntactical mistake, a simple and easy message is
displayed to correct the error easily. Run time errors can be easily
handled using exception handling.
Krishnaveni Degree College :: Narasaraopet Page No. : 2
Python For Data Science
UNIT I
Steps in Learning Python: Steps in Learning Python Programming
Language is similar to learning English Language.
Character set: A character set is a set of valid characters
acceptable by a python programming language. They include
Alphabets: All capital (A-Z) and small (a-z) alphabets.
Digits: All digits 0-9.
Special Symbols: Python supports all kind of special symbols
like, ” ‘ l ; : ! ~ @ # $ % ^ ` & * ( ) _ + – = { } [ ] \ .
White Spaces: White spaces like tab space, blank space,
newline, and carriage return.
Other: All ASCII and UNICODE characters are supported by
Python that constitutes the Python character set.
Tokens: A token is the smallest individual unit, or element in the
Python program, which is identified by interpreter. They are building
blocks of the source code.
Krishnaveni Degree College :: Narasaraopet Page No. : 3
Python For Data Science
UNIT I
Keywords: Keywords are words that have some special meaning or
significance in a programming language. They can’t be used as
variable names, function names, or any other random purpose. They
are used for their special features. There are thirty-five keywords in
Python. They are
False await else import pass
None break except in raise
True class finally is return
And continue For lambda try
As def From nonlocal while
assert del global not with
async elif If or yield
Python Keywords classification: For easy remembrance the keywords
in python are divided into 10 categories. They are
Value Keywords: True, False, None
Operator Keywords: and, or, not, in, is
Control Flow Keywords: if, elif, else
Iteration Keywords: for, while, break, continue, else
Structure Keywords: def, class, with, as, pass, lambda
Returning Keywords: return, yield
Import Keywords: import, from, as
Exception-Handling Keywords: try, except, raise, finally, else, assert
Asynchronous Programming Keywords: async, await
Variable Handling Keywords: del, global, nonlocal
Identifiers: Identifier is a name used to identify a variable, function,
class, module or other object. The rules that are to be followed for
naming an identifier are
1. An identifier starts with a letter A to Z or a to z or an
underscore (_) followed by zero or more letters, underscores
and digits (0 to 9).
Krishnaveni Degree College :: Narasaraopet Page No. : 4
Python For Data Science
UNIT I
2. Identifier does not allow punctuation characters such as @, $,
and %
3. Python is a case sensitive programming language. Thus,
Manpower and manpower are two different identifiers in
Python.
Literals: Literals are the constants used in the programs. Python
have different types of literals. They are
1. String literals
2. Numeric literals
3. Boolean literals and
4. A Special literal
String literals: String literals are sequences of characters surrounded
by single, double or triple quotes. In python we have two types of
string literals namely single line strings and multiline strings.
A single line string is the string literal that terminates on
encountering a newline. It can be defined by enclosing one or more
characters inside single or double quotes as follows.
myString="This is a single line string"
anotherString='This is also a single line string'
A multiline string can be defined by enclosing characters
expanding to multiple lines in triple quotes as follows.
myString="""This is
a
multiline string.
"""
Numeric literals: Numeric literals are used to represent numbers in a
python program. Different categories of numeric literals are
1. Integers
2. Floating point numbers and
3. Complex numbers
Integers: Integers in python are numbers with no fractional
component. Integer numbers can be represented in different number
systems. They are
1. Decimal Number System
2. Binary Number System
3. Octal Number System
4. Hexadecimal Number System
In python programming, binary numbers starts with 0b, octal
numbers starts with 0o, hexadecimal numbers starts with 0x. Default
numbers are decimal numbers.
Ex:
Decimal Numbers : 0, -9, 22 etc
Krishnaveni Degree College :: Narasaraopet Page No. : 5
Python For Data Science
UNIT I
Binary Numbers: 0b11,0b010
Octal Numbers: 0o216, 0o754, -0o35 etc
Hexadecimal constants: 0x7f, 0x2a, -0x521 etc
Floating point literal: A floating point literal in python represents a
real number which consists of Integral as well as fractional part. A
floating point number in the decimal number system can be
represented as follows.
myNum=123.345
Complex numbers: Complex numbers are in the form of a+bj where
‘a’ represents the real part and ‘b’ represents the imaginary part of
the complex number. A numeric literal representing a complex
number can be written as follows.
myNum=3+4j
Boolean literals: In python, there are two types of boolean literals
namely True and False. They can be defined in a program as follows.
myVar=True
myVar1=False
A Special literal: In python, there is one special literal namely None.
The literal ‘None’ is used to specify that the variable to which it is
assigned does not refer to any object. A variable with value ‘None’
can be defined as follows.
myObj=None
Python Operators: Operator is a symbol which tells action to be
performed. Depending on the operation performed by the operator,
the operators can be classified into seven categories. They are
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operators
6. Identity Operators
7. Membership Operators
Arithmetic Operators: Arithmetic operators are the operators which
take numerical values as the input and produces numerical values as
the output. The following table lists the arithmetic operators.
Operator Purpose Example Result
+ Addition 12 + 4.9 16.9
– Subtraction 12 - 4.9 7.1
* Multiplication 12 * 4.9 58.8
/ Division 12 / 4.9 2.45
// Floor Division 12 // 5 2
Krishnaveni Degree College :: Narasaraopet Page No. : 6
Python For Data Science
UNIT I
% Modulus 12 % 5 2
** Exponentation 5**2 25
Comparision Operators: The comparision operators compares one
operand to the other. Comparision operators are the operators which
take numerical values as the input and produces Boolean values i.e.
True or False as the output. The following table lists the relational
operators.
Operator Purpose Example Result
== Equal to 4 == 1 False
!= Not equal to 4 != 1 True
> Greater than 4>1 True
< Less than 4<1 False
>= Greater than or 4 >= 1 True
equal to
<= Less than or 4 <= 1 False
equal to
Logical Operators: Logical operators are the operators which take
Boolean values as the input and produces Boolean values as the
output. The following table lists the logical operators.
Operator Purpose Example Result
and Logical AND 2>3 and 3<4 False
Or Logical OR 2>3 or 3<4 True
not Logical unary not(2>3) True
NOT
Assignment Operators: Assignment operators are the operators
which assigns the value on R.H.S to the variable on L.H.S. The
assignment operator can combined with arithmetic operators to form
short hand assignment operators. The following table lists the
assignment operators.
Operator Purpose Example Result
= Assignment a=10 10
+= Addition Take a=10; 20
assignment a+=10
-= Subtraction Take a=10; a- 0
assignment =10
*= Multiplication Take a=10; 100
assignment a*=10
/= Division Take a=10; 3.333
assignment a/=3
Krishnaveni Degree College :: Narasaraopet Page No. : 7
Python For Data Science
UNIT I
//= Floor Take a=10; 3.333..
assignment a/=3
%= Modulus Take a=10; a 1
assignment %=3
** Exponentiation Take a=10; 100
= assignment a**=3 0
Bitwise Operators: Bitwise operators operate on individual bits of
integer (int and long) values. The following table lists the Bitwise
operators.
Operator Purpose Example Result
~ Ones ~3(0b0011) -4(-0b100)
Complement
& Bitwise AND 3&6(0b0011 2(0b0010)
&0b0110)
| Bitwise OR 3|6(0b0011 | 7(0b0111)
0b0110)
^ Bitwise 3^6(0b0011 ^ 5(0b0101)
exclusive OR 0b0110)
>> Shift right 3>>1(0b0011 1(0b0001)
>> 1)
<< Shift left 3<<1(0b0011 6(0b0110)
<< 1)
Identity operators: is and is not are the identity operators in Python.
They are used to check if two values (or variables) are located on the
same part of the memory. Two variables that are equal does not
imply that they are identical.
Operator Purpose Example Result
is True if the operands x2 = 'Hello' True
are identical (refer to y2 = 'Hello'
the same object) x2 is y2
is not True if the operands x2 = [1,2,3] True
are not identical (refer y2 = [1,2,3]
to the same object) x2 is not y2
x2 = 5
y2 = 5
x2 is not y2 False
Krishnaveni Degree College :: Narasaraopet Page No. : 8
Python For Data Science
UNIT I
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 and dictionary). In a dictionary
we can only test for presence of key, not the value.
Operato Purpose Example Result
r
in True if value or variable is x = 'Hello
found in the sequence world' True
'H' in x
not in True if value or variable is x = 'Hello
not found in the sequence world' True
'hello' not in x
x= True
{1:'a',2:'b'} False
1 in x
‘a’ in x
Precedence of Operators: To evaluate the expressions there is a
rule of precedence in Python. It guides the order in which these
operations are carried out. The operator precedence in Python is
listed in the following table. It is in descending order (upper group
has higher precedence than the lower ones).
Operators Meaning Preceden
ce
() Parentheses 1(Highest
)
** Exponent 2
+,-,~ Unary Plus, Unary Minus, 3
One’s Complement
*, /, //, % Multiplication, Division, Floor 4
division, Modulus
+, - Addition, Subtraction
<<, >> Shift Left, Shift Right 5
& Bitwise AND 6
^ Bitwise XOR 7
| Bitwise OR 8
==, !=, >, >=, <, <=, Comparisons, Identity, 9
is, is not, in, not in Membership operators
not Logical NOT 10
and Logical AND 11
or Logical OR 12
Krishnaveni Degree College :: Narasaraopet Page No. : 9
Python For Data Science
UNIT I
Associativity of Operators: When two operators have the same
precedence, associativity helps to determine the order of operations.
Associativity is the order in which an expression is evaluated that
has multiple operators of the same precedence. Almost all the
operators have left-to-right associativity. Exponent operator ** and
Assignment operator = has right-to-left associativity in Python.
Comparison operators do not have associativity in Python.
Ex: 5 * 2 // 3 ➔ (5*2)//3 ➔ 3 # left-to-right associativity
Ex: 5 ** 2 ** 3 ➔ 5**(2**3) ➔ 390625 # right-to-left associativity
Ex: 5 < 2 < 3 ➔ (5<2)and(2<3) ➔ False # No associativity
Expressions in Python: An expression is a combination of
operators and operands that is interpreted to produce some other
value. Depending on the result of the expression there are many
different types of expressions in Python. They are
1. Constant Expressions
2. Arithmetic Expressions
3. Integral Expressions
4. Floating Point Expressions
5. Relational Expressions
6. Logical Expressions
7. Bitwise Expressions
8. Combinational Expressions
Constant Expressions: Constant Expressions are the expressions
which produce constant values as the result.
Ex: 15 + 1.3
Arithmetic Expressions: An arithmetic expression is a combination of
numeric values, arithmetic operators, and sometimes parenthesis.
The result of this type of expression is also a numeric value.
Ex: 13/5
Integral Expressions: Integral Expressions are the kind of
expressions that produce only integer results after all computations
and type conversions.
Ex: 13//5
Floating Point Expressions: Floating Point Expressions are the kind of
expressions which produce floating point numbers as result after all
computations and type conversions.
Ex: 13/5
Relational Expressions: Relational Expressions are expressions that
uses numerical values as operands, comparision operators and
produce a boolean result. These expressions are also called Boolean
expressions.
Ex: 13>5
Krishnaveni Degree College :: Narasaraopet Page No. : 10
Python For Data Science
UNIT I
Logical Expressions: Logical Expressions are expressions that uses
Boolean expressions as operands, logical operators and produce a
boolean result.
Ex: 13>5 and 6<5
Bitwise Expressions: Bitwise Expressions are the kind of expressions
in which computations are performed at bit level.
Ex: 4>>2
Combinational Expressions: Combinational expressions uses
different types of expressions in a single expression.
Ex: 3 + 4 >> 1
Type Conversion: Python defines two types of Type Conversion.
They are
1. Implicit Type Conversion
2. Explicit Type Conversion
Implicit Type Conversion: In Implicit type conversion the Python
interpreter automatically converts one data type to another without
any user involvement.
x = 10 + 5.6
Explicit Type Conversion: In Explicit type conversion the user
explicitly converts one data type to another without Python
Interpreter involvement.
x = float(10) + 5.6
Data Types: Data types are the classification of data items. It
represents the kind of value that tells what operations can be
performed on a particular data. Since everything is an object in
Python programming, data types are actually classes and variables
are instance (object) of these classes. Different types of data in
Python are
Data Examples Explanation Mutable/
Types Immutable?
Strings "Hello!", Text - anything Immutable
"23.34" between
" " becomes string
Integers 5364 Whole numbers Immutable
Floats 3.1415 Decimal Numbers Immutable
Booleans True, False Truth values that Immutable
represent Yes/No
Lists [1,2,3,4,5] A collection of data, Mutable
sits between [ ]
Tuples (1,2,3,4,5) A collection of data, Immutable
sits between ( )
Krishnaveni Degree College :: Narasaraopet Page No. : 11
Python For Data Science
UNIT I
Dictionari {"a":1, A collection of data, Mutable
es "b":2, "c":3} sits between { }
Setting the Data Types: Data types are set when you assign a value
to a variable.
Example Data Type Explanation
ex_1 = "Hello String The data assigned sits in between
World" ""
ex_2 = 254 Integer The data assigned is a whole
number
ex_3 = 25.43 Float The data assigned is a decimal
number
ex_4 = ["Anna", List A list of strings - Data assigned
"Bella", "Cora"] sits in between " " , within [ ]
Check data types: type() function is used to check data types.
type(x) determines and returns what is the type of the input x
Example type() Data
Type
ex_1 = "Hello World" type(ex_ String
1)
ex_2 = 254 type(ex_ Integer
2)
ex_3 = 25.43 type(ex_ Float
3)
ex_4 = ["Anna", "Bella", type(ex_ List
"Cora"] 4)
Comments: Comments are extra explanations about the code. They
are completely ignored by the Python Interpreter. Using Comments
in program makes the code more understandable. There are three
types of comments in Python. They are
1. Single line Comments
2. Multiline Comments
3. Docstring Comments
Single-Line Comments: Python single line comment starts with the
hashtag symbol (#) and lasts till the end of the line.
Ex:
# Syntax of Single line comment
Krishnaveni Degree College :: Narasaraopet Page No. : 12
Python For Data Science
UNIT I
Multi-Line Comments: Python does not provide the option for
multiline comments. However, there are different ways through
which we can write multiline comments. They are
Using Multiple Hashtags (#)
Using String Literals
Using Multiple Hashtags (#): Multiple hashtags (#) can be used to
write multiline comments in Python. Each line should start with #
and it is considered as a single line comment.
# Syntax of Multi
# Multi line comment
Using String Literal: Python ignores the string literals that are not
assigned to a variable so string literals that are not assigned to a
variable is treated as a comment.
“”” Syntax of Multi
Multi line comment”””
Python Docstring: Python docstring is the string literals with triple
quotes that are appeared right after the function. It is used to
associate documentation that has been written with Python modules,
functions, classes, and methods. It is added right below the
functions, modules, or classes to describe what they do. In Python,
the docstring is then made available via the __doc__ attribute.
Example:
def multiply(a, b):
"""Multiplies the value of a and b"""
return a*b
# Print the docstring of multiply function
print(multiply.__doc__)
Output:
Multiplies the value of a and b
Indentation: Indentation is the leading whitespace (spaces and
tabs ) before any statement in python. Indentation in other
languages like c, c++, etc is just for readability but in python, the
indentation is a very important and mandatory concept that should
be followed when writing a python code, otherwise, Indentation Error
is thrown by the python interpreter. Python Indentation Rules
Python uses 4 spaces as default indentation spaces. However, the
number of spaces can be anything, it is up to the user. But a
minimum of one space is needed to indent a statement.
1. The first line of python code cannot have Indentation.
2. Indentation is mandatory in python to define the blocks of
statements.
3. The number of spaces must be uniform in a block of code.
Krishnaveni Degree College :: Narasaraopet Page No. : 13
Python For Data Science
UNIT I
4. It is preferred to use whitespaces instead of tabs to indent in
python.
5. Use whitespace or tabs to indent, intermixing of tabs and
whitespaces in indentation can cause wrong indentation errors.
Ex: Correct Indentation:
if( i == 1):
print("This is test code")
print("This is test code1")
Ex: Wrong Indentation(Error):
if( i == 1):
print("This is test code")
print("This is test code1")
Ex: Correct Indentation:
if( i == 1):
print("This is test code")
print("This is test code1")
Statements- Sequential Staments- Decision Making
Staements- If, If-Else, Nested If Statement , If-elif Statement,
Iterative Statements- while and For loop, The Range
Function, Nested Loop, Transfer Statements- Break,
Continue, and Pass Statement, The else Statement used with
Loops.
Statements: A program’s control flow is the order in which the
program’s code executes. Python has four types of statements. They
are
1. Sequential - default mode
2. Selection - used for decisions and branching
3. Repetition - used for looping, i.e., repeating a piece of code
multiple times.
4. Transfer statements - used for jumping
Sequential statements: Sequential statements are a set of
statements whose execution process happens in a sequence.
1. Write a Python Program to calculate sum of two numbers.
#Python Program to calculate sum of two numbers
a=float(input("Enter first number: "))
b=float(input("Enter second number: "))
sum=a+b;
print("Sum of ",a," and ", b," is ",sum)
Krishnaveni Degree College :: Narasaraopet Page No. : 14
Python For Data Science
UNIT I
2. Write a Python Program to calculate simple interest.
# Python Program to calculate simple interest
p=float(input("Enter Principal Amount: "))
t=float(input("Enter time in years: "))
r=float(input("Enter rate of interest per years: "))
si=p*t*r/100
print("Simple Interest =",si)
3. Write a C program to find area of the triangle when three
sides are given.
# Python Program to calculate area of the triangle
import math;
a=float(input("Enter first side: "))
b=float(input("Enter second side: "))
c=float(input("Enter third side: "))
s=(a+b+c)/2;
area=math.sqrt(s*(s-a)*(s-b)*(s-c))
print("Area of the triangle with sides ",a,",",b," and ", c," is
",round(area,3))
4. Write a Python program to find a/(b-c).
# Python Program to calculate a/(b-c)
a=float(input("Enter first side: "))
b=float(input("Enter second side: "))
c=float(input("Enter third side: "))
res=a/(b-c)
print("Result = ",res)
Selection Statements: Selection statements allows the program to
choose set of statements for execution based upon the outcome of
an expression or the value of a variable. There are various types of if
statement in Python. They are
1. Simple if statement
2. if-else statement
3. nested if statement
4. if-elif-else statement
Simple if Statement: The simple if statement initially tests the
condition. If the condition is true it executes the statement-block and
Krishnaveni Degree College :: Narasaraopet Page No. : 15
Python For Data Science
UNIT I
moves to the next statement. If the condition is false it skips the
statement-block and directly moves to the next statement.
Syntax: Flowchart:
if(condition):
statement-block;
next-statement;
Example: Write a Python
program to find the absolute value of number.
# Python Program to find the absolute value of the given number
num=float(input("Enter any number: "));
abs = num;
if(num < 0):
abs = -1 *num;
print("Absolute value of ",num," is ",abs);
if-else Statement: The if-else statement is an extension of simple if
statement. If-else statement initially tests the condition. If the
condition is true it executes the true-statement-block and moves to
the next statement. If the condition is false it executes the false-
statement-block and moves to the next statement. In any case ,
either true-statement-block or false-statement-block is executed and
moves to the next statement
Syntax: Flowchart:
if(condition):
true-statement-block;
else:
false-statement-block;
next-statement;
Example: Write a C
program to check whether the number is even or odd.
# Program to check whether the given number is even or odd
num=int(input("Enter any integer number: "));
if(num % 2 == 0):
print(num,"is an even number");
Krishnaveni Degree College :: Narasaraopet Page No. : 16
Python For Data Science
UNIT I
else:
print(num," is an odd number");
Nested – if: When one if statement is nested in another if statement
then it is
called as nested if statement.
Syntax: Flowchart:
if(condition1):
if(condition2):
statement1-block;
else:
statement2-block;
else:
statement3-block;
next-statement
Example: Write a C Program to
check whether year is leap year or not
# Python Program to find year is leap year or not
year=int(input("Enter any year: "));
if(year%4 == 0):
if( year%100 == 0):
if (year%400 == 0):
print(year," is a leap year\n");
else:
print(year," is not a leap year\n");
else:
print(year," is a leap year\n");
else:
print(year," is not a leap year\n");
if-elif-else: When one if statement is added in the else part of
another if statement then it is called as if-elif-else ladder statement.
Syntax: Flowchart:
if(condition1):
statement1-block;
elif(condition2):
statement2-block;
elif(condition3):
statement3-block;
else:
statement4-block;
next-statement;
Krishnaveni Degree College :: Narasaraopet Page No. : 17
Python For Data Science
UNIT I
Example: Write a Python Program to find largest among 3
numbers.
# Python Program to find largest among 3 numbers
a=float(input("Enter first number: "))
b=float(input("Enter first number: "))
c=float(input("Enter first number: "))
if((a>b)and(a>c)):
print(a," is largest");
elif(b>c):
print(b," is largest");
else:
print(c," is largest");
Switch: Python does not currently support switch or case statements
as in other languages. Python syntax supports readability even in
the presence of a good number of if elif statements.
Example: Write a Python program to display name of the day
using if-elif statement.
# Python Program to display name of the day
dayno=int(input("Enter the day number: "))
if(dayno==1):
print(dayno, "day in the week is Monday\n")
elif(dayno==2):
print(dayno, "day in the week is Tuesday \n")
elif(dayno==3):
print(dayno, "day in the week is Wedesday \n")
elif(dayno==4):
print(dayno, "day in the week is Thursday \n")
elif(dayno==5):
print(dayno, "day in the week is Friday \n")
elif(dayno==6):
print(dayno, "day in the week is Saturday \n")
else:
print(dayno,"is a wrong day number\n")
Iterative Statements: Iterative Statement repeats set of
instruction until the condition for termination is met. These
statements appear in the source code only once, but it execute
Krishnaveni Degree College :: Narasaraopet Page No. : 18
Python For Data Science
UNIT I
many times. Such kinds of statements are also called as loops.
Iteration Statement in Python are mainly of two types. They are
1. 'while' Statement
2. 'for' Statement
while Statement: The while loop is an entry controlled loop. It tests
the condition before executing the body of the loop. The condition
can be any relational or logical expression. The body of the loop will
be executed as long as the conditional expression is true. When
condition becomes false, control passes to the next line of code
immediately following the loop.
Syntax: Flowchart:
while condition:
Statement_1;
Statement_2;
next_statement;
Example: Write a Python
program to display sum of
natural numbers
#Python Program to display sum of natural numbers
n=int(input("Enter how many natural numbers: "));
i=1;
sum=0;
while(i<=n):
sum=sum+i;
i=i+1;
print("sum of ",n," natural numbers is ",sum);
For loop: In Python, the for statement is used to iterate through a
sequence like a list, a tuple, a set, a dictionary, or a string. The for
statement is used to repeat the execution of a set of statements for
every element of a sequence. The general syntax of for statement in
Python is as follows.
Syntax: Flowchart:
Krishnaveni Degree College :: Narasaraopet Page No. : 19
Python For Data Science
UNIT I
for <variable> in <sequence>:
Statement_1;
Statement_2;
Statement_3;
Next_statement;
Example: Write a Python program
to display name is vertical order.
#Python Program to display name is vertical order
name=input("Enter your name: ");
print("Printing characters of ",name,"is vertical order");
for ch in name:
print(ch);
The range Function: The range() function returns a sequence of
numbers, starting from 0 by default, and increments by 1 (by
default), and stops before a specified number.
Syntax:
range(start, stop, step)
Paramet Description
er
Start Optional. An integer number specifying at which position
to start. Default is 0.
Stop Required. An integer number specifying at which position
to stop (not included).
Step Optional. An integer number specifying the
incrementation. Default is 1
Example: Write a Python program to display n natural
numbers using range function.
#Python Program to display sum of natural numbers
n=int(input("Enter how many natural numbers: "));
i=1;
print(n,"natural numbers are");
for i in range(1,n+1):
Krishnaveni Degree College :: Narasaraopet Page No. : 20
Python For Data Science
UNIT I
print(i);
Example: Write a Python program to display n odd numbers
using range function.
#Python Program to display sum of natural numbers
n=int(input("Enter how many odd numbers: "));
i=1;
end
print(n,"odd numbers are");
for i in range(1,2*n,2):
print(i);
Nested Loops: Python allows its users to have nested loops, that is
loops that can be placed within another loop. Although this feature
will work with any loop like while loop as well as for loop, but it is
most commonly used with the for loop. Because this is easiest to
control.
Example: Write a Python program to display triangle of
numbers.
1
12
123
#Python Program to display triangle of numbers
n=int(input("Enter how many rows: "));
print(“Triangle with “,n,” rows is as follows”);
for i in range(1,n+1):
for j in range(1, i+1):
print(i+end=” “);
print();
Jump Statements: Python supports three jump statements. They
are
1. break
2. continue and
3. pass
These statements transfer control of execution to another part of the
program.
break: In Python the break statement is used to terminate the loop.
Example: Write a Python Program to check whether the
given number is prime or not using break.
Krishnaveni Degree College :: Narasaraopet Page No. : 21
Python For Data Science
UNIT I
# Python program to check whether the given number is prime or
not using break
n=int(input("Enter any number: "));
i=n//2;
while(i<=n//2):
if((n%i)==0):
break;
i=i+1;
if(i>n/2):
printf(n," is a prime number ");
else:
printf(n," is not a prime number ");
continue: continue Statement in Python is used to skip all the
remaining statements in the loop and move controls back to the top
of the loop.
# Python program to check whether the given number is prime or
not using continue
n=int(input("Enter any number: "));
i=1;
cnt=0;
while(i<=n):
if((n%i)!=0):
i=i+1;
continue;
i=i+1;
cnt=cnt+1;
if(cnt==2):
print(n," is a prime number ");
else:
print(n," is not a prime number ");
pass: pass Statement in Python does nothing. It specifies a null
operation or simply No Operation(NOP) statement. Nothing happens
when pass statement is executed.
# Python program to print the given number after some delay.
n=int(input("Enter any number: "));
i=1;
while(i<=n):
pass:
i=i+1;
print(“Given number",n);
Krishnaveni Degree College :: Narasaraopet Page No. : 22
Python For Data Science
UNIT I
The else Statement used with Loops: In Python the else
statement can be associated with a loop statement.
else Statement used while Loop: If the else statement is used with
the while loop , the else statement is executed when condition
becomes False. If the else statement is used with the for loop , the
else statement is executed when the loop has completed iterating.
Syntax:
while condition:
Statement_1;
Statement_2;
else:
false statement;
next_statement;
Example: Write a Python program to display n natural
numbers
#Python Program to display sum of natural numbers
n=int(input("Enter how many natural numbers: "));
i=1;
print(n,"natural numbers are");
while(i<=n):
print(i);
i=i+1;
else:
print("End of printing");
else Statement used for Loop: If the else statement is used with the
for loop , the else statement is executed when the loop has
completed iterating.
Syntax:
for <variable> in <sequence>:
Statement_1;
Statement_2;
Statement_3;
else:
False_satement;
next_statement;
Example: Write a Python program to display n natural
numbers
#Python Program to display sum of natural numbers
Krishnaveni Degree College :: Narasaraopet Page No. : 23
Python For Data Science
UNIT I
n=int(input("Enter how many natural numbers: "));
print(n,"natural numbers are");
for I in range(1,n+1):
print(i);
i=i+1;
else:
print("End of printing");
Output:
C:\python>python printnat.py
Enter how many natural numbers: 5
5 natural numbers are
1
2
3
4
5
End of printing
Krishnaveni Degree College :: Narasaraopet Page No. : 24