Get All Modules Using Python to Interact with the Operating System Quiz Answers
Table of Contents
Note: Questions in the course cight get chuffle or twisted everytime you attempt the quiz, Check questions and mark answers accordingly
Module 01: Getting Ready for Python Practice Quiz Answers
Q1. Which of the following is the most modern, up-to-date version of Python?
- Python 3
- Python 2
- Python 4
- Anaconda
Q2. Which of the following operating systems is compatible with Python 3?
- Redhat Linux
- Microsoft Windows
- Apple MacOS
- All of the above
Q3. Which of the following operating systems does not run on a Linux kernel?
- Android
- Chrome OS
- Mac OS
- Ubuntu
Q4. If we want to check to see what version of Python is installed, what would we type into the command line? Select all that apply.
- python -V
- python –version
- python –help
- python -v
Q5. What is pip an example of?
- A programming language
- An operating system
- A repository of Python modules
- A Python package manager
Module 01: Running Python Locally Practice Quiz Answers
Q1. When your IDE automatically creates an indent for you, this is known as what?
- Code reuse
- Interpreted language
- Syntax highlighting
- Code completion
Q2. Can you identify the error in the following code?
- The function is not indented properly.
- The y variable is not calling the numpy module properly.
- The shebang line is not necessary.
- numpy is not imported correctly because as is used.
Q2. Which type of programming language is read and converted to machine code before runtime, allowing for more efficient code?
- Object-oriented language
- Compiled language
- Interpreted language
- Intermediate code
Q3. Which of the following is not an IDE or code editor?
- Eclipse
- pip
- Atom
- PyCharm
Q4. What does the PATH variable do?
- Tells the operating system where to find executables
- Returns the current working directory
- Holds the command line arguments of your Python program in a list
- Tells the operating system where to cache frequently used files
Module 01: Automation Practice Quiz Answers
Q1. At a manufacturing plant, an employee spends several minutes each hour noting uptime and downtime for each of the machines they are running. Which of the following ideas would best automate this process?
- Provide a tablet computer to the employee to record uptime and downtime
- Hire an extra employee to track uptime and downtime for each machine
- Add an analog Internet of Things (IoT) module to each machine, in order to detect their power states, and write a script that records uptime and downtime, reporting hourly
- Add an analog IoT module to each machine, in order to detect their power states, and attach lights that change color according to the power state of the machine
Q2. One important aspect of automation is forensic value. Which of the following statements describes this term correctly?
- It is important for automated processes to leave extensive logs so when errors occur, they can be properly investigated.
- It’s important to have staff trained on how automation processes work so they can be maintained and fixed when they fail.
- It’s important to organize logs in a way that makes debugging easier.
- It’s important to remember that 20% of our tasks as system administrators is responsible for 80% of our total workload.
Q3. An employee at a technical support company is required to collate reports into a single file and send that file via email three times a day, five days a week for one month, on top of his other duties. It takes him about 15 minutes each time. He has discovered a way to automate the process, but it will take him at least 10 hours to code the automation script. Which of the following equations will help them decide whether it’s worth automating the process?
if [10 hours to automate > (15 minutes * 60 times per month)] then automate
if [10 hours to automate < (15 minutes * 60 times per month)] then automate
if [(10 hours to automate + 15 minutes) > 60 times per month)] then automate
[(10 hours to automate / 60 times per month) < 15 minutes]
Q4. A company is looking at automating one of their internal processes and wants to determine if automating a process would save labor time this year. The company uses the formula [time_to_automate < (time_to_perform * amount_of_times_done) to decide whether automation is worthwhile. The process normally takes about 10 minutes every week. The automation process itself will take 40 hours total to complete. Using the formula, how many weeks will it be before the company starts saving time on the process?
- 6 weeks
- 2 weeks
- 24 weeks
- 240 weeks
Q5. Which of the following are valid methods to prevent silent automation errors? (Check all that apply)
- Email notifications about errors
- Internal issue tracker entries
- Constant human oversight
- Regular consistency checks
Module 01 Graded Assessment Quiz Answers
Q1. Which of the following statements most accurately defines automation? Select all that apply.
Answer:
- The implementation of computer-controlled systems to manage and execute processes.
- The process of streamlining workflows and making operations more efficient.
- The use of software or technology to perform tasks that would otherwise be done manually.
Explanation: Automation refers to using technology and systems to carry out tasks that were previously performed manually. It is about streamlining processes, making operations more efficient, and applying software for managing repetitive tasks.
Q2. Which operating system can you use Python on? Select all that apply.
Answer:
- Mac OS
- Linux OS
- Windows OS
Explanation: Python can run on multiple operating systems, including macOS, Linux, and Windows. “Dell OS” is not a valid operating system.
Q3. You run the command python –version and see the output Python 3.9.9. Which version of Python is your computer running?
Answer: Python 3
Explanation: The output Python 3.9.9
indicates that the system is running Python version 3.
Q4. Which of the following best describes a compiled language?
Answer: A programming language that is converted into machine code before execution.
Explanation: Compiled languages are converted directly into machine code, which can then be executed by the system. This differs from interpreted languages, which are executed line-by-line at runtime.
Q5. IDEs can be very helpful for software developers, as they can provide a variety of tools that can save time and improve productivity. What tools do IDEs provide? Select all that apply.
Answer:
- Compiler
- Debugger
- Code editor
Explanation: IDEs typically provide tools like a compiler, debugger, and code editor to help developers write, test, and debug their code. “Code Security” is not a standard feature of IDEs.
Q6. You are a software developer working on a new Python project. You are developing a web application. You will be using a variety of Python libraries. You are starting to have concerns about the impact of your project on your system Python environment. You are worried that installing the libraries for your project will conflict with the libraries that you are using for other projects. You have heard about virtual environments, and you are wondering if they might be a solution to your problem. Which of the following statements best describes how virtual environments can help you solve your problem?
Answer: Virtual environments allow you to install libraries in a way that is isolated from your system Python environment.
Explanation: Virtual environments allow you to manage dependencies separately for each project, avoiding conflicts between libraries required by different projects.
Q7. You’re an IT admin who works for a growing company that just hired a large number of employees. In the past, the company created user accounts, mailboxes, and home folders for each new employee manually. How can the company update its process to provide employees with the accounts, mailboxes, and home folders they need in a more efficient manner?
Answer: Develop a software application or utilize existing automation tools to automate the creation of user accounts, mailboxes, and home folders.
Explanation: Automating repetitive administrative tasks, such as creating accounts and mailboxes, will save time and reduce errors.
Q8. Which of the following factors would suggest that a task is a good candidate for automation? Select all that apply.
Answer:
- The task is repetitive and time-consuming.
- The task is error-prone and difficult to complete manually.
Explanation:
Tasks that are repetitive, time-consuming, and prone to error are prime candidates for automation to improve efficiency and reduce mistakes.
Q9. You want to create a Python script that automates system monitoring tasks on your computer. What Python module should you use in your script?
Answer: psutil
Explanation: The psutil
module is used for system and process monitoring, making it a great choice for automating system monitoring tasks.
Q10. A banking company is looking to automate one of its internal processes that takes about 50 minutes each week to complete. The automation process will take 12 hours total to complete. What is the formula used to determine how many weeks the process will take?
Answer: 720 > 50x
Explanation: To find how many weeks it will take for the automated process, the equation is derived from dividing the total automation time (12 hours) by the time taken for one manual task (50 minutes per week). This equation compares total time with task time.
Module 02: Managing Files & Directories Practice Quiz Answers
Q1. The create_python_script function creates a new python script in the current working directory, adds the line of comments to it declared by the ‘comments’ variable, and returns the size of the new file. Fill in the gaps to create a script called "program.py"
.
def create_python_script(filename):
comments = "# Start of a new Python program"
with open(filename, 'w') as file:
filesize = file.write(comments)
return(filesize)
print(create_python_script("program.py"))
Output:
31
Q2. The new_directory function creates a new directory inside the current working directory, then creates a new empty file inside the new directory, and returns the list of files in that directory. Fill in the gaps to create a file "script.py"
in the directory “PythonPrograms”.
import os
def new_directory(directory, filename):
# Before creating a new directory, check to see if it already exists
if os.path.isdir(directory) == False:
os.mkdir(directory)
# Create the new file inside of the new directory
os.chdir(directory)
with open (filename, 'w') as file:
file.write("")
# Return the list of files in the new directory
os.chdir('..')
return os.listdir(directory)
print(new_directory("PythonPrograms", "script.py"))
Output:
['script.py']
Q3. Which of the following methods from the os module will create a new directory?
- path.isdir()
- listdir()
- mkdir()
- chdir()
Q4. The file_date function creates a new file in the current working directory, checks the date that the file was modified, and returns just the date portion of the timestamp in the format of yyyy-mm-dd. Fill in the gaps to create a file called “newfile.txt” and check the date that it was modified.
import os
import datetime
def file_date(filename):
# Create the file in the current directory
with open (filename,'w') as file:
pass
timestamp = os.path.getmtime(filename)
# Convert the timestamp into a readable format, then into a string
timestamp = datetime.datetime.fromtimestamp(timestamp)
# Return just the date portion
# Hint: how many characters are in “yyyy-mm-dd”?
return ("{}".format(timestamp.strftime("%Y-%m-%d")))
print(file_date("newfile.txt"))
# Should be today's date in the format of yyyy-mm-dd
Output:
2020-07-18
Q5. The parent_directory function returns the name of the directory that’s located just above the current working directory. Remember that ‘..’ is a relative path alias that means “go up to the parent directory”. Fill in the gaps to complete this function.
import os
def parent_directory():
# Create a relative path to the parent
# of the current working directory
relative_parent = os.path.abspath('..')
# Return the absolute path of the parent directory
return relative_parent
print(parent_directory())
Output:
/
Module 02: Reading & Writing CSV Files Practice Quiz Answers
Q1. We’re working with a list of flowers and some information about each one. The create_file function writes this information to a CSV file. The contents_of_file function reads this file into records and returns the information in a nicely formatted block. Fill in the gaps of the contents_of_file function to turn the data in the CSV file into a dictionary using DictReader.
import os
import csv
# Create a file with data in it
def create_file(filename):
with open(filename, "w") as file:
file.write("name,color,type\n")
file.write("carnation,pink,annual\n")
file.write("daffodil,yellow,perennial\n")
file.write("iris,blue,perennial\n")
file.write("poinsettia,red,perennial\n")
file.write("sunflower,yellow,annual\n")
# Read the file contents and format the information about each row
def contents_of_file(filename):
return_string = ""
# Call the function to create the file
create_file(filename)
# Open the file
with open(filename) as file:
# Read the rows of the file into a dictionary
reader = csv.DictReader(file)
# Process each item of the dictionary
for row in reader:
return_string += "a {} {} is {}\n".format(row["color"], row["name"], row["type"])
return return_string
#Call the function
print(contents_of_file("flowers.csv"))
Note
This question throws:
Output:
a pink carnation is annual
a yellow daffodil is perennial
a blue iris is perennial
a red poinsettia is perennial
a yellow sunflower is annual
Q2. Using the CSV file of flowers again, fill in the gaps of the contents_of_file function to process the data without turning it into a dictionary. How do you skip over the header record with the field names?
import os
import csv
# Create a file with data in it
def create_file(filename):
with open(filename, "w") as file:
file.write("name,color,type\n")
file.write("carnation,pink,annual\n")
file.write("daffodil,yellow,perennial\n")
file.write("iris,blue,perennial\n")
file.write("poinsettia,red,perennial\n")
file.write("sunflower,yellow,annual\n")
# Read the file contents and format the information about each row
def contents_of_file(filename):
return_string = ""
# Call the function to create the file
create_file(filename)
# Open the file
with open(filename, "r") as file:
# Read the rows of the file
rows = csv.reader(file)
# Process each row
for row in list(rows)[1:]:
name, color, types = row
# Format the return string for data rows only
return_string += "a {} {} is {}\n".format(color, name, types)
return return_string
#Call the function
print(contents_of_file("flowers.csv"))
Output:
a pink carnation is annual
a yellow daffodil is perennial
a blue iris is perennial
a red poinsettia is perennial
a yellow sunflower is annual
Q3. In order to use the writerows() function of DictWriter() to write a list of dictionaries to each line of a CSV file, what steps should we take? (Check all that apply)
- Create an instance of the DictWriter() class
- Write the fieldnames parameter into the first row using writeheader()
- Open the csv file using with open
- Import the OS module
Q4. Which of the following is true about unpacking values into variables when reading rows of a CSV file? (Check all that apply)
- We need the same amount of variables as there are columns of data in the CSV
- Rows can be read using both csv.reader and csv.DictReader
- An instance of the reader class must be created first
- The CSV file does not have to be explicitly opened
Q5. If we are analyzing a file’s contents to correctly structure its data, what action are we performing on the file?
- Writing
- Appending
- Parsing
- Reading
Module 02 Graded Assessment Answers
Q1. Which Python function would you use to open a CSV file?
Answer: open()
Explanation: The open()
function in Python is used to open files, including CSV files. Once the file is open, you can use other functions (like csv.reader()
) to read its contents.
Q2. You and your colleagues frequently work in a folder containing thousands of automatically generated files. One day you discover that you cannot write to any of the files in the folder. What is a likely cause of this?
Answer: Someone wrote a script that used open() to write to all the files and forgot to close them.
Explanation: If files are opened using the open()
function without being closed, they remain in an open state, preventing other processes from writing to them.
Q3. What is an advantage of using absolute paths compared to relative paths?
Answer: Absolute paths work consistently regardless of the current working directory.
Explanation: An absolute path specifies the full path from the root directory, making it independent of the current directory. This ensures consistent access to files across different locations.
Q4. Which of the following is true about the structure of a file path?
Answer: The structure of a file path depends on the OS.
Explanation: The structure of file paths varies between operating systems (e.g., Windows uses backslashes \
, while Unix-based systems use forward slashes /
).
Q5. What happens if you use the open() function in write mode (‘w’) on an existing file?
Answer: The old contents will be deleted as soon as the file is opened.
Explanation: When a file is opened in write mode ('w'
), its existing contents are deleted, and the file is ready for new data to be written.
Q6. You’re iterating through a text file line by line in Python, and you notice an extra blank line printed after each line from the file. What’s the MOST likely reason for this?
Answer: The newline character from the end of each line in the file is being included when reading the lines.
Explanation: The extra blank line is likely due to the newline (\n
) character at the end of each line. You can use .strip()
to remove it.
Q7. On Linux systems, which of the following commands is used to create a new directory?
Answer: mkdir directory_name
Explanation: The mkdir
command is used on Linux (and other Unix-based systems) to create a new directory.
Q8. What is the primary function of the line reader = csv.DictReader(software.csv)
?
Answer: It creates a dictionary reader object to iterate over rows in the software.csv file, treating each row as a dictionary.
Explanation: csv.DictReader()
reads a CSV file as a dictionary, where each row is represented as a dictionary with the column headers as keys.
Q9. Imagine you’re working in a terminal on a Linux or Unix-based system. You have a file named employees.csv and want to display its contents. Which of the following commands would achieve this?
Answer: cat employees.csv
Explanation: The cat
command is used in Linux/Unix to display the contents of a file.
Q10. In Python’s csv module, what’s the primary benefit of registering a dialect like empDialect with csv.register_dialect as shown in the code snippet: csv.register_dialect('empDialect', skipinitialspace=True, strict=True)
?
Answer: It allows you to define custom parsing behavior (like removing leading spaces) for CSV files without explicitly specifying the parameters every time you use the csv module.
Explanation: By registering a dialect, you can define parsing rules that apply consistently across multiple CSV file operations without re-specifying parameters like skipinitialspace
each time.
Reading and Writing Files
Using Python to interact with the Operating System Graded Assessment Answers
Sources
Module 03: Regular Expressions Practice Quiz Answers
Q1. When using regular expressions, which of the following expressions uses a reserved character that can represent any single character?
Answer: grep f.n /usr/share/text
Explanation: The dot (.
) is a wildcard character in regular expressions that matches any single character. Therefore, f.n
matches any string that starts with f
, ends with n
, and has any single character in between.
Q2. A programmer is writing a script to help a store manager find the product numbers associated with each product sold in their store. Which of the following methods should they use?
Answer: Use regex to find the patterns that match the product number.
Explanation: Regular expressions (regex) are powerful tools for identifying patterns in text, such as product numbers, without needing to manually check line-by-line.
Q3. The circumflex [^] and the dollar sign [$] are anchor characters. What do these anchor characters do in regex?
Answer: Match the start and end of a line.
Explanation: The circumflex (^
) matches the start of a line, and the dollar sign ($
) matches the end of a line in regular expressions.
Q4. When using regex, some characters represent particular types of characters. Some examples are the dollar sign, the circumflex, and the dot wildcard. What are these characters collectively known as?
Answer: Reserved characters
Explanation: Reserved characters have special meanings in regex. They represent patterns or positions, such as anchors (^
, $
) or wildcards (.
).
Q5. What is grep?
Answer: A command-line regex tool
Explanation: grep
is a command-line utility used to search for text patterns within files, often using regular expressions to perform advanced pattern matching.
Module 03: Basic Regular Expressions Practice Quiz Answers
Q1. The check_web_address function checks if the text passed qualifies as a top-level web address, meaning that it contains alphanumeric characters (which includes letters, numbers, and underscores), as well as periods, dashes, and a plus sign, followed by a period and a character-only top-level domain such as “.com”, “.info”, “.edu”, etc. Fill in the regular expression to do that, using escape characters, wildcards, repetition qualifiers, beginning and end-of-line characters, and character classes.
import re
def check_web_address(text):
pattern = r'^[\w\._-]*\.[A-Za-z]*$'
result = re.search(pattern, text)
return result != None
print(check_web_address("gmail.com")) # True
print(check_web_address("www@google")) # False
print(check_web_address("www.Coursera.org")) # True
print(check_web_address("web-address.com/homepage")) # False
print(check_web_address("My_Favorite-Blog.US")) # True
Answer: Full Code
import re
def check_web_address(text):
pattern = r"^[A-Za-z0-9_.+-]+\.([A-Za-z]{2,})$"
result = re.search(pattern, text)
return result != None
print(check_web_address("gmail.com")) # True
print(check_web_address("www@google")) # False
print(check_web_address("www.Coursera.org")) # True
print(check_web_address("web-address.com/homepage")) # False
print(check_web_address("My_Favorite-Blog.US")) # True
Output:
True
False
True
False
True
Q2. The check_time function checks for the time format of a 12-hour clock, as follows: the hour is between 1 and 12, with no leading zero, followed by a colon, then minutes between 00 and 59, then an optional space, and then AM or PM, in upper or lower case. Fill in the regular expression to do that. How many of the concepts that you just learned can you use here?
import re
def check_time(text):
pattern = r'^(1[0-2]|1?[1-9]):([0-5][0-9])( ?([AaPp][Mm]))'
result = re.search(pattern, text)
return result != None
print(check_time("12:45pm")) # True
print(check_time("9:59 AM")) # True
print(check_time("6:60am")) # False
print(check_time("five o'clock")) # False
Answer: Complete Code
import re
def check_time(text):
pattern = r"^([1-9]|1[0-2]):([0-5][0-9])\s?(AM|PM|am|pm)$"
result = re.search(pattern, text)
return result != None
print(check_time("12:45pm")) # True
print(check_time("9:59 AM")) # True
print(check_time("6:60am")) # False
print(check_time("five o'clock")) # False
print(check_time("6:02 am")) # True
print(check_time("6:02km")) # False
Output:
True
True
False
False
True
False
Q3. The contains_acronym function checks the text for the presence of 2 or more characters or digits surrounded by parentheses, with at least the first character in uppercase (if it’s a letter), returning True if the condition is met, or False otherwise. For example, “Instant messaging (IM) is a set of communication technologies used for text-based communication” should return True since (IM) satisfies the match conditions.” Fill in the regular expression in this function:
import re
def contains_acronym(text):
pattern = r'\(+[A-Z0-9][a-zA-Z]*\)'
result = re.search(pattern, text)
return result != None
print(contains_acronym("Instant messaging (IM) is a set of communication technologies used for text-based communication")) # True
print(contains_acronym("American Standard Code for Information Interchange (ASCII) is a character encoding standard for electronic communication")) # True
print(contains_acronym("Please do NOT enter without permission!")) # False
print(contains_acronym("PostScript is a fourth-generation programming language (4GL)")) # True
print(contains_acronym("Have fun using a self-contained underwater breathing apparatus (Scuba)!")) # True
Answer: Complete Code
import re
def contains_acronym(text):
pattern = r"\([A-Z0-9][A-Za-z0-9]*\)"
result = re.search(pattern, text)
return result != None
print(contains_acronym("Instant messaging (IM) is a set of communication technologies used for text-based communication")) # True
print(contains_acronym("American Standard Code for Information Interchange (ASCII) is a character encoding standard for electronic communication")) # True
print(contains_acronym("Please do NOT enter without permission!")) # False
print(contains_acronym("PostScript is a fourth-generation programming language (4GL)")) # True
print(contains_acronym("Have fun using a self-contained underwater breathing apparatus (Scuba)!")) # True
Output:
True
True
False
True
True
Q4. What does the “r” before the pattern string in re.search(r”Py.*n”, sample.txt) indicate?
- Raw strings
- Regex
- Repeat
- Result
Explanation: The r
before the string denotes a raw string in Python. It ensures that backslashes in the string are treated literally, which is useful for writing regular expressions where backslashes are common.
Q5. What does the plus character [+] do in regex?
- Matches plus sign characters
- Matches one or more occurrences of the character before it
- Matches the end of a string
- Matches the character before the [+] only if there is more than one
Explanation: In regex, the +
quantifier matches one or more occurrences of the preceding character or group. For example, a+
matches “a”, “aa”, “aaa”, etc.
Q6. Fill in the code to check if the text passed includes a possible U.S. zip code, formatted as follows: exactly 5 digits, and sometimes, but not always, followed by a dash with 4 more digits. The zip code needs to be preceded by at least one space, and cannot be at the start of the text.
import re
def check_zip_code (text):
result = re.search(r' \d{5}| \d{5}-\d{4}', text)
return result != None
print(check_zip_code("The zip codes for New York are 10001 thru 11104.")) # True
print(check_zip_code("90210 is a TV show")) # False
print(check_zip_code("Their address is: 123 Main Street, Anytown, AZ 85258-0001.")) # True
print(check_zip_code("The Parliament of Canada is at 111 Wellington St, Ottawa, ON K1A0A9.")) # False
Answer: Complete Code
import re
def check_zip_code(text):
# Regex pattern
pattern = r"\s\d{5}(?:-\d{4})?"
result = re.search(pattern, text)
return result != None
print(check_zip_code("The zip codes for New York are 10001 thru 11104.")) # True
print(check_zip_code("90210 is a TV show")) # True
print(check_zip_code("Their address is: 123 Main Street, Anytown, AZ 85258-0001.")) # True
print(check_zip_code("The Parliament of Canada is at 111 Wellington St, Ottawa, ON K1A0A9.")) # False
Output:
True
True
True
False
Module 03: Advanced Regular Expressions Practice Quiz Answers
Q1. We’re working with a CSV file, which contains employee information. Each record has a name field, followed by a phone number field, and a role field. The phone number field contains U.S. phone numbers, and needs to be modified to the international format, with “+1-” in front of the phone number. Fill in the regular expression, using groups, to use the transform_record function to do that.
import re
def transform_record(record):
new_record = re.sub(r",(\d{3})",r",+1-\1",record)
return new_record
print(transform_record("Sabrina Green,802-867-5309,System Administrator"))
# Sabrina Green,+1-802-867-5309,System Administrator
print(transform_record("Eli Jones,684-3481127,IT specialist"))
# Eli Jones,+1-684-3481127,IT specialist
print(transform_record("Melody Daniels,846-687-7436,Programmer"))
# Melody Daniels,+1-846-687-7436,Programmer
print(transform_record("Charlie Rivera,698-746-3357,Web Developer"))
# Charlie Rivera,+1-698-746-3357,Web Developer
Answer: Complete Code
import re
def transform_record(record):
# Use regex to match the phone number part of the record
new_record = re.sub(r"(\b\d{3}-\d{3}-\d{4}\b)", r"+1-\1", record)
return new_record
# Test cases
print(transform_record("Sabrina Green,802-867-5309,System Administrator"))
# Sabrina Green,+1-802-867-5309,System Administrator
print(transform_record("Eli Jones,684-3481127,IT specialist"))
# Eli Jones,+1-684-3481127,IT specialist
print(transform_record("Melody Daniels,846-687-7436,Programmer"))
# Melody Daniels,+1-846-687-7436,Programmer
print(transform_record("Charlie Rivera,698-746-3357,Web Developer"))
# Charlie Rivera,+1-698-746-3357,Web Developer
Output:
Sabrina Green,+1-802-867-5309,System Administrator
Eli Jones,+1-684-3481127,IT specialist
Melody Daniels,+1-846-687-7436,Programmer
Charlie Rivera,+1-698-746-3357,Web Developer
Q2. The multi_vowel_words function returns all words with 3 or more consecutive vowels (a, e, i, o, u). Fill in the regular expression to do that.
import re
def multi_vowel_words(text):
pattern = r'\w+[aiueo]{3,}\w+'
result = re.findall(pattern, text)
return result
print(multi_vowel_words("Life is beautiful"))
# ['beautiful']
print(multi_vowel_words("Obviously, the queen is courageous and gracious."))
# ['Obviously', 'queen', 'courageous', 'gracious']
print(multi_vowel_words("The rambunctious children had to sit quietly and await their delicious dinner."))
# ['rambunctious', 'quietly', 'delicious']
print(multi_vowel_words("The order of a data queue is First In First Out (FIFO)"))
# ['queue']
print(multi_vowel_words("Hello world!"))
# []
Answer: Complete Code
import re
def multi_vowel_words(text):
# Match words containing three or more consecutive vowels
pattern = r'\b\w*[aeiouAEIOU]{3,}\w*\b'
result = re.findall(pattern, text)
return result
# Test cases
print(multi_vowel_words("Life is beautiful"))
# ['beautiful']
print(multi_vowel_words("Obviously, the queen is courageous and gracious."))
# ['Obviously', 'queen', 'courageous', 'gracious']
print(multi_vowel_words("The rambunctious children had to sit quietly and await their delicious dinner."))
# ['rambunctious', 'quietly', 'delicious']
print(multi_vowel_words("The order of a data queue is First In First Out (FIFO)"))
# ['queue']
print(multi_vowel_words("Hello world!"))
# []
Output: The function identifies all words with three or more consecutive vowels as specified.
Q3. When capturing regex groups, what datatype does the groups method return?
- A string
- A tuple
- A list
- A float
Q4. The transform_comments function converts comments in a Python script into those usable by a C compiler. This means looking for text that begins with a hash mark (#) and replacing it with double slashes (//), which is the C single-line comment indicator.
For the purpose of this exercise, we’ll ignore the possibility of a hash mark embedded inside of a Python command, and assume that it’s only used to indicate a comment. We also want to treat repetitive hash marks (###), (####), etc., as a single comment indicator, to be replaced with just (//) and not (#//) or (//#). Fill in the parameters of the substitution method to complete this function:
import re
def transform_comments(line_of_code):
result = re.sub(r'\#{1,}', r'//', line_of_code)
return result
print(transform_comments("#### Start of program"))
# Should be "// Start of program"
print(transform_comments(" number = 0 ### Initialize the variable"))
# Should be " number = 0 // Initialize the variable"
print(transform_comments(" number += 1 # Increment the variable"))
# Should be " number += 1 // Increment the variable"
print(transform_comments(" return(number)"))
# Should be " return(number)"
Answer: Complete Code
import re
def transform_comments(line_of_code):
# Substitute hash marks at the start of a comment with double slashes
result = re.sub(r'#.*', r'//', line_of_code)
return result
# Test cases
print(transform_comments("### Start of program"))
# Should be "// Start of program"
print(transform_comments(" number = 0 ## Initialize the variable"))
# Should be " number = 0 // Initialize the variable"
print(transform_comments(" number += 1 # Increment the variable"))
# Should be " number += 1 // Increment the variable"
print(transform_comments(" return(number)"))
# Should be " return(number)"
Output: The function correctly transforms Python comments into C-style comments while leaving non-comment lines unchanged.
Q5. The convert_phone_number function checks for a U.S. phone number format: XXX-XXX-XXXX (3 digits followed by a dash, 3 more digits followed by a dash, and 4 digits), and converts it to a more formal format that looks like this: (XXX) XXX-XXXX. Fill in the regular expression to complete this function.
import re
def convert_phone_number(phone):
result = re.sub(r"\b(\d{3})-(\d{3})-(\d{4})\b", r"(\1) \2-\3", phone)
return result
print(convert_phone_number("My number is 212-345-9999.")) # My number is (212) 345-9999.
print(convert_phone_number("Please call 888-555-1234")) # Please call (888) 555-1234
print(convert_phone_number("123-123-12345")) # 123-123-12345
print(convert_phone_number("Phone number of Buckingham Palace is +44 303 123 7300")) # Phone number of Buckingham Palace is +44 303 123 7300
Answer: Complete Code
import re
def convert_phone_number(phone):
# Regular expression to match the U.S. phone number format and convert it
result = re.sub(r'(\b\d{3})-(\d{3})-(\d{4}\b)', r'(\1) \2-\3', phone)
return result
# Test cases
print(convert_phone_number("My number is 212-345-9999."))
# Should be "My number is (212) 345-9999."
print(convert_phone_number("Please call 888-555-1234"))
# Should be "Please call (888) 555-1234"
print(convert_phone_number("123-123-12345"))
# Should be "123-123-12345" (invalid format, no change)
print(convert_phone_number("Phone number of Buckingham Palace is +44 303 123 7300"))
# Should be "Phone number of Buckingham Palace is +44 303 123 7300" (no change)
Output:
- The function transforms valid U.S. phone numbers into the formal format.
- Numbers that don’t match the expected format are not changed.
Module 03: Work with regular expressions Assessment answers
Q1. Which of the following tasks can be accomplished using regular expressions?
Answer:
- Replacing a specific pattern in a text
- Extracting email addresses from a text
- Finding all occurrences of a word in a text
Explanation: Regular expressions are powerful for pattern matching and text manipulation. They can be used to replace specific patterns, extract data like email addresses, and find occurrences of specific words or phrases. However, generating random numbers and sorting lists are outside their scope.
Q2. What is a characteristic of a CSV file?
Answer: Data in each row is separated by a special character.
Explanation: CSV files use a delimiter (commonly a comma) to separate values in each row. Each row typically represents a record, and columns are separated by the chosen delimiter. CSV files are plain text and can be opened with text editors or spreadsheet programs.
Q3. You have a list of website urls that includes both securely encrypted websites that begin with https://www. and the unencrypted websites that begin with http://. The list includes websites that end in .com and .co.
Complete the secure_website_domain() function so it returns the part of the website between www. and the last part of the url (.com or .co) for only the secure websites.
def secure_website_domain(website):
pattern = _____ # enter the regex pattern here
result = re._____(pattern, website) # enter the re method here
if result is None:
return ""
return result_____# enter the correct capturing group
print(secure_website_domain("http://www.text.com")) #Should return nothing
print(secure_website_domain("https://www.text.com")) #Should return text
print(secure_website_domain("http://www.text.co")) #Should return nothing
print(secure_website_domain("https://www.text.co")) #Should return text
Answer: Here’s the complete implementation of the secure_website_domain
function:
import re
def secure_website_domain(website):
# Regular expression pattern to match secure websites and extract the domain name
pattern = r'^https://www\.([a-zA-Z0-9_-]+)\.(com|co)$'
result = re.search(pattern, website)
if result is None:
return ""
return result.group(1) # Capturing group for the domain name
# Test cases
print(secure_website_domain("http://www.text.com")) # Should return ""
print(secure_website_domain("https://www.text.com")) # Should return "text"
print(secure_website_domain("http://www.text.co")) # Should return ""
print(secure_website_domain("https://www.text.co")) # Should return "text"
Output:
"http://www.text.com"
→""
"https://www.text.com"
→"text"
"http://www.text.co"
→""
"https://www.text.co"
→"text"
Q4. You are exploring the punctuation at the end of sentences and want to split sentences so that each word is separate and any punctuation is included in the word next to it. Complete the parse_sentences() function to accomplish this task.
def parse_sentences(sentence):
pattern =_______ #enter the regex pattern here
result = re._____(pattern, sentence) #enter the re method here
return result
print(parse_sentences("Hello! How are you doing?")) # should return ['Hello!', 'How', 'are', 'you', 'doing?']
print(parse_sentences("what a beautiful day it is")) # should return ['what', 'a', 'beautiful', 'day', 'it', 'is']
print(parse_sentences("2 + 2 is definitely 4!")) # should return ['2', '+', '2', 'is', 'definitely', '4!']
Answer: Here’s how the parse_sentences
function can be implemented:
import re
def parse_sentences(sentence):
# Regular expression pattern to match words and punctuation as part of words
pattern = r'\w+[\w\'-]*|[^\w\s]'
result = re.findall(pattern, sentence) # Using re.findall to extract all matches
return result
# Test cases
print(parse_sentences("Hello! How are you doing?")) # ['Hello!', 'How', 'are', 'you', 'doing?']
print(parse_sentences("what a beautiful day it is")) # ['what', 'a', 'beautiful', 'day', 'it', 'is']
print(parse_sentences("2 + 2 is definitely 4!")) # ['2', '+', '2', 'is', 'definitely', '4!']
Output:
"Hello! How are you doing?"
→['Hello!', 'How', 'are', 'you', 'doing?']
"what a beautiful day it is"
→['what', 'a', 'beautiful', 'day', 'it', 'is']
"2 + 2 is definitely 4!"
→['2', '+', '2', 'is', 'definitely', '4!']
Q5. International Standard Book Numbers (ISBNs) are used to uniquely identify published books. They follow a 13-digit format:
XXX-X-XX-XXXXXX-X
where each X represents one numeric digit. You have a list of books, information about those books, and their ISBN numbers. You want to extract the 6 digits of the ISBN that come before the last hyphen of each book’s ISBN number. However, you need to be careful to avoid 6-digit strings that are not part of the ISBN numbers you’re interested in.
Complete the find_isbn() function so you can use it to extract the 6-digit portion of the ISBN numbers of the books on your list.
def find_isbn(list):
pattern = _____ #enter the regex pattern here
result = re._____(pattern, list) #enter the re method here
if result is None:
return ""
return _____ #return the correct capturing group
print(find_isbn("123-4-12-098754-0")) # Should return 098754
print(find_isbn("223094-AB-30")) # result should be blank
print(find_isbn("1123-4-12-098754-0")) # result should be blank
Answer: Updated Function Implementation:
import re
def find_isbn(book):
# Regex pattern to match the 6 digits before the last hyphen in ISBN
pattern = r'\d{3}-\d-\d{2}-(\d{6})-\d'
# Searching for the pattern in the provided book string
result = re.search(pattern, book)
# If result is None, it means no match was found, return an empty string
if result is None:
return ""
# Return the captured group (the 6-digit portion)
return result.group(1)
# Test cases
print(find_isbn("123-4-12-098754-0")) # Should return 098754
print(find_isbn("223094-AB-30")) # Should return blank (no valid ISBN)
print(find_isbn("1123-4-12-098754-0")) # Should return blank (invalid format)
Output:
find_isbn("123-4-12-098754-0")
→098754
find_isbn("223094-AB-30")
→""
(since the format is invalid)find_isbn("1123-4-12-098754-0")
→""
(invalid format)
Q6. What information does the variable old_domain_pattern
store?
Answer: A regular expression pattern to identify the old domain
Explanation: The variable old_domain_pattern
combines the old_domain
with a regex pattern ('$'
) to ensure that it matches only at the end of the string, effectively identifying email addresses that end with the old domain.
Q7. How did you accomplish the task of populating old_domain_email_list
?
Answer:
Step 1: Initialized old_domain_email_list
with an empty list.
Step 2: Used a for loop to iterate over user_email_list
, checking each email with contains_domain()
.
Step 3: Appended email addresses with the old domain to old_domain_email_list
.
Explanation: This method ensures each email in user_email_list
is evaluated for the old domain using contains_domain()
. Those that match are added to old_domain_email_list
.
Q8. What is the primary purpose of writing the updated user_data_list
to an output file?
Answer: To save the changes made to the email addresses and create a new CSV file with updated data
Explanation: The output file preserves the modified data by replacing outdated domains with new ones, ensuring that the updated information is stored for future use.
Q9. Which Python libraries are commonly employed for domain updates and saving to a separate file?
Answer: re
(regular expressions) and open()
function
Explanation:
The re
library is used to match and manipulate domain patterns, while open()
is used to handle file reading and writing.
Q10. How do contains_domain()
and replace_domain()
work together?
Answer: contains_domain()
uses a regex to identify emails with a specific domain, and replace_domain()
replaces these domains with new ones.
Explanation: contains_domain()
checks if an email contains the old domain, and replace_domain()
modifies those emails to use the updated domain, ensuring data consistency.
Using Python to interact with the Operating System Graded Assessment answers
Module 04: Data Streams Practice Quiz Answers
Q1. Which command will print out the exit value of a script that just ran successfully?
- echo $PATH
- wc variables.py
- import sys
- echo $?
Explanation: echo $?
prints the exit status of the last command executed. An exit code of 0 typically indicates success, while non-zero values indicate various errors.
Q2. Which command will create a new environment variable?
- export
- input
- wc
- env
Explanation: The export
command is used in Unix-based systems to set environment variables, making them available to child processes.
Q3. Which I/O stream are we using when we use the input function to accept user input in a Python script?
- STDOUT
- STDERR
- STDIN
- SYS
Explanation: The input()
function reads input from the standard input stream (STDIN), allowing users to provide data during script execution.
Q4. What is the meaning of an exit code of 0?
- The program ended with an unspecified error.
- The program ended with a ValueError.
- The program ended with a TypeError.
- The program ended successfully.
Explanation: In Unix-based systems, an exit code of 0 indicates that the program or script completed without errors. Non-zero exit codes signal errors.
Q5. Which statements are true about input and raw_input in Python 2? (select all that apply)
- input performs basic math operations.
- raw_input performs basic math operations.
- raw_input gets a string from the user.
- input gets a string from the user.
Explanation: In Python 2, raw_input()
always returns user input as a string, while input()
evaluates the input as a Python expression, allowing basic math or other operations.
Module 04: Python Subprocesses Practice Quiz Answers
Q1. What type of object does a run function return?
- stdout
- CompletedProcess
- capture_output
- returncode
Explanation: The subprocess.run()
function returns a CompletedProcess
object, which contains information about the completed process, such as args
, returncode
, stdout
, and stderr
.
Q2. How can you change the current working directory where a command will be executed?
- Use the env parameter.
- Use the shell parameter.
- Use the cwd parameter.
- Use the capture_output parameter.
Explanation: The cwd
parameter in subprocess.run()
specifies the working directory where the command will be executed.
Q3. When a child process is run using the subprocess module, which of the following are true? (check all that apply)
- The child process is run in a secondary environment.
- The parent process is blocked while the child process finishes.
- The parent process and child process both run simultaneously.
- Control is returned to the parent process when the child process ends.
Explanation: When running a child process with subprocess.run()
, the parent process waits for the child process to finish before resuming. Control returns to the parent once the child process terminates.
Q4. When using the run command of the subprocess module, what parameter, when set to True, allows us to store the output of a system command?
- cwd
- capture_output
- timeout
- shell
Explanation: The capture_output=True
parameter allows capturing the output (stdout
and stderr
) of the command as part of the CompletedProcess
object.
Q5. What does the copy method of os.environ do?
- Creates a new dictionary of environment variables
- Runs a second instance of an environment
- Joins two strings
- Removes a file from a directory
Explanation: The os.environ.copy()
method returns a new dictionary containing the current environment variables, which can be modified without affecting the original environment.
Module 04: Processing Log Files Practice Quiz Answers
Q1. You have created a Python script to read a log of users running CRON jobs. The script needs to accept a command line argument for the path to the log file. Which line of code accomplishes this?
- import sys
- syslog=sys.argv[1]
- print(line.strip())
- usernames = {}
Explanation: The sys.argv
list stores command-line arguments. sys.argv[1]
retrieves the first argument passed to the script (after the script name), which is used to specify the log file path.
Q2. Which of the following is a data structure that can be used to count how many times a specific error appears in a log?
- Dictionary
- Get
- Continue
- Search
Explanation: A dictionary is well-suited for counting occurrences. You can use keys for error types and values to store their counts, updating values as errors are encountered.
Q3. Which keyword will return control back to the top of a loop when iterating through logs?
- Continue
- Get
- With
- Search
Explanation: The continue
keyword skips the remaining code in the current loop iteration and moves control back to the top of the loop for the next iteration.
Q4. When searching log files using regex, which regex statement will search for the alphanumeric word “IP” followed by one or more digits wrapped in parentheses using a capturing group?
r"IP \(\d+\)$"
b"IP \((\w+)\)$"
r"IP \((\d+)\)$"
r"IP \((\D+)\)$"
Q5. Which of the following are true about parsing log files? (Select all that apply.)
- Load the entire log files into memory.
- You should parse log files line by line.
- It is efficient to ignore lines that don’t contain the information we need.
- We have to open() the log files first.
Explanation:
- Parse line by line: Parsing log files line by line is memory-efficient, especially for large files.
- Ignore irrelevant lines: This improves performance by focusing only on relevant data.
- Open files first: The
open()
function is required to access file contents before reading or parsing.
Module 04: Working with log files Graded Assessment
Q1. In the process of connecting to a virtual machine using SSH and PuTTY on Windows, which of the following steps is necessary?
Answer:
- Opening the PuTTY Secure Shell (SSH) client
- Entering the username and external IP address in the Host Name (or IP address) box.
- Downloading the PPK key file from the Qwiklabs Start Lab page
Explanation: To connect to a virtual machine using SSH and PuTTY, you need to:
- Open PuTTY.
- Enter the external IP address and username in the Host Name field.
- Use the PPK file for authentication if provided.
Entering a password may not be necessary if a key file is used for authentication.
Q2. What is the primary purpose of the sys
module in Python?
Answer: Provides functions and variables to interact with the Python interpreter and the runtime environment
Explanation: The sys
module allows you to interact with the Python runtime environment, including accessing command-line arguments, handling standard input/output, and controlling the interpreter.
Q3. What is the primary function of regular expressions (RegEx) in Python programming?
Answer: To define a sequence of characters that form a search pattern for text processing
Explanation: RegEx is used to match and manipulate strings based on specific patterns, such as validating email formats or extracting data.
Q4. Which file did you use that contained the system log?
Answer: fishy.log
Explanation: The fishy.log
file was the system log processed in the script, containing information to search for specific errors.
Q5. What is the purpose of the if __name__ == "__main__":
block, and why is it important for the execution of the script?
Answer: The if __name__ == "__main__":
block is the main entry point of the script, where the script’s execution begins when it is run as the main program.
Explanation: This block ensures that certain parts of the code are executed only when the script is run directly, not when imported as a module.
Q6. Which of the following statements is the best definition of a log file?
Answer: A file that keeps track of events in an operating system
Explanation: Log files record system or application events, which can help in troubleshooting or analyzing system behavior.
Q7. In the script’s execution process described, what are the main functions called, and in what order?
Answer: error_search() and file_output() called in that order
Explanation:
The error_search()
function identifies errors, while file_output()
writes them to a new file, maintaining a logical flow in processing.
Q8. How does the find_error.py
script process the fishy.log
file according to the provided content?
Answer: The script first searches fishy.log
for user-specified errors and then generates a new file, errors_found.log
, containing these errors.
Explanation: The script identifies specific error patterns and saves them in a separate file for further analysis.
Q9. What is the primary purpose of the re
module in Python?
Answer: To provide support for working with Regular Expressions for pattern matching in strings
Explanation: The re
module allows for complex string matching and manipulation using Regular Expressions.
Q10. How to modify the find_error.py
script to find instances of a network connection failure?
Answer: Change the error_patterns
list to include only “network” and “failure”, and then run the script with fishy.log
.
Explanation: By updating error_patterns
with relevant keywords, the script will search for logs matching “network” and “failure”.
Graded Assessment
Module 05: Simple Tests Practice Quiz Answers
Q1. You can verify that software code behaves correctly using test _.
- Cases
- Functions
- Loops
- Arguments
Explanation: Test cases are predefined inputs and expected outputs used to verify that software behaves as intended.
Q2. What is the most basic way of testing a script?
- Let a bug slip through.
- Write code to do the tests.
- Codifying tests into the software.
- Different parameters with expected results.
Explanation: Testing a script with various parameters and comparing the results with expected outcomes is the simplest way to verify functionality.
Q3. When a test is codified into its own software, what kind of test is it?
- Unit test
- Integration test
- Automatic test
- Sanity testing
Explanation: Automatic tests are coded and executed without manual intervention, ensuring consistent and repeatable validation of software behavior.
Q4. Using _ simplifies the testing process, allowing us to verify the program’s behavior repeatedly with many possible values.
- integration tests
- test cases
- test-driven development
- interpreter
Explanation: Test cases streamline testing by providing structured inputs and outputs, enabling repetitive and comprehensive validation.
Q5. The more complex our code becomes, the more value the use of _ provides in managing errors.
- loops
- functions
- parameters
- software testing
Explanation: Software testing is crucial in identifying and addressing errors in complex code, ensuring reliable performance.
Module 05: Other Test Concepts Practice Quiz Answers
Q1. In what type of test is the code not transparent?
- Smoke test
- Black-box test
- Test-driven development
- White-box test
Explanation: In a black-box test, the internal workings of the code are not known or considered. The tester only focuses on the input-output behavior.
Q2. Verifying an automation script works well with the overall system and external entities describes what type of test?
- Integration test
- Regression test
- Load test
- Smoke test
Explanation: Integration testing ensures that individual components or systems work together correctly and interact with external entities as expected.
Q3. ensures that any success or failure of a unit test is caused by the behavior of the unit in question, and doesn’t result from some external factor.
- Regression testing
- Integration
- Isolation
- White-box testing
Explanation: Isolation testing ensures that a unit test is independent, with external factors excluded, so the results accurately reflect the behavior of the specific unit.
Q4. A test that is written after a bug has been identified in order to ensure the bug doesn’t show up again later is called _
- Load test
- Black-box test
- Smoke test
- Regression test
Explanation: Regression testing is done to ensure that newly introduced code changes do not cause previously fixed bugs to reappear.
Q5. What type of software testing is used to verify the software’s ability to behave well under significantly stressed testing conditions?
- Load test
- Black-box test
- Smoke test
- Regression test
Explanation: Load testing is used to evaluate how a system performs under extreme or heavy usage, ensuring it can handle stress without failing.
Module 05: Implement unit testing Assessment Quiz Answers
Q1. What output told you whether a test passed?
Answer: OK
Explanation: When running tests, the output “OK” indicates that the test has passed successfully.
Q2. Which command did you use to view the contents of the user_emails.csv file?
Answer: cat user_emails.csv
Explanation: The cat
command is used to display the contents of a file in the terminal.
Q3. When you began working with the existing emails.py script, what mode did you need to open it in?
Answer: Edit mode
Explanation: To modify the script, you would open it in “edit mode,” allowing you to make changes to the code.
Q4. If a try clause is executed and an exception occurs, but there is no match for the exception in any of the except clauses, what happens?
Answer: It’s an unhandled exception and the execution stops with an error message.
Explanation: If no matching exception is found in the except
clauses, the exception is unhandled, causing the program to terminate with an error message.
Q5. What is the purpose of software testing?
Answer: To determine whether the software meets the specified requirements
Explanation: Software testing ensures that the software performs as expected, meets requirements, and behaves correctly in different scenarios.
Q6. When referring to unit testing, what are “classes”?
Answer: Classes bundle data and functionality together.
Explanation: In the context of unit testing, “classes” in object-oriented programming bundle related data and functions together, allowing for easier organization and management of tests.
Q7. What is the following code an example of?
if email_dict.get(fullname.lower()):
return email_dict.get(fullname.lower())
else:
return "No email address found"
- An if-else loop
- A try/except loop
- An email search
- A try/except clause
Explanation: The code is searching for an email address associated with a person’s full name (in lowercase) in the email_dict
dictionary. If the email exists for the given name, it returns the email; otherwise, it returns "No email address found"
. This is not a loop or a try/except block but rather a search operation using the .get()
method of dictionaries in Python.
email_dict.get(fullname.lower())
: Tries to retrieve the email address associated with the full name (in lowercase) from the dictionary.- If the result is found, it returns the email; otherwise, it returns
"No email address found"
Q8. When testing a working script with a known bug, what should be the overall order of your approach?
Answer: Reproduce the bug, make necessary corrections, and verify that all the tests pass.
Explanation: The correct approach when testing a working script with a known bug is to first reproduce the bug to understand its cause, then make the necessary corrections, and finally verify that all the tests pass to ensure the issue is resolved and no new issues have been introduced.
Q9. The following portion of code will return an error message if a user fails to enter the full name of the employee for a search. What will the error message be?
def find_email(argv):
""" Return an email address based on the username given."""
# Create the username based on the command line input.
try:
fullname = str(argv[1] + " " + argv[2])
# Preprocess the data
email_dict = populate_dictionary('/home/<username>/data/user_emails.csv')
# Find and print the email
return email_dict.get(fullname.lower())
except IndexError:
return "Missing name"
- “Missing name”
- “Missing username”
- “IndexError”
- “No email address found”
Q10. When writing a try/except clause, how many except clauses can be included?
Answer: As many except clauses are needed to specify handlers for different exceptions.
Explanation: In Python, you can include as many except
clauses as necessary to handle different types of exceptions. Each except
clause can be used to handle a specific exception type. This allows the program to respond differently depending on the type of error that occurs.
Lab Assessment
Graded Assessment
Scripts
Module 06: Interacting with the Command Line Practice Quiz Answers
Q1. Which of the following commands will redirect errors in a script to a file?
Answer: user@ubuntu:~$ ./calculator.py 2> error_file.txt
Explanation: In Linux, the 2>
operator is used to redirect the error output (stderr) of a command to a file. 2
refers to stderr, and >
redirects it to the specified file.
Q2. When running a kill command in a terminal, what type of signal is being sent to the process?
Answer: SIGTERM
Explanation: The kill
command sends a SIGTERM
signal by default, which is a request for the process to terminate. Other signals like SIGINT
or SIGSTOP
can also be used with the kill
command, but SIGTERM
is the default.
Q3. What is required in order to read from standard input using Python?
Answer: stdin file object from sys module
Explanation: To read from standard input in Python, you need to use sys.stdin
, which is a file object representing the standard input stream.
Q4._____ are tokens delivered to running processes to indicate a desired action.
Answer: Signals
Explanation: Signals are tokens delivered to running processes to indicate a desired action, such as stopping or continuing a process. Examples include SIGTERM
, SIGINT
, and SIGKILL
.
Q5. In Linux, what command is used to display the contents of a directory?
Answer: ls
Explanation: In Linux, the ls
command is used to list the contents of a directory. pwd
shows the current working directory, cp
copies files, and rmdir
removes directories.
Module 06: Bash Scripting Practice Quiz Answers
Q1. Which of the following commands will output a list of all files in the current directory?
- echo *
- echo a*
- echo *.py
- echo ?.py
Explanation: The echo *
command will display all files in the current directory, as the asterisk (*
) is a wildcard that matches everything in the directory.
Q2.Which module can you load in a Python script to take advantage of star [*] like in BASH?
- ps
- Glob
- stdin
- Free
Explanation: The glob
module in Python allows you to use wildcard characters like *
(star) to match file patterns, similar to how you would in BASH.
Q3. Conditional execution is based on the _ of commands.
- environment variables
- parameters
- exit status
- test results
Explanation: Conditional execution in Unix-like systems relies on the exit status of commands. An exit status of 0
typically means success, while a non-zero exit status indicates failure.
Q4. What command evaluates the conditions received on exit to verify that there is an exit status of 0 when the conditions are true, and 1 when they are false?
- test
- grep
- echo
- export
Explanation: The test
command evaluates conditions and sets the exit status to 0
if the condition is true, and 1
if false. It’s commonly used in conditional statements like if
.
Q5. The opening square bracket ([), when combined with the closing square bracket (]), is an alias for which command?
- glob
- test
- export
- if
Explanation: In shell scripting, [ ]
is an alias for the test
command. It is used for evaluating expressions, such as checking file existence or string comparisons.
Module 06: Advanced Bash Concepts Practice Quiz Answers
Q1. command does the while loop initiate a task(s) after?
Answer: do
Explanation: In a while
loop in Bash, the do
command initiates the task(s) to be executed repeatedly while the condition is true.
Q2. Which line is correctly written to start a for loop with a sample.txt file?
Answer: for file in sample.txt; do
Explanation: In a for
loop, you iterate over a list of items. The correct syntax is for variable in list; do
, where file
is the variable and sample.txt
is the file to loop over.
Q3. Which of the following Bash lines contains the condition of taking an action when n is less than or equal to 9?
Answer: while [ $n -le 9 ]; do
Explanation: In Bash, -le
means “less than or equal to”, so the condition while [ $n -le 9 ]; do
ensures that the loop runs as long as n
is less than or equal to 9.
Q4. Which of the following statements are true regarding Bash and Python? [Check all that apply]
Answer:
- Complex scripts are better suited to Python.
- Python can more easily operate on strings, lists, and dictionaries.
- If a script requires testing, Python is preferable.
Explanation:
- Python is better suited for complex scripts due to its more powerful libraries and data structures.
- Python provides more versatile tools for working with strings, lists, and dictionaries.
- Python is generally preferred when scripting requires extensive testing or more advanced data manipulation.
- Bash scripts typically work best on Unix-like systems (Linux, macOS), but Python is cross-platform, making it more universally compatible.
Q5. The _____ command lets us take only bits of each line using a field delimiter.
Answer: cut
Explanation: The cut
command in Bash allows you to extract specific fields or columns from each line of text using a delimiter, such as a space, comma, or tab.
Practice Quiz: Interacting with the Command Line
Q1. Which of the following commands will redirect errors in a script to a file?
- user@ubuntu:~$ ./calculator.py >> error_file.txt
- user@ubuntu:~$ ./calculator.py 2> error_file.txt
- user@ubuntu:~$ ./calculator.py > error_file.txt
- user@ubuntu:~$ ./calculator.py < error_file.txt
Q2. When running a kill command in a terminal, what type of signal is being sent to the process?
- PID
- SIGINT
- SIGSTOP
- SIGTERM
Q3. What is required in order to read from standard input using Python?
- echo file.txt
- cat file.txt
- The file descriptor of the STDIN stream
- Stdin file object from sys module
Q4. _ are tokens delivered to running processes to indicate the desired action.
- Signals
- Methods
- Functions
- Commands
Q5. In Linux, what command is used to display the contents of a directory?
- rmdir
- cp
- pwd
- ls
Module 06: Edit files using substrings Graded Assessment Answers
Q1. A junior programmer has asked your advice on which Linux command to use to create single or multiple files, view the contents of a file, concatenate files, and redirect output in terminal or other files. Which Linux command would you tell them to use?
Answer: The cat command
Explanation: The cat
command is used to create, view, and concatenate files in Linux. It is also commonly used to redirect output to other files.
Q2. What is the Linux command you should use to extract certain specific information columns from a larger database?
Answer: The cut command
Explanation: The cut
command is used to extract specific columns of data from a file or input, making it ideal for parsing data with delimiters.
Q3. What is a delimiter?
Answer: A character or set of characters that separate text strings
Explanation: A delimiter is a character or set of characters that marks the boundary between separate, distinct parts of data (e.g., commas in CSV files or spaces in plain text).
Q4. A single greater than sign (>) or a double greater than sign (>>) can be used to redirect standard output. What do commands with a double greater than sign (>>) do with existing file content?
Answer: Append the file content
Explanation: The double greater than sign >>
is used to append the output to an existing file, rather than overwriting its content, which is what a single >
would do.
Q5. What will executing the command grep 'jane' ../data/list.txt
do?
Answer: Return all lines containing the text string “jane” in the file list.txt.
Explanation: The grep
command searches for the pattern ‘jane’ in the file list.txt
and returns all lines that contain this text.
Q6. What will the command cd data
do?
Answer: Navigate to the data directory.
Explanation: The cd
(change directory) command is used to navigate to a specified directory. In this case, it changes the current working directory to the data
directory.
Q7. Looking at the following command, how might you predict the fields in the file list.txt are delineated?grep " jane " ../data/list.txt | cut -d '...' -f 1
Answer: By an ellipsis (…)
Explanation: The -d '...'
option in the cut
command indicates that an ellipsis (...
) is being used as the delimiter to separate the fields.
Q8. You need to write a script that quickly checks the status of all running processes on a server. Which of the following languages would work best? Select the best answer.
Answer: Bash
Explanation: Bash is well-suited for quickly checking system status and working with processes in Linux-based systems, making it the best choice for this task.
Q9. You used the replace() function to replace the old substring “jane” with the new substring “jdoe”. What is the syntax of that command?
Answer: string.replace(old_substring, new_substring)
Explanation: In Python, the replace()
function is used with the syntax string.replace(old_substring, new_substring)
to replace an old substring with a new one.
Q10. Bash script allows three different iterative statements, or “loops”. What is a “while” loop?
Answer: The execution of a set of instructions as long as the control condition remains true.
Explanation: A while
loop in Bash continues to execute a set of instructions as long as the specified condition evaluates to true
.
Graded Assessment
Module 07: Log analysis using regular expressions Graded Quiz Answers
Q1. What is the primary purpose of using regular expressions in log analysis?
Answer: To extract specific patterns and information from unstructured log data
Explanation: Regular expressions are powerful tools for searching and extracting specific patterns from unstructured log data, making it easier to analyze logs for relevant information.
Q2. What will the following command return?grep ticky syslog.log
Answer: All the logs from ticky
Explanation: The grep ticky syslog.log
command will search for all occurrences of the string “ticky” in the syslog.log
file and return the corresponding lines.
Q3. You can reverse the order of the sort using the reverse parameter. What type of argument does the reverse parameter take?
Answer: Boolean
Explanation: The reverse
parameter takes a Boolean value (True
or False
). When set to True
, it reverses the order of sorting.
Q4. When sorting this dictionary:fruit = {"oranges": 3, "apples": 5, "bananas": 4, "pears": 2}
What will the following line of code return?sorted(fruit.items(), key=operator.itemgetter(1))
Answer: [(‘pears’, 2), (‘oranges’, 3), (‘bananas’, 4), (‘apples’, 5)]
Explanation: The code uses operator.itemgetter(1)
to sort the dictionary fruit
by its values in ascending order. The resulting sorted list of tuples is: [('pears', 2), ('oranges', 3), ('bananas', 4), ('apples', 5)]
.
Q5. Why do you need to know how to write automation scripts that process a system log and generate reports from the log files?
Answer: To eliminate the need for manual log analysis, saving time, and improving efficiency
Explanation: Automation scripts help automate the tedious task of log analysis, saving time and improving overall efficiency, especially when dealing with large log files.
Q6. Why are regular expressions useful?
Answer: They allow us to search and manipulate text based on patterns
Explanation: Regular expressions are used for pattern matching and manipulation in strings, making them very useful for tasks like searching, extracting, or replacing text.
Q7. What syntax would you use to enlist all the ERROR messages of a specific kind?
Answer: grep ERROR [file-name] [message]
Explanation: To search for “ERROR” messages in a file, the correct syntax is grep ERROR [file-name]
, and [message]
would be an additional filter for a specific pattern.
Q8. In Python, regular expressions are typically handled using which module?
Answer: re
Explanation: In Python, regular expressions are handled using the re
module, which provides functions for pattern matching and manipulation of strings.
Q9. Evaluate the following problem statement: “I want to create a script to sort files.” What’s missing?
Answer: The problem statement does not specify what files to sort.
Explanation: The statement mentions sorting files, but it does not clarify which files need to be sorted, nor the criteria for sorting (by name, size, date, etc.).
Q10. If there is no python script named ticky_check.py
, what will the command nano ticky_check.py
return?
Answer: A new python script named ticky_check.py
Explanation: The nano
command opens a new file for editing. If the file ticky_check.py
does not exist, it will create a new file with that name, which can then be saved as a Python script.
Next Quiz Answers >>
Introduction to Git and Github
<< Previous Quiz Answers
All Quiz Answers of Google IT Automation with Python Professional Certificate
Course 1: Crash Course on Python Coursera Quiz Answers
Course 2: Using Python to interact with the Operating System
Course 3: Introduction to Git and GitHub
Course 4: Troubleshooting and Debugging Techniques
Course 5: Configuration Management and the Cloud
Course 6: Automating Real-World Tasks with Python