Google Python Questions

Google Python Question

Question 1

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.

 
 
def color_translator(color):
if ___ == "red":
hex_color = "#ff0000"
elif ___ == "green":
hex_color = "#00ff00"
elif ___ == "blue":
hex_color = "#0000ff"
___:
hex_color = "unknown"
return ___

print(color_translator("blue")) # Should be #0000ff
print(color_translator("yellow")) # Should be unknown
print(color_translator("red")) # Should be #ff0000
print(color_translator("black")) # Should be unknown
print(color_translator("green")) # Should be #00ff00
print(color_translator("")) # Should be unknown
 
 
 
 
Sol:

def color_translator(color):
if color == "red":
hex_color = "#ff0000"
elif color == "green":
hex_color = "#00ff00"
elif color == "blue":
hex_color = "#0000ff"
else:
hex_color = "unknown"
return hex_color
 

print(color_translator("blue")) # Should be #0000ff
print(color_translator("yellow")) # Should be unknown
print(color_translator("red")) # Should be #ff0000
print(color_translator("black")) # Should be unknown
print(color_translator("green")) # Should be #00ff00
print(color_translator("")) # Should be unknown
 
 
output:
#0000ff
unknown
#ff0000
unknown
#00ff00
unknown
 
 
 
 
Question 2

What's the value of this Python expression: "big" > "small"

True

False

Big 

Small

 

You nailed it! The conditional operator > checks if two values are equal. The result of that operation is a boolean: either True or False. Alphabetically, "big" is less than "small".

 
 
Question 3 

What is the elif keyword used for?
  
i. To mark the end of the if statement.
 
ii. To handle more than two comparison cases.
 
iii.To replace the "or" clause in the if statement.
 
iv. Nothing - it's a misspelling of the else-if keyword.
 
  

You got it! The elif keyword is used in place of multiple embedded if clauses, 
when a single if/else structure is not enough.
 
 
 
 
Question 4

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.

 

def exam_grade(score):
if ___:
grade = "Top Score"
elif ___:
grade = "Pass"
else:
grade = "Fail"
return grade

print(exam_grade(65)) # Should be Pass
print(exam_grade(55)) # Should be Fail
print(exam_grade(60)) # Should be Pass
print(exam_grade(95)) # Should be Pass
print(exam_grade(100)) # Should be Top Score
print(exam_grade(0)) # Should be Fail

 

 

 

Sol:

def exam_grade(score):
if score > 95:
grade = "Top Score"
elif score >= 60:
grade = "Pass"
else:
grade = "Fail"
return grade

print(exam_grade(65)) # Should be Pass
print(exam_grade(55)) # Should be Fail
print(exam_grade(60)) # Should be Pass
print(exam_grade(95)) # Should be Pass
print(exam_grade(100)) # Should be Top Score
print(exam_grade(0)) # Should be Fail
 
 
Output:
Pass
Fail
Pass
Pass
Top Score
Fail
 
 
 
 
Question 5

What's the value of this Python expression: 11 % 5?

i. 2.2

ii. 2

iii. 1

iv. 0


Excellent! "%" is the modulo operator, which returns the remainder of the integer division between two numbers. 11 divided by 5 equals 2 with remainder of 1.


 
 
 
Question 6

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.

 

def longest_word(word1, word2, word3):
if len(word1) >= len(word2) and len(word1) >= len(word3):
word = word1
elif ___:
word = word2
else:
word = word3
return(word)

print(longest_word("chair", "couch", "table"))
print(longest_word("bed", "bath", "beyond"))
print(longest_word("laptop", "notebook", "desktop"))

 

 

 

Sol: 

def longest_word(word1, word2, word3):
if len(word1) >= len(word2) and len(word1) >= len(word3):
word = word1
elif len(word2) > len(word1) and len(word2) > len(word3) :
word = word2
else:
word = word3
return(word)

print(longest_word("chair", "couch", "table"))
print(longest_word("bed", "bath", "beyond"))
print(longest_word("laptop", "notebook", "desktop"))

 

output:

chair
beyond
notebook

 

 
 
Question 7

What’s the output of this code?

 

def sum(x, y):
return(x+y)
print(sum(sum(1,2), sum(3,4)))
 
 
output: 10

We’re calling the sum function 3 times: returning 3, then 7, then adding up 3 plus 7 for the total of 10.


Question 8

What's the value of this Python expression?

i. True

ii. False

iii.10

iv. 5*2 


When using the "and" operator,
a statement is True if both parts of the conditional are True.


 
Question 9

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.

 

def fractional_part(numerator, denominator):

# Operate with numerator and denominator to
# keep just the fractional part of the quotient
return int(numerator*denominator)

print(fractional_part(5, 5)) # Should be 0
print(fractional_part(5, 4)) # Should be 0.25
print(fractional_part(5, 3)) # Should be 0.66...
print(fractional_part(5, 2)) # Should be 0.5
print(fractional_part(5, 0)) # Should be 0
print(fractional_part(0, 5)) # Should be 0

 

Sol: 

Not found but trying...



Question: 10

In math, the factorial of a number is defined as the product of an
integer and all the integers below it. 

For example, the factorial of
four (4!) is equal to 1*2*3*4=24. Fill in the blanks to make the
factorial function return the right number.



def factorial(n):
    result = 1
    for i in ___:
        __
    return result

print(factorial(4)) # should return 24
print(factorial(5)) # should return 120
 
 
Solution:
 
def factorial(n):
    result = 1
    for n in range(1,n+1):
        result = result * n
    return result

print(factorial(4)) # should return 24
print(factorial(5)) # should return 120



Question: 11

Given the following code: 

teams = [ 'Dragons''Wolves''Pandas''Unicorns']
for home_team in teams:
    for away_team in teams:
 
What should the next line be to avoid both variables being printed with the same value? 

 

 while home_team != away_team:

 for home_team == away_team:

away_team = home_team

if home_team != away_team:  

  

 

 

 

 Question: 12

 The validate_users function is used by the system to check if a list of users is valid or invalid. A valid user is one that is at least 3 characters long. For example, ['taylor', 'luisa', 'jamaal'] are all valid users. When calling it like in this example, something is not right. Can you figure out what to fix?

 

