Lab 02 Tools and Techniques For Data Science
Lab 02 Tools and Techniques For Data Science
1
Integers
1.2,-0.5,2e2,3E2
Floating-point numbers
TIP: Use object names to keep better track of what’s going on in your code!
[2]: #performing calculation by using variables
my_taxes = my_income*tax_rate
[3]: 10.0
OR
[4]: # printing the variable
print(my_taxes)
10.0
1.3.1 Task 1
Calculate the area of a rectangle having length of 15 cm and width of 10 cm. Use variable assignment
and perform calculations using variables. Also display the result.
[ ]: # Assign values to variables
[ ]: # Perform Calculation
2
[ ]: # Display the result
1.4 Booleans
Python comes with Booleans (with predefined True and False displays that are basically just the
integers 1 and 0). Let’s walk through a few quick examples of Booleans.
[3]: #Show
a
[3]: True
[4]: 3>2
[4]: True
We can also use comparison operators to create booleans. We will go over all the comparison
operators later on in the course.
[3]: # Output is boolean
1 > 2
[3]: False
[4]: type(4)
[4]: int
[5]: type(3.14)
[5]: float
[6]: int(False)
[6]: 0
[7]: type("True")
[7]: str
3
2 Strings
Strings are used in Python to record text information, such as names. Strings in Python are actually
a sequence, which basically means Python keeps track of every element in the string as a sequence.
For example, Python understands the string ”hello’ to be a sequence of letters in a specific order.
In this lecture we’ll learn about the following:
1.) Creating Strings
2.) Printing Strings
hello123
The reason for the error above is because the single quote in I’m stopped the string. You can use
combinations of double and single quotes to get the complete statement.
[5]: "I'm using single quotes, but this will create an error'"
[5]: "I'm using single quotes, but this will create an error'"
4
2.2 Printing a String
Using Jupyter notebook with just a string in a cell will automatically output strings, but the correct
way to display strings in your output is by using a print function.
[6]: # We can simply declare a string
'Hello World'
Hello World 1
Hello World 2
Use
to print a new line
[46]: 'l'
5
[11]: 'hello concatenate me!'
[14]: letter*10
[14]: 'zzzzzzzzzz'
2.3.1 Task 2
Make a string having your name and print it 5 times.
[15]: # string assignment
3 Lists
Lists can be thought of the most general version of a sequence in Python. Unlike strings, they are
mutable, meaning the elements inside a list can be changed!
In this section we will learn about:
1.) Creating lists
2.) Indexing and Slicing Lists
3.) Nesting Lists
Lists are constructed with brackets [] and commas separating every element in the list.
Let’s go ahead and see how we can construct lists!
[17]: # Assign a list to an variable named my_list
my_list=[1,2,3]
[18]: my_list
[18]: [1, 2, 3]
We just created a list of integers, but lists can actually hold different object types. For example:
[19]: my_list = ['A string',23,100.232,'o']
6
[20]: my_list
[22]: 'one'
You can always access the indices in reverse. For example working according to the index, my_list[0]
will be the first item and my_list[-1] will be the last one. Try the fowwlowing code.
[25]: 5
Try yourself!
[35]: # Grab the second last index in reverse
7
3.0.2 Checking the type
[36]: type(my_list)
[36]: list
[37]: int
3.0.3 Task 3
Suppose we have a list containing areas of different rooms. Complete the given tasks using indexing
and slicing.
[38]: # The list having areas of 6 rooms respectively
area=[28.3, 45.9, 123.4, 555, 213, 121]
[40]: # Show the areas of rooms first three rooms in the list
[43]: my_new
Note that lists are mutable objects i.e. a separate index can be changed through indexing
[45]: #mutable list objects can be changed
my_new[0]= 1
my_new
You would have to reassign the list to make the change permanent.
8
[46]: # Reassign
my_list = my_list + [1]
[47]: my_list
[49]: my_list*3
[49]: ['one',
'two',
'three',
4,
5,
1,
'one',
'two',
'three',
4,
5,
1,
'one',
'two',
'three',
4,
5,
1]
4 Dictionaries
We’ve been learning about sequences in Python but now we’re going to switch gears and learn about
mappings in Python. If you’re familiar with other languages you can think of these Dictionaries as
hash tables.
This section will serve as a brief introduction to dictionaries and consist of:
1.) Constructing a Dictionary
9
2.) Accessing objects from a dictionary
3.) Nesting Dictionaries
So what are mappings? Mappings are a collection of objects that are stored by a key, unlike a
sequence that stored objects by their relative position. This is an important distinction, since
mappings won’t retain order since they have objects defined by a key.
A Python dictionary consists of a key and then an associated value. That value can be almost any
Python object.
[3]: 'value2'
Its important to note that dictionaries are very flexible in the data types they can hold. For
example:
[4]: my_dict = {'key1':123,'key2':[12,23,33],'key3':['item0','item1','item2']}
[6]: dict
[9]: 123
10
[11]: #Check
my_dict['key1']
[11]: 0
We can also create keys by assignment. For instance if we started off with an empty dictionary, we
could continually add to it:
[12]: # Create a new dictionary
d = {}
[15]: #Show
d
[18]: d
[19]: 'value'
11
#print europe
5 Tuples
In Python tuples are very similar to lists, however, unlike lists they are immutable meaning they
can not be changed. You would use tuples to present things that shouldn’t be changed, such as
days of the week, or dates on a calendar.
In this section, we will get a brief overview of the following:
1.) Constructing Tuples
2.) Immutability
3.) When to Use Tuples
You’ll have an intuition of how to use tuples based on what you’ve learned about lists. We can
treat them very similarly with the major distinction being that tuples are immutable.
# Show
t
[28]: ('one', 2)
[29]: 'one'
[30]: 2
5.2 Immutability
It can’t be stressed enough that tuples are immutable. To drive that point home:
[31]: t[0]= 'change' # what will be the output of this?
12
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-31-9ca178c8039b> in <module>
----> 1 t[0]= 'change' # what will be the output of this?
Because of this immutability, tuples can’t grow. Once a tuple is made we can not add to it.
[32]: t.append('nope')
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-32-b75f5b09ac19> in <module>
----> 1 t.append('nope')
6 Sets
Sets are an unordered collection of unique elements. We can construct them by using the set()
function. Let’s go ahead and make a set to see how it works
[26]: x = set()
[27]: type(x)
[27]: set
[29]: #Show
x
[29]: {1}
13
Note the curly brackets. This does not indicate a dictionary! Although you can draw analogies as
a set being a dictionary with only keys.
We know that a set has only unique entries. So what happens when we try to add something that
is already in a set?
[30]: # Add a different element
x.add(2)
# show
x
[30]: {1, 2}
[31]: {1, 2}
Notice how it won’t place another 1 there. That’s because a set is only concerned with unique
elements! We can cast a list with multiple repeat elements to a set to get the unique elements. For
example:
[32]: # Create a list with repeats
list1 = [1,1,2,2,3,4,5,6,1,1]
[33]: {1, 2, 3, 4, 5, 6}
7 Task
[33]: # convert 80 into float type,
# convert 20.9 into a string and check its type
# convert a boolean valua into int
# convert '123' into float
14
[34]: float(10)
[34]: 10.0
[35]: a=55.5
[36]: int(a)
[36]: 55
[41]: a=11.5
b=5
r=a%b
[42]: r
[42]: 1.5
8 Tasks
8.0.1 Question#01
a). Create a list with the following elements 1, hello, [1,2,3] and True.
b). Find the value stored at index 1.
c). Retrieve the elements stored at index 1, 2 and 3 of above created list.
d). Concatenate the following lists
A = [1, ‘a’] B = [2, 1, ‘d’]:
8.0.2 Question#02
You will need this dictionary for part a and b: yourname = {“The Bodyguard”:“1992”, “Saturday
Night Fever”:“1977”}
a). In the dictionary soundtrack_dict what are the keys ?
b). In the dictionary soundtrack_dict what are the values ?
The Albums Back in Black, The Bodyguard and Thriller have the following music recording sales
in millions 50, 50 and 65 respectively:
c). Create a dictionary album_sales_dict where the keys are the album name and the sales in
millions are the values.
d). Use the dictionary to find the total sales of Thriller.
e). Find the names of the albums from the dictionary using the method keys.
f). Find the names of the recording sales from the dictionary using the method values.
8.0.3 Question#03
Consider the following tuple:
15
genres_tuple = (“pop”, “rock”, “soul”, “hard rock”, “soft rock”, “R&B”, “progressive rock”,
“disco”)
a). Find the length of the tuple?
b). Access the element, with respect to index 3.
c). Use slicing to obtain indexes 3, 4 and 5.
d). Find the first two elements of the tuple.
e). Find the first index of “disco”.
f). Generate a sorted List from the Tuple C_tuple=(-5, 1, -3).
[ ]:
16