0% found this document useful (0 votes)
74 views66 pages

Untitled Document

The document provides an overview of advanced Python topics including generators, list comprehensions, multiple function arguments, regular expressions, exception handling, sets, serialization, partial functions, code introspection, closures, decorators, and map/filter/reduce functions. It includes examples and exercises for some topics. The document is accompanied by additional information on DataCamp's online Python courses and certification opportunities.

Uploaded by

Bavithra Vasan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views66 pages

Untitled Document

The document provides an overview of advanced Python topics including generators, list comprehensions, multiple function arguments, regular expressions, exception handling, sets, serialization, partial functions, code introspection, closures, decorators, and map/filter/reduce functions. It includes examples and exercises for some topics. The document is accompanied by additional information on DataCamp's online Python courses and certification opportunities.

Uploaded by

Bavithra Vasan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

Advanced Tutorials

● Generators
● List Comprehensions
● Multiple Function Arguments
● Regular Expressions
● Exception Handling
● Sets
● Serialization
● Partial functions
● Code Introspection
● Closures
● Decorators
● Map, Filter, Reduce

Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data
Science by completing interactive coding challenges and watching videos by expert
instructors. Start Now!

Ready to take the test? Head onto LearnX and get your Python Certification!

Generators
Generators are very easy to implement, but a bit difficult to understand.

Generators are used to create iterators, but with a different approach. Generators are
simple functions which return an iterable set of items, one at a time, in a special way.

When an iteration over a set of item starts using the for statement, the generator is
run. Once the generator's function code reaches a "yield" statement, the generator
yields its execution back to the for loop, returning a new value from the set. The
generator function can generate as many values (possibly infinite) as it wants,
yielding each one in its turn.

Here is a simple example of a generator function which returns 7 random integers:


This function decides how to generate the random numbers on its own, and executes
the yield statements one at a time, pausing in between to yield execution back to the
main for loop.

Exercise
Write a generator function which returns the Fibonacci series. They are calculated
using the following formula: The first two numbers of the series is always equal to 1,
and each consecutive number returned is the sum of the last two numbers. Hint: Can
you use only two variables in the generator function? Remember that assignments
can be done simultaneously. The code
This site is generously supported by DataCamp. DataCamp offers online interactive
Python Tutorials for Data Science. Join over a million other learners and get started
learning Python for data science today!

Ready to take the test? Head onto LearnX and get your Python Certification!

Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data
Science by completing interactive coding challenges and watching videos by expert
instructors. Start Now!
Ready to take the test? Head onto LearnX and get your Python Certification!

List Comprehensions
List Comprehensions is a very powerful tool, which creates a new list based on
another list, in a single, readable line.

For example, let's say we need to create a list of integers which specify the length of
each word in a certain sentence, but only if the word is not the word "the".

Using a list comprehension, we could simplify this process to this notation:


Exercise
Using a list comprehension, create a new list called "newlist" out of the list
"numbers", which contains only the positive numbers from the list, as integers.

This site is generously supported by DataCamp. DataCamp offers online interactive


Python Tutorials for Data Science. Join over a million other learners and get started
learning Python for data science today!

Ready to take the test? Head onto LearnX and get your Python Certification!
Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data
Science by completing interactive coding challenges and watching videos by expert
instructors. Start Now!

Ready to take the test? Head onto LearnX and get your Python Certification!

Multiple Function Arguments


Every function in Python receives a predefined number of arguments, if declared
normally, like this:

Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data
Science by completing interactive coding challenges and watching videos by expert
instructors. Start Now!

Ready to take the test? Head onto LearnX and get your Python Certification!

Regular Expressions
Regular Expressions (sometimes shortened to regexp, regex, or re) are a tool for
matching patterns in text. In Python, we have the re module. The applications for
regular expressions are wide-spread, but they are fairly complex, so when
contemplating using a regex for a certain task, think about alternatives, and come to
regexes as a last resort.

An example regex is r"^(From|To|Cc).*[email protected]" Now for an


explanation: the caret ^ matches text at the beginning of a line. The following group,
the part with (From|To|Cc) means that the line has to start with one of the words
that are separated by the pipe |. That is called the OR operator, and the regex will
match if the line starts with any of the words in the group. The .*? means to
un-greedily match any number of characters, except the newline \n character. The
un-greedy part means to match as few repetitions as possible. The . character
means any non-newline character, the * means to repeat 0 or more times, and the ?
character makes it un-greedy.

