0% found this document useful (0 votes)
36 views65 pages

Day 4 Machine Learning

The document discusses Python loops and tuples. It explains while, for and nested loops in Python with examples. It also covers topics like else statement with loops, break, continue statements, tuple operations, indexing, slicing and built-in functions for tuples.

Uploaded by

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

Day 4 Machine Learning

The document discusses Python loops and tuples. It explains while, for and nested loops in Python with examples. It also covers topics like else statement with loops, break, continue statements, tuple operations, indexing, slicing and built-in functions for tuples.

Uploaded by

nisha gautam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 65

Machine Learning

Day 4
LOOPS
Python - Loops

A loop statement allows us to execute a statement


or group of statements multiple times.
Python While Loop Statements
A while loop statement in Python programming language
repeatedly executes a target statement as long as a given
condition is true.

Syntax
The syntax of a while loop in Python programming language is −
while expression: statement(s)

Here, statement(s) may be a single statement or a block of statements.


The condition may be any expression, and true is any non-zero value.
The loop iterates while the condition is true
.
When the condition becomes false, program control passes to the line
immediately following the loop.
Python While Loop Statements
Python While Loop Statements
Example
count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
print "Good bye!“

The Infinite Loop

var = 1
while (var == 1) : # This constructs an infinite loop
num = input("Enter a number :")
print("You entered: ", num)
print "Good bye!"
Using else Statement with Loops
Python supports to have an else statement associated with
a loop statement.
If the else statement is used with a for loop, the else
statement is executed when the loop has exhausted
iterating the list.
If the else statement is used with a while loop, the else
statement is executed when the condition becomes false.
The following example illustrates the combination of an
else statement with a while statement that prints a number
as long as it is less than 5, otherwise else statement gets
executed.
Using else Statement with Loops
Example

count = 0
while count < 5:
print count, " is less than 5"
count = count + 1
else:
print count, " is not less than 5"
Single Statement Suites
Similar to the if statement syntax, if your while clause
consists only of a single statement, it may be placed on the
same line as the while header.

Here is the syntax and example of a one-line while clause −

flag = 1
while (flag): print 'Given flag is really true!'
print "Good bye!"

It is better not try above example because it goes into


infinite loop and you need to press CTRL+C keys to exit.
Python for Loop Statements
It has the ability to iterate over the items of any sequence,
such as a list or a string.
Syntax
for iterating_var in sequence:
statements(s)

If a sequence contains an expression list, it is evaluated


first. Then, the first item in the sequence is assigned to the
iterating variable iterating_var. Next, the statements block
is executed. Each item in the list is assigned to
iterating_var, and the statement(s) block is executed until
the entire sequence is exhausted.
Python for Loop Statements
Python for Loop Statements
Example
for letter in 'Python':
print ('Current Letter :', letter)
fruits = ['banana', 'apple', 'mango']
for fruit in fruits:
print ('Current fruit :', fruit)
print ("Good bye!”)

Iterating by Sequence Index


fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print ('Current fruit :', fruits[index])
print "Good bye!"
Python for Loop Statements

range() Function

The range() function returns a sequence of numbers,


starting from 0 by default, and increments by 1 (by
default), and ends at a specified number.
Ex-
x = range(6)
for n in x:
print(n)
Python for Loop Statements
range() Function

Parameter Values

Parameter Description
start An integer number specifying at which position to
start. Default is 0

stop An integer number specifying at which position to


end.

step An integer number specifying the incrementation.


Default is 1
Python for Loop Statements
range() Function
Example
Create a sequence of numbers from 3 to 5, and print each
item in the sequence:
x = range(3, 6)
for n in x:
print(n)
Example
Create a sequence of numbers from 3 to 19, but
increment by 2 instead of 1:
x = range(3, 20, 2)
for n in x:
print(n)
Python nested loops
Python programming language allows to use one loop
inside another loop. Following section shows few examples
to illustrate the concept.

Syntax
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
Python nested loops
Example
The following program uses a nested for loop to find the
prime numbers from 2 to 100 −

i=2
while(i < 100):
j=2
while(j <= (i/j)):
if not(i%j): break
j=j+1
if (j > i/j) : print( i, " is prime”)
i=i+1
print "Good bye!"
Loop Control Statements

break statement Terminates the loop statement and


transfers execution to the statement immediately
following the loop.
continue statement Causes the loop to skip the
remainder of its body and immediately retest its
condition prior to reiterating.
Python break statement

for i in range(9):
if i > 3:
break
print(i)
Python continue statement

for i in range(9):
if i == 3:
continue
print(i)
Python - Tuples
A tuple is a sequence of immutable Python objects. Tuples are
sequences, just like lists. The differences between tuples and lists are,
the tuples cannot be changed unlike lists and tuples use parentheses,
whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-separated
values. Optionally you can put these comma-separated values between
parentheses also. For example −
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"
Accessing Values in Tuples
To access values in tuple, use the square brackets for slicing along with
the index or indices to obtain value available at that index. For example-
Return the item in position 1:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
Change Tuple Values
Once a tuple is created, you cannot change its values.
Loop Through a Tuple

You can loop through the tuple items by using a for loop.
Iterate through the items and print the values:

thistuple = ("apple", "banana", "cherry")


for x in thistuple:
print(x)
Check if Item Exists

To determine if a specified item is present in a tuple use the in


keyword:
Check if "apple" is present in the tuple:
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
Find Tuple Length
To determine how many items a tuple has, use the len() method:
Print the number of items in the tuple:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))
Add Items

