Cousera Answers

Python Operating System Coursera Quiz & Assessment Answers | Google IT Automation with Python Professional Certificate 2021

Python Operating System Coursera Quiz & Assessment Answers | Google IT Automation with Python Professional Certificate 2021 – Today at healthyguide we provide 100% correct✅ answers of all week, assessment, and final exam answers of Python Operating System Coursera Quiz & Assessment from Coursera Free Certification Course.

NOTE: IF YOU HAVE A NEW QUESTION FOR THIS TEST, PLEASE LEAVE A COMMENT IN THE FORM BELOW WITH THE QUESTION AND MULTIPLE-CHOICE LIST. WE WILL RESPOND TO YOUR QUESTIONS AS SOON AS POSSIBLE. THANK YOU VERY MUCH! YOUR CONTRIBUTION TO THE WEBSITE IS GREATLY APPRECIATED.

About The Coursera

CourseraIndia’s biggest learning platform which launched millions of free courses for students daily. These courses are from various recognized universities, where industry experts and professors teach in a very well manner and in a more understandable way.

Tips : All answers to Python Operating System Coursera Quiz & Assessment Answers has been indicated in different Color which are given below.

Apply Here – Using Python to Interact with the Operating System

Sponsored Links
1. Getting Your Python On

Practice Quiz: Automation

  • Total points: 5
  • Score: 100%

Question 1

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

This is a practical application of using Python (and some extra hardware, in this case) to automate a task, freeing up a human’s time. The solutions can be complex if the return in saved human time warrants it.

Question 2

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.

Forensic value, in relation to automation, is the value we get while debugging from properly logging every action our automation scripts take.

Question 3

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]

With 10 hours to automate, the employee will start saving time before the month is over.

Question 4

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

It’s safe to say that the company won’t find it worth it’s time to automate.

Question 5

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

Email notifications for errors or task completions can help keep track of automated processes.

Internal issue tracker entries are created as part of reporting on errors in our automation script in this lesson.

Automated consistency checks, such as hash checks on backups, can help identify problems ahead of time.

Practice Quiz: Getting Ready for Python

  • Total points: 5
  • Score: 100%

Question 1

Which of the following is the most modern, up-to-date version of Python?

  • Python 3
  • Python 2
  • Python 4
  • Anaconda

Python 3 is the latest version of Python, with Python 3.8.0 being released on October 14, 2019.

Question 2

Which of the following operating systems is compatible with Python 3?

  • Redhat Linux
  • Microsoft Windows
  • Apple MacOS
  • All of the above

Python is a cross-platform language. You can use it on Windows, macOS, Linux, and even on lesser-known Unix variants like FreeBSD.

Question 3

Which of the following operating systems does not run on a Linux kernel?

  • Android
  • Chrome OS
  • Mac OS
  • Ubuntu

Mac OS is a proprietary operating system designed by Apple and uses a proprietary kernel based on BSD.

Question 4

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

Typing python -V (note the capital V) at the command line will tell you if Python is currently installed and if so, what version.

Typing python –version (note the double dashes) at the command line will tell you if Python is currently installed and if so, what version.

Question 5

What is pip an example of?

  • A programming language
  • An operating system
  • A repository of Python modules
  • A Python package manager

pip is a command line tool commonly used as the main method of managing packages in Python.

Practice Quiz: Running Python Locally

  • Total points: 5
  • Score: 100%

Question 1

When your IDE automatically creates an indent for you, this is known as what?

  • Code reuse
  • Interpreted language
  • Syntax highlighting
  • Code completion

Code completion is an IDE feature that takes educated guesses about what you might be trying to type next, and offers suggestions to complete it for you.

Question 2

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.

While the x variable is calling numpy using its declared local name, y is not using the local name. This will result in an error.

Question 3

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

A compiled language is translated into code readable by the target machine during development using a compiler.

Question 4

Which of the following is not an IDE or code editor?

  • Eclipse
  • pip
  • Atom
  • PyCharm

The package manager pip is used in Python to install packages from repositories such as PyPI.

Question 5

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

The PATH variable tells the operating system where to find executables.

Peer Graded Assessment

https://drive.google.com/drive/folders/1lyU1LBA2ONAMK1WOFvozEZGlCi46EHks?usp=sharing

2. Managing Files With Python

Practice Quiz: Managing Files & Directories

  • Total points: 5
  • Score: 100%

Question 1

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

Question 2

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']

Question 3

Which of the following methods from the os module will create a new directory?

  • path.isdir()
  • listdir()
  • mkdir()
  • chdir()

os.mkdir() will create a new directory with the name provided as a string parameter.

Question 4

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

Question 5

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:

/

Practice Quiz: Reading & Writing CSV Files

  • Total points: 5
  • Score: 80% (?)

Question 1

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:

Incorrect\
Something went wrong! Contact Coursera Support about this question!

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

Question 2

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

Question 3

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

We have to create a DictWriter() object instance to work with, and pass to it the fieldnames parameter defined as a list of keys.

The non-optional fieldnames parameter list values should be written to the first row.

The CSV file has to be open before we can write to it.

Question 4

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

We need to have the exact same amount of variables on the left side of the equals sign as the length of the sequence on the right side when unpacking rows into individual variables.

