0% found this document useful (0 votes)
48 views27 pages

Python Course Solutions

The document provides examples of functions to complete for various exercises related to Python programming. The functions cover topics like calculating letters from national identity numbers, VAT calculations, circle area, integer division, weight calculations, random number lists, factorials, greatest common divisors, Roman numeral conversions, and checking for file existence.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views27 pages

Python Course Solutions

The document provides examples of functions to complete for various exercises related to Python programming. The functions cover topics like calculating letters from national identity numbers, VAT calculations, circle area, integer division, weight calculations, random number lists, factorials, greatest common divisors, Roman numeral conversions, and checking for file existence.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

ACTIVITY 1

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.

def exercise_4(number1, number2):


quotient = number1 // number2
remainder = number1 % number2
return quotient, remainder

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.

def exercise_5(product1, product2):


result = ( product1 * 147) + (product2 * 2400)
return result

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.

def ejercicio2(lista_entrada, divisor): lista_salida = []


for i in range(len(input_list)): output_list.append(input_list[i]):
output_list.append(input_list[i]) / divisor)
return output_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.

exercise3 = lambda p : [int(p[i]) for i in range(len(p))]]

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:

Roman = "" normal = ""

def __init__(self, normal):


self.roman = Numero.normal_a_romano(normal)
self.normal = normal

def print(self):
string = ("{} {}")
print(string.format(self.normal, self.roman))

def sum_romano(self, romano):


numero_anterior = Numero .romano_a_normal(self.romano)
numero_nuevo = Numero .romano_a_normal(romano) res = int
(numero_anterior) + int(new_number)
self.roman = Numero.normal_a_romano(res)
self.normal = res

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

for i in range(0, len(roman)):


if i == 0 or dic[roman[i]] <= dic[roman[i - 1]]:
res += dic[roman[i]]
else:
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
while normal:
div = normal // num[i]

normal %= num[i] while div:


res += str(rom[i])
div -= 1
i -= 1
return res

def is_romano(self, romano):


roman_pattern =
M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$" if
re.search(roman_pattern, roman):
return True
else:
return False

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

def subtract(self, Roman):


numero_anterior = Numero .romano_a_normal(self.romano)
numero_nuevo = Numero .romano_a_normal(romano) res = int
(numero_anterior) - int (new_number)
self.roman = Numero.normal_a_roman(res)
self.normal = res

def multiply(self, Roman):


numero_anterior = Numero .romano_a_normal(self.romano)
numero_nuevo = Numero .romano_a_normal(romano) res = int
(numero_anterior) * int(new_number)
self.roman = Numero.normal_a_roman(res)
self.normal = res

def iterate(self, list):


numero_anterior = Numero . numero .romano_a_normal(self.romano)
accumulator = 0
for element in lista:
try:
accumulator += Numero.roman_a_normal(element) except
TypeError:
print("The number failed " + str(element))
res = previous_number + accumulator
self.roman = self .roman = Numero .normal_a_romano(res)
self.normal = res

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.

Which of the following properties does Python have?


A. The type of the variables is done dynamically.
B. They can be programmed in different paradigms such as object-oriented programming or
functional programming.
C. We can extend the functionality of Python by creating C++ modules.
D. All of the above.

The version of Python we should use is:


A. We have to use version 3.8 or later.
B. We can use any version of Python, since they do not change much.
C. We have to use version 2.7.
D. It depends on the characteristics of our equipment.

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.

Which of the following tools can we not use to program in Python?


A. Plain text editor such as Atom.
B. The system console.
C. Office applications such as Word.
D. Advanced development environments such as PyCharm.

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.

How can I install Jupyter Notebook on my computer?


A. Installing the Anaconda distribution.
B. Installing the basic Python distribution.
C. Installing a plain text editor.
D. Through a subscription.

Jupyter Notebook is a free application that is included in the Anaconda distribution.


What is the difference between Python distributions?
A. The basic Python distribution includes more modules than Anaconda.
B. The Anaconda distribution includes more modules than the basic version.
C. Anaconda does not allow to install more modules.
D. The basic version of Python does not allow you to install more modules.

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.

What is Jupyter Notebook?


A. A plain text editor.
B. A console command to execute Python instructions.
C. An environment that allows you to create cells with different functionalities (writing code,
documenting, etc.).
D. Another distribution to install Python in our computer.

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.

What type of cells can we use in Jupyter Notebook?


A. Cells with Python code.
B. Cells with markdown-based text.
C. Console formatted text.
D. All of the above.

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.

Which of these statements is not correct?