So, the following lines would be matched by that regex: From:


[email protected] To: !asp]<,. [email protected]

A complete reference for the re syntax is available at the python docs.


As an example of a "proper" email-matching regex (like the one in the exercise), see
this

This site is generously supported by DataCamp. DataCamp offers online interactive


Python Tutorials for Data Science. Join over a million other learners and get started
learning Python for data science today!

Ready to take the test? Head onto LearnX and get your Python Certification!
Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data
Science by completing interactive coding challenges and watching videos by expert
instructors. Start Now!

Ready to take the test? Head onto LearnX and get your Python Certification!

Exception Handling
When programming, errors happen. It's just a fact of life. Perhaps the user gave bad
input. Maybe a network resource was unavailable. Maybe the program ran out of
memory. Or the programmer may have even made a mistake!

Python's solution to errors are exceptions. You might have seen an exception before.

Oops! Forgot to assign a value to the 'a' variable.

But sometimes you don't want exceptions to completely stop the program. You might
want to do something special when an exception is raised. This is done in a
try/except block.

Here's a trivial example: Suppose you're iterating over a list. You need to iterate over
20 numbers, but the list is made from user input, and might not have 20 numbers in
it. After you reach the end of the list, you just want the rest of the numbers to be
interpreted as a 0. Here's how you could do that:
There, that wasn't too hard! You can do that with any exception. For more details on
handling exceptions, look no further than the Python Docs

Exercise
Handle all the exception! Think back to the previous lessons to return the last name
of the actor.

This site is generously supported by DataCamp. DataCamp offers online interactive


Python Tutorials for Data Science. Join over a million other learners and get started
learning Python for data science today!
Ready to take the test? Head onto LearnX and get your Python Certification!

Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data
Science by completing interactive coding challenges and watching videos by expert
instructors. Start Now!

Ready to take the test? Head onto LearnX and get your Python Certification!

Sets
Sets are lists with no duplicate entries. Let's say you want to collect a list of words
used in a paragraph:

This will print out a list containing "my", "name", "is", "Eric", and finally "and". Since the
rest of the sentence uses words which are already in the set, they are not inserted
twice.

Sets are a powerful tool in Python since they have the ability to calculate differences
and intersections between other sets. For example, say you have a list of
participants in events A and B:
To find out which members attended both events, you may use the "intersection"
method:

To find out which members attended only one of the events, use the
"symmetric_difference" method:
To find out which members attended only one event and not the other, use the
"difference" method:

To receive a list of all participants, use the "union" method:


In the exercise below, use the given lists to print out a set containing all the
participants from event A which did not attend event B.
This site is generously supported by DataCamp. DataCamp offers online interactive
Python Tutorials for Data Science. Join over a million other learners and get started
learning Python for data science today!

Ready to take the test? Head onto LearnX and get your Python Certification!

Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data
Science by completing interactive coding challenges and watching videos by expert
instructors. Start Now!

Ready to take the test? Head onto LearnX and get your Python Certification!

Serialization
Python provides built-in JSON libraries to encode and decode JSON.

In Python 2.5, the simplejson module is used, whereas in Python 2.7, the json module
is used. Since this interpreter uses Python 2.7, we'll be using json.

In order to use the json module, it must first be imported:


There are two basic formats for JSON data. Either in a string or the object
datastructure. The object datastructure, in Python, consists of lists and dictionaries
nested inside each other. The object datastructure allows one to use python
methods (for lists and dictionaries) to add, list, search and remove elements from
the datastructure. The String format is mainly used to pass the data into another
program or load into a datastructure.

To load JSON back to a data structure, use the "loads" method. This method takes a
string and turns it back into the json object datastructure:
To encode a data structure to JSON, use the "dumps" method. This method
takes an object and returns a String:

Python supports a Python proprietary data serialization method called pickle (and a
faster alternative called cPickle).

You can use it exactly the same way.

The aim of this exercise is to print out the JSON string with key-value pair "Me"
: 800 added to it.
This site is generously supported by DataCamp. DataCamp offers online interactive
Python Tutorials for Data Science. Join over a million other learners and get started
learning Python for data science today!

