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

Unit 2

The document discusses Python programming language including its history, versions, uses, and basic syntax. It covers Python data types like numeric, string, None, and basic operations. It also discusses Python variables, naming conventions, and installing Anaconda.

Uploaded by

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

Unit 2

The document discusses Python programming language including its history, versions, uses, and basic syntax. It covers Python data types like numeric, string, None, and basic operations. It also discusses Python variables, naming conventions, and installing Anaconda.

Uploaded by

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

Data Analytics for Decision Making

using Python
Unit 2
Prof. J. Katyayani
T. Jahnavi

Prof J. Katyayani, T.Jahnavi


Introduction
• Python is a popular general purpose programming language.
• It was created by Guido van Rossum, and released in 1991.
• Further developed by the Python Software Foundation.
• Python is a high level interpreted, object oriented
programming language, popular for its readability and clear
syntax.
• It is used for:
➢ web development (server-side),
➢ software development,
➢ mathematics,
➢ system scripting.
• There are two major Python versions:
Python 2 and Python 3.
Prof J. Katyayani, T.Jahnavi
Comparison Parameter Python 2 Python 3
Year of Release Python 2 was released in the Python 3 was released in the
year 2000. year 2008.
“Print” Keyword In Python 2, print is considered In Python 3, print is considered
to be a statement and not a to be a function and not a
function. statement.
Storage of Strings In Python 2, strings are stored In Python 3, strings are stored
as ASCII by default. as UNICODE by default.

Division of Integers On the division of two On the division of two


integers, we get an integral integers, we get a floating-
value in Python 2. For point value in Python 3. For
instance, 7/2 yields 3 instance, 7/2 yields 3.5
Ease of Syntax Python 2 has more Python 3 has an easier syntax
complicated syntax than compared to Python 2.
Python 3.
Libraries A lot of libraries of Python 2 A lot of libraries are created in
are not forward compatible. Python 3 to be strictly used
with Python 3.
Usage in today’s times Python 2 is no longer in use Python 3 is more popular than
since 2020. Python 2 and is still in use in
today’s times.
Application Python 2 was mostly used to Python 3 is used in a lot of
become a DevOps Engineer. It fields like Software
is no longer in use after 2020. Engineering, Data Science, etc.

Prof J. Katyayani, T.Jahnavi


What can Python do?
• Python can be used on a server to create web
applications.
• Python can be used alongside software to create
workflows.
• Python can connect to database systems. It can
also read and modify files.
• Python can be used to handle big data and
perform complex mathematics.
• Python can be used for rapid prototyping, or for
production-ready software development.

Prof J. Katyayani, T.Jahnavi


