Lesson2 Python
Lesson2 Python
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
Arithmetic Operators
Arithmetic operators
+ Addition
- Subtraction
* Multiplication
/ Division
% Mod (the remainder after dividing)
** Exponentiation (note that ^ does not do this operation, as you might have seen in other
languages)
// Divides and rounds down to the nearest integer
The usual order of mathematical operations holds in Python, which you
can review in this Math Forum page if needed.
Variables I
Variables are used all the time in Python! Below is the example you
saw in the video where we performed the following:
mv_population = 74728
Variables II
In this video you saw that the following two are equivalent in terms of assignment:
x = 3
y = 4
z = 5
and
x, y, z = 3, 4, 5
However, the above isn't a great way to assign variables in most cases, because our variable names
should be descriptive of the values they hold.
Besides writing variable names that are descriptive, there are a few things to watch out for when
naming variables in Python.
1. Only use ordinary letters, numbers and underscores in your variable names. They can’t have
spaces, and need to start with a letter or underscore.
2. You can’t use reserved words or built-in identifiers that have important purposes in Python,
which you’ll learn about throughout this course. A list of python reserved words is described here.
Creating names that are descriptive of the values often will help you avoid using any of these words.
A quick table of these words is also available below.
3. The pythonic way to name variables is to use all lowercase letters and underscores to separate
words.
YES
my_height = 58
my_lat = 40
my_long = 105
NO
my height = 58
MYLONG = 40
MyLat = 105
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.
Assignment Operators
Below are the assignment operators from the video. You can also use *= in a similar way, but this is
less common than the operations shown below. You can find some practice with much of what we
have already covered here.
Integers and Floats
There are two Python data types that could be used for numeric
values:
Good
print(4 + 5)
Bad
print( 4 + 5)
You should limit each line of code to 80 characters, though 99 is okay
for certain use cases. You can thank IBM for this ruling.
Comparison Operators
Symbol Use
Case Bool Operation
3 == 5 False Equal To
And there are three logical operators you need to be familiar with:
5 < 3 and 5 == 5 False and - Evaluates if all provided statements are True
Strings
Strings in Python are shown as the variable type str. You can define a string with either double
quotes " or single quotes '. If the string you are creating actually has one of these two values in it,
then you need to be careful to assure your code doesn't give an error.
>>> my_string = 'this is a string!'
>>> my_string2 = "this is also a string!!!"
You can also include a \ in your string to be able to include one of these quotes:
>>> this_string = 'Simon\'s skateboard is in the garage.'
>>> print(this_string)
Simon's skateboard is in the garage.
If we don't use this, notice we get the following error:
HelloThere
Hello There
>>> print(first_word * 5)
HelloHelloHelloHelloHello
>>> print(len(first_word))
5
Unlike the other data types you have seen so far, you can also index into strings, but you will see
more on this soon! For now, here is a small example. Notice Python uses 0 indexing - we will discuss
this later in this lesson in detail.
>>> first_word[0]
>>> first_word[1]
e
The len() function
len() is a built-in Python function that returns the length of an object, like a string. The length of a
string is the number of characters in the string. This will always be an integer.
There is an example above, but here's another one:
print(len("ababa") / len("ab"))
2.5
String Methods
In this video you were introduced to methods. Methods are like some of the functions you have
already seen:
1. len("this")
2. type(12)
3. print("Hello world")
These three above are functions - notice they use parentheses, and accept one or more arguments.
Functions will be studied in much more detail in a later lesson!
A method in Python behaves similarly to a function. Methods actually are functions that are called
using dot notation. For example, lower() is a string method that can be used like this, on a string
called "sample string": sample_string.lower().
Methods are specific to the data type for a particular variable. So there are some built-in methods that
are available for all strings, different methods that are available for all integers, etc.
Below is an image that shows some methods that are possible with any string.
Each of these methods accepts the string itself as the first argument of the method. However, they
also could receive additional arguments, that are passed inside the parentheses. Let's look at the
output for a few examples.
>>> my_string.islower()
True
>>> my_string.count('a')
2
>>> my_string.find('a')
3
You can see that the count and find methods both take another argument. However,
the .islower() method does not accept another argument.
No professional has all the methods memorized, which is why understanding how to use
documentation and find answers is so important. Gaining a strong grasp of the foundations of
programming will allow you to use those foundations to use documentation to build so much more
than someone who tries to memorize all the built-in methods in Python.
Lists!
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.
You saw here that you can create a list with square brackets. Lists
can contain any mix and match of the data types you have seen so far.
list_of_random_things = [1, 3.4, 'a string', True]
This is a list of 4 elements. All ordered containers (like lists) are
indexed in python using a starting index of 0. Therefore, to pull the
first value from the above list, we can write:
>>> list_of_random_things[0]
1
It might seem like you can pull the last element with the following
code, but this actually won't work:
>>> list_of_random_things[len(list_of_random_things)]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-34-f88b03e5c60e> in <module>()
----> 1 lst[len(lst)]
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!
Correction: In the above video, at timestamp 0:42, the code should read
print("scores: " + str(scores))
print("grades: " + str(grades))
append method
A helpful method called append adds an element to the end of a list.
letters = ['a', 'b', 'c', 'd']
letters.append('z')
print(letters)
Output:
['a', 'b', 'c', 'd', 'z']
Try It Out!
In the beginning of the first video, you saw how the behaviour of variables containing mutable and
immutable objects is very different and might even seem surprising at times! Experiment, use the
print functions and double-check your work where you can, to make sure that your programs
correctly keep track of their data. While you experiment with lists, try out some of the useful
functions above.
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 latitude and
longitude:
location = (13.4125, 103.866667)
print("Latitude:", location[0])
print("Longitude:", location[1])
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.
In the second line, three variables are assigned from the content of the
tuple dimensions. 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 dimensions directly, we could shorten those
two lines of code into a single line that assigns three variables in one
go!
length, width, height = 52, 40, 100
print("The dimensions are {} x {} x {}".format(length, width, height))
Sets
A set is a data type for mutable unordered collections of unique
elements. One application of a set is to quickly remove duplicates from a
list.
numbers = [1, 2, 6, 3, 1, 1, 6]
unique_nums = set(numbers)
print(unique_nums)
This would output:
{1, 2, 3, 6}
Sets support the in operator the same as lists do. You can add elements
to sets using the add method, and remove elements using
the pop method, similar to lists. Although, when you pop an element from
a set, a random element is removed. Remember that sets, unlike lists, are
unordered so there is no "last element".
fruit = {"apple", "banana", "orange", "grapefruit"} # define a set
Dictionaries
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.
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"))
This would output:
True
None
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.
Identity Operators
Keyword Operator
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)
This would output:
True
False
Compound Data Structures
We can include containers in other containers to create compound
data structures. For example, this dictionary maps keys to values that
are also dictionaries!
elements = {"hydrogen": {"number": 1,
"weight": 1.00794,
"symbol": "H"},
"helium": {"number": 2,
"weight": 4.002602,
"symbol": "He"}}
We can access elements in this nested dictionary like this.
helium = elements["helium"] # get the helium dictionary
hydrogen_weight = elements["hydrogen"]["weight"] # get hydrogen's weight
You can also add a new key to the element dictionary.
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)
Output is:
elements = {"hydrogen": {"number": 1,
"weight": 1.00794,
"symbol": 'H'},
"helium": {"number": 2,
"weight": 4.002602,
"symbol": "He"},
"oxygen": {"number": 8,
"weight": 15.999,
"symbol": "O"}}
* You can use curly braces to define a set like this: {1, 2, 3} . However, if
you leave the curly braces empty like this: {} Python will instead create
an empty dictionary. So to create an empty set, use set() .
** A dictionary itself is mutable, but each of its individual keys must be
immutable.