def validate_users(users):
  for user in users:
    if is_valid(user):
      print(user + " is valid")
    else:
      print(user + " is invalid")

validate_users("purplecat")

 

 Solution:

def validate_users(users):
  for user in users:
    if is_valid(user):
      print(user + " is valid")
    else:
      print(user + " is invalid")

validate_users(["purplecat"])



 Question: 13

How are while loops and for loops different in Python? 

a. While loops can be used with all data types, for loops can only be used with numbers.

b. For loops can be nested, but while loops can't.

c. While loops iterate while a condition is true, for loops iterate through a sequence of elements.  

d. While loops can be interrupted using break, for loops using continue.

  

 

 Question: 14

 Fill in the blanks to make the factorial function return the factorial of n. Then, print the first 10 factorials (from 0 to 9) with the corresponding number. Remember that the factorial of a number is defined as the product of an integer and all integers before it. For example, the factorial of five (5!) is equal to 1*2*3*4*5=120. Also recall that the factorial of zero (0!) is equal to 1.

 

def factorial(n):
    result = 1
    for x in range(1,n+1):
        result = result * x
    return result

for n in range(1,10):
    print(n, factorial(n))
 
 
Solution:
 
 

 

 

 

 

 Question: 15

Write a script that prints the first 10 cube numbers (x**3), starting with x=1 and ending with x=10. 

Solution:

for x in range(1,11):
  print(x**3)
 
 
 

 Question: 16

Write a script that prints the multiples of 7 between 0 and 100. Print one multiple per line and avoid printing any numbers that aren't multiples of 7. Remember that 0 is also a multiple of 7.

 

 

 

 Solution:


for i in range(0,100,7):
    print(i)
 
 
Question 17

The retry function tries to execute an operation that might fail, it retries the operation for a number of attempts. Currently the code will keep executing the function even if it succeeds. Fill in the blank so the code stops trying after the operation succeeded.

 

def retry(operation, attempts):
  for n in range(attempts):
    if operation():
      print("Attempt " + str(n) + " succeeded")
    ___
    else:
      print("Attempt " + str(n) + " failed")

retry(create_user, 3)
retry(stop_service, 5)

 

 

 Solution:

def retry(operation, attempts):
  for n in range(attempts):
    if operation():
      print("Attempt " + str(n) + " succeeded")
    if n == 1:
      break
    else:
      print("Attempt " + str(n) + " failed")

retry(create_user, 3)
retry(stop_service, 5)
retry(create_user, 3)
retry(stop_service, 5)
 
 
 Output:
Attempt 0 failed
Attempt 0 failed
Attempt 1 succeeded
Attempt 0 failed
None
 
 
 
 

 Question: 18

What is  

 

 

 Question: 19

The function sum_positive_numbers should return the sum of all positive numbers between the number n received and 1. For example, when n is 3 it should return 1+2+3=6, and when n is 5 it should return 1+2+3+4+5=15. Fill in the gaps to make this work: 

 

def sum_positive_numbers(n):
    # The base case is n being smaller than 1
    if n < 1:
        return ___

    # The recursive case is adding this number to 
    # the sum of the numbers smaller than this one.
    return ___ + sum_positive_numbers(___)

print(sum_positive_numbers(3)) # Should be 6
print(sum_positive_numbers(5)) # Should be 15

 

 

 
 
def sum_positive_numbers(n):
    # The base case is n being smaller than 1
    if n < 1:
        return n

    # The recursive case is adding this number to 
    # the sum of the numbers smaller than this one.
    return n + sum_positive_numbers(n-1)

print(sum_positive_numbers(3)) # Should be 6
print(sum_positive_numbers(5)) # Should be 15
 
 

 Question: 20

  Which of the following scenarios would benefit the most from using a recursive function to
solve the problem?

 

Solution:

a. You need to print out a list of the employees in your company.

b.You need to know how many files are present in a single directory of your computer.

c. You need to create a family tree, showing several generations of your ancestors,
 with all of their children.  

d. You need to calculate the square root of numbers 1 through 10. 

 

 

 Question: 21

 What is recursion used for?

a. Recursion is used to create loops in languages where other loops are not available.

b. We use recursion only to implement mathematical formulas in code.

c. Recursion is used to iterate through sequences of files and directories.

d. Recursion lets us tackle complex problems by reducing the problem to a simpler one.

 

 Question: 22

Which of these activities are good use cases for recursive programs? Check all that apply.

 

a. Going through a file system collecting information related to directories and files. 

b.  Creating a user account.

c. Installing or upgrading software on the computer.

d. Managing permissions assigned to groups inside a company,
 when each group can contain both subgroups and users.  

e. Checking if a computer is connected to the local network. 


 

Question 23

Fill in the blanks to make the is_power_of function return whether the number is a power of the given base. Note: base is assumed to be a positive number. Tip: for functions that return a boolean value, you can return the result of a comparison.

 

def is_power_of(number, base):
  # Base case: when number is smaller than base.
  if number < base:
    # If number is equal to 1, it's a power (base**0).
    return __

  # Recursive case: keep dividing number by base.
  return is_power_of(__, ___)

print(is_power_of(8,2)) # Should be True
print(is_power_of(64,4)) # Should be True
print(is_power_of(70,10)) # Should be False
 
 

Solution: 