Ready to take the test? Head onto LearnX and get your Python Certification!

Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data
Science by completing interactive coding challenges and watching videos by expert
instructors. Start Now!

Ready to take the test? Head onto LearnX and get your Python Certification!

Partial functions
You can create partial functions in python by using the partial function from the
functools library.

Partial functions allow one to derive a function with x parameters to a function with
fewer parameters and fixed values set for the more limited function.

Import required:
This code will return 8.

An important note: the default values will start replacing variables from the
left. The 2 will replace x. y will equal 4 when dbl(4) is called. It does not make
a difference in this example, but it does in the example below.
Exercise
Edit the function provided by calling partial() and replacing the first three variables in
func(). Then print with the new partial function using only one input variable so that
the output equals 60.
This site is generously supported by DataCamp. DataCamp offers online interactive
Python Tutorials for Data Science. Join over a million other learners and get started
learning Python for data science today!

Ready to take the test? Head onto LearnX and get your Python Certification!

Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data
Science by completing interactive coding challenges and watching videos by expert
instructors. Start Now!

Ready to take the test? Head onto LearnX and get your Python Certification!

Code Introspection
Code introspection is the ability to examine classes, functions and keywords to know
what they are, what they do and what they know.

Python provides several functions and utilities for code introspection.


Often the most important one is the help function, since you can use it to find what
other functions do.

Exercise
Print a list of all attributes of the given Vehicle object.

This site is generously supported by DataCamp. DataCamp offers online interactive


Python Tutorials for Data Science. Join over a million other learners and get started
learning Python for data science today!
Ready to take the test? Head onto LearnX and get your Python Certification!

Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data
Science by completing interactive coding challenges and watching videos by expert
instructors. Start Now!

Ready to take the test? Head onto LearnX and get your Python Certification!

Closures
A Closure is a function object that remembers values in enclosing scopes even if
they are not present in memory. Let us get to it step by step

Firstly, a Nested Function is a function defined inside another function. It's very
important to note that the nested functions can access the variables of the enclosing
scope. However, at least in python, they are only readonly. However, one can use the
"nonlocal" keyword explicitly with these variables in order to modify them.

For example:

This works well as the 'data_transmitter' function can access the 'message'.
To demonstrate the use of the "nonlocal" keyword, consider this
Without the nonlocal keyword, the output would be "3 9", however, with its usage, we
get "3 3", that is the value of the "number" variable gets modified.