Although they read the CSV rows into different datatypes, both csv.reader or csv.DictReader can be used to parse CSV files.

We have to create an instance of the reader class we are using before we can parse the CSV file.

Question 5

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

Parsing a file means analyzing its contents to correctly structure the data. As long as we know what the data is, we can organize it in a way our script can use effectively.

Reading and Writing Files

Video: Reading Files

What is the difference between the readline() and read() methods?

  • The readline() method starts from the current position, while the read() method reads the whole file.
  • The read() method reads a single line, the readline() method reads the whole file.
  • The readline() method reads the first line of the file, the read() method reads the whole file.
  • The readline() method reads a single line from the current position, the read() method reads from the current position until the end of the file.

Both methods read from the current position. The readline() method reads one line, while read() reads until the end of the file.

Video: Iterating through Files

Can you identify which code snippet will correctly open a file and print lines one by one without whitespace?

  • with open(“hello_world.txt”) as text: for line in text: print(line)
  • with open(“hello_world.txt”) as text: for line in text: print(text)
  • with open(“hello_world.txt”) as text: print(line)
  • with open(“hello_world.txt”) as text: for line in text: print(line.strip())

Here, we are iterating line by line, and the strip() command is used to remove extra whitespace.

Video: Writing Files

What happens to the previous contents of a file when we open it using “w” (“write” mode)?

  • The new contents get added after the old contents.
  • A new file is created and the old contents are kept in a copy.
  • The old contents get deleted as soon as we open the file.
  • The old contents get deleted after we close the file.

When using write mode, the old contents get deleted as soon as the file is opened.


Managing Files and Directories

Video: Working with Files

How can we check if a file exists inside a Python script?

  • Renaming the file with os.rename.
  • Creating the file with os.create.
  • Using the os.path.exists function.
  • Deleting the file with os.remove.

The os.path.exists function will return True if the file exists, False if it doesn’t.

Video: More File Information

Some more functions of the os.path module include getsize() and isfile() which get information on the file size and determine if a file exists, respectively. In the following code snippet, what do you think will print if the file does not exist?

import os
file= "file.dat"
if os.path.isfile(file):
    print(os.path.isfile(file))
    print(os.path.getsize(file))
else:
    print(os.path.isfile(file))
    print("File not found")
  • file.dat

    1024

  • False

    2048

  • True

    512

  • False
    File not Found

Because the file does not exist, getsize() will never be called and our error message will be printed instead.

Video: Directories

What’s the purpose of the os.path.join function?

  • It creates a string containing cross-platform concatenated directories.
  • It creates new directories.
  • It lists the file contents of a directory.
  • It returns the current directory.

By using os.path.join we can concatenate directories in a way that can be used with other os.path() functions.


Reading and Writing CSV Files

Video: What is a CSV file?

If we have data in a format we understand, then we have what we need to parse the information from the file. What does parsing really mean?

  • Reducing the logical size of a file to decrease disk space used and increase network transmission speed.
  • Uploading a file to a remote server for later use, categorized by format
  • Using rules to understand a file or datastream as structured data.
  • Writing data to a file in a format that can be easily read later

If we know the format of the data, we can separate it into understandable parts.

Video: Reading CSV Files

Which of the following lines would correctly interpret a CSV file called “file” using the CSV module? Assume that the CSV module has already been imported.

  • data=file.csv()
  • file.opencsv()
  • data=csv.reader(file)
  • data=csv.open(file)

The reader() function of the CSV module will interpret the file as a CSV.

Video: Generating CSV

Which of the following must we do before using the csv.writer() function?

  • Open the file with read permissions.
  • Import the functools module.
  • Import the argparse module.
  • Open the file with write permissions.

The file must be open, preferably using with open() as, and write permissions must be given.

Video: Reading and Writing CSV Files with Dictionaries

DictReader() allows us to convert the data in a CSV file into a standard dictionary. DictWriter() \ allows us to write data from a dictionary into a CSV file. What’s one parameter we must pass in order for DictWriter() to write our dictionary to CSV format?

  • The DictReader() function must be passed the CSV file
  • The writerows() function requires a list of key
  • The writeheader() function requires a list of keys
  • The fieldnames parameter of DictWriter() requires a list of keys

This will help DictWriter() organize the CSV rows properly.

Reading and Writing Files

https://drive.google.com/file/d/1UjX9fTGae2e5Pe_uCfSrSQvtBXle0-vN/view?usp=sharing

Graded Assessment

https://drive.google.com/drive/folders/1RnKAVUyCvPDCxRlbkk26_Q7OUZ5lGG5U?usp=sharing

Source

https://drive.google.com/drive/folders/1u3K4_IVCnVIsDqMq2NSrbmGR57Zq97-9?usp=sharing

3. Regular Expressions

Practice Quiz: Advanced Regular Expressions

  • Total points: 5
  • Score: 100%

Question 1

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

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

Question 2

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!")) 
# []

Output:

['beautiful']
['Obviously', 'queen', 'courageous', 'gracious']
['rambunctious', 'quietly', 'delicious']
['queue']
[]

Question 3

When capturing regex groups, what datatype does the groups method return?

  • A string
  • A tuple
  • A list
  • A float

Because a tupleis returned, we can access each index individually.