Once a tuple is created, you cannot add items to it. Tuples are
unchangeable.
You cannot add items to a tuple:
thistuple = ("apple", "banana", "cherry")
thistuple[3] = "orange" # This will raise an error
print(thistuple)
Remove Items

Tuples are unchangeable, so you cannot remove items from it, but
you can delete the tuple completely:

The del keyword can delete the tuple completely:


thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists
The tuple() Constructor

It is also possible to use the tuple() constructor to make a tuple.

Using the tuple() method to make a tuple:


thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)
Basic Tuples Operations
Tuples respond to the + and * operators much like strings; they mean
concatenation and repetition here too, except that the result is a new tuple,
not a string.

In fact, tuples respond to all of the general sequence operations we used on


strings in the prior chapter −

Python Expression Results Description


len((1, 2, 3)) 3 Length
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation
('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition
3 in (1, 2, 3) True Membership
for x in (1, 2, 3): print x, 123 Iteration
Indexing, Slicing, and Matrixes
Because tuples are sequences, indexing and slicing work the same way for
tuples as they do for strings. Assuming following input −

L = ('spam', 'Spam', 'SPAM!')

Python Expression Results Description


L[2] 'SPAM!' Offsets start at zero
Negative: count from the
L[-2] 'Spam' right
L[1:] ['Spam', 'SPAM!'] Slicing fetches sections
Built-in Tuple Functions
len() Method
The method len() returns the number of elements in the tuple.
Following is the syntax for len() method −
len(tuple)

Parameters
tuple − This is a tuple for which number of elements to be
counted.
Built-in Tuple Functions
max() Method
The method max() returns the elements from the tuple with
maximum value.

Following is the syntax for max() method −


max(tuple)

Parameters
tuple − This is a tuple from which max valued element to be
returned.
Built-in Tuple Functions
min() Method
The method min() returns the elements from the tuple with
minimum value.

Following is the syntax for min() method −


min(tuple)

Parameters
tuple − This is a tuple from which min valued element to be
returned.
Where use tuple
Using tuple instead of list is used in the following scenario.

Using tuple instead of list gives us a clear idea that tuple data is
constant and must not be changed.
List Vs Tuple
List Tuple
The literal syntax of list is shown by the The literal syntax of the tuple is shown
[]. by the ().
The List is mutable. The tuple is immutable.
The List has the variable length. The tuple has the fixed length.

The list provides more functionality The tuple provides less functionality
than tuple. than the list.

The list is used in the scenario in which The tuple is used in the cases where
we need to store the simple collections we need to store the read-only
with no constraints where the value of collections i.e., the value of the items
the items can be changed. can not be changed. It can be used as
the key inside the dictionary.
Nesting List and tuple
We can store list inside tuple or tuple inside the list up to
any number of level.
Lets see an example of how can we store the tuple inside
the list.

Employees =
[(101, "Ayush", 22), (102, "john", 29), (103, "james", 45), (104, "Ben",
34)]
print("----Printing list----");
for i in Employees:
print(i)
Employees[0] = (110, "David",22)
print("----Printing list after modification----");
for i in Employees:
print(i)
Convert List to Tuple

l = [4,5,6]
t=tuple(l)
print(t)

Convert Tuple to List

t = (4,5,6)
l=list(t)
print(l)
Python Dictionary
Dictionary in Python is an unordered collection of data values, used to store
data values like a map, which unlike other Data Types that hold only single
value as an element, Dictionary holds key: value pair. Key value is provided in
the dictionary to make it more optimized. Each key-value pair in a Dictionary
is separated by a colon :, whereas each key is separated by a ‘comma’.

A Dictionary in Python works similar to the Dictionary in a real world. Keys of


a Dictionary must be unique and of immutable data type such as Strings,
Integers and tuples, but the key-values can be repeated and be of any type.

Note – Dictionary keys are case sensitive, same name but different cases of
Key will be treated distinctly.
Python Dictionary
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Properties of Dictionary Keys
Dictionary values have no restrictions. They can be any arbitrary Python
object, either standard objects or user-defined objects. However, same is not
true for the keys.

(a) More than one entry per key not allowed. Which means no duplicate key
is allowed. When duplicate keys encountered during assignment, the last
assignment wins.

(b) Keys must be immutable. Which means you can use strings, numbers or
tuples as dictionary keys but something like ['key'] is not allowed.
Accessing Items

You can access the items of a dictionary by referring to its key name, inside
square brackets:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Get the value of the "model" key:
x = thisdict["model"]

There is also a method called get() that will give you the same result:
Get the value of the "model" key:
x = thisdict.get("model")
Change or Add Elements in a Dictionary
Dictionary are mutable. We can add new items or change the value of
existing items using assignment operator.

If the key is already present, value gets updated, else a new key: value pair is
added to the dictionary.

my_dict = {'name':'Jack', 'age': 26}


my_dict['age'] = 27
print(my_dict)
my_dict['address'] = 'Downtown'
print(my_dict)
Delete or Remove Elements from a Dictionary

We can remove a particular item in a dictionary by using the method pop().


This method removes as item with the provided key and returns the value.

The method, popitem() can be used to remove and return an arbitrary item
(key, value) from the dictionary. All the items can be removed at once using
the clear() method.

We can also use the del keyword to remove individual items or the entire
dictionary itself.
Delete or Remove Elements from a Dictionary

# create a dictionary # delete a particular item


squares = {1:1, 2:4, 3:9, 4:16, 5:25} del squares[5]
# remove a particular item # Output: {2: 4, 3: 9}
# Output: 16 print(squares)
print(squares.pop(4))
# remove all items
# Output: {1: 1, 2: 4, 3: 9, 5: 25} squares.clear()
print(squares)
# Output: {}
# remove an arbitrary item print(squares)
# Output: (1, 1)
# delete the dictionary itself
print(squares.popitem())
del squares
# Output: {2: 4, 3: 9, 5: 25}
# Throws Error
print(squares)
#print(squares)
Loop Through a Dictionary
You can loop through a dictionary by using a for loop.
When looping through a dictionary, the return value are the keys of the
dictionary, but there are methods to return the values as well.
Print all key names in the dictionary, one by one:
for x in thisdict:
print(x)
Print all values in the dictionary, one by one:
for x in thisdict:
print(thisdict[x])
You can also use the values() function to return values of a dictionary:
for x in thisdict.values():
print(x)
Loop through both keys and values, by using the items() function:
for x, y in thisdict.items():
print(x, y)
Check if Key Exists
To determine if a specified key is present in a dictionary use the in keyword:

Example

Check if "model" is present in the dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Functions
len()
The method len() gives the total length of the dictionary. This would be equal to
the number of items in the dictionary.

Following is the syntax for len() method −


len(dict)

Parameters
dict − This is the dictionary, whose length needs to be calculated.

Return Value
This method returns the length.
Functions
str()
The method str() produces a printable string representation of a dictionary.

Following is the syntax for str() method −


str(dict)

Parameters
dict − This is the dictionary.

Return Value
This method returns string representation.
Functions
type()
The method type() returns the type of the passed variable. If passed variable is
dictionary then it would return a dictionary type.

Following is the syntax for type() method −


type(dict)

Parameters
dict − This is the dictionary.

Return Value
This method returns the type of the passed variable.
Dictionary Methods
clear() Method
The clear() method removes all the elements from a dictionary.

Remove all elements from the car list:


car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.clear()
print(car)
Dictionary Methods
copy() Method
The copy() method returns a copy of the specified dictionary.

Copy the car dictionary:


car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.copy()

print(x)
Dictionary Methods
fromkeys() Method
The fromkeys() method returns a dictionary with the specified keys
and values.
Create a dictionary with 3 keys, all with the value 0:
x = ('key1', 'key2', 'key3')
y=0

thisdict = dict.fromkeys(x, y)

print(thisdict)
Dictionary Methods
get() Method
The get() method returns the value of the item with the specified
key.

Get the value of the "model" item:


car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.get("model")
print(x)
Dictionary Methods
keys() Method
The keys() method returns a view object. The view object contains
the keys of the dictionary, as a list.
The view object will reflect any changes done to the dictionary,
see example below.
Return the keys:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
print(x)
Dictionary Methods
pop() Method
The pop() method removes the specified item from the dictionary.
Remove "model" from the dictionary:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

car.pop("model")

print(car)
Dictionary Methods
update() Method
The update() method inserts the specified items to the dictionary.

Insert an item to the dictionary:


car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

car.update({"color": "White"})
print(car)
Dictionary Methods
values() Method
The values() method returns a view object. The view object
contains the values of the dictionary, as a list.

Return the values:


car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x)
Python - Sets
Mathematically a set is a collection of items not in any
particular order. A Python set is similar to this mathematical
definition with below additional conditions.

