Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

9/8/22, 7:18 PM Data_Types_Operators.

ipynb - Colaboratory

Code Text

Data Types and Operators


Welcome to this lesson on Data Types and Operators! You'll learn about:
Data Types: Integers, Floats, Booleans, Strings, Lists, Tuples, Sets, Dictionaries

Operators: Arithmetic, Assignment, Comparison, Logical, Membership, Identity

Built-In Functions, Compound Data Structures, Type Conversion

Whitespace and Style Guidelines

1. Print() function in python:


You will be seeing this print function very frequently in python programming. It helps us to see
what exactly is happening in our code.

Try to run the next lines of code and see what happens next:

2+7
2*7

You will see that even though you had written 2 lines of code only the last line of code gets
seen in the output area.

Now this happens because you haven't told python what to alctually do with it.

This is where print() comes in. print() in python is a useful builtin function that we can use to
display input value as text in the output.

print(2+7)
print(2*7)

print('Hello World!!!!')

4. Variables:

Understanding variables is very important in any programming language they are used all the
time in python. Using variables in place of direct numbers have many advantages. Variables are

https://colab.research.google.com/github/ShapeAI/Python-and-Machine-Learning/blob/main/Important_concepts_in_python.ipynb 1/22
9/8/22, 7:18 PM Data_Types_Operators.ipynb - Colaboratory

used to store information to be referenced and manipulated in a computer program.

Creating a new variable in python is very simple, lets create one together, here in this example
below the variable name is month, the equal sign is the assignment operator and the value of the
variable is 12.

month=12

print(month)

Now its your turn create a variable named rent with its value being 1700

# create and print the varibale rent down below

Expected output:

1700

In any case, whatever term is on the left side, is now a name for whatever value is on the right
side. Once a value has been assigned to a variable name, you can access the value from the
variable name.

For example if we run this code we will get 3 as the output here as in the first line we assigned 3
to a and in the second line we assigned a to b so when we print b we get 3 as the output.

a=3

b=a

print(b)

If we don't declare the variable and try to print the output then we will get the following error

print(x)

5. Multiple Assignment Operator:


Suppose you are making a program where in you enter the dimensions of the tank and it will give
the volume of the tank as the output. So you can write code as:

height = 3

length = 6

width = 2

volume = height * length * width

print(volume)

https://colab.research.google.com/github/ShapeAI/Python-and-Machine-Learning/blob/main/Important_concepts_in_python.ipynb 2/22
9/8/22, 7:18 PM Data_Types_Operators.ipynb - Colaboratory

Now python has a very useful way to assign multiple variables together in a single line using
multiple assignment like this:

# this will now assign 3 to height, 6 to length and 2 to width just as before.

height , length , width = 3 , 6 , 2

volume = height * length * width

print(volume)

6. Variable Naming Conventions:


There are some rules we need to follow while giving a name for a Python variable.

Rule-1: You should start variable name with an alphabet or underscore(_) character.
Rule-2: A variable name can only contain A-Z,a-z,0-9 and underscore(_).
Rule-3: You cannot start the variable name with a number.
Rule-4: You cannot use special characters with the variable name such as such as
$,%,#,&,@.-,^ etc.
Rule-5: Variable names are case sensitive. For example str and Str are two different
variables.
Rule-6: Do not use reserve keyword as a variable name for example keywords like class,
for, def, del, is, else, try, from, etc. more examples are given below and as we go through
the course we will come across many more. Creating names that are descriptive of the
values often will help you avoid using any of these words.

#Allowed variable names

x=2

y="Hello"

mypython="PythonGuides"

my_python="PythonGuides"

_my_python="PythonGuides"

_mypython="PythonGuides"

MYPYTHON="PythonGuides"

myPython="PythonGuides"

myPython7="PythonGuides"

#Variable name not Allowed

7mypython="PythonGuides"

-mypython="PythonGuides"

myPy@thon="PythonGuides"

my Python="PythonGuides"

for="PythonGuides"

https://colab.research.google.com/github/ShapeAI/Python-and-Machine-Learning/blob/main/Important_concepts_in_python.ipynb 3/22
9/8/22, 7:18 PM Data_Types_Operators.ipynb - Colaboratory

#It shows invalid syntax. 

#It will execute one by one and will show the error.

Also there are some naming convention that needs to be followed like:

try to keep the name of the variables descriptive short but descriptive. for example: when
taking inputs for the height of a tree of a box the appropriate variable name will be just
height not x not h not height_of_the_tree.