def is_power_of(number, base):
  # Base case: when number is smaller than base.
  if number < base:
    # If number is equal to 1, it's a power (base**0).
    return number == 1

  # Recursive case: keep dividing number by base.
  return is_power_of(number//base, base)

print(is_power_of(8,2)) # Should be True
print(is_power_of(64,4)) # Should be True
print(is_power_of(70,10)) # Should be False
 
  
 
 
 
Question 24
 
The count_users function recursively counts the amount of users that belong to a group in the company system, by going through each of the members of a group and if one of them is a group, recursively calling the function and counting the members. But it has a bug! Can you spot the problem and fix it? 
 
def count_users(group):
  count = 0
  for member in get_members(group):
    count += 1
    if is_group(member):
      count += count_users(member)
  return count

print(count_users("sales")) # Should be 3
print(count_users("engineering")) # Should be 8
print(count_users("everyone")) # Should be 18
 
 
 
Solution:
 
def count_users(group):
  count = 0
  for member in get_members(group):
    if is_group(member):
      count += count_users(member)
    else:
      count += 1
  return count

print(count_users("sales")) # Should be 3
print(count_users("engineering")) # Should be 8
print(count_users("everyone")) # Should be 18
 
 

Question 25

Implement the sum_positive_numbers function, as a recursive function that returns the sum of all positive numbers between the number n received and 1. For example, when n is 3 it should return 1+2+3=6, and when n is 5 it should return 1+2+3+4+5=15.

 

def sum_positive_numbers(n):
  return 0

print(sum_positive_numbers(3)) # Should be 6
print(sum_positive_numbers(5)) # Should be 15

 

Solution:

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

print(sum_positive_numbers(3)) # Should be 6
print(sum_positive_numbers(5)) # Should be 15

 

  

Question 26

Fill in the blanks of this code to print out the numbers 1 through 7.

number = 1
while number ___ 7:
print(number, end=" ")
___


Solution: 

number = 1
while number <= 7:
print(number, end=" ")
number += 1

 

 

 

Question 27

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

 

def show_letters(word):
for __:
print(__)

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

Solution: 


def show_letters(word):
for letters in word:
print(letters)

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

 

 

 Question 28

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.

 

def digits(n):
count = 0
if n == 0:
___
while (___):
count += 1
___
return count
print(digits(25)) # Should print 2
print(digits(144)) # Should print 3
print(digits(1000)) # Should print 4
print(digits(0)) # Should print 1

 

 

Solution: 

 

def digits(n):
count = 0
if n == 0:
return 1
while (int(n/10) != 0):
count += 1
n = int(n/10)
return count + 1
print(digits(25)) # Should print 2
print(digits(144)) # Should print 3
print(digits(1000)) # Should print 4
print(digits(0)) # Should print 1


 
 

 Question 29

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 2 3

2 4 6

3 6 9

 

def multiplication_table(start, stop):
for x in ___:
for y in ___:
print(str(x*y), end=" ")
print()

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

 


 Solution:  
def multiplication_table(start, stop):
for x in range(start, stop+1):
for y in range(start,stop+1):
print(str(x*y), end=" ")
print()

multiplication_table(1, 3)
# Should print the multiplication table shown above
 
 
 
Question 30

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

 

a. Incrementing by 10 instead of 1

b. Failure to initialize variables 

c. Nothing is happening inside the while loop

d. Wrong comparison operator

 
 
Question 31
The even_numbers function returns a space-separated string of all 
positive numbers that are divisible by 2, up to and including the 
maximum that's passed into the function. For example, even_numbers(6) 
returns “2 4 6”. Fill in the blank to make this work.  
 
def even_numbers(maximum):
return_string = ""
for x in ___:
return_string += str(x) + " "
return return_string.strip()

print(even_numbers(6)) # Should be 2 4 6
print(even_numbers(10)) # Should be 2 4 6 8 10
print(even_numbers(1)) # No numbers displayed
print(even_numbers(3)) # Should be 2
print(even_numbers(0)) # No numbers displayed
 
 Solution:   






Question 32
 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.
 
 
def counter(start, stop):
x = start
if ___:
return_string = "Counting down: "
while x >= stop:
return_string += str(x)
if ___:
return_string += ","
___
else:
return_string = "Counting up: "
while x <= stop:
return_string += str(x)
if ___:
return_string += ","
___
return return_string

print(counter(1, 10)) # Should be "Counting up: 1,2,3,4,5,6,7,8,9,10"
print(counter(2, 1)) # Should be "Counting down: 2,1"
print(counter(5, 5)) # Should be "Counting up: 5"
 
 
 Solution:   
 
 
 
 
 
 Question 33
How does this function need to be called to print yes, no, 
and maybe as possible options to vote for?
 
def votes(params):
for vote in params:
print("Possible option:" + vote)


a. votes("yes", "no", "maybe")
b.votes(yes, no, maybe) 
c.votes([yes, no, maybe]) 
d. votes(['yes', 'no', 'maybe']) 
 
 
 Question 34
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)
 
Solution: 8
 
 
 
 Question 35
What is the value of x at the end of the following code? 

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

 Question 36
 Modify the double_word function so that it returns the same word 
repeated twice, followed by the length of the new doubled word. For 
example, double_word("hello") should return hellohello10.
 
def double_word(word):
return

print(double_word("hello")) # Should return hellohello10
print(double_word("abc")) # Should return abcabc6
print(double_word("")) # Should return 0
 
 Solution:
def double_word(word):
return word + word + str(len(word) * 2)

print(double_word("hello")) # Should return hellohello10
print(double_word("abc")) # Should return abcabc6
print(double_word("")) # Should return 0
 
 
 
 Question 37
 Want to give it a go yourself? Be my guest! Modify the first_and_last 
function so that it returns True if the first letter of the string is 
the same as the last letter of the string, False if they’re different. 
Remember that you can access characters using message[0] or message[-1].
Be careful how you handle the empty string, which should return True 
since nothing is equal to nothing.
 
def first_and_last(message):
return False

print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
 
 
  Solution:
 
def first_and_last(message):
return False
def first_and_last(message):
if len(message)==0:
return True
elif message[0] == message[-1]:
return True
else:
return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
 
 
 Question 38

Try using the index method yourself now!

Using the index method, find out the position of "x" in "supercalifragilisticexpialidocious".

 
word = "supercalifragilisticexpialidocious"
print(___)


 Solution:
word = "supercalifragilisticexpialidocious"
print(word.index("x"))
 
 
 
 


 
 Question 39

Want to try some string methods yourself? Give it a go!

Fill in the gaps in the initials function 

so that it returns the initials of the words contained in the phrase received, in upper case. 

For example: "Universal Serial Bus" should return "USB"; "local area network"should return "LAN”.

 
 
def initials(phrase):
words = phrase.___
result = ""
for word in words:
result += ___
return ___

