Day 4 Machine Learning
Day 4 Machine Learning
Day 4
LOOPS
Python - Loops
Syntax
The syntax of a while loop in Python programming language is −
while expression: statement(s)
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.
flag = 1
while (flag): print 'Given flag is really true!'
print "Good bye!"
range() Function
Parameter Values
Parameter Description
start An integer number specifying at which position to
start. Default is 0
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
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:
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:
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.
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.
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)
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’.
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.
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
Example
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.
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.
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.
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.
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.
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.
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.
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
Note: If the item to remove does not exist, remove() will raise an error.
Removing Item from a Set
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)