META BACK-END DEVELOPER PROFESSIONAL CERTIFICATE

Course 2 – Programming in Python

Week 2: Basic Programming with Python

Coursera Study Guide

Click to Enroll in Coursera Meta Back-End Professional Certificate

CONTENT

Learn basic Python syntax, to use control flow and loops and work with functions and data structures. You will also learn how to recognise possible errors, their causes and how to handle them.

Learning Objectives

  • Explain the core concepts that underpin the Python programming language.
  • Work with variables and different data types in Python.
  • Use control flow and loops to execute code under specific conditions.
  • Work with functions and data structures in Python.
  • Recognize possible errors, their causes and how to handle them.
  • Create, read and write data in files

PRACTICE QUIZ: FUNCTIONS, LOOPS AND DATA STRUCTURES

1. What keyword is used to create a function in Python?

  • var
  • func
  • def (CORRECT)
  • for

Correct: Correct, the def keyword is used for creating new functions in Python.

2. What function in Python allows you to output data onto the screen?

  • input()
  • print() (CORRECT)
  • output()
  • while

Correct: Correct – the print function is used for printing data in the console.

3. A variable that is declared inside a function cannot be accessed from outside the function?

  • True (CORRECT)
  • False

Correct: Correct – The variable is only accessible from inside the function scope.

4. Which of the declarations is correct when creating a for loop?

  • for while in:
  • for x in items: (CORRECT)
  • for in items:
  • for if in items:

Correct: Correct! The x here is a temporary variables iterating over items data structure.

5. What error will be thrown from the below code snippet?

1 nums = 34
2 for i in nums:
3     print(i)
  • Exception
  • MemoryError
  • TypeError: ‘int’ object is not iterable (CORRECT)
  • FloatingPointError

Correct: Correct – the output function does not exist.

KNOWLEDGE CHECK: FUNCTIONS AND DATA STRUCTURES

1. The scope inside a function is referred to as?

  • Local Scope (CORRECT)
  • Outer Scope
  • Global Scope
  • Built-in Scope

Correct: Correct! Scope inside a function is referred to as local scope.

2. Given the below list, what will be the output of the print statement be?

1 list_items = [10, 22, 45, 67, 90]
2 print(list_items[2])
  • 45 (CORRECT)
  • 10
  • 67
  • 22

Correct: Correct! The index for 45 is 2.

3. Which data structure type would be most suited for storing information that should not change?

  • Dictionary
  • Tuple (CORRECT)
  • List

Correct: Correct! A Tuple is suited as it is immutable and does not allow edits or changes once set.

4. Which of the options below is not considered a built-in Python data structure?

  • Tuple
  • Set
  • Dictionary
  • Tree (CORRECT)

Correct: Correct! A Tree is a User defined Python data structure.

5. A Set in Python does not allow duplicate values?

  • True (CORRECT)
  • False

Correct: Correct! A Set will not allow duplicate values.

PRACTICE QUIZ: EXCEPTIONS IN PYTHON

1. What type of specific error will be raised when a file is not found?

  • BufferError
  • ImportError
  • FileNotFoundError (CORRECT)
  • Exception

Correct: Correct! The FileNotFoundError will be displayed where a file cannot be located.

2. Which of the following keywords are used to handle an exception?

  • try except (CORRECT)
  • try catch
  • try again
  • try def

Correct: Correct! try except is used in Python for exception handling.

3. Which of the following is the base class for all user-defined exceptions in Python?

  • Exception (CORRECT)
  • BaseException
  • AssertionError
  • EOFError

Correct: Correct! Exception is the base class for all user-defined exceptions in Python.

PRACTICE QUIZ: READ IN DATA, STORE, MANIPULATE AND OUTPUT NEW DATA TO A FILE

1. What function allows reading and writing files in Python?

  • open() (CORRECT)
  • output()
  • input()
  • read_write()

