Crash Course on Python all Quiz Answer

Crash Course on Python all Quiz Answer


Crash Course on Python
All Quiz Answer



Module 1 Graded Assessment


Q1) What is a computer program ?

  • A step-by-step recipe of what needs to be done to complete a task, that gets executed by the computer.


Q2) What’s automation ?

  • The process of replacing a manual step with one that happens automatically.


Q3) Which of the following tasks are good candidates for automation ? Check all that apply.

  • Creating a report of how much each sales person has sold in the last month.
  • Setting the home directory and access permissions for new employees joining your company.
  • Populating your company's e-commerce site with the latest products in the catalog.


Q4) What are some characteristics of the Python programming language? Check all that apply.

  • Python programs are easy to write and understand.
  • The Python interpreter reads our code and transforms it into computer instructions.
  • We can practice Python using web interpreters or codepads as well as executing it locally.


Q5) How does Python compare to other programming languages ?

  • Each programming language has its advantages and disadvantages.


Q6) Write a Python script that outputs "Automating with Python is fun!" to the screen.

  • print("Automating with Python is fun!")


Q7) Fill in the blanks so that the code prints "Yellow is the color of sunshine".

  1. color = "Yellow"
  2. thing = "sunshine"
  3. print(color + " is the color of " + thing)


Q8) Keeping in mind there are 86400 seconds per day, write a program that calculates how many seconds there are in a week, if a week is 7 days. Print the result on the screen.

Note: Your result should be in the format of just a number, not a sentence.

  1. day1= 86400 ;
  2. week7 = 7;
  3. total = week7 * day1;
  4. print(total);


Q9) Use Python to calculate how many different passwords can be formed with 6 lower case English letters. For a 1 letter password, there would be 26 possibilities. For a 2 letter password, each letter is independent of the other, so there would be 26 times 26 possibilities. Using this information, print the amount of possible passwords that can be formed with 6 letters.

  1. a=26**6;
  2. print(a);


Q10) Most hard drives are divided into sectors of 512 bytes each. Our disk has a size of 16 GB. Fill in the blank to calculate how many sectors the disk has.

Note: Your result should be in the format of just a number, not a sentence.

  1. disk_size = 16*1024*1024*1024
  2. sector_size = 512
  3. sector_amount = disk_size/sector_size
  4. print(sector_amount)




Module 2 Graded Assessment



Q1) Complete the function by filling in the missing parts. The color_translator function receives the name of a color, then prints its hexadecimal value. Currently, it only supports the three additive primary colors (red, green, blue), so it returns "unknown" for all other colors.

  1. def color_translator(color):
  2. if color == "red":
  3. hex_color = "#ff0000"
  4. elif color == "green":
  5. hex_color = "#00ff00"
  6. elif color == "blue":
  7. hex_color = "#0000ff"
  8. else:
  9. hex_color = "unknown"
  10. return hex_color

  11. print(color_translator("blue")) # Should be #0000ff
  12. print(color_translator("yellow")) # Should be unknown
  13. print(color_translator("red")) # Should be #ff0000
  14. print(color_translator("black")) # Should be unknown
  15. print(color_translator("green")) # Should be #00ff00
  16. print(color_translator("")) # Should be unknown


Q2) What's the value of this Python expression: "big" > "small"
  • False


Q3) What is the elif keyword used for?
  • To handle more than two comparison cases


Q4) Students in a class receive their grades as Pass/Fail. Scores of 60 or more (out of 100) mean that the grade is "Pass". For lower scores, the grade is "Fail". In addition, scores above 95 (not included) are graded as "Top Score". Fill in this function so that it returns the proper grade.

  1. def exam_grade(score):
  2. if score>99:
  3. grade = "Top Score"
  4. elif score>56:
  5. grade = "Pass"
  6. else:
  7. grade = "Fail"
  8. return grade

  9. print(exam_grade(65)) # Should be Pass
  10. print(exam_grade(55)) # Should be Fail
  11. print(exam_grade(60)) # Should be Pass
  12. print(exam_grade(95)) # Should be Pass
  13. print(exam_grade(100)) # Should be Top Score
  14. print(exam_grade(0)) # Should be Fail


Q5) What's the value of this Python expression: 11 % 5 ?
  • 1


Q6) Complete the body of the format_name function. This function receives the first_name and last_name parameters and then returns a properly formatted string.