print(initials("Universal Serial Bus")) # Should be: USB
print(initials("local area network")) # Should be: LAN
print(initials("Operating system")) # Should be: OS
 
 
Solution:
 
def initials(phrase):
words = phrase.split()
result = ""
for word in words:
result += word[0].upper()
return result

print(initials("Universal Serial Bus")) # Should be: USB
print(initials("local area network")) # Should be: LAN
print(initials("Operating system")) # Should be: OS
 
 

Note: 

Advanced String Methods

We've covered a bunch of String class methods already, so let's keep building on those and run down some more advanced methods.

The string method lower will return the string with all characters changed to lowercase. The inverse of this is the upper method, which will return the string all in uppercase. Just like with previous methods, we call these on a string using dot notation, like "this is a string".upper(). This would return the string "THIS IS A STRING". This can be super handy when checking user input, since someone might type in all lowercase, all uppercase, or even a mixture of cases.

You can use the strip method to remove surrounding whitespace from a string. Whitespace includes spaces, tabs, and newline characters. You can also use the methods  lstrip and rstrip to remove whitespace only from the left or the right side of the string, respectively.

The method count can be used to return the number of times a substring appears in a string. This can be handy for finding out how many characters appear in a string, or counting the number of times a certain word appears in a sentence or paragraph.

If you wanted to check if a string ends with a given substring, you can use the method endswith. This will return True if the substring is found at the end of the string, and False if not.

The isnumeric method can check if a string is composed of only numbers. If the string contains only numbers, this method will return True. We can use this to check if a string contains numbers before passing the string to the int() function to convert it to an integer, avoiding an error. Useful!

We took a look at string concatenation using the plus sign, earlier. We can also use the join method to concatenate strings. This method is called on a string that will be used to join a list of strings. The method takes a list of strings to be joined as a parameter, and returns a new string composed of each of the strings from our list joined using the initial string. For example, " ".join(["This","is","a","sentence"]) would return the string "This is a sentence".

The inverse of the join method is the split method. This allows us to split a string into a list of strings. By default, it splits by any whitespace characters. You can also split by any other characters by passing a parameter.

 

 

Question 40
 Modify the student_grade function using the format method, so that it 
returns the phrase "X received Y% on the exam". For example, 
student_grade("Reed", 80) should return "Reed received 80% on the exam".
 
 
def student_grade(name, grade):
return ""

print(student_grade("Reed", 80))
print(student_grade("Paige", 92))
print(student_grade("Jesse", 85))
 
 
 
solution:
 
def student_grade(name, grade):
return "{} received {}% on the exam".format(name, grade)

print(student_grade("Reed", 80))
print(student_grade("Paige", 92))
print(student_grade("Jesse", 85))
 
 
 Note:

String Formatting

You can use the format method on strings to concatenate and format strings in all kinds of powerful ways. To do this, create a string containing curly brackets, {}, as a placeholder, to be replaced. Then call the format method on the string using .format() and pass variables as parameters. The variables passed to the method will then be used to replace the curly bracket placeholders. This method automatically handles any conversion between data types for us. 

If the curly brackets are empty, they’ll be populated with the variables passed in the order in which they're passed. However, you can put certain expressions inside the curly brackets to do even more powerful string formatting operations. You can put the name of a variable into the curly brackets, then use the names in the parameters. This allows for more easily readable code, and for more flexibility with the order of variables.

You can also put a formatting expression inside the curly brackets, which lets you alter the way the string is formatted. For example, the formatting expression {:.2f} means that you’d format this as a float number, with two digits after the decimal dot. The colon acts as a separator from the field name, if you had specified one. You can also specify text alignment using the greater than operator: >. For example, the expression {:>3.2f} would align the text three spaces to the right, as well as specify a float number with two decimal places. String formatting can be very handy for outputting easy-to-read textual output.

 
 
 
 Note:

String Reference Cheat Sheet

In Python, there are a lot of things you can do with strings. In this cheat sheet, you’ll find the most common string operations and string methods.

String operations

  • len(string) Returns the length of the string

  • for character in string Iterates over each character in the string

  • if substring in string Checks whether the substring is part of the string

  • string[i] Accesses the character at index i of the string, starting at zero

  • string[i:j] Accesses the substring starting at index i, ending at index j-1. 

    If i is omitted, it's 0 by default. If j is omitted, it's len(string) by default.

String methods

  • string.lower() / string.upper() Returns a copy of the string with all lower / upper case characters

  • string.lstrip() / string.rstrip() / string.strip() Returns a copy of the string without left / right / left or right whitespace

  • string.count(substring) Returns the number of times substring is present in the string

  • string.isnumeric() Returns True if there are only numeric characters in the string. If not, returns False.

  • string.isalpha() Returns True if there are only alphabetic characters in the string. If not, returns False.

  • string.split() / string.split(delimiter) Returns a list of substrings that were separated by whitespace / delimiter

  • string.replace(old, new) Returns a new string where all occurrences of old have been replaced by new.

  • delimiter.join(list of strings) Returns a new string with all the strings joined by the delimiter

 
Check out the official documentation for all available String methods.   



Question 41
 
The is_palindrome function checks if a string is a palindrome. A 
palindrome is a string that can be equally read from left to right or 
right to left, omitting blank spaces, and ignoring capitalization. 
Examples of palindromes are words like kayak and radar, and phrases like
 "Never Odd or Even". Fill in the blanks in this function to return True
 if the passed string is a palindrome, False if not.
 
def is_palindrome(input_string):
# We'll create two strings, to compare them
new_string = ""
reverse_string = ""
# Traverse through each letter of the input string
for ___:
# Add any non-blank letters to the
# end of one string, and to the front
# of the other string.
if ___:
new_string = ___
reverse_string = ___
# Compare the strings
if ___:
return True
return False

print(is_palindrome("Never Odd or Even")) # Should be True
print(is_palindrome("abc")) # Should be False
print(is_palindrome("kayak")) # Should be True
 
 
 
Solution:
 