Why Python?
• Python works on different platforms (Windows, Mac,
Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English
language.
• Python has syntax that allows developers to write
programs with fewer lines than some other
programming languages.
• Python runs on an interpreter system, meaning that
code can be executed as soon as it is written. This
means that prototyping can be very quick.
• Python can be treated in a procedural way, an object-
oriented way or a functional way.

Prof J. Katyayani, T.Jahnavi


Installation of Anaconda
• https://www.anaconda.com/products/distribu
tion/start-coding-immediately
• Anaconda will be downloaded.
• Once downloaded run the
anaconda.
• Once installed go to Jupyter
Notebook and Enter the code.

Prof J. Katyayani, T.Jahnavi


Online Jupyter Notebook
• https://colab.research.google.com/drive/1OiX
4TzXRQHIgO9bW2DF_y2NZclCtGnU1
• Those who did not download directly click on
the above link, Colab are providing online
Jupyter notebooks and we can use and save
the written codes of ours.

Prof J. Katyayani, T.Jahnavi


Python Syntax compared to other
programming languages
• Python was designed for readability.
• It has some similarities to the English language with
influence from mathematics.
• Python uses new lines to complete a command, while
others often use semicolons or parentheses.
• Python relies on indentation, using whitespace, to define
scope; such as the scope of loops, functions and classes.
Other programming languages often use curly-brackets
for this purpose.
• Example:
• Print (“Hello Class, welcome to python”)
Prof J. Katyayani, T.Jahnavi
Variables
• Variables are the very basic building blocks of python.
• We use them to store the pieces of data, which can be
easily accessed throughout the code.
• In short variable is a memory location to store the data.
• Generally variables have 3 elements
1. Symbolic name or Variable name
2. Assignment operator, in most cases “ = ”
3. Value that to be stored.
Example:
x = “Hi!”
a = 12
next_year = 2023
• Variables are categorized into different data types.
Prof J. Katyayani, T.Jahnavi
Naming the Variables
• Python has got its rules in naming the variable.
1. A variable name cannot start with number.
2. A variable name can only contain
i. A – z (52 letters / characters)
ii. Numbers from 0 to 9 and
iii. “ _ ” (underscore)
3. Variable names are case sensitive.
4. We cannot use any of Python’s reserved
keywords as a variable name.

Prof J. Katyayani, T.Jahnavi


Python’s Reserved Keywords
and del from not
as elif global or
assert else if pass
break except import print
class exec in raise
continue finally is return
def for lambda try
while with yield type

Prof J. Katyayani, T.Jahnavi


Data types
• Simple Data types: Advanced Data types:
– None (Null) List
– Numeric Tuple
– String Set
– Boolean Dictionary
• To check the data type of a variable. We use
“type()”
• Example : type(variable name)

Prof J. Katyayani, T.Jahnavi


None
• None is an immutable object that represents an
empty value.
• None is not the same as 0, False, or an empty
string. None is a data type of its own (NoneType)
and only None can be None.
• The None object can be used in many ways.
• One of the ways is to initialize a variable that will
be assigned a value later in the program.
• This helps us to verify the variable’s value and
take appropriate decisions.
Prof J. Katyayani, T.Jahnavi
Example
• KEY = None # Initialize variable
• # Check variable and take decision
• if KEY is None:
• # condition holds
• print("Key hasn't been set yet")
• else:
• print("Key has been set")

• # set the variable


• KEY = '3848774939‘
• # check variable and take decision
• if KEY is None:
• print("Key hasn't been set yet")
• else:
• # condition holds
• print("Key has been set")
Prof J. Katyayani, T.Jahnavi
Numeric
• Numeric:
– int 5, 10, -3 etc
– float 3.5, 2.1, -5.6 etc
– complex 6+2j, where j = squareroot(-1)
– bool True, False
(1) (0) (in int format)
– for complex numbers we should use “j” instead of
“i” in python.

Prof J. Katyayani, T.Jahnavi


Converting from one data type to
another in Numeric
• a = 5.6
b = int(a)
• l = 10
k = float(l)
• x=2
y=4
z = complex(x, y)
• int (True)
• int (False)

Prof J. Katyayani, T.Jahnavi


Integer and Float
Basic Operations
• a = 12 # declaration of variables
• b=3
• print(a + b)
• print(a - b)
• print(a * b)
• print(a / b)
• print(a ** b) # square operation
• ##Even if 2 integers are divided, we can get the
output as float where as in the most other
programming languages it is as Integer.
Prof J. Katyayani, T.Jahnavi
String
Basic Operations
• String is any set of characters in the quotation
marks either single or double quotes.
• Example: “1”, “Hello!”, ‘12.7’ etc
• Accessing of elements:
• We use index numbers to access elements. In
python index start from 0 and continues.
• Even the spaces count.
• Example:
• x = “rain bow”
[0 1 2 3 4 5 6 7] Index Numbers
[-8 -7 -6 -5 -4 -3 -2 -1] Reverse Index Numbers

• len(x) #to identify the length of string


Prof J. Katyayani, T.Jahnavi
• x[2]
• x[4]
• x[-3]
• We cannot change or replace the characters of the
string. They are immutable.
• To access a set of characters from string
• x[1:3]
• The output does not contain the index 3 value.
• We always get n-1 output.
• x.upper() # changes string to all uppercase
• x.lower() # changes string to all lowercase
Prof J. Katyayani, T.Jahnavi
• String Concatenation using “ , ”:
• pet = “cat”
• pet_name = ‘fluffy’
• pet_age = “2”
• print(pet, pet_name, pet_age)
• print(“I have a “, pet, “his name is”, pet_name,
“and he is”, pet_age, “years old”)
• print(“I have a “, pet, “\nHis name is”, pet_name,
“\n He is”, pet_age, “years old”)
• #it can only be done in Print statements using
comma
Prof J. Katyayani, T.Jahnavi
• String Concatenation using “ + ”:
• my_pet = “my” + pet + “is” + pet_age + “years
old”
• print(my_pet)
• String Concatenation using format method:
• my_pet2 = “I have a {}, his name is {}, and he is
{} years old”.format(pet, pet_name, pet_age)
• print(my_pet2)
Prof J. Katyayani, T.Jahnavi
String
Mathematical operations
• There are 2 mathematical operations using String.
– Summation of 2 Strings
– Multiplication of a String by any integer or float
• Example:
• a= “pink”
• b= “rose”
• print( a + b)
• print(a * 2)
• print(b * 3)
Prof J. Katyayani, T.Jahnavi
Boolean
• Boolean gives the output either “True” or “False” to the conditional
statements.
• We use boolean for categorical output.
• Example:
• my_boolean = 3 < 6
• print(my_boolean)
• Comparison operators:
▪ == Equal
▪ != Not equal
▪ > Greater than
▪ >= Greater than or equal to
▪ < Lesser than
▪ <= Lesser than or equal to

Prof J. Katyayani, T.Jahnavi


• Using boolean we can create “if statements” and
“while loops”.
• Example:
• if statement:
• if my_boolean is True:
• print(“ 3 is lesser to 6”)
• while loop:
• while my_boolean is False:
• print(“ while loop started”)
• my_boolean = True
• print(“loop ended”)

Prof J. Katyayani, T.Jahnavi


List
• It is a collection of array which can be ordered
and changed.
• Lists can have heterogeneous data types.
• Lists are mutable
• Example:
• a = [1, 3, 12, 12, “hi”, ‘python’]
[0 1 2 3 4 5] Index values
[-6 -5 -4 -3 -2 -1] Reverse Index values

Prof J. Katyayani, T.Jahnavi


Creating a List
# Creating an empty List:
list1 = []
# Creating a List:
list2 = [1, 2, 3, “python”, “class”]
# To add elements in List: we have 3 functions
1. append()
2. extend()
3. insert()
Prof J. Katyayani, T.Jahnavi
To Add Elements in List
• Using “append ()” function:
• append() adds value to the end of the List.
• list2.append(6)
• print (list2)
• To give more than 1 element:
• list2.append((6,7))
• The output of this append function can be seen
as tuple in the List.
• print(list2)
Prof J. Katyayani, T.Jahnavi
• Using “extend ()” function:
• list2.extend((2,0))
• The output of this extend function can be
seen as individual elements in the List.
• Using “insert ()” function:
• list2.insert(3 , “Welcome to”)
• we can add the required element anywhere in
the list based on the index number.
Prof J. Katyayani, T.Jahnavi
To delete elements from List
• # To delete data from List: We have 3 ways.
1. del keyword
2. pop() function
3. remove() function
• Using “del” keyword:
• del list2[3]
• #give the index number of the element to be
deleted from the list.

Prof J. Katyayani, T.Jahnavi


• Using “pop ()” function:
• pop() function gives the data that is deleted from
the list as the output.
• A = list2.pop(4) # give index number
• print(A)
• Using “remove ()” function:
• list2.remove(2) # give the element present in the list
• print(list2)

Prof J. Katyayani, T.Jahnavi


Access of Elements from List
• # To access elements from the List:
• print(list2)
• print(list2[ : ])
• print(list2[0:2]) # give the index values
• print(list2[0:4:2]) # to skip the 2 elements
• print(list2[ : : -1]) # to reverse the List
(or)
• list2.reverse() # to reverse the list
• print(list2)

Prof J. Katyayani, T.Jahnavi


• # Creating a new list:
• list3 = [1, 2, 3 , 65, 12, 546, 0]
• # Using “sorted()” function:
• sorted() function rearranges the list in the
ascending / descending order but this doesn’t
change the original List
• print(sorted(list3))
• print(sorted(list3, reverse = True))
Prof J. Katyayani, T.Jahnavi
• # Using “sort()” function:
• sort() function rearranges the list in the
ascending / descending order and changes the
original List too.
• print(list3.sort(reverse = True))
• # Using “index()” function:
• This functions helps us to identify the index value
of the elements in the list.
• print(list3.index(546))

Prof J. Katyayani, T.Jahnavi


• # To count the elements from a list:
• List4 = [1, 12, 3, 4, 12, 13, 3, 12]
• list4.count(12) # we have to give the element in
the count function in order to identify the count
of that element.
• print(list4.count(3))
• # To change an element from the list:
• Mention the index number that to be changed
and assign the required value.
• list4[1] = 15

Prof J. Katyayani, T.Jahnavi


Tuple
• A Tuple is a ordered, unchanged (immutable)
and duplicate values can be present.
• They are same as List but works faster than
the Lists.
• Example:
• tuple1 = (1, 2, 3)
• To add data into the tuple we use
concatenation.
Prof J. Katyayani, T.Jahnavi
• # Concatenation:
• tuple1 = tuple1 + (4, 5, 6)
• print(tuple1)
• Tuples donot support item assignment
• tuple1[1] = 12 # it gives error.

Prof J. Katyayani, T.Jahnavi


• # Accessing of elements in tuple:
• animals = (‘lion’, ‘deer’, ‘fish’, 1, 2, 3, 3)
• Accessing elements:
• animals[2]
• animals.count(3) # to count duplicate values

Prof J. Katyayani, T.Jahnavi


Dictionary
• It is collection like list but unordered, can change
(mutable) and have index.
• No duplicate values are allowed.
• It has 2 elements namely “key” and “value”, we
name it “key-value pairs”.
• Example:
• sub = {‘a’: “FM”, ‘b’: “HRM”, ‘c’: “MM”}
• Here a,b,c are keys and FM, HRM, MM are values
of key, which are key value pairs.

Prof J. Katyayani, T.Jahnavi


Dictionary
Basic Operations
• sub [‘c’]
• sub.get(‘a’)
• # to change a value in the dictionary
• sub [‘b’] = ‘Python’
• # to add a value in the dictionary
• sub[‘d’] = “HRM”
• # to del a value in the dictionary
• del sub[‘a’]
• print(sub.pop(‘a’))
• print(sub.popitem()) # this returns a tuple with key
value pair. popitem function removes last item in dict
Prof J. Katyayani, T.Jahnavi
• # to get keys in the dictionary
• print(sub.keys())
• # to get values in the dictionary
• print(sub.values())
• # to get key-value pairs / items in the dictionary
• print(sub.items())

Prof J. Katyayani, T.Jahnavi


Set
• This is similar to mathematical set.
• It is unordered and no duplicate values are
allowed.
• Sets are mutable
• Index values are not present in set.
• So there is no chance of accessing of element like
other datatypes.
• Example:
• set1 = {‘lion’, 12, ‘lion’, 13, 10, 10, 12, ‘tiger’}

Prof J. Katyayani, T.Jahnavi


• set1 = {1, 2, 3, 4}
• print(set1)
• # to add elements
• print(set1.add(5))
• Functions:
1. union()
2. intersection()
3. difference()
4. symmetric_difference()
Prof J. Katyayani, T.Jahnavi
Example
• set1 = {1, 2, 3, 4}
• set2 = {3, 4, 5, 6}
• # union() function:
• print(set1.union(set2))
• # intersection() function:
• print(set1.intersection(set2))

Prof J. Katyayani, T.Jahnavi


• # difference() function:
• # the difference function removes the common
elements from sets and give the output to only
set1
• print(set1.difference(set2)) # output: (1,2)
• # symmetric_difference() function:
• # the symmetric_difference function removes the
common elements from sets and give the output
to both the sets
• print(set1.symmetric_difference(set2)) # output
(1, 2, 5, 6)
Prof J. Katyayani, T.Jahnavi
Parameters/ List [ ] Tuple ( ) Set { } Dictionary { }
Datatypes
Brace Square [ ] Round ( ) Curly { } Curly { }
Immutable No Yes Yes No
Duplicate Values Yes Yes No No
Accessing Yes Yes No Yes
elements
Index values Yes Yes No No
Elements Collection of Collection of Collection of Key Value Pairs
Simple data types Simple data types Simple data types
Ordered Yes Yes No No
Sequence

Prof J. Katyayani, T.Jahnavi


Type Conversion
1. int() - This function changes any data type to
integer data type
2. float() - This function changes any data type to
float data type
3. tuple() - This function changes any data type to
tuple
4. list() - This function changes any data type to list
5. set() - This function changes any data type to set
6. dict() - This function changes any data type to
dictionary

Prof J. Katyayani, T.Jahnavi


Range
• Range is used whenever we are iterating through values.
• 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.
• Sy: range(start, stop, step)
• Parameter Description:
• 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
increment. Default is 1

Prof J. Katyayani, T.Jahnavi


• Example:
1. x = range(6)
for n in x:
print(n)
# Create a sequence of numbers from 3 to 19, but
increment by 2 instead of 1:
2. x = range(3, 20, 2)
for n in x:
print(n)
3. x = range(3, 6)
for n in x:
print(n)
4. list(range(11))

Prof J. Katyayani, T.Jahnavi


Functions
• A function is a “Set of Instructions” to perform a
specific task.
• It reduces long blocks of code into a single
command, which avoids repetition.
• A function is a block of code which only runs
when it is called.
• You can pass data, known as parameters, into a
function.
• A function can return data as a result.

Prof J. Katyayani, T.Jahnavi


• We define the function with “def” keyword.
• Next we give the name for the function and
end with round braces with a colon.
• Next we enter the body of the function, it
should be intended.
• Variables used inside the body of function
cannot be used outside the function. If used
error appears. Hence called “Local Variables”.

Prof J. Katyayani, T.Jahnavi


• The output of the function will be passed to the
“return statement”.
• Return statement represents the “end” of the
function.
• A Python function will always have a return value.
There is no notion of procedure or routine in
Python.
• So, if you don’t explicitly use a return value in
a return statement, or if you totally omit
the return statement, then Python will implicitly
return a default value for you.
Prof J. Katyayani, T.Jahnavi
• Example:
def multiply():
• a=2
• b=3
• return a * b
multiply()
• a , b are local variables

Prof J. Katyayani, T.Jahnavi


• What if we want to change the values of
variables in the functions.
• We use “Parameters” instead of variables.
• From a function's perspective:
• A parameter is the variable listed inside the
parentheses in the function definition.
• An argument is the value that is sent to the
function when it is called.
Prof J. Katyayani, T.Jahnavi
• Example:
• def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))