Question 4

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)"

Output:

// Start of program
  number = 0   // Initialize the variable
  number += 1   // Increment the variable
  return(number)

Question 5

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

Output:

My number is (212) 345-9999.
Please call (888) 555-1234
123-123-12345
Phone number of Buckingham Palace is +44 303 123 7300

Practice Quiz: Basic Regular Expressions

  • Total points: 6
  • Score: 100%

Question 1

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

Output:

True
False
True
False
True

Question 2

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

Output:

True
True
False
False

Question 3

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

Output:

True
True
False
True
True

Question 4

What does the “r” before the pattern string in re.search(r”Py.*n”, sample.txt) indicate?

  • Raw strings
  • Regex
  • Repeat
  • Result

“Raw” strings just means the Python interpreter won’t try to interpret any special characters and, instead, will just pass the string to the function as it is.

Question 5

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

The plus character [+], matches one or more occurrences of the character that comes before it.

Question 6

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

Output:

True
False
True
False

Practice Quiz: Regular Expressions

  • Total points: 5
  • Score: 100%

Question 1

When using regular expressions, which of the following expressions uses a reserved character that can represent any single character?

  • re.findall(f.n, text)
  • re.findall(f*n, text)
  • re.findall(fu$, text)
  • re.findall(^un, text)

The dot (.) represents any single character.

Question 2

Which of the following is NOT a function of the Python regex module?

  • re.search()
  • re.match()
  • re.findall()
  • re.grep()

The grep command utilizes regular expressions on Linux, but is not a part of the standard re Python module.

Question 3

The circumflex [^] and the dollar sign [$] are anchor characters. What do these anchor characters do in regex?

  • Match the start and end of a word.
  • Match the start and end of a line
  • Exclude everything between two anchor characters
  • Represent any number and any letter character, respectively

The circumflex and the dollar sign specifically match the start and end of a line.

Question 4

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?

  • Special characters
  • Anchor characters
  • Literal characters
  • Wildcard characters

Special characters, sometimes called meta characters, give special meaning to the regular expression search syntax.

Question 5

What is grep?

  • An operating system
  • A command for parsing strings in Python
  • A command-line regex tool
  • A type of special character

The grep command is used to scan files for a string of characters occurring that fits a specified sequence.

Regular Expressions

Video: What are regular expressions?

Which of the following demonstrates how regex (regular expressions) might be used?

  • Recognize an image
  • Calculate Pi
  • Find strings of text that match a pattern
  • Multiply and divide arrays

Video: Why use regular expressions?

Rather than using the index() function of the string module, we can use regular expressions, which are more flexible. After importing the regular expression module re, what regex function might be used instead of standard methods?

  • re.regex()
  • re.pid()
  • re.search()
  • re.index()

Video: Basic Matching with grep

Using the terminal, which of the following commands will correctly use grep to find the words “sling” and “sting” (assuming they are in our file, file.txt)?

  • user@ubuntu:~$ grep(s.ing) /usr/file.txt
  • user@ubuntu:~$ grep sting+sling /usr/file.txt
  • user@ubuntu:~$ grep s.ing /usr/file.txt
  • user@ubuntu:~$ grep s+ing /usr/file.txt

Basic Regular Expressions

Video: Simple Matching in Python

Fill in the code to check if the text passed contains the vowels a, e and i, with exactly one occurrence of any other character in between.

import re
def check_aei (text):
  result = re.search(r"a.e.i", text)
  return result != None

print(check_aei("academia")) # True
print(check_aei("aerial")) # False
print(check_aei("paramedic")) # True

Output:

True
False
True

Video: Wildcards and Character Classes

Fill in the code to check if the text passed contains punctuation symbols: commas, periods, colons, semicolons, question marks, and exclamation points.

import re
def check_punctuation (text):
  result = re.search(r"[,.:;?!]", text)
  return result != None

print(check_punctuation("This is a sentence that ends with a period.")) # True
print(check_punctuation("This is a sentence fragment without a period")) # False
print(check_punctuation("Aren't regular expressions awesome?")) # True
print(check_punctuation("Wow! We're really picking up some steam now!")) # True
print(check_punctuation("End of the line")) # False

Output:

True
False
True
True
False

Video: Repetition Qualifiers

The repeating_letter_a function checks if the text passed includes the letter “a” (lowercase or uppercase) at least twice. For example, repeating_letter_a(“banana”) is True, while repeating_letter_a(“pineapple”) is False. Fill in the code to make this work.

import re
def repeating_letter_a(text):
  result = re.search(r"[Aa].*[Aa]", text)
  return result != None

print(repeating_letter_a("banana")) # True
print(repeating_letter_a("pineapple")) # False
print(repeating_letter_a("Animal Kingdom")) # True
print(repeating_letter_a("A is for apple")) # True

Output:

True
False
True
True

Video: Escaping Characters

Fill in the code to check if the text passed has at least 2 groups of alphanumeric characters (including letters, numbers, and underscores) separated by one or more whitespace characters.

import re
def check_character_groups(text):
  result = re.search(r"[0-9]\w", text)
  return result != None

print(check_character_groups("One")) # False
print(check_character_groups("123  Ready Set GO")) # True
print(check_character_groups("username user_01")) # True
print(check_character_groups("shopping_list: milk, bread, eggs.")) # False