def is_palindrome(input_string):
# We'll create two strings, to compare them
new_string = ""
reverse_string = ""
# Traverse through each letter of the input string
for string in input_string.lower():
# Add any non-blank letters to the
# end of one string, and to the front
# of the other string.
if string.replace(" ",""):
new_string = string + new_string
reverse_string = string +reverse_string
# Compare the strings
if new_string[::-1]==reverse_string:
return True
return False

print(is_palindrome("Never Odd or Even")) # Should be True
print(is_palindrome("abc")) # Should be False
print(is_palindrome("kayak")) # Should be True
 
 
 
Question 42
 
Using the format method, fill in the gaps in the convert_distance function so that it returns the phrase "X miles equals Y km", with Y having only 1 decimal place. For example, convert_distance(12) should return "12 miles equals 19.2 km".
 
solution:
 
def convert_distance(miles):
km = miles * 1.6
result = "{} miles equals {:.1f} km".format(miles, km)
return result

print(convert_distance(12)) # Should be: 12 miles equals 19.2 km
print(convert_distance(5.5)) # Should be: 5.5 miles equals 8.8 km
print(convert_distance(11)) # Should be: 11 miles equals 17.6 km
 
 
 
Question 43

If we have a string variable named Weather = "Rainfall", which of the following will print the substring or all characters before the "f"?

a. print(Weather[:4])

b. print(Weather[4:])

c. print(Weather[1:4])   

d. print(Weather[:"f"]) 

 

 

 

Question 44
 Fill in the gaps in the nametag function so that it uses the format 
method to return first_name and the first initial of last_name followed 
by a period. For example, nametag("Jane", "Smith") should return "Jane 
S."
 
solution:
def nametag(first_name, last_name):
return("{} {}.".format(first_name, last_name[0]))

print(nametag("Jane", "Smith"))
# Should display "Jane S."
print(nametag("Francesco", "Rinaldi"))
# Should display "Francesco R."
print(nametag("Jean-Luc", "Grand-Pierre"))
# Should display "Jean-Luc G."
  
 

Note:

Lists Defined

Lists in Python are defined using square brackets, with the elements stored in the list separated by commas: list = ["This", "is", "a", "list"]. You can use the len() function to return the number of elements in a list: len(list) would return 4. You can also use the in keyword to check if a list contains a certain element. If the element is present, it will return a True boolean. If the element is not found in the list, it will return False. For example, "This" in list would return True in our example. Similar to strings, lists can also use indexing to access specific elements in a list based on their position. You can access the first element in a list by doing list[0], which would allow you to access the string "This".

In Python, lists and strings are quite similar. They’re both examples of sequences of data. Sequences have similar properties, like (1) being able to iterate over them using for loops; (2) support indexing; (3) using the len function to find the length of the sequence; (4) using the plus operator + in order to concatenate; and (5) using the in keyword to check if the sequence contains a value. Understanding these concepts allows you to apply them to other sequence types as well.

  
 
mutable mean they can change.
unmutable mean they can't change.
 
 
 
 
Note:

Modifying Lists

While lists and strings are both sequences, a big difference between them is that lists are mutable. This means that the contents of the list can be changed, unlike strings, which are immutable. You can add, remove, or modify elements in a list.

You can add elements to the end of a list using the append method. You call this method on a list using dot notation, and pass in the element to be added as a parameter. For example, list.append("New data") would add the string "New data" to the end of the list called list.

If you want to add an element to a list in a specific position, you can use the method insert. The method takes two parameters: the first specifies the index in the list, and the second is the element to be added to the list. So list.insert(0, "New data") would add the string "New data" to the front of the list. This wouldn't overwrite the existing element at the start of the list. It would just shift all the other elements by one. If you specify an index that’s larger than the length of the list, the element will simply be added to the end of the list.

You can remove elements from the list using the remove method. This method takes an element as a parameter, and removes the first occurrence of the element. If the element isn’t found in the list, you’ll get a ValueError error explaining that the element was not found in the list.

You can also remove elements from a list using the pop method. This method differs from the remove method in that it takes an index as a parameter, and returns the element that was removed. This can be useful if you don't know what the value is, but you know where it’s located. This can also be useful when you need to access the data and also want to remove it from the list.

Finally, you can change an element in a list by using indexing to overwrite the value stored at the specified index. For example, you can enter list[0] = "Old data" to overwrite the first element in a list with the new string "Old data".

  
 
 
 Question: 45
Let's use tuples to store information about a file: its name, its type and its size in bytes. Fill in the gaps in this code to return the size in kilobytes (a kilobyte is 1024 bytes) up to 2 decimal places. 
 
 
def file_size(file_info):
___, ___, ___= file_info
return("{:.2f}".format(___ / 1024))

print(file_size(('Class Assignment', 'docx', 17875))) # Should print 17.46
print(file_size(('Notes', 'txt', 496))) # Should print 0.48
print(file_size(('Program', 'py', 1239))) # Should print 1.21



solution:
 
 
 
def file_size(file_info):
name,type,size = file_info
return("{:.2f}".format(size / 1024))

print(file_size(('Class Assignment', 'docx', 17875))) # Should print 17.46
print(file_size(('Notes', 'txt', 496))) # Should print 0.48
print(file_size(('Program', 'py', 1239))) # Should print 1.21




Note:

Tuples

As we mentioned earlier, strings and lists are both examples of sequences. Strings are sequences of characters, and are immutable. Lists are sequences of elements of any data type, and are mutable. The third sequence type is the tuple. Tuples are like lists, since they can contain elements of any data type. But unlike lists, tuples are immutable. They’re specified using parentheses instead of square brackets.

You might be wondering why tuples are a thing, given how similar they are to lists. Tuples can be useful when we need to ensure that an element is in a certain position and will not change. Since lists are mutable, the order of the elements can be changed on us. Since the order of the elements in a tuple can't be changed, the position of the element in a tuple can have meaning. A good example of this is when a function returns multiple values. In this case, what gets returned is a tuple, with the return values as elements in the tuple. The order of the returned values is important, and a tuple ensures that the order isn’t going to change. Storing the elements of a tuple in separate variables is called unpacking. This allows you to take multiple returned values from a function and store each value in its own variable.