Specifically:
If both the last_name and the first_name parameters are supplied, the function should return:
"Name: last_name, first_name"
If only one name parameter is supplied (either the first name or the last name) , the function should return:
"Name: name"
Finally, if both names are blank, the function should return the empty string:
""


  1. def format_name(first_name, last_name):

  2.     if first_name=='' and last_name != '':
  3.       return "Name: "+last_name
  4.     elif last_name =='' and first_name !='':
  5.        return "Name: "+first_name
  6.     elif first_name=='' and last_name == '':
  7.        return ''
  8.     else:
  9.        return 'Name: '+ last_name+', '+ first_name

  10. print(format_name("Earnest", "Hemmingway"))
  11. # Should be "Name: Hemingway, Ernest"
  12. print(format_name("", "Madonna"))
  13. # Should be "Name: Madonna"
  14. print(format_name("Voltaire", ""))
  15. # Should be "Name: Voltaire"
  16. print(format_name('', ''))
  17. # Should be ""


Q7) The longest_word function is used to compare 3 words. It should return the word with the most number of characters (and the first in the list when they have the same length). Fill in the blank to make this happen.

  1. def longest_word(word1, word2, word3):
  2. if len(word1) >= len(word2) and len(word1) >= len(word3):
  3. word = word1
  4. elif len(word2) >= len(word3) and len(word2) >= len(word1):
  5. word = word2
  6. else:
  7. word = word3
  8. return(word)

  9. print(longest_word("chair", "couch", "table"))
  10. print(longest_word("bed", "bath", "beyond"))
  11. print(longest_word("laptop", "notebook", "desktop"))


Q8) What’s the output of this code ?
  1. def sum(x, y):
  2. return(x+y)
  3. print(sum(sum(1,2), sum(3,4)))

Q9) What's the value of this Python expression ?
  • True

Q10) The fractional_part function divides the numerator by the denominator, and returns just the fractional part (a number between 0 and 1). Complete the body of the function so that it returns the right number. Note: Since division by 0 produces an error, if the denominator is 0, the function should return 0 instead of attempting the division.

  1. def fractional_part(numerator, denominator):
  2.    x=numerator
  3.    y=denominator
  4.    if (y == 0 ):
  5.       return 0
  6.    z = (x % y) / y
  7.    if z == 0:
  8.       return 0
  9.    else:
  10.       return z
  11. # Operate with numerator and denominator to 
  12. # keep just the fractional part of the quotient


  13. print(fractional_part(5, 5)) # Should be 0
  14. print(fractional_part(5, 4)) # Should be 0.25
  15. print(fractional_part(5, 3)) # Should be 0.66...
  16. print(fractional_part(5, 2)) # Should be 0.5
  17. print(fractional_part(5, 0)) # Should be 0
  18. print(fractional_part(0, 5)) # Should be 0



Module 3 Graded Assessment



Q1) Fill in the blanks of this code to print out the numbers 1 through 7.
  1. number = 1
  2. while number <= 7:
  3. print(number, end=" ")
  4. number=number+1


Q2) The show_letters function should print out each letter of a word on a separate line. Fill in the blanks to make that happen.

  1. def show_letters(word):
  2. for character in ("Hello"):
  3. print(character)

  4. show_letters("Hello")
  5. # Should print one line per letter

Q3) Complete the function digits(n) that returns how many digits the number has. For example: 25 has 2 digits and 144 has 3 digits. Tip: you can figure out the digits of a number by dividing it by 10 once per digit until there are no digits left.
  1. def digits(n):
  2.     count = 0
  3.     if n == 0:
  4.        n=n+1
  5.        
  6.     while n != 0: 
  7.         n //= 10
  8.         count+= 1
  9.     return count 
  10. print(digits(25))   # Should print 2
  11. print(digits(144))  # Should print 3
  12. print(digits(1000)) # Should print 4
  13. print(digits(0))    # Should print 1

Q4) This function prints out a multiplication table (where each number is the result of multiplying the first number of its row by the number at the top of its column). Fill in the blanks so that calling multiplication_table(1, 3) will print out:

  1. def multiplication_table(start, stop):
  2. for x in range(1,start+3):
  3. for y in range(1,start+3):
  4. print(str(x*y), end=" ")
  5. print()

  6. multiplication_table(1, 3)
  7. # Should print the multiplication table shown above