Output:

False
True
True
False

Video: Regular Expressions in Action

Fill in the code to check if the text passed looks like a standard sentence, meaning that it starts with an uppercase letter, followed by at least some lowercase letters or a space, and ends with a period, question mark, or exclamation point.

import re
def check_sentence(text):
  result = re.search(r"^[A-Z][a-z| ]*[.?!]$", text)
  return result != None

print(check_sentence("Is this is a sentence?")) # True
print(check_sentence("is this is a sentence?")) # False
print(check_sentence("Hello")) # False
print(check_sentence("1-2-3-GO!")) # False
print(check_sentence("A star is born.")) # True

Output:

True
False
False
False
True

Advance Regular Expressions

Video: Capturing Groups

Fix the regular expression used in the rearrange_name function so that it can match middle names, middle initials, as well as double surnames.

import re
def rearrange_name(name):
  result = re.search(r'^([\w \.-]*), ([\w \.-]*)', name)
  if result == None:
    return name
  return "{} {}".format(result[2], result[1])

name=rearrange_name("Kennedy, John F.")
print(name)

Output:

John F. Kennedy

Video: More on Repetition Qualifiers

The long_words function returns all words that are at least 7 characters. Fill in the regular expression to complete this function.

import re
def long_words(text):
  pattern = r'\w{7,}'
  result = re.findall(pattern, text)
  return result

print(long_words("I like to drink coffee in the morning.")) # ['morning']
print(long_words("I also have a taste for hot chocolate in the afternoon.")) # ['chocolate', 'afternoon']
print(long_words("I never drink tea late at night.")) # []

Output:

['morning']
['chocolate', 'afternoon']
[]

Video: Extracting a PID Using regexes in Python

Add to the regular expression used in the extract_pid function, to return the uppercase message in parenthesis, after the process id.

import re
def extract_pid(log_line):
    regex = r"\[(\d+)\]: (\w+)"
    result = re.search(regex, log_line)
    if result is None:
        return None
    return "{} ({})".format(result[1],result[2])

print(extract_pid("July 31 07:51:48 mycomputer bad_process[12345]: ERROR Performing package upgrade")) # 12345 (ERROR)
print(extract_pid("99 elephants in a [cage]")) # None
print(extract_pid("A string that also has numbers [34567] but no uppercase message")) # None
print(extract_pid("July 31 08:08:08 mycomputer new_process[67890]: RUNNING Performing backup")) # 67890 (RUNNING)

Output:

12345 (ERROR)
None
None
67890 (RUNNING)

Video: Splitting and Replacing

We want to split a piece of text by either the word “a” or “the”, as implemented in the following code. What is the resulting split list?

re.split(r"the|a", "One sentence. Another one? And the last one!")
  • ['One sentence. Another one? And ', ' last one!']
  • ['One sentence. Another one? And ', 'the', ' last one!']
  • ['One sentence. Ano', 'r one? And ', ' l', 'st one!']
  • ['One sentence. Ano', 'the', 'r one? And ', 'the', ' l', 'a', 'st one!']

Graded Assessment

https://drive.google.com/drive/folders/1Kw7a_j4pumsyHYbLE5gKD4LgeHrCJQC5?usp=sharing

4. Managing Data & Process

Practice Quiz: Data Streams

  • Total points: 5
  • Score: 100%

Question 1

Which command will print out the exit value of a script that just ran successfully?

  • echo $PATH
  • wc variables.py
  • import sys
  • echo $?

Echo will print out the exit value (question mark variable) of a script that just ran successfully.

Question 2

Which command will create a new environment variable?

  • export
  • input
  • wc
  • env

This command will create a new environment variable, and give it a value.

Question 3

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

STDIN is the standard I/O stream for input.

Question 4

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.

An exit value of 0 always indicates the program exited without error.

Question 5

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.

In Python 2, input evaluates the user’s input as an expression.

raw_input gets a raw string from the user.

Practice Quiz: Processing Log Files

  • Total points: 5
  • Score: 100%

Question 1

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 = {}

This will assign the script’s first command line argument to the variable “syslog”.

Question 2

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

A dictionary is useful to count appearances of strings.

Question 3

Which keyword will return control back to the top of a loop when iterating through logs?

  • Continue
  • Get
  • With
  • Search

The continue statement is used to return control back to the top of a loop.

Question 4

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+)\)$"

This expression will search for the word “IP” followed by a space and parentheses. It uses a capture group and \d+ to capture any digit characters found in the parentheses.

Question 5

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.

Since log files can get pretty large, it’s a good idea to parse them one line at a time instead of loading the entire file into memory at once.

We can save a lot of time by not parsing lines that don’t contain what we need.

Before we can parse our log file, we have to use the open() or with open() command on the file first.

Practice Quiz: Python Subprocesses

  • Total points: 5
  • Score: 100%

Question 1

What type of object does a run function return?

  • stdout
  • CompletedProcess
  • capture_output
  • returncode

This object includes information related to the execution of a command.

Question 2

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.