• def multiply (a , b):


– print (a*b)
multiply( 2, 4)

# here a, b are parameters.


# here 2,4 are arguments.
Prof J. Katyayani, T.Jahnavi
Example
• def myfunction(a, b):
if(a > b):
return True # Return True
elif(a == b):
return 'A is Equal to B' # Return String
else:
return False # Return False
# Check Boolean
print(myfunction(10, 34)) # False
print(myfunction(10, 10)) # A is Equal to B
print(myfunction(22, 11)) # True

Prof J. Katyayani, T.Jahnavi


Example for Function
def about_me(name, profession, pet):
print(“Hi my name is”, name)
print(“I am a”, profession)
print(“and I have a”, pet)

about_me(“Suman”, “Manager”, “Cat”)


about_me(“Mohan”, “Student”, “puppy”)

Prof J. Katyayani, T.Jahnavi


Return Print()

Print the value of function on


Returns the value of a function as
terminal.
output.

The output of the function can be Output can not pass to other
pass to other function. function.

# working on return statement def addvalue(a, b):


# Print the value of a+b
def addvalue(a, b): print(a + b)
return a + b
addvalue(10, 34)
c = addvalue(10, 34)
print(c)

Prof J. Katyayani, T.Jahnavi


Built in Functions
• Python 3.6 version has 67 built in functions.
• Well known built in functions:
– print() append() insert()
– max() min() count()
– remove() reverse() range()
– int() float() tuple()
– list() set() dict()
– sorted() sort() pop()
– extend() while() for()
– upper() lower() type()
Prof J. Katyayani, T.Jahnavi
Function Description
abs() Returns the absolute value of a number
bin() Returns the binary version of a number
bool() Returns the boolean value of the specified object
chr() Returns a character from the specified Unicode code.
complex() Returns a complex number
enumerate() Takes a collection (e.g. a tuple) and returns it as an enumerate
object
eval() Evaluates and executes an expression
filter() Use a filter function to exclude items in an iterable object
format() Formats a specified value
getattr() Returns the value of the specified attribute (property or method)
help() Executes the built-in help system
hex() Converts a number into a hexadecimal value