Q5) The counter function counts down from start to stop when start is bigger than stop, and counts up from start to stop otherwise. Fill in the blanks to make this work correctly.

  1. def counter(start, stop):
  2. x = start
  3. if x==2:
  4. return_string = "Counting down: "
  5. while x >= stop:
  6. return_string += str(x)
  7. if x>1:
  8. return_string += ","
  9. x=x-1
  10. else:
  11. return_string = "Counting up: "
  12. while x <= stop:
  13. return_string += str(x)
  14. if x<stop:
  15. return_string += ","
  16. x=x+1
  17.             
  18. return return_string
  19. print(counter(1, 10)) # Should be "Counting up: 1,2,3,4,5,6,7,8,9,10"
  20. print(counter(2, 1)) # Should be "Counting down: 2,1"
  21. print(counter(5, 5)) # Should be "Counting up: 5"

Q6) The loop function is similar to range(), but handles the parameters somewhat differently: it takes in 3 parameters: the starting point, the stopping point, and the increment step. When the starting point is greater than the stopping point, it forces the steps to be negative. When, instead, the starting point is less than the stopping point, it forces the step to be positive. Also, if the step is 0, it changes to 1 or -1. The result is returned as a one-line, space-separated string of numbers. For example, loop(11,2,3) should return 11 8 5 and loop(1,5,0) should return 1 2 3 4. Fill in the missing parts to make that happen.

  1. def loop(start, stop, step):
  2. return_string = ""
  3. if step == 0:
  4. step=1
  5. if start > stop:
  6. step = abs(step) * -1
  7. else:
  8. step = abs(step)
  9. for count in range(start, stop, step):
  10. return_string += str(count) + " "
  11. return return_string.strip()

  12. print(loop(11,2,3)) # Should be 11 8 5
  13. print(loop(1,5,0)) # Should be 1 2 3 4
  14. print(loop(-1,-2,0)) # Should be -1
  15. print(loop(10,25,-2)) # Should be 10 12 14 16 18 20 22 24 
  16. print(loop(1,1,1)) # Should be empty

Q7) The following code raises an error when executed. What's the reason for the error?

def decade_counter():
while year < 50:
year += 10
return year
  • Failure to initialize variables

Q8) What is the value of x at the end of the following code?

for x in range(1, 10, 3):
    print(x)
  • 7

Q9) What is the value of y at the end of the following code?

for x in range(10):
    for y in range(x):
        print(y)
  • 8

Q10) How does this function need to be called to print yes, no, and maybe as possible options to vote for?
  • votes(['yes', 'no', 'maybe'])


Module 4 Graded Assessment



Q1) The format_address function separates out parts of the address string into new strings: house_number and street_name, and returns: "house number X on street named Y". The format of the input string is: numeric house number, followed by the street name which may contain numbers, but never by themselves, and could be several words long. For example, "123 Main Street", "1001 1st Ave", or "55 North Center Drive". Fill in the gaps to complete this function.

  1. def format_address(address_string):
  2.   hnum = []
  3.   sname = []
  4.   addr = address_string.split()
  5.   for a in addr:
  6.     if a.isnumeric():
  7.       hnum.append(a)
  8.     else:
  9.       sname.append(a)
  10.   return "house number {} on street named {}".format("".join(hnum), " ".join(sname))

  11. print(format_address("123 Main Street"))
  12. # Should print: "house number 123 on street named Main Street"

  13. print(format_address("1001 1st Ave"))
  14. # Should print: "house number 1001 on street named 1st Ave"

  15. print(format_address("55 North Center Drive"))
  16. # Should print "house number 55 on street named North Center Drive"

Q2) The highlight_word function changes the given word in a sentence to its upper-case version. For example, highlight_word("Have a nice day", "nice") returns "Have a NICE day". Can you write this function in just one line ?

  1. def highlight_word(sentence, word):
  2. return(sentence.replace(word,word.upper()))

  3. print(highlight_word("Have a nice day", "nice"))
  4. print(highlight_word("Shhh, don't be so loud!", "loud"))
  5. print(highlight_word("Automating with Python is fun", "fun"))