A. Comments can be single-line or block comments.
B. I can create an identifier called and.
C. Identifiers cannot contain special symbols (@, $...).
D. Python does not execute comments.

What should we use to make Python detect different code blocks?


A. Keys ({}).
B. The reserved words begin and end.
C. Indents of one or more spaces.
D. Four-space indents.

In Python we use the four-space indentation to define new code blocks, for example, after
declaring an if statement.

What type of data does the following operation return? 2 / 3


A. int.
B. bool.
C. float.
D. error.

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.

When can an object be converted to a character string?


A. Provided that the object is not a complex number.
B. Provided that the value of the object is not None.
C. Always.
D. Only if the object has characters.

Modifying a basic type object or None to a string has no restrictions.

What is the result of the following Boolean operation: bool(0) or not(bool())


A. False.
B. It will give an error for not putting an object in the bool() statement.
C. It will give an error because logical operations cannot be used while changing the data
type.
D. 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.

To access the value of a dictionary element we need to know:


A. Its position in the dictionary.
B. The size of the dictionary.
C. The value of the element we want to access.
D. The key that has been assigned to the element.

The sets are:


A. Unordered collections of elements without repetitions
B. Unordered collections of elements with repetitions.
C. Ordered collections of elements without repetitions.
D. Ordered collections of elements with repetitions.

Arrays are data structures that store their objects in an unordered form without repetition.

In a conditional execution, a block of code after an else statement is executed:


A. If the expression of the if statement resulted in False.
B. If the expressions of the if and elif statements have resulted in False.
C. If the else statement expression resulted in False.
D. Always.

In a while loop, a block of code after an else statement is executed:


A. If the while statement expression resulted in True.
B. Only if there has been an error in the execution.
C. Before executing the loop.
D. Always.

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.

What numbers will not be printed in this code?


for i in range(1,10):
if (i % 3 != 0):
print(i)
else:
continue
A. 3.
B. 1, 9.
Test
Subject 4
C. 3, 6, 9.
D. All will be displayed.
Which of the following would return the even numbers from 0 to 19?
A. range(0,19).
B. range(20).
C. range(0, 20, 2).
D. range(0, 20, 1).

What will be the result of running this code? list = ['a', 5, 7]


iterator = iter(list) next(iterator) * 10
A. 'aaaaaaaaaaaaaa'.
B. 50.
C. 70.
D. None.

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 of the following objects cannot be used in an iterator?


A. A string of characters.
B. A dictionary.
C. A whole number.
D. A tuple.
Test
Subject 4
How many arguments can the following function receive and how should they be set?
def example(*args):
print(args)
A. A single argument.
B. As many as you want, and they will be placed by position.
C. As many as you want, and they will be placed by name.
D. It does not admit arguments.

What is the result of executing the following function?


def calculo(numero_1, numero_2 = 3): return numero1 / numero2
A. 0.
B. It will return a runtime error.
C. 3.33.
D. 10.

The return statement of a function allows:


A. Return a single result.
B. Return more of aresult, but to will return like a list.
C. Return more of aresult, but to will return like a set.
D. Return more of aresult, but to will return like a tuple.

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.

What is the functionality of the sys.argv variable?


A. Store the path where Python is located.
B. Store the arguments entered in the console when executing the script.
C. Store the Python version.
D. Store the name of the system user.

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.

What does the following function return?


function = lambda x: x >= 5 and x < 10
list(filter(function, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
A. [1, 2, 3, 4].
B. [5, 10].
C. [2, 4, 6, 8, 10].
D. [5, 6, 7, 8, 9].

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]))
A. A list with all the elements converted to a string.
B. A list equal to the one passed as a parameter.
C. It will give an error because a list cannot be converted to a string.
D. It will return an empty list.

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.

How useful is the alias when importing a module?


A. The alias allows you to assign another identifier to this module.
B. The alias should be set for modules that take up a lot of space.
C. Aliases cannot be used when importing modules, only when importing packages.
D. Aliasing improves the efficiency of a module.

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.

How should we create a package in Python?


A. Creating a folder whose name starts with pkg.
B. Creating a module that only includes import instructions.
C. Creating a folder where a file named __init__.py exists.
D. Assigning modules to a package type object.

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 in a class, what is the self parameter for?


A. To give the method the instance of the object to use.
B. This is an anonymous parameter.
C. This parameter indicates that the function is a method.
D. This parameter does not have to be included in the methods.

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 are docstrings used for?


