# Course 2 – Programming in Python

## Coursera Study Guide

Click to Enroll in Coursera Meta Back-End Professional Certificate

## CONTENT

Learn about the paradigms of procedural programming and the associated logical concepts. You’ll explore functional and object-oriented programming, and get an introduction to algorithms.

## Learning Objectives

• Use functions to explore algorithmic thinking
• Use the logical concepts associated with procedural program flow.
• Identify and explain the paradigms of procedural programming.
• Instantiate and work with objects, classes and methods in Python.
• Explain the object-oriented programming concepts that underpin Python

## SELF-REVIEW: MAKE A CUP OF COFFEE

### 1. True or False:  While writing pseudocodes, we ideally put instructions for commands on the same line.

• True
• False (CORRECT)

Correct: Correct! Pseudocode describes the algorithmic flow and does not have instructions that may be confusing to read

### 2. What variable type would be best suited for determining if the kettle was boiling?

• float
• string
• Boolean (CORRECT)
• list

Correct: Correct – Boolean values are well suited for this type as they can be checked for true or false.

### 3. Assuming milk and sugar are booleans and both are True. What conditional statement is correct for a user who wants both milk and sugar in their coffee?

• if milk or sugar:
• if milk and sugar: (CORRECT)
• while milk and sugar:
• for milk and sugar:

Correct: Correct – You are correct. The if and statement will check for both to be True.

## KNOWLEDGE CHECK: PROCEDURAL PROGRAMMING

### 1. Which of the algorithm types below finds the best solution in each and every step instead of being overall optimal?

• Dynamic Programming
• Divide and conquer
• Greedy (CORRECT)
• Recursive

Correct: Correct. Greedy algorithms optimise at every step.

### 2. Which of the following Big O notations for function types has the slowest time complexity?

• O(log(n))
• O(c)
• O(n!) (CORRECT)
• O(n^3).

Correct: Correct. O(n!) has the slowest time complexity.

### 3. True or False: Linear time algorithms will always run under the same time and space regardless of the size of input.

• True
• False (CORRECT)

Correct: Correct! This is the definition of Constant time complexity. Linear time is dependent on the size of the input.

### 4. For determining efficiency, which of the following factors must be considered important?

• Time complexity
• Space complexity
• Neither of the two options above
• Both A and B (CORRECT)

Correct: Correct. Both time and space complexity are important

## PRACTICE QUIZ: MAPPING KEY VALUES TO DICTIONARY DATA STRUCTURES

### 1. What will be the output of the following code:

a = [[96], [69]]
print(''.join(list(map(str, a))))
• “[96][69]” (CORRECT)
• “[96],[69]”
• [96][69]
• “9669”

Correct: Correct – It will initially be a list of strings such as [‘[96]’, ‘[69]’] which is then converted into a conjoined string.

### 2. Which of the following is TRUE about the map() and filter() functions?

• Both the map() and filter() functions need to be defined before we use them.
• Both the map() and filter() functions are built-in. (CORRECT)
• The map() function needs to be defined first, but the filter() function is built-in.
• The map() function is built-in, but the filter() function needs to be defined first.

Correct: Correct! Function you pass to filter() and map() function may need definition, but they both are built-in.

### 3. What will be the output of the following code:

z = ["alpha","bravo","charlie"]
new_z = [i[0]*2for i in z]
print(new_z)
• [‘aa’], [‘bb’], [‘cc’]
• [‘aa’, ‘bb’, ‘cc’] (CORRECT)
• [‘a’, ‘b’, ‘c’]
• [‘alphaalpha’, ‘bravobravo’, ‘charliecharlie’]

Correct: Correct. The output will be a list of strings.

## KNOWLEDGE CHECK: FUNCTIONAL PROGRAMMING

### 1.

def sum(n):
if n == 1:
return 0
return n + sum(n-1)

a = sum(5)
print(a)

