0% found this document useful (0 votes)
22 views

Lesson2 Python

Uploaded by

moamenadel199
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Lesson2 Python

Uploaded by

moamenadel199
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

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

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:

 int - for integer values


 float - for decimal or floating point values
You can create a value that follows the data type by using the
following syntax:
x = int(4.7) # x is now an integer 4
y = float(4) # y is now a float of 4.0
You can check the type by using the type function:
>>> print(type(x))
int
>>> print(type(y))
float
Because the float, or approximation, for 0.1 is actually slightly more
than 0.1, when we add several of them together we can see the
difference between the mathematically correct answer and the one
that Python creates.
>>> print(.1 + .1 + .1 == .3)
False

Python Best Practices


For all the best practices, see the PEP8 Guidelines.
You can use the atom package linter-python-pep8 to use pep8 within
your own programming environment in the Atom text editor, but more
on this later. If you aren't familiar with text editors yet, and you are
performing all of your programming in the classroom, no need to worry
about this right now.
Follow these guidelines to make other programmers and future you
happy!

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.

Booleans, Comparison Operators, and Logical Operators


The bool data type holds one of the values True or False, which are
often encoded as 1 or 0, respectively.
There are 6 comparison operators that are common to see in order to
obtain a boolvalue:

Comparison Operators

Symbol Use
Case Bool Operation

5<3 False Less Than


Symbol Use
Case Bool Operation

5>3 True Greater Than

3 <= 3 True Less Than or Equal To

3 >= 5 False Greater Than or Equal To

3 == 5 False Equal To

3 != 5 True Not Equal To

And there are three logical operators you need to be familiar with:

Logical Use Bool Operation

5 < 3 and 5 == 5 False and - Evaluates if all provided statements are True

5 < 3 or 5 == 5 True or - Evaluates if at least one of many statements is True

not 5 < 3 True not - Flips the Bool Value

Here is more information on how George Boole changed the world!

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:

>>> this_string = 'Simon's skateboard is in the garage.'


File "<ipython-input-20-e80562c2a290>", line 1
this_string = 'Simon's skateboard is in the garage.'
^
SyntaxError: invalid syntax
The color highlighting is also an indication of the error you have in your string in this second case.
There are a number of other operations you can use with strings as well. In this video you saw a few:
>>> first_word = 'Hello'
>>> second_word = 'There'
>>> print(first_word + second_word)

HelloThere

>>> print(first_word + ' ' + second_word)

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

Type And Type Conversion


You have seen four data types so far:
1. int
2. float
3. bool
4. string
You got a quick look at type() from an earlier video, and it can be
used to check the data type of any variable you are working with.
>>> print(type(4))
int
>>> print(type(3.7))
float
>>> print(type('this'))
str
>>> print(type(True))
bool
You saw that you can change variable types to perform different
operations. For example,
"0" + "5"
provides completely different output than
0 + 5
What do you think the below would provide?
"0" + 5
How about the code here:
0 + "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.

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 printstatements.
We can best illustrate how to use format() by looking at some examples:
# Example 1
print("Mohammed has {} balloons".format(27))
Mohammed has 27 balloons
# Example 2
animal = "dog"
action = "bite"
print("Does your {} {}?".format(animal, action))
Does your dog bite?
# Example 3
maria_string = "Maria loves {} and {}"
print(maria_string.format("math","statistics"))
Maria loves math and 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.

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)]

IndexError: list index out of range


However, you can retrieve the last element by reducing the index by 1.
Therefore, you can do the following:
>>> list_of_random_things[len(list_of_random_things) - 1]
True
Alternatively, you can index from the end of a list by using negative
values, where -1 is the last element, -2 is the second to last element
and so on.
>>> list_of_random_things[-1]
True
>>> list_of_random_things[-2]
a string
Slice and Dice with Lists
You saw that we can pull more than one value from a list at a time by
using slicing. When using slicing, it is important to remember that
the lower index is inclusiveand the upper index is exclusive.
Therefore, this:
>>> list_of_random_things = [1, 3.4, 'a string', True]
>>> list_of_random_things[1:2]
[3.4]
will only return 3.4 in a list. Notice this is still different than just
indexing a single element, because you get a list back with this
indexing. The colon tells us to go from the starting value on the left of
the colon up to, but not including, the element on the right.
If you know that you want to start at the beginning, of the list you can
also leave out this value.
>>> list_of_random_things[:2]
[1, 3.4]
or to return all of the elements to the end of the list, we can leave off a
final element.
>>> list_of_random_things[1:]
[3.4, 'a string', True]
This type of indexing works exactly the same on strings, where the
returned value will be a string.