Also the pythonic way to name variables is to use all lowercase letters and underscores to
separate words.

# pythonic way

my_height = 58

my_lat = 40

my_long = 105

# not pythonic way

my height = 58 # wont work

MYLONG = 40    # will work still avoid using it

MyLat = 105    # will work still avoid using it

Though the last two of these would work in python, they are not pythonic ways to name
variables. The way we name variables is called snake case, because we tend to connect the
words with underscores.

What if we want to change or update the value of a variable for example take the example of rent
= 1700, suppose the rent has hiked and the new rent is 2000 we can just assign the variable its
new value as:

rent = 1700

rent = 2000

print(rent)

This is called overwriting the variable , i.e, When a new value is assigned to a variable, the old
one is forgotten.

If we had then caused some damages to the property during our crazy house party and we have
to pay for them then we can just apply these changes directly to this variable.

rent = 1700

rent = 2000

https://colab.research.google.com/github/ShapeAI/Python-and-Machine-Learning/blob/main/Important_concepts_in_python.ipynb 4/22
9/8/22, 7:18 PM Data_Types_Operators.ipynb - Colaboratory

rent =rent + 700

print(rent)

in the line 3 the variable rent is being assigned to itself plus 700 which results to 2700.

Because such increment and assignment operations are very common python has a very special
assignment operator for this.

rent = 1700

rent = 2000

rent += 700

print(rent)

we can actually use this += operator to tell python that we are incrementing the value on the left
by the value on the right. += is a example of assignment operator -= *= /= are some more
examples of assignment operators. All of these operators just apply arithmetic operation to the
variable on the left with the value on the right which makes your code more concise and easier
to read and understand.

7. Integers and Floats:


So far the numbers that we have dealt with were mostly whole numbers or integers, but as you
may have notices that other types of numbers also do exist. For example dividing one integer by
another gives us a number that isn't an integer, in python we represent such a number as a float,
which is short for floating point number.

print(3/2)

Numbers with a decimal point, such as 3.14, are called floating-point numbers (or floats). Note
that even though the value 42 is an integer, the value 42.0 would be a floating-point number. And
if 2 integers are divided then also we get float as an answer.

You can check the datatype of any value by using the builtin function of type, that returns the
type of an object. Here as you can see they type of a number without a decimal and the type of a
number with a decimal.

a = 3

b = 2.5

print(type(a))

print(type(b))

https://colab.research.google.com/github/ShapeAI/Python-and-Machine-Learning/blob/main/Important_concepts_in_python.ipynb 5/22
9/8/22, 7:18 PM Data_Types_Operators.ipynb - Colaboratory

An operation involving an int and a float will always give float as its output. We can also covert
one datatype to another by constructing new objects of those types with int and float.

When we convert a float to an int the part after the decimal point is dropped and hence there is
no rounding. eg 28.9 will be cut to 28.

Similarly converting int to float just adds a decimal at the end of the number and a 0 after that.
example 3 will become 3.0

a = float(3)

b = int(28.9)

print(a)

print(b)

Another point that you need to keep in mind is float are an approximation to the
number they represent. As float can represent very large range of numbers python
must use approximation to represent these numbers. For example this floating
point number 0.23 is in reality slightly more than 0.23. such that if we add up 0.23
to itself a few times and check its equality to the expected resultant it will be
different. Although the difference is very small but it exists never the less and you
should know about it.

print(0.23 + 0.23 + 0.23 + 0.23 + 0.23 + 0.23

       + 0.23 + 0.23 + 0.23 + 0.23 + 0.23 + 0.23

       + 0.23 + 0.23 + 0.23 + 0.23 + 0.23 + 0.23

       + 0.23 + 0.23 + 0.23 + 0.23 + 0.23 + 0.23

       + 0.23 + 0.23 + 0.23 + 0.23+ 0.23 + 0.23 == 6.9)

9. Boolean Datatype, Comparison and Logical Operators:


Bool is another datatype that is commonly used in Python. Bool is short for Boolean which can
have a value of either True or False. Boolean algebra is the branch of algebra in which the values
of the variables are the truth values true or false. Boolean algebra us the framework on which all
electronic devices and built and exists fundamentally in every line of code inside a computer. In
python we can easily assign boolean values like this:

python_awsome = True

doumentation_bad = False