Question: 46
Try out the enumerate function for yourself in this quick exercise. 
Complete the skip_elements function to return every other element from 
the list, this time using the enumerate function to check 
if an element is on an even position or an odd position.

def skip_elements(elements):
# code goes here
return ___

print(skip_elements(["a", "b", "c", "d", "e", "f", "g"]))
 # Should be ['a', 'c', 'e', 'g']
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach']))
 # Should be ['Orange', 'Strawberry', 'Peach']
 
 Solution:
def skip_elements(elements):
# code goes here
element = [x for i, x in enumerate(elements) if i % 2 == 0]
return element

print(skip_elements(["a", "b", "c", "d", "e", "f", "g"]))
 # Should be ['a', 'c', 'e', 'g']
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach']))
 # Should be ['Orange', 'Strawberry', 'Peach']
 
 
Note:

Iterating Over Lists Using Enumerate

When we covered for loops, we showed the example of iterating over a list. This lets you iterate over each element in the list, exposing the element to the for loop as a variable. But what if you want to access the elements in a list, along with the index of the element in question? You can do this using the enumerate() function. The enumerate() function takes a list as a parameter and returns a tuple for each element in the list. The first value of the tuple is the index and the second value is the element itself.

 

Question: 46
The odd_numbers function returns a list of odd numbers between 1 and n, 
inclusively. Fill in the blanks in the function, using list 
comprehension. Hint: remember that list and range counters start at 0 
and end at the limit minus 1. 

def odd_numbers(n):
return [x for x in ___ if ___]

print(odd_numbers(5)) # Should print [1, 3, 5]
print(odd_numbers(10)) # Should print [1, 3, 5, 7, 9]
print(odd_numbers(11)) # Should print [1, 3, 5, 7, 9, 11]
print(odd_numbers(1)) # Should print [1]
print(odd_numbers(-1)) # Should print []

Solution:

def odd_numbers(n):
return [x for x in range(0, n+1) if x%2 != 0]

print(odd_numbers(5)) # Should print [1, 3, 5]
print(odd_numbers(10)) # Should print [1, 3, 5, 7, 9]
print(odd_numbers(11)) # Should print [1, 3, 5, 7, 9, 11]
print(odd_numbers(1)) # Should print [1]
print(odd_numbers(-1)) # Should print []
 
 
 
 
 
 
 
Note:

List Comprehensions

You can create lists from sequences using a for loop, but there’s a more streamlined way to do this: list comprehension. List comprehensions allow you to create a new list from a sequence or a range in a single line.

For example, [ x*2 for x in range(1,11) ] is a simple list comprehension. This would iterate over the range 1 to 10, and multiply each element in the range by 2. This would result in a list of the multiples of 2, from 2 to 20.

You can also use conditionals with list comprehensions to build even more complex and powerful statements. You can do this by appending an if statement to the end of the comprehension. For example, [ x for x in range(1,101) if x % 10 == 0 ] would generate a list containing all the integers divisible by 10 from 1 to 100. The if statement we added here evaluates each value in the range from 1 to 100 to check if it’s evenly divisible by 10. If it is, it gets added to the list.

List comprehensions can be really powerful, but they can also be super complex, resulting in code that’s hard to read. Be careful when using them, since it might make it more difficult for someone else looking at your code to easily understand what the code is doing.

 
 
 
Note:
 

Lists and Tuples Operations Cheat Sheet

Lists and Tuples Operations Cheat Sheet

Lists and tuples are both sequences, so they share a number of sequence operations. But, because lists are mutable, there are also a number of methods specific just to lists. This cheat sheet gives you a run down of the common operations first, and the list-specific operations second.

Common sequence operations

  • len(sequence) Returns the length of the sequence

  • for element in sequence Iterates over each element in the sequence

  • if element in sequence Checks whether the element is part of the sequence

  • sequence[i] Accesses the element at index i of the sequence, starting at zero

  • sequence[i:j] Accesses a slice starting at index i, ending at index j-1. If i is omitted, it's 0 by default. If j is omitted, it's len(sequence) by default.

  • for index, element in enumerate(sequence) Iterates over both the indexes and the elements in the sequence at the same time

Check out the official documentation for sequence operations.

List-specific operations and methods

  • list[i] = x Replaces the element at index i with x

  • list.append(x) Inserts x at the end of the list

  • list.insert(i, x) Inserts x at index i

  • list.pop(i) Returns the element a index i, also removing it from the list. If i is omitted, the last element is returned and removed.

  • list.remove(x) Removes the first occurrence of x in the list

  • list.sort() Sorts the items in the list

  • list.reverse() Reverses the order of items of the list

  • list.clear() Removes all the items of the list

  • list.copy() Creates a copy of the list

  • list.extend(other_list) Appends all the elements of other_list at the end of list

Most of these methods come from the fact that lists are mutable sequences. For more info, see the official documentation for mutable sequences and the list specific documentation.

List comprehension

  • [expression for variable in sequence] Creates a new list based on the given sequence. Each element is the result of the given expression.

  • [expression for variable in sequence if condition] Creates a new list based on the given sequence. Each element is the result of the given expression; elements only get added if the condition is true.

 
 
Question: 47
 Given a list of filenames, we want to rename all the files with 
extension hpp to the extension h. To do this, we would like to generate a
 new list called newfilenames, consisting of the new filenames. Fill in 
the blanks in the code using any of the methods you’ve learned thus far,
 like a for loop or a list comprehension.
 
filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
# Generate newfilenames as a list containing the new filenames
# using as many lines of code as your chosen method requires.
___

print(newfilenames)
# Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]
 
 
Solution: 
filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
# Generate newfilenames as a list containing the new filenames
# using as many lines of code as your chosen method requires.
newfilenames = [file.replace('.hpp', '.h') for file in filenames]

print(newfilenames)
# Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]
 
 
 
 
Question: 48
Let's create a function that turns text into pig latin: a simple text transformation that modifies each word moving the first character to the end and appending "ay" to the end. For example, python ends up as ythonpay.
 
 
def pig_latin(text):
say = ""
# Separate the text into words
words = ___
for word in words:
# Create the pig latin word and add it to the list
___
# Turn the list back into a phrase
return ___
print(pig_latin("hello how are you"))  
# Should be "ellohay owhay reaay ouyay"
print(pig_latin("programming in python is fun"))  
# Should be "rogrammingpay niay ythonpay siay unfay"
 
 
 