What will be the output of the recursive code above?

• RecursionError: maximum recursion depth exceeded
• 0
• 14 (CORRECT)
• 15

Correct: Correct! The output will be the sum of values from 2 to 5.

### Statement B: Functions in Python always returns a value.

• Both A and B are True
• B is True but A is False
• A is True but B is False (CORRECT)
• Both A and B are False

Correct: Correct! Functions need to be called and don’t always have to return a value.

### 3.

some = ["aaa", "bbb"]

#1
def aa(some):
return

#2
def aa(some, 5):
return

#3
def aa():
return

#4
def aa():
return "aaa"

Which of the above are valid functions in Python? (Select all that apply)

• 2
• 4 (CORRECT)
• 3 (CORRECT)
• 1 (CORRECT)

Correct: Correct. You can return a string such as “aaa” from a function.

Correct: Correct. An empty function can exist even if it has no functionality.

Correct: Correct. The function can return even if the argument passed is unused

### 4. For the following code:

numbers = [15, 30, 47, 82, 95]
def lesser(numbers):
return numbers < 50

small = list(filter(lesser, numbers))
print(small)

If you modify the code above and change filter() function to map() function, what will be the list elements in the output that were not there earlier?

• None of the other options (CORRECT)
• 15, 30, 47, 82, 95
• 82, 95
• 15, 30, 47

Correct: Correct! The values returned by the map() function in this case are boolean values from the comparison done in the lesser() function. So the right answer is: True, False.

## SELF-REVIEW: DEFINE A CLASS

### Select all the correct answers.