Correct: Correct – open() both reading and writing of files.

2. Which method allows reading of only a single line of a file containing multiple lines?

  • readlines()
  • readall()
  • readline() (CORRECT)
  • read()

Correct: Correct – Readline allows the reading of a single line of a file.

3. What is the default mode for opening a file in python?

  • write mode
  • read and write
  • copy mode
  • read mode (CORRECT)

Correct: Correct! By default the file is opened in read mode.

4. What is the difference between write and append mode?

  • Nothing, they are both the same.
  • Write mode overwrites the existing data. Append mode adds new data to the existing file. (CORRECT)
  • Write mode will append data to the existing file. Append will overwrite the data.
  • Write mode will not allow edits if content already exists. Append mode will add new data to the file.

Correct: Correct. Both write and append mode serve different usecases!

5. What error is returned if a file does not exist?

  • LookupError
  • AssertionError
  • FileNotFoundError (CORRECT)
  • Exception

Correct: Correct. The FileNotFoundError is returned when a file cannot be found.

MODULE QUIZ: BASIC PROGRAMMING WITH PYTHON

1. Which of the following is not a sequence data-type in Python?

  • String
  • List
  • Tuples
  • Dictionary (CORRECT)

Correct: Correct! Dictionaries have key-value object structure and are not sequences.

2. For a given list called new_list, which of the following options will work:

new_list = [1,2,3,4]

Select all that apply.

  • new_list[4] = 10
  • new_list.extend(new_list) (CORRECT)
  • new_list.insert(0, 0) (CORRECT)
  • new_list.append(5) (CORRECT)

Correct: Correct. This will extend the list to give [1,2,3,4,1,2,3,4]

Correct: Correct. This will insert 0 at the 0th index giving: [0,1,2,3,4]

Correct: Correct. This will append the value 5 to the list giving: [1,2,3,4,5]

3. Which of the following is not a type of variable scope in Python?

  • Local
  • Global
  • Enclosing
  • Package (CORRECT)

Correct: Correct. Packages do not define a scope, they are external installations that we bring to extend code functionality.

4. Which of the following is a built-in data structure in Python?

  • Set (CORRECT)
  • Tree
  • Queue
  • LinkedList

Correct: Correct! Set is a built-in data structure such as list, tuple, etc.

5. For a given file called ‘names.txt’, which of the following is NOT a valid syntax for opening a file:

  • with open(‘names.txt’, ‘r’) as file:
  •  print(type(file))
  • with open(‘names.txt’, ‘w’) as file:
  •  print(type(file))
  • with open(‘names.txt’, ‘rb’) as file:
  •  print(type(file))
  • with open(‘names.txt’, ‘rw’) as file:
  •  print(type(file)) (CORRECT)

Correct: Correct. It should either be ‘r’ mode for reading or ‘w’ mode for writing.

6. Which among the following is not a valid Exception in Python?

  • ZeroDivisionException
  • FileNotFoundError
  • IndexError
  • LoopError (CORRECT)

Correct: Correct. There is no such Exception defined in Python.

7. For a file called name.txt containing the lines below:

1 First line
2 Second line
3 And another !

What will be the output of the following code:

1 with open('names.txt', 'r') as file:
2  lines = file.readlines()
3 print(lines)
  • ‘First line’
  • [‘First line\n’, (CORRECT)
  • ‘Second line\n’,
  • ‘And another !’]
  • [‘First line’]
  • ‘First line’
  • ‘Second line’
  • ‘And another !’

Correct: Correct! readlines() returns an ordered list with lines in the text file as items in the list.

8. State TRUE or FALSE:

*args passed to the functions can accept the key-value pair.

  • True
  • False (CORRECT)

Correct: Correct! You use **kwargs for passing dictionaries or videos containing key-value pairs.

9. A function is a modular piece of code that can be used repeatedly. True or false?     

  • False
  • True (CORRECT)

