Python Course Solutions
Python Course Solutions
Exercise 1
Complete the following function so that given a national identity card (DNI) number, a letter is returned.
This letter is obtained by calculating the remainder of the DNI by 23 and from that value assign a letter
from the following table:
REMAINDER 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 2021 22
LETTER T R W A G M Y F P D X B N J Z S Q V V H L C K E
The DNI value will be an integer and the letter must be a character string containing a single uppercase
letter.
def exercise_1(dni):
result = "TRWAGMYFPDXBNJZSQVHLCKE"[dni % 23]
return result
Exercise 2
Complete the following function so that given the price of a product, the total price to be paid by the
customer, i.e. including VAT (21% on the product price), is calculated and returned. The total price should
be the price value only, i.e. it should not contain the currency symbol.
def exercise_2(price):
result = round(price * 1.21, 2)
return result
Exercise 3
Complete the following function so that given the diameter of a circle, the area of the circle containing the
circle is calculated. The PI value will be 3.1415.
def exercise_3(diameter):
result = 3.1415 * ((diameter / 2) ** 2)
return result
Exercise 4
Complete the function so that given two integers and two whole numbers, we calculate the quotient and
the remainder of doing the integer division between n and m.
Exercise 5
Complete the function so that given the number of units a user has purchased of 2 different products,
return the total weight of the package to send his purchase by courier. The weight of each unit of product1
is 147 units and the weight of each unit of product2 is 2400 units. The function should return only the total
weight.
ACTIVITY 2
Exercise 1
Write a function called exercise1 that generates a list of 15 random integer values ranging from 1 to 100.
The function must return the list with all values.
import random as r
def exercise1():
output_list = []
for i in range(15):
output_list.append(r.randint(1, 100))
return output_list
Exercise 2
Write a function called exercise2 that receives 2 arguments: the first will be the list that we have
implemented in Exercise 1 and the second a number by which each of the elements of the list will be
divided. The result will be a new list.
Exercise 3
Using anonymous functions, create a new list containing the integer values of each of the elements of the
list returned by the function implemented in Exercise 2.
Exercise 4
Implement a function, called exercise4, that receives as arguments two integers and returns in a tuple the
following values: the factorial of the first argument and the greatest common divisor of both arguments.
import math as m
def exercise4(number1, number2):
factorial = m .factorial(numero1)
mcd = m .gcd(number1, number2)
return factorial, mcd
Exercise 5
Create an exercise5 function that returns a list of all values contained in a list passed as an argument but
eliminating repeated values. Test the operation of this function with the list obtained in Exercise 1.
def exercise5(input_list):
output_list = []
for i in input_list:
if i not in output_list:
output_list.append(i)
return listsoutput
ACTIVITY 3
Exercise 1
Write a class called Number. This class must have a constructor that receives a number and stores that
number in 2 attributes: Roman that will store the number in Roman numeral format as a string and normal
that will store the number given to us in the constructor.
Exercise 2
Creates two new methods in the Number class. The first method, called print() prints a message showing
the value of both attributes; the second attribute, sum_roman() will have as parameters a string of
characters that will represent another Roman numeral and that we will add to the attributes we already had.
Exercise 3
Defines a function within the Number class that, starting from a string of characters, returns True if that
string of characters corresponds to a Roman numeral and false otherwise. Then, modify the method to
throw an error in case the value passed as a parameter does not correspond to the pattern of a Roman
numeral
import re
class Numero:
def print(self):
string = ("{} {}")
print(string.format(self.normal, self.roman))
def roman_a_normal(roman):
Python was created for the purpose of:..............................................................................1
Which of the following properties does Python have?.......................................................1
The version of Python we should use is:............................................................................1
Which of the following tools can we not use to program in Python?................................1
How can I install Jupyter Notebook on my computer?......................................................1
What is the difference between Python distributions?.......................................................7
What is Jupyter Notebook?................................................................................................7
What type of cells can we use in Jupyter Notebook?.........................................................7
What kind of files can't we create with the Jupyter Notebook file browser?.....................7
In Jupyter Notebook:..........................................................................................................7
Identifiers in Python:..........................................................................................................2
Which of these statements is not correct?..........................................................................2
What should we use to make Python detect different code blocks?...................................2
What type of data does the following operation return? 2 / 3............................................2
We have the following string stored in a variable: phrase = "Hello, Python!". If we
access the positions phrase[-7:12], what will be the result?...............................................9
Using the same variable as in the previous question, we execute the following
instruction: phrase.replace("Goodbye", "Good morning"). What will be the result?........9
Continuing with the previous variable, what is the result of this statement: len("Hello")
<= phrase.find(',')................................................................................................................9
When can an object be converted to a character string?.....................................................9
What is the result of the following Boolean operation: bool(0) or not(bool())..................9
Which of these statements is not correct?..........................................................................3
To access the value of a dictionary element we need to know:..........................................3
The sets are:........................................................................................................................3
In a conditional execution, a block of code after an else statement is executed:...............3
In a while loop, a block of code after an else statement is executed:.................................3
How many times will the message be printed in this code? for i in range(1,9):................3
What numbers will not be printed in this code?.................................................................3
Which of the following would return the even numbers from 0 to 19?...........................11
What will be the result of running this code? list = ['a',
5, 7] 11
Which of the following objects cannot be used in an iterator?........................................11
How many arguments can the following function receive and how should they be set?...4
What is the result of executing the following function?.....................................................4
The return statement of a function allows:.........................................................................4
Which Python function can be used to obtain the integer part of a number?.....................4
What is the functionality of the sys.argv variable?............................................................4
We want to check if the file '/Folder/file.py' exists on the system. How could this be
done in the simplest way?...................................................................................................4
What does the following function return?........................................................................13
An anonymous function:..................................................................................................13
What does the following function return?........................................................................13
What does the following function return: function = lambda x: str(x)
list(map(map(function, [1, 2, 3, 4, 4, 5, 6, 7, 8, 9, 10]))...................................................13
What is the main feature of the modules?..........................................................................5
How useful is the alias when importing a module?............................................................5
How should we create a package in Python?.....................................................................5
In the following package import, how should we access the test() function of the module
my_module?.......................................................................................................................5
What is an object?..............................................................................................................5
When we implement a method in a class, what is the self parameter for?.........................5
For the next class, how could we create an instance?......................................................15
When we implement a class that is an inheritance of another class, what elements of the
parent class can we access from the child class?..............................................................15
Suppose we have implemented the following classes. What will be displayed in the
console if we execute the print method of the object?.....................................................15
What are docstrings used for?..........................................................................................15
Running the following code, what result will be displayed at the end of the execution?. .6
In the following example, what pattern are you looking for?............................................6
What does the match() function return when it has not found any results in the string?...6
What is an exception?.........................................................................................................6
When is the else block executed in try-except statements?................................................6
When is the finally block executed in try-except statements?............................................6
What result will the execution of the following code return?..........................................17
Which list will the next instruction block return?............................................................17
What data structures can be created with the compression technique?............................17
How to create a matrix with 3 rows and 3 columns using numpy?....................................7
numpy is a useful library for:.............................................................................................7
pandas is:............................................................................................................................7
To obtain with pandas the statistical information of the structure and information
contained in a dataframe we call the function:...................................................................7
The iloc function of pandas:...............................................................................................7
The statement df[df.A>0]:..................................................................................................7
What does the groupby() function do in pandas?...............................................................7
What does the substract() function do in pandas?............................................................19
Which function allows us to sort a dataframe by its index?.............................................19
How should I call the read_csv() function to read a test.csv file where the values are
separated by semicolons (;)?............................................................................................19
The data used in the graphs in matplotlib, what type of data structure should they have? 8
What is the name of the function that allows us to display matplotlib plots?....................8
To generate a histogram, which matplotlib function should we use?................................8
To create a pie chart the data must:....................................................................................8
What does the savefig() function in matplotlib do?...........................................................8
In plotly, each of the plots is represented by an object in the module:..............................8
Which attribute of the Scatter object should we modify to make the graph a dot plot?...21
Which attribute allows us to modify the range of values to be displayed in a histogram?
..........................................................................................................................................21
Do the values of a Pie chart need to be normalized, i.e. add up to 1?..............................21
To generate an image with several graphs, which function should we use?....................21
Exercise 4
Implements a BestNumber class. This class will inherit the properties of Numero and will include two new
methods to subtract and multiply attributes by receiving another Roman numeral as parameter.
Exercise 5
In the BestNumber class, create a new method that receives a list of 3 Roman numerals. Then, iterating
over the elements of the list will call the function sum_romano(). Possible errors will have to be handled
with exceptions to display a message and continue executing the next issue.
class BestNumber(Number):
def __init__(self, normal):
self.roman = Numero .normal_a_romano(normal) self.normal = Num
ero.normal
ACTIVITY 4
Exercise 1
Create a function called exercise1, which receives the path where a dataset is located and returns a
DataFrame with the data in the dataset. To test this function use the titanic.csv dataset included in
this activity.
import pandas as pd
def exercise1(dataset):
return pd.read_csv(dataset)
Exercise 2
Create another function called exercise2. This function receives a single argument which is a dataframe.
Specifically, it must receive the dataframe obtained from reading the titanic.csv dataset. This
function will return another dataset including only passengers under 35 years of age and traveling in 3rd
class.
def exercise2(dataframe):
filter = dataframe [(dataframe.Age < 35) & (dataframe.Pclass == 3)]
return filter
Exercise 3
Create a function called exercise3, which, receiving as argument the output dataframe of exercise 2,
calculates the percentage of passengers under 35 years of age in 3rd class who survived.
def exercise3(dataframe):
total_records = dataframe .Survived.count()
survivors = dataframe [(dataframe.Survived ==
1)].Survived.count()
p_survivors = (survivors * 100) / total_records
return p_survivors
Exercise 4
Implement a function called exercise4 that, receiving the dataframe with the Titanic data, returns in a tuple
the percentage of men and women who traveled on the Titanic, rounded to the second decimal place.
def exercise4(dataframe):
total_records = dataframe .Survived.count()
n_men = dataframe[(dataframe.Sex == "male")].Sex.count()
n_women = dataframe[(dataframe.Sex == "female")].Sex.count()
p_men = round((n_men * 100) / total_records, 2)
p_women = round((n_women * 100) / total_records, 2)
return p_men, p_women
Exercise 5
Implement a function called exercise5 that receives the dataframe with the Titanic data and returns in a
list the number of passengers that traveled in 1st, 2nd and 3rd class.
def exercise5(dataframe):
list = []
list.insert(0, dataframe[(dataframe.Pclass == 1)].Pclass.count())
list.insert(1, dataframe[(dataframe.Pclass == 2)].Pclass.count())
list.insert(2, dataframe[(dataframe.Pclass == 3)].Pclass.count())
return list
Test
Subject 1
Python was created for the purpose of:
A. To be more powerful than other languages of the time.
B. Create a language that is easy to use and learn.
C. Programming using visual interfaces.
D. To be able to create server applications more easily.
Python's main goal was to create a language as powerful as others of the time but easy to use
and learn by simplifying its syntax.
The version of Python that we should use, whatever our equipment, is version 3.8 or later, as
other versions have been discontinued since January 2020.
Python allows the use of different tools to create programs, from the system console to
advanced environments. However, you cannot create non-plain text programs such as Word
or WordPad.
The Anaconda distribution includes more modules than the basic version of Python because it
is oriented towards data analysis. In addition, both distributions allow you to install new
modules.
Jupyter Notebook is a development environment whose main feature is the cells, which allow
you to create blocks with different contents such as Python code, text or graphics.
In Jupyter Notebook we can create cells containing Python and text code, either in markdown
or console format.
What kind of files can't we create with the Jupyter Notebook file browser?
A. Notebooks.
B. Folders.
C. Text Files.
D. PDF files.
Within the Jupyter Notebook file browser we can create different types of files such as folders,
notebooks or text files. However, other formats such as PDF files cannot be created here.
In Jupyter Notebook:
A. Output cells are created automatically.
B. We have to execute the instructions in the Python console.
C. Notebooks cannot be exported to other formats such as PDF or HTML.
D. You cannot restart the kernel to clear the memory.
The only cells that are automatically created in Jupyter Notebook are the output cells, which
show the result of a cell containing Python code. It is not necessary to execute the instructions
in the console and actions C and D are allowed in Jupyter.
Test
Subject 2
Identifiers in Python:
A. They can have any type of character or symbol.
B. They cannot be capitalized.
C. They have a maximum length of 20 characters.
D. They can include digits as long as they are not at the beginning of the identifier.
Identifiers in Python cannot include special symbols, can be lowercase or uppercase, can
include digits except at the beginning of the identifier, and can be of any length.
In Python we use the four-space indentation to define new code blocks, for example, after
declaring an if statement.
This operator is a normal division so, even if it is two integers, the data type returned by this
operator is float.
If we start from a var variable with an initial value equal to 10 and we want to multiply it by
3 storing the result in the same variable, what is the most effective way to achieve this?
A. var = var + 10.
B. var += int('10').
C. var -= 10.
D. var*= 3
The most effective way to multiply 3 to a variable and store the value in the same variable is to
use multiplication with assignment. In addition, no change in the data type is required.
We have the following string stored in a variable: phrase = "Hello, Python!". If we access the
positions phrase[-7:12], what will be the result?
A. "Python.
B. "Hello."
C. "the, P".
D. It will return an error.
In this case we are accessing from position 7 counting from the right, i.e., P, to position 11
counting from the left (it is position 12 minus one position), i.e., n. The result is "Python".
Using the same variable as in the previous question, we execute the following instruction:
phrase.replace("Goodbye", "Good morning"). What will be the result?
A. "Goodbye, Python!".
B. It will return an error.
C. "Hello, Good morning."
D. "Hello, Python!".
Since there is no match to "Goodbye" within the phrase variable, it will return the same value
that the phrase variable originally had.
Continuing with the previous variable, what is the result of this statement: len("Hello") <=
phrase.find(',')
A. True.
B. It will return an error.
C. False.
D. "False".
This operation is comparing whether the length of the string "Hello" (4) is less than or equal to
the position of the comma within the variable phrase (4). Being a comparison operator, it will
return a boolean data and, if true, it will return True.
The result will be True, since the first operator bool(0) will return False and the second
operator will return not(False), i.e. True. So the result of False or True will be True.
Test
Subject 3
Which of these statements is not correct?
A. The objects included in a list can be modified.
B. The elements of a list can only be of the same type.
C. Lists can contain other data structures, such as another list.
D. There are two ways to create an empty list.
Arrays are data structures that store their objects in an unordered form without repetition.
How many times will the message be printed in this code? for i in range(1,9):
A. 10.
B. 8.
C. 9.
D. 11.
The iterator will go through the different positions of the list, when calling the next function,
it will return the first element of the list 'a'. As it is a string type, the multiplication returns the
letter 'a' repeated 10 times.
Which Python function can be used to obtain the integer part of a number?
A. math.trunc().
B. math.ceil().
C. sys.trunc().
D. It does not exist, a new function must be implemented.
The Python math library has many arithmetic functions that we can use, including the
trunc() function that returns the integer part of a decimal number.
We want to check if the file '/Folder/file.py' exists on the system. How could this be
done in the simplest way?
A. Creating a function that reads files in the system.
B. Create the same file and, if it gives error, it means that it already exists.
C. Using the os.path.basename() function.
D. Using the os.path.exists() function.
What does the following function return?
def test():
list = [2, 6, 'Hello', 10, 7]
return random.choice(list)
A. A permutation of the elements defined in the list.
B. A randomly selected item from the list.
C. A random number from 0 to the highest number in the list.
D. Several randomly selected items from the list.
An anonymous function:
A. It must have only one arithmetic expression.
B. You can have a block with several instructions.
C. It must have a single expression, regardless of the type of that expression.
D. It cannot be stored in a variable.
In this code fragment a map is being applied to convert each of the elements of the list into
string objects.
Test
Subject 5
What is the main feature of the modules?
A. To be able to test our development.
B. Organize the code so that we can group the different elements we develop.
C. Implement the graphical interface of our application.
D. Adapt our programming code to a development environment.
When importing a module we can assign an alias to it. This alias allows us to refer to the
module with a new identifier that is usually shorter or easier to remember.
In the following package import, how should we access the test() function of the module
my_module?
from package import my_module as mod
A. package.my_module.test().
B. my_module.mod.test().
C. package.mod.test().
D. mod.test().
What is an object?
A. A set of functions for our code.
B. A module that can be included in Python.
C. An abstraction of data that has state, behavior and identity.
D. A data structure.
When we implement a method inside a class we must pass as first parameter the element self.
This parameter is used to allow the method to access the instance of the object that invoked
the method.
For the next class, how could we create an instance?
class MyClass:
def __init__(self, name, score=0.0):
self.name = name
self.score = score
For the next class, how could we create an instance? class
MyClass:
def __init__(self, name, score=0.0): self.name = name
self.score = score
A. object = new MyClass().
B. object = MyClass().
C. object = MyClass.__init__('Hello', 10).
D. object = MyClass('Hello').
When we implement a class that is an inheritance of another class, what elements of the
parent class can we access from the child class?
A. Only to the attributes of the parent class.
B. Only to the methods of the parent class.
C. To the attributes and methods of the parent class.
D. Only to the constructor of the parent class.
Suppose we have implemented the following classes. What will be displayed in the console if
we execute the print method of the object?
class ParentClass:
def print(self):
print('Hello, I am the parent class')
class DaughterClass(ParentClass):
def print(self):
print('Hello, I am the child class')
object = DaughterClass()
A. It will display an error as it does not know which method we are referring to.
B. "Hi, I'm the daughter class."
C. "Hi, I'm the parent class."
D. It cannot be printed because we have not passed the self argument.
What does the match() function return when it has not found any results in the string?
A. The same input character string.
B. None.
C. -1.
D. Returns a failure.
What is an exception?
A. A variable where an error that has occurred is stored.
B. The block of code that can produce failures.
C. A bug that Python throws when it has failed to execute a statement.
D. A block of code that allows the execution of a program to continue when an error has been
detected.
The else statement is placed at the end of the try-except block and allows us to define a set of
instructions to be executed when there is no error in the try statement.
From the following list, we want to create a dictionary where, for each element, the key is
the user's name and the value is the age. Only users under 35 years of age will be stored in
the dictionary. Which of the following statements should be used? users = [[['Juan', 33],
['Alicia', 28], ['Rebeca', 56]]]
A. [item[0]: item[1] for item in users if item[1] < 35].
B. {item[0]: item[1] for item in users if item[0] < 35}.
C. [item[0]: item[1] for item in users}.
D. {item[0]: item[1] for item in users if item[1] < 35}.
Test
Subject 7
How to create a matrix with 3 rows and 3 columns using numpy?
A. np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]).
B. np.array([[[1, 2, 3, 4], [5, 6, 7, 8, 9]]]).
C. np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]]]).
D. np.matrix([[[1, 2, 3], [4, 5, 6], [7, 8, 9]])).
pandas is:
A. A programming language.
B. A symbolic calculation library.
C. A library to facilitate data processing.
D. All of the above.
To obtain with pandas the statistical information of the structure and information contained
in a dataframe we call the function:
A. summary().
B. descr().
C. describe().
D. review().
The iloc function allows us to access a dataframe position using the index, that is, the position
number it occupies.
How should I call the read_csv() function to read a test.csv file where the values are
separated by semicolons (;)?
A. read_csv('test.csv').
B. read_csv('test.csv', ';').
C. read_csv('test.csv', sep=[',', ';']).
D. read_csv('test.csv', sep=';').
Test
Subject 8
The data used in the graphs in matplotlib, what type of data structure should they have?
A. numpy lists or arrays.
B. Sets.
C. Text string.
D. Tuples.
matplotlib reads data from structures such as Python lists or numpy arrays to generate the
plots.
What is the name of the function that allows us to display matplotlib plots?
A. iplot().
B. graph().
C. show().
D. plot().
In Scatter objects we can change the type of graph (line or point) with the attribute
mode=`marker`. Then, we can change the type of point displayed with the symbol attribute.