• ({ } ) – Curly braces
• ( @ ) – at sign
• ( # ) – Hashtag (CORRECT)
• (‘’’ ‘’’) – Triple quotations (CORRECT)

Correct: Correct! Hashtags is used for commenting.

Correct: Correct! These are called as docstrings and used for commenting.

### 2. What will be the output of running the following code:

value = 7
class A:
value = 5
a = A()
a.value = 3
print(value)
• None
• 7 (CORRECT)
• 3
• 5

Correct: Correct! This will be the output for value.

### 3. What will be the output of the following code:

bravo = 3
b = B()
class B:
bravo = 5
print("Inside class B")
c = B()
print(b.bravo)
• No output
• 3
• Error (CORRECT)
• 5

Correct: Correct! NameError: name ‘B’ is not defined.

### 4. Which of the following keywords allows the program to continue execution without impacting any functionality or flow?

• Skip
• break
• pass (CORRECT)

Correct: Correct! It can be used in class, function declarations as well as conditional statements.

## SELF-REVIEW: INSTANTIATE A CUSTOM OBJECT

### 1. Were you able to complete the code and get the expected final output mentioned?

• ​Yes (CORRECT)
• ​No

Correct: Very well done ! Keep practicing!

### The expected code for the program is as follows:

class MyFirstClass():
print("Who wrote this?")
index = "Author-Book"
def hand_list(self, philosopher, book):
print(MyFirstClass.index)
print(philosopher + " wrote the book: " + book)
whodunnit = MyFirstClass()
whodunnit.hand_list("Sun Tzu", "The Art of War")
• ​5 (CORRECT)
• 7 (CORRECT)
• ​4 (CORRECT)
• ​6 (CORRECT)
• None (CORRECT)
• ​8 (CORRECT)
• ​1 (CORRECT)
• ​3 (CORRECT)
• ​2 (CORRECT)

Correct!

### 3. Which of the following is the class variable in the code above?

• MyFirstClass
• Index (CORRECT)
• philosopher
• whodunnit

Correct: Correct! This is the class variable as it is declared within the class

### 4. How will you modify the code below if you want to include a “year” of publication in the output?

class MyFirstClass():
print("Who wrote this?")
index = "Author-Book"
def hand_list(self, philosopher, book):
print(MyFirstClass.index)
print(philosopher + " wrote the book: " + book)
whodunnit = MyFirstClass()
whodunnit.hand_list("Sun Tzu", "The Art of War")

Correct: Modify line numbers 4, 6 and 8 such as:

def hand_list(self, philosopher, book, year):
print(philosopher + " wrote the book: " + book + “in the year ” + year)
whodunnit.hand_list("Sun Tzu", "The Art of War", “5th century BC”)

## PRACTICE QUIZ: ABSTRACT CLASSES AND METHODS

### 1. Which of the following is not a requirement to create an abstract method in Python?

• A function called ABC
• Use of a decorator called abstractmethod
• Function called abstract (CORRECT)
• A module called abc

Correct: Correct! The name of the function required inside the abc module is abstract method.

### 2. There is a direct implementation of Abstraction in Python.

• True
• False (CORRECT)

Correct: Correct! Python makes use of the abc class to implement abstraction.

### 3. Which OOP principle is majorly used by Python to perform Abstraction?

• Polymorphism
• Inheritance (CORRECT)
• Encapsulation

Correct: Correct! Python makes use of class abc as a superclass to implement Abstraction.

### 4. Which of the following statements about abstract classes is true?

• Abstract classes act only as a base class for other classes to derive from. (CORRECT)
• Abstract classes help redefine the objects derived from them in a derived class.
• Abstract classes are used to instantiate abstract objects.
• Abstract classes inherit from other base classes.

Correct: Correct! Abstract class acts only as a base class for other classes to derive from it.

### 5. True or False: Abstract classes cannot exist without Abstract methods present inside them.

• True
• False (CORRECT)

Correct: Correct!  Abstract classes may or may not cannot abstract method definitions.

## SELF-REVIEW: WORKING WITH METHODS

### 1. True or False: A class can serve as a base class for many derived classes.

• True (CORRECT)
• False

Correct: Correct! Theoretically it can be superclass for infinite subclasses.

### 2. In case of multiple inheritance where C is a derived class inheriting from both class A and B, and where a and b are the respective objects for these classes, which of the following code will inherit the classes A and B correctly? (Select all that apply)

• class(a, B)
• class (a, b)
• class C(A, B) (CORRECT)
• class C(B, A) (CORRECT)

Correct: Correct! Code works irrespective of the order the classes are passed.

### 3. In Example 3 of the previous exercise, if we had modified the code to include a global variable ‘a = 5’ as follows:

a = 5
class A:
a = 7
pass

class B(A):
pass

class C(B):
pass

c = C()
print(c.a())

Will the code work and what will be the output if it does?

• Yes and it will print the value 5
• Yes and it will print the value 7
• No (CORRECT)

Correct: Correct! As the print statement is over the object c.

### 4. What function can be used other than mro() to see the way classes are inherited in a given piece of code?

• dir()
• info()
• class()
• help() (CORRECT)

Correct: Correct! help() can be used other than mro() to see the way classes are inherited in a given piece of code.

### 5. The super() function is used to? (Select all that apply)

• call different parent class method
• call child class __init__() (CORRECT)
• called over the __init__() method of the class it is called from (CORRECT)

Correct: Correct! It is called over child class __init__() and refers parent class __init__()

Correct: Correct. That will refer the __init__() of parent class.

### 6. What is the type of inheritance in the code below:

class A():
pass
class B(A):
pass
class C(B):
pass
• Multi-level (CORRECT)
• Multiple
• Single
• Hierarchical

Correct: Correct! Multi-level is the type of inheritance in the code

### 1. Which of the following can be used for commenting a piece of code in Python? (Select all that apply)

• ({ }) – Curly Brackets
• ( @ ) – At the rate sign
• (‘’’ ‘’’) – Triple quotation marks (CORRECT)
• • ( # ) – Hashtag * (CORRECT)

Correct: Correct! Triple quotation marks can be used for commenting a piece of code in Python.

Correct: Correct! Hashtag * can be used for commenting a piece of code in Python

### 2. What will be the output of running the following code?

value = 7
class A:
value = 5

a = A()
a.value = 3
print(value)
• None of the above
• 7 (CORRECT)
• 5
• 3

Correct: Correct! The print function is passed the global value variable.

### 3. What will be the output of running the following code?

bravo = 3
b = B()
class B:
bravo = 5
print("Inside class B")
c = B()
print(b.bravo)
• None
• 5
• 3
• Error (CORRECT)

Correct: Correct! The output on the code will be an error.

### 4. Which of the following keywords allows the program to continue execution without impacting any functionality or flow?

• Pass (CORRECT)
• continue
• break
• skip

Correct: Correct!  Pass is a keyword that allows the program to continue execution without impacting any functionality or flow.

### 5. Which of the following is not a measure of Algorithmic complexity?

• Execution time (CORRECT)
• Constant time
• Exponential Time
• Logarithmic Time

Correct: Correct! Execution time is not a measure of Algorithmic complexity.

### 6. Which of the following are the building blocks of Procedural programming?

• Procedures and functions (CORRECT)
• Variables and methods
• All of the options.
• Objects and Classes

Correct: Correct! Procedures and functions are the building blocks of Procedural programming.

### 7. True or False: Pure functions can modify global variables.

• True
• False (CORRECT)

Correct: Correct! Pure functions can modify global variables.

### 8. Which of the following is an advantage of recursion?

• Recursion is memory efficient
• Recursive code can make your code look neater (CORRECT)
• Easy to debug
• Easier to follow

Correct: Correct! Recursion code is easier to write.

### 9. Python allows for procedural, object oriented and functional programming paradigms. Which of the following statements are true? Choose all that apply.

• You will likely use only the procedural programming paradigm when coding.
• You will likely use a combined approach that relies on procedural, object oriented and functional programming paradigms. (CORRECT)
• Working within a paradigm helps you to write code that is easy to update and create new functionality. (CORRECT)

Correct: That’s correct! Most programming requires more than one approach.

Correct: That’s correct! Working with a certain approach in mind can help you write code that is easy to update and create new functionality.

### 10. Algorithms are very useful in programming. Which of the following statements about an algorithm are true?  Select all that apply.

• An algorithm is a method used only on simple problems to break them into smaller parts.
• An algorithm is a series of steps to solve a problem. (CORRECT)
• Once created the steps of an algorithm are the same every time. (CORRECT)

Correct: That’s correct! An algorithm solves both small and complex problems by executing the same steps each time.

Correct: That’s correct! An algorithm solves both small and complex problems by executing the same steps each time.

### 11. Understanding algorithmic complexity is an important aspect of optimizing code. Which one of the following descriptions applies to linear time?

• An algorithm that’s growth doubles with each iteration.
• An algorithm that will always run under the same time and space regardless of the size.
• An algorithm that grows depending on the size of the input. (CORRECT)

Correct:  That’s correct! A linear time algorithm means that the speed of an operation will decrease as the input increases.

### 12. Which of the following do you think are attributes of functional programming? Check all that apply

• Functional programming can be traditional or pure and will not affect data on a global scale.
• Functional programming is easy to maintain and saves a lot of development time. (CORRECT)
• Functional programming utilizes reusable functions for clean and elegant code. (CORRECT)
• Functional programming does not change the data outside the scope of the function. (CORRECT)

Correct: Correct. Functional programs using reusable functions are quick to use and easy to maintain.

Correct: Correct. Functional programming offers functions that can be reused and this simplifies your code.

Correct: That’s right. This simply means that the function should avoid modifying the input data or arguments being passed. Instead, it should only return the completed result of the intended function being called.

### 13. Pure functions are used in functional programming to assure the integrity of data outside the scope of the pure function.

• Yes (CORRECT)
• No

Correct: Correct. A pure function is used in functional programming because it does not change or have any effect on a variable, data, list, or set beyond its own scope.

### 14. Which of the following are advantages of using recursions? Check all that apply.

• In terms of memory, they are expensive and something inefficient.
• Difficult to debug and step through the code.
• Recursive code can make your code neater and less bulky. (CORRECT)
• Generation of sequences can be easier to understand than nested loops. (CORRECT)

Correct: Yes, that is correct.  Recursive code is simpler than nested loops.

Correct: Correct. Recursive code is especially good for working on things that have many possible branches and are too complex for an iterative approach.

Correct: Yes! It is easier to create a sequence with a recursion than with nested loops.

### 15. The syntax of the extended slice is:

• String_name[startparameter:stepparameter]
• Function_name[startparameter:stopparameter:stepparameter]
• String_name[startparameter:stopparameter:stepparameter] (CORRECT)

Correct: Yes! The order of the parameters is always start, stop and step. The start and stopparameters are the indices between which the function manipulates the string. The stepparameter are the hops or jumps the function makes while it traverses a given string.

### 16. State if the following definitions are correct.

map(): It returns all elements of an iterable when function returns True.
filter(): Applies function to every item in an iterable.
• No. (CORRECT)
• Yes.

Correct: Correct! This explanation is actually the other way around. map() returns every item in an iterable and filter() returns values if True.

### 17. You have defined the class computer, which has the attributes processor and RAM. You’ve also created a child class laptop, for which you’ve added the attribute size, in addition to those of the parent class. Which one of the four concepts of object-oriented programming does this exemplify?

• Abstraction
• Inheritance (CORRECT)
• Polymorphism
• Encapsulation

Correct: Correct! An instance of taking attributes from a class is known as inheritance.

### 18. You would like to instantiate an instance object in Python. What steps must you take to do this? Choose all that apply:

• Write a class method
• Define a class (CORRECT)
• Declare an instance (CORRECT)
• Initialize the instance (CORRECT)

Correct: Correct! To instantiate an instance object, it is necessary to define a class, declare an instance, and initialize that instance.

### 19. You have written the following Python code that uses a Class:

class Bicycle:
def __init__(self, size, gears)
self.size = size
self.gears = gears

The output will be ‘gears’. True or false?​

• False (CORRECT)
• True

Correct: Correct! In this code, no roadBike object has been instantiated, so running this code would produce an error.​

### 20. Your code has the class meal, along with the method calories() that prints a number value. You also have three instance objects: breakfast, lunch, and dinner. If you call calories() in an instance and change the value, the other instances are not affected. True or false?

• True (CORRECT)
• False

Correct: Correct! Changes made in an instance object affect only that instance.

### 21. In your code you have the parent class Pet and the child class Cat. If you update attributes in Cat which were inherited from Pet, then the same attributes would change for Pet as well. True or false?

• True
• False (CORRECT)

Correct: Correct! Changes made to a child class do not extend to the parent class.

### 22. Before implementing an abstract method, which steps do you need to take? Select all that apply:

• Define the abstract base class
• Assign a value to ABC
• Create a class that inherits the abstract base class (CORRECT)
• Import the abstract base class module (CORRECT)

Correct: Correct! Before implementing an abstract method, you need to import the abstract base class module, and create a class that inherits it.

Correct: Correct! Before implementing an abstract method, you need to import the abstract base class module, and create a class that inherits it.

### 23. Which of the following is among the five primary types of inheritance? Choose all that apply:

• Linear inheritance
• Hierarchical inheritance (CORRECT)
• Hybrid inheritance (CORRECT)
• Multi level inheritance (CORRECT)

Correct: Correct! Hierarchical, multi level and linear are all major types of inheritance.

#### Subscribe to our site

Get new content delivered directly to your inbox.

## Quiztudy Top Courses

Liking our content? Then, don’t forget to ad us to your BOOKMARKS so you can find us easily!