Prof J. Katyayani, T.Jahnavi


Function Description
len() Returns the length of an object
list() Returns a list
map() Returns the specified iterator with the specified function
applied to each item
round() Rounds a numbers
setattr() Sets an attribute (property/method) of an object
slice() Returns a slice object
str() Returns a string object
reduce() Iterates over each item in a list, or any other iterable data
type, and returns a single value.
split() Breaks a string based on set criteria
strip() It repeatedly removes the first character from the string, if it
matches any of the supplied characters
join() It lets you merge string items in a list.
replace() It lets you replace some parts of a string with another
character.
Prof J. Katyayani, T.Jahnavi
Flow Control Statements
• A Flow Control Statement defines the flow of the
execution of the Program.
• The control flow of a Python program is regulated
by conditional statements, loops, and function
calls.
• Python has three types of control structures:
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.

Prof J. Katyayani, T.Jahnavi


Sequential
1. Sequential statements:
• These are a set of statements whose
execution process happens in a sequence.
• The problem with sequential statements is
that if the logic has broken in any one of the
lines, then the complete source code
execution will break.

Prof J. Katyayani, T.Jahnavi


• ## This is a Sequential statement
• a=20
• b=10
• c=a-b
• print("Subtraction is : ",c)

Prof J. Katyayani, T.Jahnavi