We can use comparison operators to compare 2 values and produce boolean results like:
https://colab.research.google.com/github/ShapeAI/Python-and-Machine-Learning/blob/main/Important_concepts_in_python.ipynb 6/22
9/8/22, 7:18 PM Data_Types_Operators.ipynb - Colaboratory

a = 3 > 1

print(a)

Here 3 is greater than 1 so printing out the output gives us a boolean value to true. There are
many comparison operators in python, as you can see here are all of them.

As you will see the function of all these comparison operators are evident from their names
itself these are less than, greater than , less than or equal to, greater than or equal to, not equal
to.

Working with boolean has its own set of operators called as logical operators. These operators
very useful when working with boolean, and evaluates if both the sides are true, OR evaluates if
atleast one side is true and not evaluates the inverse of the input boolean.

Lets understand if via an example:

rent = 1200

is_affordable = rent > 1000 and rent < 2000

print(is_affordable)

Here we check if the rent of a house is affordable or not, here in the second line we evaluate
both the sides ie rent > 1000, yes, so it is true while the second condition is rent < 200, that too is
true. as both the condition on the left and right side of and is true hence the boolean value of
true will be assigned to the is_affordable variable. In other words if the rent is greater than 1000
and less than 2000 then only it is affordable.

And here you can see how not works:

rent = 1200

is_affordable = not(rent > 1000 and rent < 2000) #"not" just inverts bool value

print(is_affordable)

