0 ratings0% found this document useful (0 votes) 45 views20 pagesPython Boot Camp
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
‘r2Ain2, 5:54 °M Notebooks
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 pytho
You will be seeing this print function very frequently in python programming. It helps us to
see what exactly is happening in our code
Ty to run the next lines of code and see what happens next
247
27
* 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. Variable:
Understanding variables is very important in any programming language they are used al
the time in python. Using variables in place of direct numbers have many advantages.
hitpsigthub.com/ShapeAliPython-ané-Machine-Learingiblobimairvimportant_concepts_in_python.ipynb 10‘r2Ain2, 5:54 °M
Notebooks
Variables are 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 anc
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:
1760 "
In any case, whatever term is on the left side, is now a name for whatever value is on the
‘ight 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 asin 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
a3
bea
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. Mul
ple 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
volune = height * length * width
print (volume)
hitpsigthub.com/ShapeAliPython-ané-Machine-Learingiblobfmaivimportant_concepts_in_python.ipyn 2120‘r2Ain2, 5:54 °M
Notebooks
Now python has a very useful way to assign multiple variables together in a single line
using multiple assignment lke 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
25 $,%,#,84@-,* 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
ike 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
xe2
y="Hello"
nypython="PythonGuides"
rny_python="PythonGuides
_tty_python="PythonGuides"
“nypython="PythonGuides
NYPYTHON="PythonGuide:
yPython="PythonGuides
myPython7="PythonGuides
#VariabLe name not ALLowed
‘7mypython="PythonGuides
-mypython="PythonGuides'
myPyaithon="PythonGuides
ny Python="PythonGuides
for="PythonGuides"
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:
hitpsigthub.com/ShapeAliPython-ané-Machine-Learingiblobimairvimportant_concepts_in_python.ipynb
312012022, 554 PM Notebooks
* 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 anc
underscores to separate words
# pythonic way
my_height = 5i
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
rent =rent + 760
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)
hitpsigthub.com/ShapeAliPython-ané-Machine-Learingiblobimairvimportant_concepts_in_python.ipynb 4720‘r2Ain2, 5:54 °M Notebooks
we can actually use this += operator to tell python that we are incrementing the value or
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 Float:
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 if2 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 anc
the type of a number with a decimal
print(type(a))
print (type(b))
‘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 ane
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 approximatior
hitpsigthub.com/ShapeAliPython-ané-Machine-Learingiblob/maivimportant_concepts_in_python.ipynb 512012022, 554 PM Notebooks
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(9.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 + 8.23 + 0.23 + 0.23
+ 0.23 + 0.23 + 0.23 + 0.23 + 0.23 + 0.23
+ 0.23 + 0.23 + 0.23 + 0.234 0.23 + 0.23,
9. Boolean Datatype, Compa
Operators:
on and Logical
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
a=3>4
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 wil 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,
ORevaluates if atleast one side is true and not evaluates the inverse of the input boolean
Lets understand if via an example
rent = 1208
is_affordable = rent > 1000 and rent < 2000
hitpsigthub.com/ShapeAliPython-ané-Machine-Learingiblobimaivimportant_concepts_in_python.ipynb 2120‘r2Ain2, 5:54 °M
hitpsigthub.com/ShapeAliPython-ané-Machine-Learingiblob/maivimportant_concepts_in_python.ipynb
Notebooks
print (is_affordable)
Here we check ifthe rent of a house is affordable or not, here in the second line we
evaluate both the sides ie rent > 1000. yes, so itis 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 rentis greater than 1000 and less than 2000 then only itis 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. String:
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
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 ("ShapeaT")
# using Single Quotes
print (‘Shapear' )
In this example we printed the word Shaped’ using single and double quotes and got the
same output ShapeAl.
We can also assign a string to a variable just lke float and int
motto = “Learn | Code | Conpete | Intern”
print (motto)
Strings in Python are shown as the variable type str.
type(notto)
String can contain ary character number symbol space within the quotes.
720‘r2Ain2, 5:54 °M
Notebooks
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 ¢
problem.
dialogue = ‘shiva said, "you learn as you grow’
print (dialogue)
‘Lin 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)
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
helloworlé 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
oy 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
hitpsigthub.com/ShapeAliPython-ané-Machine-Learingiblobimaivimportant_concepts_in_python.ipynb 820‘r2Ain2, 5:54 °M
Notebooks
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, lenGis a little
different from print( as the value retumed from length can be stored in a variable as seer
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 = 1en("Shapear™)
print (word_length)
Question:
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.
# 1000: 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 = “vcci6"
iteration
accuracy
# TODO: print a Log message using the variables above
# This message should have the same format as this one:
# "the accuracy of ResNET5S@ model in 180th 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 = "Shas
family_name = "Mishr:
name_length = #todo: calculate how Long this name is
hitpsigthub.com/ShapeAliPython-ané-Machine-Learingiblobimaivimportant_concepts_in_python.ipynb 9120‘r2Ain2, 5:54 °M
Notebooks
# Now we check to make sure that the name fits within the driving License charact
# Nothing you need to do here
driving_license_character_limit = 28
print(nane_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.
print type(75))
print type(75.2))
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 anc
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 asin 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 @
new variable called decima'
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
hitpsigthub.com/ShapeAliPython-ané-Machine-Learingiblob/maiivimportant_concepts_in_python.ipyn 10120‘r2Ain2, 5:54 °M
Notebooks
marks = 15
subject = “coding
semester = "first"
result = "I scored * + str(marks) +" in" + subject +" during my " + semester «
print (result)
we can also create an float from string
marks = "15"
print (type(marks))
marks = float (marks)
print (type(marks))
Question:
In this quiz, youll 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: 00%, where 14x 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
wed_sales
‘thurs_sales
fri_sales
#700: 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(non_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 ind 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("Mohanmed has {} balloons" .format(27))
# Exam
print(
animal
action
print("Does your {} (}2".format(animal, action))
hitpsigthub.com/ShapeAliPython-ané-Machine-Learingiblob/maiivimportant_concepts_in_python.ipyn 120‘r2Ain2, 5:54 °M
Notebooks
# Example 3
print(
maria_string = "Maria loves {} and {}"
print(maria_string. format("math”, "statistics"))
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 isa string that signifies the name of a student
The data inside alist 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 lst just like we have done below.
print (students [0])
print (students (2])
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 lst that doesn't exist then you will get an Error as seer
oelow.
hitpsigthub.com/ShapeAliPython-ané-Machine-Learingiblob/maiivimportant_concepts_in_python.ipyn 12720‘r2Ain2, 5:54 °M
Notebooks
print (students[20])
Question:
Ty to use lend to pull the last element from the above list
# ToD0: write your code here
students[en(students)-1]
13
In addition to accessing individual elements froma a lst, we can use pythons sliceing
notation to access a subsequence of a list.
. Membership Operators:[Lists]
Slicing means using indicies to slice off parts of an object lke 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 (de)
print (#lash)
# slice from the begining
normal = students[:4]
flash = student[:3]
print (normal)
print (#lash)
# Length of the List and the string
print (1en(students))
print (1en(student ))
Of the types we have seen lists are most familier to strings, both supports the len(;
function, indexing and slicing
Here above you have seen that the length of a string is the no of characters
in the string, while the length of alist is the no of elements in the list.
hitpsigthub.com/ShapeAliPython-ané-Machine-Learingiblobfmaivimportant_concepts_in_python.ipyn
13920‘r2Ain2, 5:54 °M Notebooks
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
ist'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 (lke alist or string) can be changed (lke a lst can), then itis called mutable.
However, ifan object cannot be changed without creating a completely new object (ike
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 alist
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, itis useful to
understand how 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!
hitpsigthub.com/ShapeAliPython-ané-Machine-Learingiblobfmaivimportant_concepts_in_python.ipyn 1412012022, 554 PM Notebooks
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 = "pan"
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 = ['san', ‘pan’, ‘rocky’, ‘austin', ‘steve’, ‘banner’, ‘tony’, ‘bruce’,
henry’, ‘clark’, ‘diana’]
characters = students
print (characters)
characters[1]= “pete
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 alist.
3, min): returns the smallest element of alist.
4, sorted(: returns a copy of the list in order from smallest to the largest. leaving the
orignal list unchanged
max element in a lst 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 = "parry"
print(max(students))
print(max(student))
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
ist 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
Ips gthub comiShapeAlPython-ané Machine-Learing/bobimainfporant_concepts.n_pythonipynd 1520‘r2Ain2, 5:54 °M Notebooks
sep_str = "\n".Join(["Jack",
print(sep_str)
Lantern")
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.
=" Join(["Jack",
print (name)
‘o", "Lantern" ])
Its 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', a")
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, 2) coordinates
vector = (4, 5, 9)
print("x-coordinat
print("y-coordinate:
print("z-coordinat
» vector[2])
vector[1])
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))
hitpsigthub.com/ShapeAliPython-ané-Machine-Learingiblobimairvimportant_concepts_in_python.ipynb 1612012022, 554 PM Notebooks
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 2
dictionary that stores elements and their atomic numbers
elenents = ("hydrogen": 1, “heliun": 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.
print(elements["heliun"]) # print the value mapped to "helium"
elements["lithiun"] = 3 # insert “Lithium” with a value of 3 into the dictionary
We can check whether a value is ina dictionary the same way we check whether a value is
ina list or set with the in keyword. Dicts have a related method that's also useful, get(),
gett) looks up values in a dictionary, but unlike square brackets, get returns None (or 2
default value of your choice) if the key isn't found.
print("carbon" in elenents)
print (elements. get ("dilithiun"))
Carbon is in the dictionary, so True is printed. Dilithium isn’t in our dictionary so None is
retumed 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 Operator:
is: evaluates if both sides have the same identity
© is not evaluates if both sides have different identities
hitpsigthub.com/ShapeAliPython-ané-Machine-Learingiblobfmaivimportant_concepts_in_python.ipyn 17120‘r2Ain2, 5:54 °M Notebooks
You can check if a key returned None with the és operator. You can check for the opposite
using és not.
n = elenents.get("dilithiun")
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)
16.b. Get() with a Default Value:
Dictionaries have a related method that's also useful, get(. get() looks up values in
dictionary, but unlike looking up values with square brackets, get() returns None (or ¢
default value of your choice) ifthe key isn't found. If you expect lookups to sometimes fal
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 suck
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
hitpsigthub.com/ShapeAliPython-ané-Machine-Learingiblobfmaivimportant_concepts_in_python.ipyn 18120‘r2Ain2, 5:54 °M Notebooks
adjusting this dictionary so that it maps the element names to an other dictionary, that
stores that collection of data
elements = {"hydrogen": (“nunber": 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
rackets or the get method
helium = elenents["heliun"] # 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
‘oxygen = ("number
elements ["oxygen"]
‘weight":15.999,"symbol":"0"} # create a new oxygen dictior
xygen # assign ‘oxygen’ as a key to the elements dictionar
print(‘elements = ', elenents)
Question:
Ty 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'Iis_noble_gas'))
False
print(elements(helium'('is_noble_gas')
Tue
elements = {‘hydrogen': (‘number': 1, ‘weight': 1.00794, ‘synbol
helium’: (‘number’: 2, ‘weight
“W),
4.002602, ‘symbol’: ‘He'}}
# todo: Add an "is_nobLe_gas’ entry to the hydrogen and helium dictionaries
# hint: helium is @ noble gas, hydrogen isn't
elenents[ ‘helium’ ]['is_noble_gas'] = True
elements ‘hydrogen’ ]["is_noble_gas’] = False
elements
Tr
hitpsigthub.com/ShapeAliPython-ané-Machine-Learingiblobfmaiivimportant_concepts_in_python.ipynb 1912072422, 554 PM Notebooks
hitpsiigthu.com/ShapeAliPython-ané-Machine-Learingiblobfmainvimportant_concepts_in_python.ipynb 20120