This will `change the current working directory where the command will be executed.

Question 3

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.

To run the external command, a secondary environment is created for the child subprocess, where the command is executed.

While the parent process is waiting on the subprocess to finish, it’s blocked, meaning the parent can’t do any work until the child finishes.

After the external command completes its work, the child process exits, and the flow of control returns to the parent.

Question 4

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

The capture_output parameter allows us to get and store the output of the system command we’re using.

Question 5

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

The copy method of os.environ makes a new copy of the dictionary containing the environment variables, making modification easier.

Data Streams

Video: Reading Data interactively

Which line of code from the seconds.py script will convert all integer inputs into seconds?

  • int(input(“Enter the number of seconds: “))
  • int(input(“Enter the number of minutes: “))
  • int(input(“Enter the number of hours: “))
  • to_seconds(hours, minutes, seconds)

This line of code uses a function to convert the number of hours, minutes, and seconds into seconds.

Video: Standard Streams

Which I/O stream is the output function using when showing an error message?

  • STDIN
  • STDOUT
  • STDERR
  • PRINT

STDERR displays output specifically for error messages.

Video: Environment Variables

Which directory is NOT listed in the PATH variable by default?

  • /usr/local/sbin
  • /usr/sbin/temp
  • /bin
  • /sbin

This directory is not listed by default.

Video: Command-Line Arguments and Exit Status

Where are the command line arguments stored?

  • argv
  • sys
  • parameters.py
  • print

The list of arguments are stored in the sys module.


Python Subprocesses

Video: Running System Commands in Python

A system command that sends ICMP packets can be executed within a script by using which of the following?

  • subprocess.run
  • Ping
  • CompletedProcess
  • Arguments

This function will execute a system command such as ping.

Video: Obtaining the Output of a System Command

Which of the following is a Unicode standard used to convert an array of bytes into a string?

  • UTF-8
  • stdout
  • capture_output
  • Host

This encoding is part of the Unicode standard that can transform an array of bytes into a string.

Video: Advanced Subprocess Management

Which method do you use to prepare a new environment to modify environment variables?

  • join
  • env
  • copy
  • cwd

Calling this method of the os.environ dictionary will copy the current environment variables to store and prepare a new environment.


Processing Log Files

Video: Filtering Log Files with Regular Expressions

We’re using the same syslog, and we want to display the date, time, and process id that’s inside the square brackets. We can read each line of the syslog and pass the contents to the show_time_of_pid function. Fill in the gaps to extract the date, time, and process id from the passed line, and return this format: Jul 6 14:01:23 pid:29440.

import re
def show_time_of_pid(line):
  pattern = r"([a-zA-Z]+ \d+ \d+:\d+:\d+).*\[(\d+)\]\:"
  result = re.search(pattern, line)
  return "{} pid:{}".format(result.group(1), result.group(2))

print(show_time_of_pid("Jul 6 14:01:23 computer.name CRON[29440]: USER (good_user)")) # Jul 6 14:01:23 pid:29440
print(show_time_of_pid("Jul 6 14:02:08 computer.name jam_tag=psim[29187]: (UUID:006)")) # Jul 6 14:02:08 pid:29187
print(show_time_of_pid("Jul 6 14:02:09 computer.name jam_tag=psim[29187]: (UUID:007)")) # Jul 6 14:02:09 pid:29187
print(show_time_of_pid("Jul 6 14:03:01 computer.name CRON[29440]: USER (naughty_user)")) # Jul 6 14:03:01 pid:29440
print(show_time_of_pid("Jul 6 14:03:40 computer.name cacheclient[29807]: start syncing from \"0xDEADBEEF\"")) # Jul 6 14:03:40 pid:29807
print(show_time_of_pid("Jul 6 14:04:01 computer.name CRON[29440]: USER (naughty_user)")) # Jul 6 14:04:01 pid:29440
print(show_time_of_pid("Jul 6 14:05:01 computer.name CRON[29440]: USER (naughty_user)")) # Jul 6 14:05:01 pid:29440

Output:

Jul 6 14:01:23 pid:29440
Jul 6 14:02:08 pid:29187
Jul 6 14:02:09 pid:29187
Jul 6 14:03:01 pid:29440
Jul 6 14:03:40 pid:29807
Jul 6 14:04:01 pid:29440
Jul 6 14:05:01 pid:29440

Video: Making Sense out of the Data

Which of the following is a correct printout of a dictionary?

  • {‘carrots’:100, ‘potatoes’:50, ‘cucumbers’: 65}
  • {50:’apples’, 55:’peaches’, 15:’banana’}
  • {55:apples, 55:peaches, 15:banana}
  • {carrots:100, potatoes:50, cucumbers: 65}

A dictionary stores key:value pairs.

Graded Assessment

https://drive.google.com/drive/folders/1CUVgWeJl_24ieCeCmUvcwc8Rq-a6Ivnz?usp=sharing

5. Testing With Python

Practice Quiz: Other Test Concepts

  • Total points: 5
  • Score: 100%

Question 1

In what type of test is the code not transparent?

  • Smoke test
  • Black-box test
  • Test-driven development
  • White-box test

This type of test relies on the tester having no knowledge of the code.

Question 2

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

This test verifies that the different parts of the overall system interact as expected.

Question 3

_ 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

By ensuring the unit of code we are testing is isolated, we can ensure we know where the bug originated.

Question 4

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

Regression testing is a type of software test used to confirm that a recent program or code change has not adversely affected existing features, by re-executing a full or partial selection test cases.

Question 5

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

Load testing verifies the behavior of the software remains consistent under conditions of significant load.

Practice Quiz: Simple Tests

  • Total points: 5
  • Score: 100%

Question 1

You can verify that software code behaves correctly using test _.

  • Cases
  • Functions
  • Loops
  • Arguments

The software code should behave the way you expect with as many possible values or test cases.

Question 2

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.

The most basic way of testing a script is to use different parameters and get the expected results.

Question 3

When a test is codified into its own software, what kind of test is it?

  • Unit test
  • Integration test
  • Automatic test
  • Sanity testing

Codifying tests into its own software and code that can be run to verify that our programs do what we expect them to do is automatic testing.

Question 4

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

Test cases automatically test with a range of possible values to verify the program’s behavior.

Question 5

The more complex our code becomes, the more value the use of _ provides in managing errors.

  • loops
  • functions
  • parameters
  • software testing

Software testing is the process of evaluating computer code to determine whether or not it does what you expect it to do, and the more complex the code, the more likely failure is.

Simple Tests

Video: What is testing?

When you test software, what are you really looking for?

  • Loops
  • Conditionals
  • Modules
  • Defects

You want to find errors and defects when testing software.

Video: Manual Testing and Automated Testing

The advantage of running automated tests is that they will always get the same expected _ if the software code is good.

  • Command line arguments
  • Parameters
  • Results
  • Interpreters

Automatic tests will always get the same expected result if the software code is good.

Unit Tests

Video: Unit Tests

An important characteristic of a unit test is _.

  • Isolation.
  • A production environment
  • An external database
  • Automation.

Unit tests test the piece of code they target.

Video: Writing Unit Tests in Python

What module can you load to use a bunch of testing methods for your unit tests?

  • TestCase
  • unittest
  • assertEqual
  • Test

This module provides a TestCase class with a bunch of testing methods.

Video: Edge Cases

Which of the following would NOT be considered as an edge case when testing a software’s input for a user’s first and last name?

  • -100
  • Jeffrey
  • Ben05
  • 0

A user’s name with only letters is expected.

Video: Additional Test Cases

Which of the following is NOT an advantage of running an automatic unit test in a suite for a single function?

  • Efficiency
  • Creating multiple test scripts
  • Creating one script for multiple test cases
  • Reusable test cases

It’s harder to manage multiple test scripts.


Other Test Concepts

Video: Black Box vs. White Box

Which of the following is descriptive of a black-box test case?

  • The tester is familiar with the code.
  • The code is open-source.
  • Code is opaque.
  • Tests are created alongside the code development.

Black-box tests have no knowledge of the code.

Video: Other Test Types

Running a piece of software code as-is to see if it runs describes what type of testing?

  • Load test
  • Smoke test
  • Integration test
  • Regression test

Keep it up! This test finds out if the program can run in its basic form before undergoing more refined test cases.


Errors and Exceptions

Video: The Try-Except Construct

When a try block is not able to execute a function, which of the following return examples will an exception block most likely NOT return?

  • Empty String
  • Zero
  • Error
  • Empty List

An exception is not meant to produce an error, but to bypass it.

Video: Raising Errors

What keyword can help provide a reason an error has occurred in a function?

  • return
  • assert
  • raise
  • minlen

This keyword is used to produce a message when a conditional is false.

Video: Testing for Expected Errors

When using the assertRaises method, what is passed first?

  • Error
  • Function name
  • Parameters
  • Conditional

Way to go! The expected error is passed first.

Lab Assessment

https://drive.google.com/file/d/1zUmxGfwgDPgIO6XDslLZNkQupnSqSdHa/view?usp=sharing

https://drive.google.com/file/d/1zTmJePKsmMB8Vegvqozc4jnmxjJ39Jbm/view?usp=sharing

Graded Assessment

https://drive.google.com/drive/folders/1AtcGoLqqfmJMVVussqD-GykdeJwJePIy?usp=sharing

Scripts

https://drive.google.com/drive/folders/1u9-a7c_9_M-72IXVysSB-S2JBx-zjNpI?usp=sharing

5. Testing in Python

Practice Quiz: Other Test Concepts

  • Total points: 5
  • Score: 100%

Question 1

In what type of test is the code not transparent?

  • Smoke test
  • Black-box test
  • Test-driven development
  • White-box test

This type of test relies on the tester having no knowledge of the code.

Question 2

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

This test verifies that the different parts of the overall system interact as expected.

Question 3

_ 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

By ensuring the unit of code we are testing is isolated, we can ensure we know where the bug originated.

Question 4

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

Regression testing is a type of software test used to confirm that a recent program or code change has not adversely affected existing features, by re-executing a full or partial selection test cases.

Question 5

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

Load testing verifies the behavior of the software remains consistent under conditions of significant load.

Practice Quiz: Simple Tests

  • Total points: 5
  • Score: 100%

Question 1

You can verify that software code behaves correctly using test _.

  • Cases
  • Functions
  • Loops
  • Arguments

The software code should behave the way you expect with as many possible values or test cases.

Question 2

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.

The most basic way of testing a script is to use different parameters and get the expected results.

Question 3

When a test is codified into its own software, what kind of test is it?

  • Unit test
  • Integration test
  • Automatic test
  • Sanity testing

Codifying tests into its own software and code that can be run to verify that our programs do what we expect them to do is automatic testing.

Question 4

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

Test cases automatically test with a range of possible values to verify the program’s behavior.

Question 5

The more complex our code becomes, the more value the use of _ provides in managing errors.

  • loops
  • functions
  • parameters
  • software testing

Software testing is the process of evaluating computer code to determine whether or not it does what you expect it to do, and the more complex the code, the more likely failure is.

Simple Tests

Video: What is testing?

When you test software, what are you really looking for?

  • Loops
  • Conditionals
  • Modules
  • Defects

You want to find errors and defects when testing software.

Video: Manual Testing and Automated Testing

The advantage of running automated tests is that they will always get the same expected _ if the software code is good.

  • Command line arguments
  • Parameters
  • Results
  • Interpreters

Automatic tests will always get the same expected result if the software code is good.

Unit Tests

Video: Unit Tests

An important characteristic of a unit test is _.

  • Isolation.
  • A production environment
  • An external database
  • Automation.

Unit tests test the piece of code they target.

Video: Writing Unit Tests in Python

What module can you load to use a bunch of testing methods for your unit tests?

  • TestCase
  • unittest
  • assertEqual
  • Test

This module provides a TestCase class with a bunch of testing methods.

Video: Edge Cases

Which of the following would NOT be considered as an edge case when testing a software’s input for a user’s first and last name?

  • -100
  • Jeffrey
  • Ben05
  • 0

A user’s name with only letters is expected.

Video: Additional Test Cases

Which of the following is NOT an advantage of running an automatic unit test in a suite for a single function?

  • Efficiency
  • Creating multiple test scripts
  • Creating one script for multiple test cases
  • Reusable test cases

It’s harder to manage multiple test scripts.


Other Test Concepts

Video: Black Box vs. White Box

Which of the following is descriptive of a black-box test case?

  • The tester is familiar with the code.
  • The code is open-source.
  • Code is opaque.
  • Tests are created alongside the code development.

Black-box tests have no knowledge of the code.

Video: Other Test Types

Running a piece of software code as-is to see if it runs describes what type of testing?

  • Load test
  • Smoke test
  • Integration test
  • Regression test

Keep it up! This test finds out if the program can run in its basic form before undergoing more refined test cases.


Errors and Exceptions

Video: The Try-Except Construct

When a try block is not able to execute a function, which of the following return examples will an exception block most likely NOT return?

  • Empty String
  • Zero
  • Error
  • Empty List

An exception is not meant to produce an error, but to bypass it.

Video: Raising Errors

What keyword can help provide a reason an error has occurred in a function?

  • return
  • assert
  • raise
  • minlen

This keyword is used to produce a message when a conditional is false.

Video: Testing for Expected Errors

When using the assertRaises method, what is passed first?

  • Error
  • Function name
  • Parameters
  • Conditional

Way to go! The expected error is passed first.

Lab Assessment

https://drive.google.com/file/d/1zUmxGfwgDPgIO6XDslLZNkQupnSqSdHa/view?usp=sharing

https://drive.google.com/file/d/1zTmJePKsmMB8Vegvqozc4jnmxjJ39Jbm/view?usp=sharing

Graded Assessment

https://drive.google.com/drive/folders/1AtcGoLqqfmJMVVussqD-GykdeJwJePIy?usp=sharing

Scripts

https://drive.google.com/drive/folders/1u9-a7c_9_M-72IXVysSB-S2JBx-zjNpI?usp=sharing

6. Bash Scripting

Practice Quiz – Advanced Bash Concepts

  • Total points: 5
  • Score: 100%

Question 1

Which command does the while loop initiate a task(s) after?

  • done
  • while
  • do
  • n=1

Tasks to be performed are written after do.

Question 2

Which line is correctly written to start a FOR loop with a sample.txt file?

  • do sample.txt for file
  • for sample.txt do in file
  • for file in sample.txt; do
  • for sample.txt in file; do

The contents of sample.txt are loaded into a file variable which will do any specified task.

Question 3

Which of the following Bash lines contains the condition of taking an action when n is less than or equal to 9?

  • while [ $n -le 9 ]; dowhile [ $n -le 9 ]; do
  • while [ $n -lt 9 ]; do
  • while [ $n -ge 9 ]; do
  • while [ $n -ot 9 ]; do

This line will take an action when n is less than or equal to 9.

Question 4

Which of the following statements are true regarding Bash and Python? [Check all that apply]

  • Complex scripts are better suited to Python.
  • Bash scripts work on all platforms.
  • Python can more easily operate on strings, lists, and dictionaries.
  • If a script requires testing, Python is preferable.

When a script is complex, it’s better to write it in a more general scripting language, like Python.

Bash scripts aren’t as flexible or robust as having the entire Python language available, with its many different functions to operate on strings, lists, and dictionaries.

Because of the ease of testing and the fact that requiring testing implies complexity, Python is preferable for code requiring verification.

Question 5

The _ command lets us take only bits of each line using a field delimiter.
1 / 1 point

  • cut
  • echo
  • mv
  • sleep

The cut command lets us take only bits of each line using a field delimiter.

Practice Quiz: Bash Scripting

  • Total points: 5
  • Score: 100%

Question 1

Which of the following commands will output a list of all files in the current directory?

  • **echo ***
  • echo a*
  • echo *.py
  • echo ?.py

The star [*] globe will echo or output all files in the current directory.

Question 2

Which module can you load in a Python script to take advantage of star [*] like in BASH?

  • ps
  • Glob
  • stdin
  • Free

The glob module must be imported into a Python script to utilize star [*] like in BASH.

Question 3

Conditional execution is based on the _ of commands.

  • environment variables
  • parameters
  • exit status
  • test results

In Bash scripting, the condition used in conditional execution is based on the exit status of commands.

Question 4

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

test is a command that evaluates the conditions received and exits with zero when they’re true and with one when they’re false.

Question 5

The opening square bracket ([), when combined with the closing square bracket (]), is an alias for which command?

  • glob
  • test
  • export
  • if

The test command can be called with square brackets ([]).

Practice Quiz: Interacting with the Command Line

  • Total points: 5
  • Score: 100%

Question 1

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

The “2>” sign will redirect errors to a file.

Question 2

When running a kill command in a terminal, what type of signal is being sent to the process?

  • PID
  • SIGINT
  • SIGSTOP
  • SIGTERM

The kill command sends a SIGTERM signal to a processor ID (PID) to terminate.

Question 3

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

Using sys.stdin, we can read from standard input in Python.

Question 4

_ are tokens delivered to running processes to indicate a desired action.

  • Signals
  • Methods
  • Functions
  • Commands

Using signals, we can tell a program that we want it to pause or terminate, or many other possible commands.

Question 5

In Linux, what command is used to display the contents of a directory?

  • rmdir
  • cp
  • pwd
  • ls

The ls command lists the file contents of a directory.

Interacting with the Command Line Shell

Video: Basic Linux Commands

Which of the following Linux commands will create an empty file?

  • touch
  • pwd
  • mkdir
  • cd

The touch command will create an empty file.

Video: Redirecting Streams

How do you append the output of a command to a .txt file?

  • user@ubuntu:~$ ./calculator.py > result.txt
  • user@ubuntu:~$ ./calculator.py >> result.txt
  • user@ubuntu:~$ ./calculator.py < result.txt
  • user@ubuntu:~$ print(“This will append”)

A double greater than sign will append a command output to a file.

Video: Pipes and Pipelines

Which of the following is the correct way of using pipes?

  • user@ubuntu:~$ cat sample.txt ./process.py
  • user@ubuntu:~$ cat sample.txt || ./process.py
  • user@ubuntu:~$ tr ‘ ‘ ‘\n’ | sort | cat sample.txt
  • user@ubuntu:~$ cat sample.txt | tr ‘ ‘ ‘\n’ | sort

The contents of the txt file are passed on to be placed in their own line and sorted in alphabetical order on the display.

Video: Signalling Processes

What can you type in the terminal to stop the traceroute command from running cleanly?

  • Ctrl-C
  • SIGINT
  • Ctrl-Z
  • SIGSTOP

This sends a SIGINT signal to the program to stop processing cleanly.


Bash Scripting

Video: Creating Bash Scripts

Which command will correctly run a bash script?

  • user@ubuntu:~$ #!/bin/bash
  • user@ubuntu:~$ ./bash.py
  • user@ubuntu:~$ ./bash_sample.sh
  • user@ubuntu:~$ ./sh.bash

A bash script is run with the .sh file extension.

Video: Using Variables and Globs

When defining a variable you receive the “command not found” message. Which of the following commands will resolve this error?

  • User1= billy
  • $User2 =billy
  • User3 = $billy
  • User4=billy

The variable “User4” has a value of “billy”.

Video: Conditional Execution in Bash

A conditional block in Bash that starts with ‘if’, ends with which of the following lines?

  • fi
  • if
  • else
  • grep

The if conditional ends with fi (a backwards “if”).


Advanced Bash Concept

Video: For Loops in Bash Scripts

Which “for” conditional line will add users Paul and Jeremy to a user variable?

  • for users in Paul Jeremy
  • for user in Paul Jeremy
  • for Paul Jeremy in user
  • for Paul & Jeremy in user

The elements Paul and Jeremy are added to the user variable.

Video: Advanced Command Interaction

When using the following command, what would each line of the output start with?

user@ubuntu:~$ tail /var/log/syslog | cut -d' ' -f3-

  • CRON[257236]:
  • October
  • 31
  • 10:18:41

The time of the log will be shown with the -f3- or field three option of the cut command.

Video: Choosing Between Bash and Python

Which of the following statements would make it better to start using Python instead of Bash?

  • Operate with system commands.
  • Use on multi-platforms.
  • Operate with system files.
  • Run a single process on multiple files.

It is better to use Python and its standard library to use when working across multiple platforms.

Graded Assessment

https://drive.google.com/drive/folders/1nft5uJpNcsofzHs7I5G-EKNL5RbW-wUB?usp=sharing

7. Final Projects

https://drive.google.com/drive/folders/1f1okoiaT4i4OSZwBfL_pQkPUo3EnlrxY?usp=sharing

Back to top button