A. To obtain module, package or class information, such as creation date, author, etc.
B. To define string type variables.
C. To define constants in a module.
D. To write documentation that can then be consulted by the help() instruction.
Test
Subject 6
Running the following code, what result will be displayed at the end of the execution?
message = 'Hi, I like to study Python' re.sub('\w{4},', 'Good
morning', message) A. "Hi, I like to study Python."
B. It will return an error.
C. "Good morning I like to study Python."
D. "Good morning, I like to study Python."

In the following example, what pattern are you looking for?


string = 'Today 10 people ate a 12 euro menu. and 2 children 2
sandwiches for 4 euros. In total we paid 128 euros.' result =
re.findall('\d+', string)
print(result)
A. The numbers of more than one digit in the string, i.e. ['10', '12', '128'].
B. Words containing the character d more than once.
C. Numbers having 1 digit or none, i.e. ['2', '2', '4'].
D. All numbers in the string, i.e. ['10', '12', '2', '2', '2', '4', '128'].

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.

When is the else block executed in try-except statements?


A. It is executed when there has been no error in the try block.
B. It is always executed, whether or not an error occurs.
C. It is executed when an error has occurred in the try statement.
D. There is no else statement within a try-except block.

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.

When is the finally block executed in try-except statements?


A. There is no finally statement within a try-except block.
B. It is always executed, whether or not an error occurs.
C. It is executed when there has been no error in the try block.
D. They are executed when an error has occurred in the try statement.
What result will the execution of the following code return?
try: hello'+ 5
except ValueError: print('Error 1')
except TypeError: print('Error 2')
except: print('Error 3')
A. Hello5.
B. Error 3.
C. Error 1.
D. Error 2.

Which list will the next instruction block return?


list = list(range(1,10)) [x / 2 for x in list if x * 4 < 15]
A. [2.0, 2.5, 3.0, 3.5, 4.0, 4.5].
B. [0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5].
C. [1, 2, 3].
D. [0.5, 1.0, 1.5].

What data structures can be created with the compression technique?


A. Lists only.
B. Lists, sets and dictionaries.
C. Lists and dictionaries.
D. From any data structure.

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

numpy is a useful library for:


A. Process CSV files.
B. Interactive visualization.
C. Streaming.
D. Calculation of vectors and matrices.

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 of pandas:


A. It allows us to access the values through the index position.
B. Returns the memory location of a value.
C. Returns a pointer to memory.
D. Returns a logical value.

The iloc function allows us to access a dataframe position using the index, that is, the position
number it occupies.

The statement df[df.A>0]:


A. It does not work.
B. Makes all values of A in df greater than zero.
C. Change df by removing all values less than zero.
D. Displays only the rows of df that in its column A have a value greater than zero.

What does the groupby() function do in pandas?


A. Allows to join more than one dataframe.
B. Allows you to group the data according to the values of the columns specified by the by=
argument.
C. Allows to sum all the values of a column of the dataframe.
Test
Subject 8
D. Displays the dataframe indexes.
What does the substract() function do in pandas?
A. Gets the length of the array.
B. Sum the values of all the elements of an array.
C. Subtracts a value from all the elements of an array.
D. Subtract the values of two arrays element by element.

Which function allows us to sort a dataframe by its index?


A. sort_values(index).
B. sort(index).
C. sort_index().
D. You can only sort by columns, not by indexes.

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().

To generate a histogram, which matplotlib function should we use?


A. bar().
B. hist().
C. plot().
D. hist2d().

To create a pie chart the data must:


A. Add 100%.
B. Add 100 to make the cake complete.
C. Add between 0 and 1, the pie being complete only when they add up to 1.
D. Being whole numbers

What does the savefig() function in matplotlib do?


A. Include a graphic in an image that already contains other graphics.
B. Export the image of the graph as a .pdf, .png, .svg or .jpg file.
C. Store the figure metadata in a .json file.
D. Save the figure in a variable for later use.

In plotly, each of the plots is represented by an object in the module:


A. plot.
B. figure.
C. offline.
D. graph_object.
Which attribute of the Scatter object should we modify to make the graph a dot plot?
A. mode=`markers`.
B. symbol=`point`.
C. type=`markers`.
D. These plots are not made with the Scatter object.

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.

Which attribute allows us to modify the range of values to be displayed in a histogram?


A. range.
B. start - ends.
C. xbins.
D. values.

Do the values of a Pie chart need to be normalized, i.e. add up to 1?


A. Yes, otherwise the correct graph will not be displayed.
B. Yes. Otherwise Python will show us an error.
C. No, Pie calculates the representation of each data in the chart automatically.
D. No, the values passed to Pie are of string type and cannot be added.

To generate an image with several graphs, which function should we use?


A. add_graph().
B. make_subplots().
C. include_subplot().
D. make_figure().

You might also like