Selection/Decision control statements
2. Selection/Decision control statements:
• In Python, the selection statements are also
known as Decision control
statements or branching statements.
• The selection statement allows a program to
test several conditions and execute
instructions based on which condition is true.

Prof J. Katyayani, T.Jahnavi


• Some Decision Control Statements are:
– Simple if
– if-else
– nested if
– if-elif-else

Prof J. Katyayani, T.Jahnavi


Simple if
• If statements are control flow statements that
help us to run a particular code, but only when a
certain condition is met or satisfied.
• A simple if only has one condition to check.
• In simple words, if a certain condition is true then
a block of statement is executed otherwise not.
• Sy:
if condition:
statement1
statement2

Prof J. Katyayani, T.Jahnavi


Simple if

Prof J. Katyayani, T.Jahnavi


• Here, the condition after evaluation will be either
true or false. if the statement accepts boolean
values – if the value is true then it will execute
the block of statements below it otherwise not.
• We can use condition with bracket ‘(‘ ‘)’ also.
• As we know, python uses indentation to identify a
block. So the block under an if statement will be
identified as shown in the below example:

Prof J. Katyayani, T.Jahnavi


Example
1. n = 10
if n % 2 == 0:
print(n, “is an even number")

2. i = 10
if i > 25:
print("condition is satisfied")

Prof J. Katyayani, T.Jahnavi


if else
• The if-else statement evaluates the condition and
will execute the body of ‘if’ if the test condition is
True, but if the condition is False, then the body
of ‘else’ is executed.
• Sy:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Prof J. Katyayani, T.Jahnavi
if-else

Prof J. Katyayani, T.Jahnavi


Example
1. n = 10
if n % 2 == 0:
print(n, “is an even number")
else:
print(n, “is odd number”)

Prof J. Katyayani, T.Jahnavi


Example
We can give either ways for if else:
1. i = 10
if i > 25:
print("condition is satisfied")
print("condition is not satisfied")

2. i = 50
if i > 25:
print("condition is satisfied")
else:
print("condition is not satisfied")
Prof J. Katyayani, T.Jahnavi
Example
# python program to illustrate if else statement
i = 20
if (i < 15):
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")

Prof J. Katyayani, T.Jahnavi


nested if
• Nested if statements are an if statement inside another
if statement.
• With if...elif...else, elif is a shortened form of else if.
• It works the same as 'if' statements, where the if block
condition is false then it checks to elif blocks.
• If all blocks are false, then it executes an else
statement. There are multiple elif blocks possible for a
Nested if...else.
• Remember there is no condition statement associated
with else part of these flow control statements.

Prof J. Katyayani, T.Jahnavi


Prof J. Katyayani, T.Jahnavi
Syntax
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here

Prof J. Katyayani, T.Jahnavi


Example
a = 5;b = 10; c = 15
if a > b:
if a > c:
print("a value is big")
else: print("c value is big")
elif b > c:
print("b value is big")
else: print("c is big")

Prof J. Katyayani, T.Jahnavi


if-elif-else
• The if-elif-else statement is used to
conditionally execute a statement or a block
of statements

Prof J. Katyayani, T.Jahnavi


Example
1. num = 6.5
if num > 0:
print(num, "is a positive number")
elif num == 0:
print(num, "is zero")
else:
print(num, "is negative number")

Prof J. Katyayani, T.Jahnavi


2. x = 15; y = 12
if x == y:
print("Both are Equal")
elif x > y:
print("x is greater than y")
else:
print("x is smaller than y")

Prof J. Katyayani, T.Jahnavi


3. Repetition:
• A repetition statement is used to repeat a
group(block) of programming instructions.
• In Python, we generally have two
loops/repetitive statements:
• for loop
• while loop

Prof J. Katyayani, T.Jahnavi


for loop
• A for loop is used to iterate over a sequence
that is either a list, tuple, dictionary, or a set.
• We can execute a set of statements once for
each item in a list, tuple, or dictionary.
• The for loop statement has variable iteration
in a sequence(list, tuple or string) and
executes statements until the loop does not
reach the false condition

Prof J. Katyayani, T.Jahnavi


Flow chart for “for loop”

Prof J. Katyayani, T.Jahnavi


• A for loop is a control flow statement that executes
code for a predefined number of iterations. The
keyword used in this control flow statement is “for”.
When the number of iterations is already known, the
for loop is used.
• The for loop is divided into two parts −
• Header: The header part specifies the iteration of the
loop. In this part, the loop variable is also declared,
which tells the body which iteration is executed.
• Body: This part contains the statement executed per
iteration

Prof J. Katyayani, T.Jahnavi


• The initialization, condition checking, and iteration
statements are written at the beginning of the loop.
• It is used only when the number of iterations is known
beforehand.
• If the condition is not mentioned in the 'for' loop, then
the loop iterates the infinite number of times.
• The initialization is done only once, and it is never
repeated.
• The iteration statement is written at the beginning.
• Hence, it executes once all statements in the loop have
been executed.
Prof J. Katyayani, T.Jahnavi
• The flow of the for loop:
• Initialise the starting value
• Check that the starting value is less than the
stopping value.
• Execute the statement.
• Increment the starting value.
• Example:
• n = [1, 2, 3] # Initialization
• for i in n: # Condition and Updation
• print(i)
Prof J. Katyayani, T.Jahnavi
example
1. lst = [1, 2, 3, 4, 5]
for i in range(len(lst)):
print(lst[i], end = " ")

2. for j in range(0,10):
print(j, end = " ")

3. numbers = [6,5,3,8,4,2,5,4]
sum = 0
for val in numbers:
sum =sum + val
print("the sum is:", sum)
Prof J. Katyayani, T.Jahnavi
while loop
• In Python, while loops are used to execute a
block of statements repeatedly until a given
condition is satisfied.
• Then, the expression is checked again and, if it
is still true, the body is executed again.
• This continues until the expression becomes
false.

Prof J. Katyayani, T.Jahnavi


Flow chart

Prof J. Katyayani, T.Jahnavi


• A loop that runs a single statement or a set of
statements for a given true condition. This
loop is represented by the keyword "while."
• When the number of iterations is unknown, a
"while" loop is used.
• The statement is repeated until the boolean
value is false. Because the condition is tested
at the beginning of a while loop, it is also
known as the pre-test loop.

Prof J. Katyayani, T.Jahnavi


• The initialization and condition checking are done
at the beginning of the loop.
• It is used only when the number of iterations isn’t
known.
• If the condition is not mentioned in the 'while'
loop, it results in a compilation error.
• If the initialization is done when the condition is
being checked, then initialization occurs every
time the loop is iterated through.
• The iteration statement can be written within any
point inside the loop.
Prof J. Katyayani, T.Jahnavi
• The flow of the while loop:
• Initialise the starting value
• Check that the starting value is less than the
stopping value.
• Execute the statement.
• Increment the starting value

Prof J. Katyayani, T.Jahnavi


example
1. m = 5; i = 0
while i < m:
print(i, end = " ")
i=i+1
print("End")

Prof J. Katyayani, T.Jahnavi


2. Adding of natural numbers till n:
n = 20
add = 0
i=1
while i <= n:
add = add + i
i = i +1
Print(“the sum is”, add)

Prof J. Katyayani, T.Jahnavi


Difference b/w for and while loops

Basis of Comparison For Loop While Loop


Keyword Uses for keyword Uses while keyword
Used For loop is used when the While loop is used when the
number of iterations is number of iterations is
already known. already Unknown.
absence of condition The loop runs infinite times Returns the compile time
error
Nature of Initialization Once done, it cannot be In the while loop, it can be
repeated repeated at every iteration.
Functions To iterate, the range or There is no such function in
xrange function is used. the while loop.

Initialization based on To be done at the beginning It is possible to do this


iteration of the loop. anywhere in the loop body.
Speed The for loop is faster than While loop is relatively
the while loop. slower as compared to for
Prof J. Katyayani, T.Jahnavi loop.
Break statement
• The Python Break statement is used to break a
loop in a certain condition.
• It terminates the loop. Also, we can use it
inside the loop then it will first terminate the
innermost loop.

Prof J. Katyayani, T.Jahnavi


Example
1. for a in “python”:
if a == ‘h’:
break
print(a)

print(“Loop ends”)

Prof J. Katyayani, T.Jahnavi


2. for num in range(0,10):
if num == 5:
break
print('Iteration:', num)

Prof J. Katyayani, T.Jahnavi


Continue Statement
• A continue statement won’t continue the
loop, it executes statements until the
condition matches True.

Prof J. Katyayani, T.Jahnavi


Example
1. for a in “python”:
if a == “h”:
continue
print(a)
print(“Loop ends”)

Prof J. Katyayani, T.Jahnavi


2. for num in range(0,10):
if num == 5:
continue
print('Iteration:', num)

Prof J. Katyayani, T.Jahnavi


Pass
• The pass statement in Python is used when a
statement or a condition is required to be
present in the program, but we don’t want
any command or code to execute. It’s typically
used as a placeholder for future code

Prof J. Katyayani, T.Jahnavi


1. for a in “python”:
if a == “h”:
pass
print(a)
print(“Loop ends”)

Prof J. Katyayani, T.Jahnavi


2. for num in range(0,10):
if num == 5:
pass
print('Iteration: ‘, num)

Prof J. Katyayani, T.Jahnavi


Classes/Objects
• Python is an object oriented programming
language.
• Almost everything in Python is an object, with
its properties and methods.
• A Class is like an object constructor, or a
"blueprint" for creating objects.

Prof J. Katyayani, T.Jahnavi


• Before creating an “object” we have to create
“class”.
• We can create class by giving “class” key word
and a name to it and end with “:” .
• Eg: class class_name:
• After creating a class, the body of the class has
2 elements:
i. Attributes
ii. Behaviour

Prof J. Katyayani, T.Jahnavi


• Attributes: these are variables.
• Behaviour: also called Methods.
• Methods are nothing but the functions. If
Functions are part of the class we call it as
Methods.

Prof J. Katyayani, T.Jahnavi


• Create a Class:
• To create a class, use the keyword ‘class’:
• Example
• Create a class named MyClass, with a property
named x.
class MyClass:
x=5

Prof J. Katyayani, T.Jahnavi


• Create Object:
• Now we can use the class named MyClass to
create objects:
• Example:
• Create an object named p1, and print the
value of x:
p1 = MyClass()
print(p1.x)
Prof J. Katyayani, T.Jahnavi

You might also like