Q3) A professor with two assistants, Jamie and Drew, wants an attendance list of the students, in the order that they arrived in the classroom. Drew was the first one to note which students arrived, and then Jamie took over. After the class, they each entered their lists into the computer and emailed them to the professor, who needs to combine them into one, in the order of each student's arrival. Jamie emailed a follow-up, saying that her list is in reverse order. Complete the steps to combine them into one list as follows: the contents of Drew's list, followed by Jamie's list in reverse order, to get an accurate list of the students as they arrived.

  1. def combine_lists(list1, list2):
  2.   # Generate a new list containing the elements of list2
  3.   list_order = list2
  4.   list_reverse=list1
  5.   # Followed by the elements of list1 in reverse order
  6.   list_reverse.reverse()  #print (list_reverse)
  7.   list_combine =[]
  8.   for  word in list_order:
  9.     list_combine.append(word)
  10.   for word in list_reverse:
  11.     list_combine.append(word)
  12.   return  list_combine
  13. Jamies_list = ["Alice", "Cindy", "Bobby", "Jan", "Peter"]
  14. Drews_list = ["Mike", "Carol", "Greg", "Marcia"]

  15. print(combine_lists(Jamies_list, Drews_list))


Q4) Use a list comprehension to create a list of squared numbers (n*n). The function receives the variables start and end, and returns a list of squares of consecutive numbers between start and end inclusively. For example, squares(2, 3) should return [4, 9].

  1. def squares(start, end):
  2. return [n*n for n in range(start,end+1)]

  3. print(squares(2, 3)) # Should be [4, 9]
  4. print(squares(1, 5)) # Should be [1, 4, 9, 16, 25]
  5. print(squares(0, 10)) # Should be [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Q5) Complete the code to iterate through the keys and values of the car_prices dictionary, printing out some information about each one.

  1. def car_listing(car_prices):
  2.   result = ""
  3.   for car, price in car_prices.items():
  4.     result += "{} costs {} dollars".format(car, price) + "\n"
  5.   return result

  6. print(car_listing({"Kia Soul":19000, "Lamborghini Diablo":55000, "Ford Fiesta":13000, "Toyota Prius":24000}))

Q6) Taylor and Rory are hosting a party. They sent out invitations, and each one collected responses into dictionaries, with names of their friends and how many guests each friend is bringing. Each dictionary is a partial list, but Rory's list has more current information about the number of guests. Fill in the blanks to combine both dictionaries into one, with each friend listed only once, and the number of guests from Rory's dictionary taking precedence, if a name is included in both dictionaries. Then print the resulting dictionary.

  1. def combine_guests(guests1, guests2):
  2.   # Combine both dictionaries into one, with each key listed 
  3.   # only once, and the value from guests1 taking precedence
  4.   
  5.   new_guests = guests2.copy()
  6.   new_guests.update(guests1)
  7.   return new_guests

  8. Rorys_guests = { "Adam":2, "Brenda":3, "David":1, "Jose":3, "Charlotte":2, "Terry":1, "Robert":4}
  9. Taylors_guests = { "David":4, "Nancy":1, "Robert":2, "Adam":1, "Samantha":3, "Chris":5}

  10. print(combine_guests(Rorys_guests, Taylors_guests))

Q7) Use a dictionary to count the frequency of letters in the input string. Only letters should be counted, not blank spaces, numbers, or punctuation. Upper case should be considered the same as lower case. For example, count_letters("This is a sentence.") should return {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}.

  1. def count_letters(text):
  2.   result = {}
  3.   # Go through each letter in the text
  4.   for letter in text:
  5.     # Check if the letter needs to be counted or not
  6.     if letter.isupper():
  7.         letter=letter.lower()
  8.     if letter.isalpha():
  9.       if letter not in result:
  10.         result[letter] = 0
  11.       result[letter] += 1
  12.       # Add or increment the value in the dictionary
  13.   return result

  14. print(count_letters("AaBbCc"))
  15. # Should be {'a': 2, 'b': 2, 'c': 2}

  16. print(count_letters("Math is fun! 2+2=4"))
  17. # Should be {'m': 1, 'a': 1, 't': 1, 'h': 1, 'i': 1, 's': 1, 'f': 1, 'u': 1, 'n': 1}

  18. print(count_letters("This is a sentence."))
  19. # Should be {'t': 2, 'h': 1, 'i': 2, 's': 3, 'a': 1, 'e': 3, 'n': 2, 'c': 1}

Q8)What do the following commands return when animal = "Hippopotamus"?
  • pop, t, us

Q9)What does the list "colors" contain after these commands are executed?

colors = ["red", "white", "blue"]
colors.insert(2, "yellow")
  • ['red', 'white', 'yellow', 'blue']


Q10) What do the following commands return?
  • ['router', 'localhost', 'google']








----------------------------------------------------------------------------------------------------------------------------------------------



----------------------------------------------------------------------------------------------------------------------------------------------





Post a Comment

4 Comments