Correct: Well done, a function is a modular piece of code that can be used repeatedly.

10. In your program, you’ve declared the enclosed variable a = ‘Hello’.

At which scope levels is this variable accessible?

Select all that apply.     

  • Global
  • Built-in
  • Enclosed (CORRECT)
  • Local (CORRECT)

Correct: Correct! As this is the level of declaration, the variable is accessible here.     

Correct: Correct! Enclosed variables can be accessed locally.     

11. You need to add a new item to an existing list at a specified point in the index in your Python code. Which of the following functions can you use to complete this action?

  • append()
  • extend()
  • insert() (CORRECT)

Correct: Correct! The insert function is used to insert an item within an existing list at a specified index.   

12. You have declared the following tuple my_tuple = (1, 2, “hello”). This tuple contains two items of type integer and a third item of type string. Can you create tuples that have items with different data types?

  • No
  • Yes (CORRECT)

Correct: Correct! A tuple can accept any mix of data types.

13. Can you place duplicate values inside your declared sets?

  • No (CORRECT)
  • Yes

Correct: Correct! Sets do not accept duplicate values.

14. In a Python dictionary, each value has a unique identifier. This combination is known as:

  • The Value-Item Pair
  • The Item-Key Pair
  • The Key-Value Pair (CORRECT)

Correct: Well done.  Each item in the dictionary is a value within a key-value pairing.

15. The advantage of using args and kwargs is that you can pass in which of the following? Select all that apply. 

  • Keyword variables
  • Keyword arguments (CORRECT)
  • Non-keyword variables (CORRECT)

Correct: Correct! You can use kwargs to pass keyword arguments.

Correct: Correct! You can use kwargs to pass in non-keyword variables.

​16. Errors are unavoidable in programming and in Python, it is no different. For example, syntax errors are known errors that need to be handled.

  • No (CORRECT)
  • Yes

Correct: That’s correct! Syntax errors are caused by human errors such as typos or misspelling. Known errors that need to be handled are exceptions.

17. Like with any programming language exceptions happen in Python. You can handle more than one exception by chaining the except statement by adding another except statement.​

  • True (CORRECT)
  • False

Correct: That’s correct! It is possible to handle more than one exception without knowing what they are ahead oftime by chaining except statements together.​

18. The open function is a versatile method that is used for file handling in Python. Which of the following statements are true? Choose all that apply.​

  • You use the r+ mode with the open function to open a file only for writing.
  • You can use it with the statement in the open function so that the file is automatically closed for you. (CORRECT)
  • The open function can accept two arguments: the file name or file location, and the mode. (CORRECT)
  • The open function can be used in three modes: reading, writing, or creating files. (CORRECT)

Correct: Well done. It can also accept two arguments: the file name or file location and the mode, and you can use it with the statement in the open function so that the file is automatically closed for you. 

Correct: Well done.  The open function can also be used in three modes: reading, writing or creating files, and the open function can accept two arguments: the file name or file location, and the mode.

Correct: Well done. The open function can also be used in three modes: reading, writing or creating files, and you can use it with the statement in the open function so that the file is automatically closed for you. 

19. In Python you can create files and insert content into those files. Which method allows youto write a list in a file instead of just a single line of text? 

  • writelines function (CORRECT)
  • open function
  • write function

Correct: Correct! To write multiple lines of content you use the writelines() function. You use the write() function to add one line of content and the open() function to create, write or read a file. 

20. You want to read the entire contents of a file. What two methods can you use to do this?

  • readfile()
  • readline()
  • read() (CORRECT)
  • readlines() (CORRECT)

Correct:That’s right. The Read method returns the entire contents of the file as a string that will contain all the characters.

Correct: That’s right. The Readlines method reads the entire contents of the file and then returns it in an ordered list. This is useful because it allows you to iterate over the list or pick out specific lines based on a condition.

Subscribe to our site

Get new content delivered directly to your inbox.