10. Strings:
Python has another datatype in its toolkit called as Strings, as the name suggest this datatype
deals with characters words and text. String is a immutable order of sequences of characters
(eg, Letters, numbers, spaces and symbols. We will be explaining what does immutable order
means later on.

https://colab.research.google.com/github/ShapeAI/Python-and-Machine-Learning/blob/main/Important_concepts_in_python.ipynb 7/22
9/8/22, 7:18 PM Data_Types_Operators.ipynb - Colaboratory

You can create a string by using quotes as seen here, you can use either single / double quotes
they both work equally well but there are some cases where you might prefer one over the other
which we will be discussing below.
# using Double Quotes

print("ShapeAI")

# using Single Quotes

print('ShapeAI')

In this example we printed the word ShapeAI using single and double quotes and got the same
output ShapeAI.

We can also assign a string to a variable just like float and int.

motto = "Learn | Code | Compete | Intern" 

print(motto)

Strings in Python are shown as the variable type str.

type(motto)

String can contain any character number symbol space within the quotes.
However
if we want to have quotes inside the string we get an error.

dialogue = "shiva said, "you learn as you grow""

Python provides 2 easy ways to handle such problem:

1. Place the string in single quotes rather than double quotes. This will solve your problem for
having double quotes within the string. But sometimes you will want to have both double
and single quotes in your string in that case this will prove to be a problem.

dialogue = 'shiva said, "you learn as you grow"'

print(dialogue)

2. In that case we can use a backslash to skip quotes as you can see in this example. The
backslash helps python to know that the the single quote should be interpreted as part of
the string rather than the quote that ends the string.

dialogue = '"shiva you\'re bag is red"'

print(dialogue)

https://colab.research.google.com/github/ShapeAI/Python-and-Machine-Learning/blob/main/Important_concepts_in_python.ipynb 8/22
9/8/22, 7:18 PM Data_Types_Operators.ipynb - Colaboratory

There are a few operators that we use on floats and ints that can also be used on strings. For
example we can use the '+' to combine / concatenate 2 strings together and we can use '*' to
repeat the string let us look at an example for each.

print("hello" + "world")

print("hello" + " " + "world")

here in this example we can see that using the plus arithmetic operator we get
*helloworld written together but this word that is printed out has no meaning, we
need to have a space between both the words to have a meaning. We can add
another string containing just a space in between the words to do so.*

word = "hello"

print(word * 5)

Now in the second example we can see that using the multiplication operator on a string we get
repetition of the same word as many time as the number we multiplied the string by in the
output.

However unlike multiplication and addition operators the other arithmetic operators like division
and subtraction cannot be used on strings any attempt to do so would result in an error that
string is an unsupported datatype for the division/subtraction operator.

word_1 = "hello"

word_2 = "world"

print(word_1 / word_2)

A useful builtin function for string datatypes is len() which stands for length. As the name
suggests (it returns the length of an object ie., it returns the no of characters in a string.

It takes in values in a parenthesis and returns the length of the string. len() is a little different
from print() as the value returned from length can be stored in a variable as seen in the example
here. The len() function outputs a value 7 that is then stored in a variable called as word_length
which is then printed out.

word_length = len("ShapeAI")

print(word_length)

Question:

https://colab.research.google.com/github/ShapeAI/Python-and-Machine-Learning/blob/main/Important_concepts_in_python.ipynb 9/22
9/8/22, 7:18 PM Data_Types_Operators.ipynb - Colaboratory

The line of code in the following code block will cause a SyntaxError, thanks to the misuse of
quotation marks. First run it with Test Run to view the error message. Then resolve the problem
so that the quote (from Mahatama Gandhi) is correctly assigned to the variable gandhi_quote.

# TODO: Fix this string!

gandhi_quote = 'If you don't ask, you don't get it'

Question:
In this question you have to print the accuracy logs of a model in training.

model = "VGG16"

iteration = "150"

accuracy = "67.98"

# TODO: print a log message using the variables above

# This message should have the same format as this one:

# "the accuracy of ResNET50 model in 100th iteration is: 42.16%"

Question:
Use string concatination and len() function to fing the length of a persons complete name and
store it in the variable name_length.

As a business card designer find if the name can fit into a business card.

given_name = "Rahul"

middle_names = "Shastri"

family_name = "Mishra"

name_length = #todo: calculate how long this name is

# Now we check to make sure that the name fits within the driving license character limit

# Nothing you need to do here

driving_license_character_limit = 28

print(name_length <= driving_license_character_limit)

11. Type and Type Conversion Revision:


Till now we have covered 4 different datatypes int, float, bool and string. As you can recall from
the previous classes python has a builtin function called as type that returns the type of an
object.

https://colab.research.google.com/github/ShapeAI/Python-and-Machine-Learning/blob/main/Important_concepts_in_python.ipynb 10/22
9/8/22, 7:18 PM Data_Types_Operators.ipynb - Colaboratory

print(type(75))

print(type(75.0))

print(type("75"))

print(type(True))

Look at the code example we can see that even though the first 3 values appear to be same they
can be encoded into different datatypes each with their own set of functions operations and
uses.

This is to note that here we have called the function print on another function type to output the
return value of the function type. In such a case always the function inside the parenthesis is run
first ie. here it will be type.

Different types have different properties with their own set of functions operations and uses and
hence while choosing a variable you need to choose the correct set of datatype for it depending
upon how you care going to use it this is very important.

There might be sometimes when you don't have the control over the type of the data being
provided to you like one that has been received from a user as in input. But the good news is that
python allows you to create new objects from old and change the datatypes for these new
objects. As we had previously seen in the integers and floats video.

For example here we created a float ie 3.0 from an int 3 and assigned it to a new
variable called decimal

decimal = float(3)

print(decimal)

print(type(decimal))

In this next example we created a string from the integer variable marks and used
that to create a larger string.

marks = 15

subject = "coding"

semester = "first"

result = "I scored " + str(marks) + " in " + subject + " during my " + semester + " semest
print(result)

we can also create an float from string

marks = "15"

https://colab.research.google.com/github/ShapeAI/Python-and-Machine-Learning/blob/main/Important_concepts_in_python.ipynb 11/22
9/8/22, 7:18 PM Data_Types_Operators.ipynb - Colaboratory

print(type(marks))

marks = float(marks)

print(type(marks))

Question:
In this quiz, you’ll need to change the types of the input and output data in order to get the result
you want.

Calculate and print the total sales for the week from the data provided. Print out a string of the
form "This week's total sales: xxx", where xxx will be the actual total of all the numbers. You’ll
need to change the type of the input data in order to calculate that total.

mon_sales = "121"

tues_sales = "105"

wed_sales = "110"

thurs_sales = "98"

fri_sales = "95"

#TODO: Print a string with this format: This week's total sales: xxx

# You will probably need to write some lines of code before the print statement.

total_sales = (float(mon_sales) + float(tues_sales) + float(wed_sales) 

                + float(thurs_sales) + float(fri_sales))

print("This week\'s total sales: " + str(total_sales))

12.a. One important string method: format()


We will be using the format() string method a good bit in our future work in Python, and you will
find it very valuable in your coding, especially with your print statements.

We can best illustrate how to use format() by looking at some examples:

# Example 1

print("EG:1")

print("Mohammed has {} balloons".format(27))

# Example 2

print("EG:2")

animal = "dog"

action = "bite"

print("Does your {} {}?".format(animal, action))

# Example 3

print("EG:3")

maria_string = "Maria loves {} and {}"

print(maria_string.format("math","statistics"))

https://colab.research.google.com/github/ShapeAI/Python-and-Machine-Learning/blob/main/Important_concepts_in_python.ipynb 12/22
9/8/22, 7:18 PM Data_Types_Operators.ipynb - Colaboratory

Notice how in each example, the number of pairs of curly braces {} you use inside the string is
the same as the number of replacements you want to make using the values inside format().

More advanced students can learn more about the formal syntax for using the format() string
method here.

13. Lists and Membership Operators:


Data structures are containers that organize and group data types together in different ways. A
list is one of the most common and basic data structures in Python. It is a mutable ordered
sequence of elements.

The code below defines a variable students which contains a list of strings. Each element in the
list is a string that signifies the name of a student.

The data inside a list can be a mixture of any number and combination of diffrent
data types.

students = ['sam', 'pam', 'rocky', 'austin', 'steve', 'banner']

List are ordered, we can look up individual elements by their index, we can look elements from a
list just like we have done below.

print(students[0])

print(students[1])

print(students[2])

Notice that the first element in the list is accessed by the index 0, many programming language
follow this convection called as zero based indexing.

We can also access the elements from the end of the list using negative index as seen in the
examples below.

print(students[-1])

print(students[-2])

print(students[-3])

If you try to access an index in a list that doesn't exist then you will get an Error as seen below.

print(students[20])

https://colab.research.google.com/github/ShapeAI/Python-and-Machine-Learning/blob/main/Important_concepts_in_python.ipynb 13/22
9/8/22, 7:18 PM Data_Types_Operators.ipynb - Colaboratory

Question:
Try to use len() to pull the last element from the above list

# TODO: write your code here

students[len(students)-1]

13.a. Membership Operators:[Lists]


In addition to accessing individual elements froma a list, we can use pythons sliceing notation to
access a subsequence of a list.

Slicing means using indicies to slice off parts of an object like list/string. Look at an example

students = ['sam', 'pam', 'rocky', 'austin', 'steve', 'banner', 'tony', 'bruce', 

            'henry', 'clark', 'diana']

student = "Barry"

# slice a particular range

marvel = students[4:7]

flash = student[1:3]

print(marvel)

print(flash)

# slice from the end

dc = students[7:]

flash = student[1:]

print(dc)

print(flash)

# slice from the begining

normal = students[:4]

flash = student[:3]

print(normal)

print(flash)

# length of the list and the string

print(len(students))

print(len(student))

Of the types we have seen lists are most familier to strings, both supports the len() function,
indexing and slicing.

https://colab.research.google.com/github/ShapeAI/Python-and-Machine-Learning/blob/main/Important_concepts_in_python.ipynb 14/22
9/8/22, 7:18 PM Data_Types_Operators.ipynb - Colaboratory

Here above you have seen that the length of a string is the no of characters in the
string, while the length of a list is the no of elements in the list.

Another thing that they both supports aare membership operators:

in: evaluates if an object on the left side is included in the object on the right side.
not in: evaluates if object on left side is not included in object on right side.

greeting = "Hello there"

print('her' in greeting, 'her' not in greeting)

print('ShapeAI' in students, 'ShapeAI' not in students)

13.b. Mutability and Order:


So how are Lists diffrent from Strings, both supporst slicing, indexing, in and not in operators.

The most obvious diffrence between them is that string is a sequence of characters while list's
elements can be any type of bojects string, integers, floats orr bools.

A more important diference is that lists can be modified but string can't. Look at the example
below to understand more.

students = ['sam', 'pam', 'rocky', 'austin', 'steve', 'banner', 'tony', 'bruce', 

            'henry', 'clark', 'diana']

students[2] = 'ben'

print(students)

student = "Barry"

student[1] = "e"

print(student)

Mutability is about whether or not we can change an object once it has been created. If an
object (like a list or string) can be changed (like a list can), then it is called mutable. However, if
an object cannot be changed without creating a completely new object (like strings), then the
object is considered immutable.

Order is about whether the position of an element in the object can be used to access the
element. Both strings and lists are ordered. We can use the order to access parts of a list and
string.

However, you will see some data types in the next sections that will be unordered.
For each of the upcoming data structures you see, it is useful to understand how

https://colab.research.google.com/github/ShapeAI/Python-and-Machine-Learning/blob/main/Important_concepts_in_python.ipynb 15/22
9/8/22, 7:18 PM Data_Types_Operators.ipynb - Colaboratory

you index, are they mutable, and are they ordered. Knowing this about the data
structure is really useful!

Additionally, you will see how these each have different methods, so why you would use one
data structure vs. another is largely dependent on these properties, and what you can easily do
with it!

Previously when we created a variable that heald an immutable object like string, the value of the
immutable object was saved in memory. Like as you can see below

student = "pam"

character = student

print(character)

character = "peter"

print(character)

print(student)

Lists are diffrent from strings as they are mutable as can be seen from the example below

students = ['sam', 'pam', 'rocky', 'austin', 'steve', 'banner', 'tony', 'bruce', 

            'henry', 'clark', 'diana']

characters = students

print(characters)

characters[1]= "peter"

print(characters)

print(students)

There are some useful functions for lists that you should get familier with.

1. len(): returns how many elements does the list has.


2. max(): returns the greatest element of a list.
3. min(): returns the smallest element of a list.
4. sorted(): returns a copy of the list, in order from smallest to the largest. leaving the orignal
list unchanged

max element in a list of integers is the largest integer, while in the case of string is
the string that will come last if the list was sorted alphabetically.

students = ['sam', 'pam', 'rocky', 'austin', 'steve', 'banner', 'tony', 'bruce', 

            'henry', 'clark', 'diana']

student = "barry"

print(max(students))

print(max(student))

https://colab.research.google.com/github/ShapeAI/Python-and-Machine-Learning/blob/main/Important_concepts_in_python.ipynb 16/22
9/8/22, 7:18 PM Data_Types_Operators.ipynb - Colaboratory

a point to note is that even though you can have a list cntaining int and string a
max function will be undefined upon such a list.

max([2, 'two'])

characters = sorted(students)

print(characters)

Join() is an other useful function for lists(string lists), Join is a string method that takes a list of
strings as an argument, and returns a string consisting of the list elements joined by a separator
string. Look at the example below to understand.

sep_str = "\n".join(["Jack", "O", "Lantern"])

print(sep_str)

In this example we use the string "\n" as the separator so that there is a newline between each
element.
We can also use other strings as separators with .join. Here we use a hyphen.

name = "-".join(["Jack", "O", "Lantern"])

print(name)

It is important to remember to separate each of the items in the list you are joining
with a comma (,). Forgetting to do so will not trigger an error, but will also give you
unexpected results.

append() is an other useful method that adds an element to the end of a list.

letters = ['a', 'b', 'c', 'd']

letters.append('e')

print(letters)

14. Tuples:
A tuple is another useful container. It's a data type for immutable ordered sequences of
elements. They are often used to store related pieces of information. Consider this example
involving (x, y, z) coordinates:

https://colab.research.google.com/github/ShapeAI/Python-and-Machine-Learning/blob/main/Important_concepts_in_python.ipynb 17/22
9/8/22, 7:18 PM Data_Types_Operators.ipynb - Colaboratory

vector = (4, 5, 9)

print("x-coordinate:", vector[0])

print("y-coordinate:", vector[1])

print("z-coordinate:", vector[2])

Tuples are similar to lists in that they store an ordered collection of objects which can be
accessed by their indices. Unlike lists, however, tuples are immutable - you can't add and remove
items from tuples, or sort them in place.

Tuples can also be used to assign multiple variables in a compact way.

The parentheses are optional when defining tuples, and programmers frequently
omit them if parentheses don't clarify the code.

location = 108.7774, 92.5556

latitude, longtitude = location

print("The coordinates are {} x {}".format(latitude, longtitude))

In the second line, two variables are assigned from the content of the tuple location. This is
called tuple unpacking. You can use tuple unpacking to assign the information from a tuple into
multiple variables without having to access them one by one and make multiple assignment
statements.

If we won't need to use location directly, we could shorten those two lines of code into a single
line that assigns three variables in one go!

location = 108.7774, 92.5556

print("The coordinates are {} x {}".format(latitude, longtitude))

16. Dictionaries and Identity Operators:


A dictionary is a mutable data type that stores mappings of unique keys to values. Here's a
dictionary that stores elements and their atomic numbers.

elements = {"hydrogen": 1, "helium": 2, "carbon": 6}

Dictionaries can have keys of any immutable type, like integers or tuples, not just strings. It's not
even necessary for every key to have the same type! We can look up values or insert new values
in the dictionary using square brackets that enclose the key.

https://colab.research.google.com/github/ShapeAI/Python-and-Machine-Learning/blob/main/Important_concepts_in_python.ipynb 18/22
9/8/22, 7:18 PM Data_Types_Operators.ipynb - Colaboratory

print(elements["helium"])  # print the value mapped to "helium"

elements["lithium"] = 3  # insert "lithium" with a value of 3 into the dictionary

We can check whether a value is in a dictionary the same way we check whether a value is in a
list or set with the in keyword. Dicts have a related method that's also useful, get(). get() looks up
values in a dictionary, but unlike square brackets, get returns None (or a default value of your
choice) if the key isn't found.

print("carbon" in elements)

print(elements.get("dilithium"))

Carbon is in the dictionary, so True is printed. Dilithium isn’t in our dictionary so None is returned
by get and then printed. If you expect lookups to sometimes fail, get might be a better tool than
normal square bracket lookups because errors can crash your program.

16.a. Keyword Operators:


is: evaluates if both sides have the same identity
is not evaluates if both sides have different identities

You can check if a key returned None with the is operator. You can check for the opposite using
is not.

n = elements.get("dilithium")

print(n is None)

print(n is not None)

Task:
Define a dictionary named population that contains this data:

Keys -> Values

New York -> 17.8

Spain -> 13.3

Dhaka -> 13.0

Mumbai -> 12.5

population = {"New York":17.8, "Spain":13.3, "Dhaka":13.0, "Mumbai":12.5}

print(population)

https://colab.research.google.com/github/ShapeAI/Python-and-Machine-Learning/blob/main/Important_concepts_in_python.ipynb 19/22
9/8/22, 7:18 PM Data_Types_Operators.ipynb - Colaboratory

16.b. Get() with a Default Value:


Dictionaries have a related method that's also useful, get(). get() looks up values in a dictionary,
but unlike looking up values with square brackets, get() returns None (or a default value of your
choice) if the key isn't found. If you expect lookups to sometimes fail, get() might be a better tool
than normal square bracket lookups.

print(population.get('London'))

population['London']

population.get('London', 'There\'s no such place!')

In the last example we specified a default value (the string 'There's no such
element!') to be returned instead of None when the key is not found.

16.c. Compound Data Structures:


Previously we have seen a dictonary called elements in which the element names are maped to
their atomic numbers which are integers. But what if we want to store more information about
each element like their atomic weight and symbol. We can do that by adjusting this dictionary so
that it maps the element names to an other dictionary, that stores that collection of data.

elements = {"hydrogen": {"number": 1,

                         "weight": 1.00794,

                         "symbol": "H"},

              "helium": {"number": 2,

                         "weight": 4.002602,

                         "symbol": "He"}}

We can look up information about an element using this nested dictionary, using square
brackets or the get() method.

helium = elements["helium"]  # get the helium dictionary
hydrogen_weight = elements["hydrogen"]["weight"]  # get hydrogen's weight

print(helium)

print(hydrogen_weight)

You can also add a new key to the element dictionary.

https://colab.research.google.com/github/ShapeAI/Python-and-Machine-Learning/blob/main/Important_concepts_in_python.ipynb 20/22
9/8/22, 7:18 PM Data_Types_Operators.ipynb - Colaboratory

oxygen = {"number":8,"weight":15.999,"symbol":"O"}  # create a new oxygen dictionary 

elements["oxygen"] = oxygen  # assign 'oxygen' as a key to the elements dictionary

print('elements = ', elements)

Question:
Try your hand at working with nested dictionaries. Add another entry, 'is_noble_gas,' to each
dictionary in the elements dictionary. After inserting the new entries you should be able to
perform these lookups:

print(elements['hydrogen']['is_noble_gas'])

False

print(elements['helium']['is_noble_gas'])
True

elements = {'hydrogen': {'number': 1, 'weight': 1.00794, 'symbol': 'H'},

            'helium': {'number': 2, 'weight': 4.002602, 'symbol': 'He'}}

# todo: Add an 'is_noble_gas' entry to the hydrogen and helium dictionaries

# hint: helium is a noble gas, hydrogen isn't

elements['helium']['is_noble_gas'] = True

elements['hydrogen']['is_noble_gas'] = False

elements

https://colab.research.google.com/github/ShapeAI/Python-and-Machine-Learning/blob/main/Important_concepts_in_python.ipynb 21/22

You might also like