Solution: 
def pig_latin(text):
say = ""
# Separate the text into words
words = text.split()
for word in words:
# Create the pig latin word and add it to the list
pig_latin_word = word[1:] + word[0] + 'ay'
say += ' ' + pig_latin_word
# Turn the list back into a phrase
return say
print(pig_latin("hello how are you")) 
 # Should be "ellohay owhay reaay ouyay"
print(pig_latin("programming in python is fun"))
 # Should be "rogrammingpay niay ythonpay siay unfay"
 
 
 
 
 
 
Question: 49
The permissions of a file in a Linux system are split into three sets of
 three permissions: read, write, and execute for the owner, group, and 
others. Each of the three values can be expressed as an octal number 
summing each permission, with 4 corresponding to read, 2 to write, and 1
 to execute. Or it can be written with a string using the letters r, w, 
and x or - when the permission is not granted.
For example: 
640 is read/write for the owner, read for the group, and no permissions 
for the others; converted to a string, it would be: "rw-r-----"
755 is read/write/execute for the owner, and read/execute for group and 
others; converted to a string, it would be: "rwxr-xr-x"
Fill in the blanks to make the code convert a permission in octal format
 into a string format.
 
def octal_to_string(octal):
result = ""
value_letters = [(4,"r"),(2,"w"),(1,"x")]
# Iterate over each of the digits in octal
for ___ in [int(n) for n in str(octal)]:
# Check for each of the permissions values
for value, letter in value_letters:
if ___ >= value:
result += ___
___ -= value
else:
___
return result
print(octal_to_string(755)) # Should be rwxr-xr-x
print(octal_to_string(644)) # Should be rw-r--r--
print(octal_to_string(750)) # Should be rwxr-x---
print(octal_to_string(600)) # Should be rw-------
 
 
 
 
Solution:
def octal_to_string(octal):
result = ""
value_letters = [(4,"r"),(2,"w"),(1,"x")]
# Iterate over each of the digits in octal
for digit in [int(n) for n in str(octal)]:
# Check for each of the permissions values
for value, letter in value_letters:
if digit >= value:
result += letter
digit -= value
else:
result += '-'
return result
print(octal_to_string(755)) # Should be rwxr-xr-x
print(octal_to_string(644)) # Should be rw-r--r--
print(octal_to_string(750)) # Should be rwxr-x---
print(octal_to_string(600)) # Should be rw-------
 
 
Question: 50
 
Tuples and lists are very similar types of sequences. 
What is the main thing that makes a tuple different from a list? 
 
 
a. A tuple is mutable
b. A tuple contains only numeric characters
c. A tuple is immutable
d. A tuple can contain only one type of data at a time    
 
 
 
 
 Note:

Dictionaries Defined

Dictionaries are another data structure in Python. They’re similar to a list in that they can be used to organize data into collections. However, data in a dictionary isn't accessed based on its position. Data in a dictionary is organized into pairs of keys and values. You use the key to access the corresponding value. Where a list index is always a number, a dictionary key can be a different data type, like a string, integer, float, or even tuples.

When creating a dictionary, you use curly brackets: {}. When storing values in a dictionary, the key is specified first, followed by the corresponding value, separated by a colon. For example, animals = { "bears":10, "lions":1, "tigers":2 } creates a dictionary with three key value pairs, stored in the variable animals. The key "bears" points to the integer value 10, while the key "lions" points to the integer value 1, and "tigers" points to the integer 2. You can access the values by referencing the key, like this: animals["bears"]. This would return the integer 10, since that’s the corresponding value for this key.

You can also check if a key is contained in a dictionary using the in keyword. Just like other uses of this keyword, it will return True if the key is found in the dictionary; otherwise it will return False.

Dictionaries are mutable, meaning they can be modified by adding, removing, and replacing elements in a dictionary, similar to lists. You can add a new key value pair to a dictionary by assigning a value to the key, like this: animals["zebras"] = 2. This creates the new key in the animal dictionary called zebras, and stores the value 2. You can modify the value of an existing key by doing the same thing. So animals["bears"] = 11 would change the value stored in the bears key from 10 to 11. Lastly, you can remove elements from a dictionary by using the del keyword. By doing del animals["lions"] you would remove the key value pair from the animals dictionary.

 
 
 
 
Question: 51
  
Complete the code to iterate through the keys and values of the cool_beasts dictionary. Remember that the items method returns a tuple of key, value for each element in the dictionary.
 
cool_beasts = {"octopuses":"tentacles", "dolphins":"fins", "rhinos":"horns"}
for ___ in cool_beasts.items():
print("{} have {}".format(___))
 
 
Solution:
cool_beasts = {"octopuses":"tentacles", "dolphins":"fins", "rhinos":"horns"}
for animal,thing in cool_beasts.items():
print("{} have {}".format(animal,thing))
 
 
 
Note:

Iterating Over Dictionaries

You can iterate over dictionaries using a for loop, just like with strings, lists, and tuples. This will iterate over the sequence of keys in the dictionary. If you want to access the corresponding values associated with the keys, you could use the keys as indexes. Or you can use the items method on the dictionary, like dictionary.items(). This method returns a tuple for each element in the dictionary, where the first element in the tuple is the key and the second is the value.

If you only wanted to access the keys in a dictionary, you could use the keys() method on the dictionary: dictionary.keys(). If you only wanted the values, you could use the values() method: dictionary.values().

 

  
 
Question: 52
 
 In Python, a dictionary can only hold a single value for a given key. To
 workaround this, our single value can be a list containing multiple 
values. Here we have a dictionary called "wardrobe" with items of 
clothing and their colors. Fill in the blanks to print a line for each 
item of clothing with each color, for example: "red shirt", "blue 
shirt", and so on.
  
wardrobe = {"shirt":["red","blue","white"], "jeans":["blue","black"]}
for __:
for __:
print("{} {}".format(__))