• The elements in the set cannot be duplicates.


• The elements in the set are immutable(cannot be
modified) but the set as a whole is mutable.
• There is no index attached to any element in a python set.
So they do not support any indexing or slicing operation.
Creating a set
A set is created by using the set() function or placing all the
elements within a pair of curly braces.

Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
Months={"Jan","Feb","Mar"}
Dates={21,22,17}
print(Days)
print(Months)
print(Dates)
Accessing Values in a Set
We cannot access individual values in a set. We can only
access all the elements together as shown above. But we can
also get a list of individual elements by looping through the
set.

Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
for d in Days:
print(d)
Adding Items to a Set
We can add elements to a set by using add() method. Again
as discussed there is no specific index attached to the newly
added element.

Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])
Days.add("Sun")
print(Days)
Removing Item from a Set

Remove Item

We can remove elements from a set by using discard()


method.
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)

Note: If the item to remove does not exist, remove() will raise an error.
Removing Item from a Set

Remove the item by using the discard() Method

Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])
Days.discard("Sun")
print(Days)
Note: If the item to remove does not exist, discard() will
NOT raise an error.
Union of Sets
The union operation on two sets produces a new set
containing all the distinct elements from both the sets. In the
below example the element “Wed” is present in both the
sets.

DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA|DaysB
print(AllDays)
Intersection of Sets
The intersection operation on two sets produces a new set
containing only the common elements from both the sets. In
the below example the element “Wed” is present in both the
sets.

DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA & DaysB
print(AllDays)
Difference of Sets
The difference operation on two sets produces a new set
containing only the elements from the first set and none
from the second set. In the below example the element
“Wed” is present in both the sets so it will not be found in
the result set.

DaysA = set(["Mon","Tue","Wed"])
DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
AllDays = DaysA - DaysB
print(AllDays)

You might also like