Now, how about we return the function object rather than calling the nested function
within. (Remember that even functions are objects. (It's Python.))

And we call the function as follows:


Even though the execution of the "transmit_to_space()" was completed, the message
was rather preserved. This technique by which the data is attached to some code
even after end of those other original functions is called as closures in python

ADVANTAGE : Closures can avoid use of global variables and provides some form of
data hiding.(Eg. When there are few methods in a class, use closures instead).

Also, Decorators in Python make extensive use of closures.

Exercise
Make a nested loop and a python closure to make functions to get multiple
multiplication functions using closures. That is using closures, one could make
functions to create multiply_with_5() or multiply_with_4() functions using closures.
This site is generously supported by DataCamp. DataCamp offers online interactive
Python Tutorials for Data Science. Join over a million other learners and get started
learning Python for data science today!

Ready to take the test? Head onto LearnX and get your Python Certification!

Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data
Science by completing interactive coding challenges and watching videos by expert
instructors. Start Now!

Ready to take the test? Head onto LearnX and get your Python Certification!

Decorators
Decorators allow you to make simple modifications to callable objects like functions,
methods, or classes. We shall deal with functions for this tutorial. The syntax
Is equivalent to:

As you may have seen, a decorator is just another function which takes a
functions and returns one. For example you could do this:
This would make a function repeat twice.

You can also make it change the output


change input

and do checking.
Let's say you want to multiply the output by a variable amount. You could define the
decorator and use it as follows:
You can do anything you want with the old function, even completely ignore it!
Advanced decorators can also manipulate the doc string and argument number. For
some snazzy decorators, go to http://wiki.python.org/moin/PythonDecoratorLibrary.

Exercise
Make a decorator factory which returns a decorator that decorates functions with
one argument. The factory should take one argument, a type, and then returns a
decorator that makes function should check if the input is the correct type. If it is
wrong, it should print("Bad Type") (In reality, it should raise an error, but error raising
isn't in this tutorial). Look at the tutorial code and expected output to see what it is if
you are confused (I know I would be.) Using isinstance(object, type_of_object) or
type(object) might help.
This site is generously supported by DataCamp. DataCamp offers online interactive
Python Tutorials for Data Science. Join over a million other learners and get started
learning Python for data science today!

Ready to take the test? Head onto LearnX and get your Python Certification!

Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data
Science by completing interactive coding challenges and watching videos by expert
instructors. Start Now!

Ready to take the test? Head onto LearnX and get your Python Certification!

Map, Filter, Reduce


Map, Filter, and Reduce are paradigms of functional programming. They allow the
programmer (you) to write simpler, shorter code, without neccessarily needing to
bother about intricacies like loops and branching.

Essentially, these three functions allow you to apply a function across a number of
iterables, in one fell swoop. map and filter come built-in with Python (in the
__builtins__ module) and require no importing. reduce, however, needs to be
imported as it resides in the functools module. Let's get a better understanding of
how they all work, starting with map.
Map
The map() function in python has the following syntax:

map(func, *iterables)

Where func is the function on which each element in iterables (as many as they
are) would be applied on. Notice the asterisk(*) on iterables? It means there can be
as many iterables as possible, in so far func has that exact number as required input
arguments. Before we move on to an example, it's important that you note the
following:

1. In Python 2, the map() function returns a list. In Python 3, however, the


function returns a map object which is a generator object. To get the result as
a list, the built-in list() function can be called on the map object. i.e.
list(map(func, *iterables))
2. The number of arguments to func must be the number of iterables listed.

Let's see how these rules play out with the following examples.

Say I have a list (iterable) of my favourite pet names, all in lower case and I need
them in uppercase. Traditonally, in normal pythoning, I would do something like this:

Which would then output ['ALFRED', 'TABITHA', 'WILLIAM', 'ARLA']

With map() functions, it's not only easier, but it's also much more flexible. I simply do
this:
Which would also output the same result. Note that using the defined map() syntax
above, func in this case is str.upper and iterables is the my_pets list -- just one
iterable. Also note that we did not call the str.upper function (doing this:
str.upper()), as the map function does that for us on each element in the my_pets
list.

What's more important to note is that the str.upper function requires only one
argument by definition and so we passed just one iterable to it. So, if the function
you're passing requires two, or three, or n arguments, then you need to pass in two,
three or n iterables to it. Let me clarify this with another example.

Say I have a list of circle areas that I calculated somewhere, all in five decimal
places. And I need to round each element in the list up to its position decimal places,
meaning that I have to round up the first element in the list to one decimal place, the
second element in the list to two decimal places, the third element in the list to three
decimal places, etc. With map() this is a piece of cake. Let's see how.

Python already blesses us with the round() built-in function that takes two
arguments -- the number to round up and the number of decimal places to round the
number up to. So, since the function requires two arguments, we need to pass in two
iterables.
See the beauty of map()? Can you imagine the flexibility this evokes?

The range(1,7) function acts as the second argument to the round function (the
number of required decimal places per iteration). So as map iterates through
circle_areas, during the first iteration, the first element of circle_areas, 3.56773 is
passed along with the first element of range(1,7), 1 to round, making it effectively
become round(3.56773, 1). During the second iteration, the second element of
circle_areas, 5.57668 along with the second element of range(1,7), 2 is passed to
round making it translate to round(5.57668, 2). This happens until the end of the
circle_areas list is reached.

I'm sure you're wondering: "What if I pass in an iterable less than or more than the
length of the first iterable? That is, what if I pass range(1,3) or range(1, 9999) as
the second iterable in the above function". And the answer is simple: nothing! Okay,
that's not true. "Nothing" happens in the sense that the map() function will not raise
any exception, it will simply iterate over the elements until it can't find a second
argument to the function, at which point it simply stops and returns the result.

So, for example, if you evaluate result = list(map(round, circle_areas,


range(1,3))), you won't get any error even as the length of circle_areas and the
length of range(1,3) differ. Instead, this is what Python does: It takes the first
element of circle_areas and the first element of range(1,3) and passes it to
round. round evaluates it then saves the result. Then it goes on to the second
iteration, second element of circle_areas and second element of range(1,3),
round saves it again. Now, in the third iteration (circle_areas has a third element),
Python takes the third element of circle_areas and then tries to take the third
element of range(1,3) but since range(1,3) does not have a third element, Python
simply stops and returns the result, which in this case would simply be [3.6, 5.58].

Go ahead, try it.

The same thing happens if circle_areas is less than the length of the second
iterable. Python simply stops when it can't find the next element in one of the
iterables.

To consolidate our knowledge of the map() function, we are going to use it to


implement our own custom zip() function. The zip() function is a function that
takes a number of iterables and then creates a tuple containing each of the elements
in the iterables. Like map(), in Python 3, it returns a generator object, which can be
easily converted to a list by calling the built-in list function on it. Use the below
interpreter session to get a grip of zip() before we create ours with map()
As a bonus, can you guess what would happen in the above session if my_strings
and my_numbers are not of the same length? No? try it! Change the length of one of
them.

Onto our own custom zip() function!

Just look at that! We have the same result as zip.


Did you also notice that I didn't even need to create a function using the def
my_function() standard way? That's how flexible map(), and Python in general, is! I
simply used a lambda function. This is not to say that using the standard function
definition method (of def function_name()) isn't allowed, it still is. I simply
preferred to write less code (be "Pythonic").

That's all about map. Onto filter()

Filter
While map() passes each element in the iterable through a function and returns the
result of all elements having passed through the function, filter(), first of all,
requires the function to return boolean values (true or false) and then passes each
element in the iterable through the function, "filtering" away those that are false. It
has the following syntax:

filter(func, iterable)

The following points are to be noted regarding filter():

1. Unlike map(), only one iterable is required.


2. The func argument is required to return a boolean type. If it doesn't, filter
simply returns the iterable passed to it. Also, as only one iterable is required,
it's implicit that func must only take one argument.
3. filter passes each element in the iterable through func and returns only the
ones that evaluate to true. I mean, it's right there in the name -- a "filter".

Let's see some examples

The following is a list (iterable) of the scores of 10 students in a Chemistry exam.


Let's filter out those who passed with scores more than 75...using filter.
The next example will be a palindrome detector. A "palindrome" is a word, phrase, or
sequence that reads the same backwards as forwards. Let's filter out words that are
palindromes from a tuple (iterable) of suspected palindromes.

Which should output ['madam', 'anutforajaroftuna'].

Pretty neat huh? Finally, reduce()

Reduce
reduce applies a function of two arguments cumulatively to the elements of an
iterable, optionally starting with an initial argument. It has the following syntax:

reduce(func, iterable[, initial])

Where func is the function on which each element in the iterable gets cumulatively
applied to, and initial is the optional value that gets placed before the elements of
the iterable in the calculation, and serves as a default when the iterable is empty. The
following should be noted about reduce(): 1. func requires two arguments, the first
of which is the first element in iterable (if initial is not supplied) and the second
element in iterable. If initial is supplied, then it becomes the first argument to
func and the first element in iterable becomes the second element. 2. reduce
"reduces" (I know, forgive me) iterable into a single value.

As usual, let's see some examples.

Let's create our own version of Python's built-in sum() function. The sum() function
returns the sum of all the items in the iterable passed to it.

The result, as you'll expect is 68.

So, what happened?

As usual, it's all about iterations: reduce takes the first and second elements in
numbers and passes them to custom_sum respectively. custom_sum computes their
sum and returns it to reduce. reduce then takes that result and applies it as the first
element to custom_sum and takes the next element (third) in numbers as the second
element to custom_sum. It does this continuously (cumulatively) until numbers is
exhausted.

Let's see what happens when I use the optional initial value.
The result, as you'll expect, is 78 because reduce, initially, uses 10 as the first
argument to custom_sum.

That's all about Python's Map, Reduce, and Filter. Try on the below exercises to help
ascertain your understanding of each function.

Exercise
In this exercise, you'll use each of map, filter, and reduce to fix broken code.
This site is generously supported by DataCamp. DataCamp offers online interactive
Python Tutorials for Data Science. Join over a million other learners and get started
learning Python for data science today!

Ready to take the test? Head onto LearnX and get your Python Certification!

Other Python Tutorials


● DataCamp has tons of great interactive Python Tutorials covering data
manipulation, data visualization, statistics, machine learning, and more
● Read Python Tutorials and References course from After Hours Programming

Contributing Tutorials
Read more here: Contributing Tutorials

This site is generously supported by DataCamp. DataCamp offers online interactive


Python Tutorials for Data Science. Join over a million other learners and get started
learning Python for data science today!

Ready to take the test? Head onto LearnX and get your Python Certification!
The Python Interface
In the Python script on the right, you can type Python code to solve the exercises. If
you hit Run Code or Submit Answer, your python script (script.py) is executed
and the output is shown in the IPython Shell. Submit Answer checks whether your
submission is correct and gives you feedback.
You can hit Run Code and Submit Answer as often as you want. If you're stuck, you
can click Get Hint, and ultimately Get Solution.

You can also use the IPython Shell interactively by simply typing commands and
hitting Enter. When you work in the shell directly, your code will not be checked for
correctness so it is a great way to experiment.

Instructions
100 XP
● Experiment in the IPython Shell; type 5 / 8, for example.
● Add another line of code to the Python script on the top-right (not in the Shell):
print(7 + 10).
● Hit Submit Answer to execute the Python script and receive feedback.
When to use Python?
Python is a pretty versatile language. For which applications can you use Python?

Instructions
50 XP
Possible Answers

● You want to do some quick calculations.


● For your new business, you want to develop a database-driven website.
● Your boss asks you to clean and analyze the results of the latest satisfaction
survey.
● All of the above.

Any comments?
Something that Hugo didn't mention in his videos is that you can add comments to
your Python scripts. Comments are important to make sure that you and others can
understand what your code is about.

To add comments to your Python script, you can use the # tag. These comments are
not run as Python code, so they will not influence your result. As an example, take
the comment in the editor, # Division; it is completely ignored during execution.

Instructions
100 XP

Above the print(7 + 10), add the comment

# Addition
Python as a calculator
Python is perfectly suited to do basic calculations. Apart from addition, subtraction,
multiplication and division, there is also support for more advanced operations such
as:

● Exponentiation: **. This operator raises the number to its left to the power of
the number to its right. For example 4**2 will give 16.
● Modulo: %. This operator returns the remainder of the division of the number
to the left by the number on its right. For example 18 % 7 equals 4.

The code in the script gives some examples.

Instructions
100 XP

Suppose you have $100, which you can invest with a 10% return each year. After
one year, it's

100×1.1=110

dollars, and after two years it's

100×1.1×1.1=121
. Add code to calculate how much money you end up with after 7 years, and print the
result.

Take Hint (-30 XP)

# Addition, subtraction
print(5 + 5)
print(5 - 5)

# Multiplication, division, modulo, and exponentiation


print(3 * 5)
print(10 / 2)
print(18 % 7)
print(4 ** 2)

# How much is your $100 worth after 7 years?


print(100 * 1.1 ** 7)

10
0
15
5.0
4
16
194.87171000000012

In [1]:

Variable Assignment
In Python, a variable allows you to refer to a value with a name. To create a variable
use =, like this example:

x = 5

You can now use the name of this variable, x, instead of the actual value, 5.

Remember, = in Python means assignment, it doesn't test equality!

Instructions
100 XP
● Create a variable savings with the value 100.
● Check out this variable by typing print(savings) in the script.
Calculations with variables
Remember how you calculated the money you ended up with after 7 years of
investing $100? You did something like this:
100 * 1.1 ** 7

Instead of calculating with the actual values, you can use variables instead. The
savings variable you've created in the previous exercise represents the $100 you
started with. It's up to you to create a new variable to represent 1.1 and then redo
the calculations!

Instructions
100 XP
Instructions
100 XP
● Create a variable growth_multiplier, equal to 1.1.
● Create a variable, result, equal to the amount of money you saved after 7
years.
● Print out the value of result.
Other variable types
In the previous exercise, you worked with two Python data types:

● int, or integer: a number without a fractional part. savings, with the value
100, is an example of an integer.
● float, or floating point: a number that has both an integer and fractional part,
separated by a point. growth_multiplier, with the value 1.1, is an
example of a float.
Next to numerical data types, there are two other very common data types:

● str, or string: a type to represent text. You can use single or double quotes to
build a string.
● bool, or boolean: a type to represent logical values. Can only be True or
False (the capitalization is important!).

Instructions
100 XP
Instructions
100 XP
● Create a new string, desc, with the value "compound interest".
● Create a new boolean, profitable, with the value True.
Guess the type
To find out the type of a value or a variable that refers to that value, you can use the
type() function. Suppose you've defined a variable a, but you forgot the type of this
variable. To determine the type of a, simply execute:

type(a)

We already went ahead and created three variables: a, b and c. You can use the
IPython shell to discover their type. Which of the following options is correct?

Instructions
50 XP
Instructions
50 XP
Possible Answers

● a is of type int, b is of type str, c is of type bool


● a is of type float, b is of type bool, c is of type str
● a is of type float, b is of type str, c is of type bool
● a is of type int, b is of type bool, c is of type str
Operations with other types
Hugo mentioned that different types behave differently in Python.

When you sum two strings, for example, you'll get different behavior than when you
sum two integers or two booleans.

In the script some variables with different types have already been created. It's up to
you to use them.

Instructions
100 XP
Instructions
100 XP
● Calculate the product of savings and growth_multiplier. Store the
result in year1.
● What do you think the resulting type will be? Find out by printing out the type
of year1.
● Calculate the sum of desc and desc and store the result in a new variable
doubledesc.
● Print out doubledesc. Did you expect this?
Type conversion
Using the + operator to paste together two strings can be very useful in building
custom messages.

Suppose, for example, that you've calculated the return of your investment and want
to summarize the results in a string. Assuming the integer savings and float
result are defined, you can try something like this:

print("I started with $" + savings + " and now have $" +

result + ". Awesome!")

This will not work, though, as you cannot simply sum strings and integers/floats.

To fix the error, you'll need to explicitly convert the types of your variables. More
specifically, you'll need str(), to convert a value into a string. str(savings), for
example, will convert the integer savings to a string.

Similar functions such as int(), float() and bool() will help you convert Python
values into any type.

● Hit Run Code to run the code. Try to understand the error message.
● Fix the code such that the printout runs without errors; use the function str()
to convert the variables to strings.
● Convert the variable pi_string to a float and store this float as a new
variable, pi_float.
Can Python handle everything?
Now that you know something more about combining different sources of
information, have a look at the four Python expressions below. Which one of these
will throw an error? You can always copy and paste this code in the IPython Shell to
find out!

Instructions
50 XP
Possible Answers

● "I can add integers, like " + str(5) + " to strings."


● "I said " + ("Hey " * 2) + "Hey!"
● "The correct answer to this multiple choice exercise is
answer number " + 2
● True + False
Create a list
As opposed to int, bool etc., a list is a compound data type; you can group
values together:

a = "is"
b = "nice"
my_list = ["my", "list", a, b]
After measuring the height of your family, you decide to collect some information on
the house you're living in. The areas of the different parts of your house are stored in
separate variables for now, as shown in the script.

Instructions
100 XP
● Create a list, areas, that contains the area of the hallway (hall), kitchen
(kit), living room (liv), bedroom (bed) and bathroom (bath), in this order.
Use the predefined variables.
● Print areas with the print() function.
Select the valid list
A list can contain any Python type. But a list itself is also a Python type. That means
that a list can also contain a list! Python is getting funkier by the minute, but fear not,
just remember the list syntax:

my_list = [el1, el2, el3]

Can you tell which ones of the following lines of Python code are valid ways to build
a list?

A. [1, 3, 4, 2] B. [[1, 2, 3], [4, 5, 7]] C. [1 + 2, "a" * 5, 3]

Instructions
50 XP
Instructions
50 XP
Possible Answers

● A, B and C
● B
● B and C
● C
List of lists
As a data scientist, you'll often be dealing with a lot of data, and it will make sense to
group some of this data.

Instead of creating a flat list containing strings and floats, representing the names
and areas of the rooms in your house, you can create a list of lists. The script in the
editor can already give you an idea.

Don't get confused here: "hallway" is a string, while hall is a variable that
represents the float 11.25 you specified earlier.

Instructions
100 XP
● Finish the list of lists so that it also contains the bedroom and bathroom data.
Make sure you enter these in order!
● Print out house; does this way of structuring your data make more sense?
● Print out the type of house. Are you still dealing with a list?

You might also like