Solution:
wardrobe = {"shirt":["red","blue","white"], "jeans":["blue","black"]}
for key, value in wardrobe.items():
for i in value:
print("{} {}".format(i, key))
 
 
 
 
 
 
 
 
 
 
Note:

Dictionary Methods Cheat Sheet


Definition

x = {key1:value1, key2:value2}

Operations

  • len(dictionary) - Returns the number of items in the dictionary

  • for key in dictionary - Iterates over each key in the dictionary

  • for key, value in dictionary.items() - Iterates over each key,value pair in the dictionary

  • if key in dictionary - Checks whether the key is in the dictionary

  • dictionary[key] - Accesses the item with key key of the dictionary

  • dictionary[key] = value - Sets the value associated with key

  • del dictionary[key] - Removes the item with key key from the dictionary

Methods

  • dict.get(key, default) - Returns the element corresponding to key, or default if it's not present

  • dict.keys() - Returns a sequence containing the keys in the dictionary

  • dict.values() - Returns a sequence containing the values in the dictionary

  • dict.update(other_dictionary) - Updates the dictionary with the items coming from the other dictionary. Existing entries will be replaced; new entries will be added.

  • dict.clear() - Removes all the items of the dictionary

Check out the official documentation for dictionary operations and methods.

  
 
 
 Question: 53
 The email_list function receives a dictionary, which contains domain 
names as keys, and a list of users as values. Fill in the blanks to 
generate a list that contains complete email addresses (e.g. 
diana.prince@gmail.com).
 
 
def email_list(domains):
emails = []
for ___:
for user in users:
emails.___
return(emails)

print(email_list({"gmail.com": ["clark.kent", "diana.prince"
 "peter.parker"], "yahoo.com": ["barbara.gordon",  
"jean.grey"], "hotmail.com": ["bruce.wayne"]}))
 
 
Solution:
def email_list(domains):
emails = []
for domain, users in domains.items():
for user in users:
emails.append("{}@{}".format(user, domain))
return(emails)

print(email_list({"gmail.com": ["clark.kent", "diana.prince", "peter.parker"],
 "yahoo.com": ["barbara.gordon", "jean.grey"], "hotmail.com": ["bruce.wayne"]}))
 
 
 
 Question: 54
The groups_per_user function receives a dictionary, which contains group
 names with the list of users. Users can belong to multiple groups. Fill
 in the blanks to return a dictionary with the users as keys and a list 
of their groups as values.  


def groups_per_user(group_dictionary):
user_groups = {}
# Go through group_dictionary
for ___:
# Now go through the users in the group
for ___:
# Now add the group to the the list of
# groups for this user, creating the entry
# in the dictionary if necessary

return(user_groups)

print(groups_per_user({"local": ["admin", "userA"],
"public": ["admin", "userB"],
"administrator": ["admin"] }))




Solution:
 
def groups_per_user(group_dictionary):
user_groups = {}
# Go through group_dictionary
for group, users in group_dictionary.items():
# Now go through the users in the group
for users in group_dictionary[group]:
# Now add the group to the the list of
if users in user_groups:
user_groups[users].append(group)
else:
user_groups[users] = [group]
# groups for this user, creating the entry
# in the dictionary if necessary

return(user_groups)

print(groups_per_user({"local": ["admin", "userA"],
"public": ["admin", "userB"],
"administrator": ["admin"] }))
 
 
 Question: 55
The dict.update method updates one dictionary with the items coming from
 the other dictionary, so that existing entries are replaced and new 
entries are added. What is the content of the dictionary “wardrobe“ at 
the end of the following code? 

wardrobe = {'shirt': ['red', 'blue', 'white'], 'jeans': ['blue', 'black']}
new_items = {'jeans': ['white'], 'scarf': ['yellow'], 'socks': ['black', 'brown']}
wardrobe.update(new_items)
 
a. {'jeans': ['white'], 'scarf': ['yellow'], 'socks': ['black', 'brown']} 
b.{'shirt': ['red', 'blue', 'white'], 'jeans': ['white'], 'scarf': ['yellow'], 'socks': ['black', 'brown']} 
c. {'shirt': ['red', 'blue', 'white'], 'jeans': ['blue', 'black', 'white'], 'scarf': ['yellow'], 'socks': ['black', 'brown']}
d. {'shirt': ['red', 'blue', 'white'], 'jeans': ['blue', 'black'], 'jeans': ['white'], 'scarf': ['yellow'], 'socks': ['black', 'brown']}

Solution: b
 
 
 
 Question: 56
What’s a major advantage of using dictionaries over lists?  
 
a. Dictionaries are ordered sets
b. Dictionaries can be accessed by the index number of the element
c. Elements can be removed and inserted into dictionaries
d. It’s quicker and easier to find a specific element in a dictionary    
 
Solution:  d. It’s quicker and easier to find a specific element in a dictionary    




Question: 57
The add_prices function returns the total price of all of the groceries 
in the  dictionary. Fill in the blanks to complete this function.
 
def add_prices(basket):
# Initialize the variable that will be used for the calculation
total = 0
# Iterate through the dictionary items
for ___:
# Add each price to the total calculation
# Hint: how do you access the values of
# dictionary items?
total += ___
# Limit the return value to 2 decimal places
return round(total, 2)

groceries = {"bananas": 1.56, "apples": 2.50, "oranges": 0.99, "bread": 4.59,
"coffee": 6.99, "milk": 3.39, "eggs": 2.98, "cheese": 5.44}

print(add_prices(groceries)) # Should print 28.44


 
 
Solution: 
def add_prices(basket):
# Initialize the variable that will be used for the calculation
total = 0
# Iterate through the dictionary items
for item, price in basket.items():
# Add each price to the total calculation
# Hint: how do you access the values of
# dictionary items?
total += price
# Limit the return value to 2 decimal places
return round(total, 2)

groceries = {"bananas": 1.56, "apples": 2.50, "oranges": 0.99, "bread": 4.59,
"coffee": 6.99, "milk": 3.39, "eggs": 2.98, "cheese": 5.44}

print(add_prices(groceries)) # Should print 28.44


 
  
 
 
إرسال تعليق (0)
أحدث أقدم