Are you in OR not in?


You saw that we can also use in and not in to return a bool of
whether an element exists within our list, or if one string is a substring
of another.
>>> 'this' in 'this is a string'
True
>>> 'in' in 'this is a string'
True
>>> 'isa' in 'this is a string'
False
>>> 5 not in [1, 2, 3, 4, 6]
True
>>> 5 in [1, 2, 3, 4, 6]
False

Mutability and Order


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 with creating a completely new object (like strings), then the
object is considered immutable.
>>> my_lst = [1, 2, 3, 4, 5]
>>> my_lst[0] = 'one'
>>> print(my_lst)
['one', 2, 3, 4, 5]
As shown above, you are able to replace 1 with 'one' in the above list.
This is because lists are mutable.
However, the following does not work:
>>> greeting = "Hello there"
>>> greeting[0] = 'M'
This is because strings are immutable. This means to change this
string, you will need to create a completely new string.
There are two things to keep in mind for each of the data types you are
using:

1. Are they mutable?


2. Are they ordered?
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 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!

Correction: In the above video, at timestamp 0:42, the code should read
print("scores: " + str(scores))
print("grades: " + str(grades))

Useful Functions for Lists I


1. len() returns how many elements are in a list.
2. max() returns the greatest element of the list. How the greatest element is determined depends on
what type objects are in the list. The maximum element in a list of numbers is the largest number.
The maximum elements in a list of strings is element that would occur last if the list were sorted
alphabetically. This works because the the max function is defined in terms of the greater than
comparison operator. The max function is undefined for lists that contain elements from different,
incomparable types.
3. min() returns the smallest element in a list. min is the opposite of max, which returns the largest
element in a list.
4. sorted() returns a copy of a list in order from smallest to largest, leaving the list unchanged.

Useful Functions for Lists II


join method
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.
new_str = "\n".join(["fore", "aft", "starboard", "port"])
print(new_str)
Output:
fore
aft
starboard
port
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(["García", "O'Kelly"])
print(name)
Output:
García-O'Kelly
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 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.

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


dimensions = 52, 40, 100
length, width, height = dimensions
print("The dimensions are {} x {} x {}".format(length, width, height))
The parentheses are optional when defining tuples, and programmers
frequently omit them if parentheses don't clarify the code.

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

print("watermelon" in fruit) # check for element

fruit.add("watermelon") # add an element


print(fruit)

print(fruit.pop()) # remove a random element


print(fruit)
This outputs:
False
{'grapefruit', 'orange', 'watermelon', 'banana', 'apple'}
grapefruit
{'orange', 'watermelon', 'banana', 'apple'}
Other operations you can perform with sets include those of
mathematical sets. Methods like union, intersection, and difference are
easy to perform with sets, and are much faster than such operators with
other containers.
Have questions? Head to the forums for discussion with the Udacity
Community.

Dictionaries And Identity Operators

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

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)
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"}}

Congratulations on completing this lesson on


Data Structures!
A good understanding of data structures is integral for programming and
data analysis. As a data analyst, you will be working with data and code
all the time, so a solid understanding of what data types and data
structures are available and when to use each one will help you write
more efficient code.

Remember, you can get more practice on sites like HackerRank.


In this lesson, we covered four important data structures in Python:
Data Mutabl
Structure Ordered e Constructor Example

List Yes Yes [ ] or list() [5.7, 4, 'yes', 5.7]

Tuple Yes No ( ) or tuple() (5.7, 4, 'yes', 5.7)

Set No Yes {} * or set() {5.7, 4, 'yes'}

Dictionary No No** { } or dict() {'Jun': 75, 'Jul': 89}

* 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.

You might also like