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.
#0000ff
unknown
#ff0000
unknown
#00ff00
unknown
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".
What is the elif keyword used for?
You got it! The elif keyword is used in place of multiple embedded if clauses,
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.
Sol:
Pass
Fail
Pass
Pass
Top Score
Fail 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.
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.
Sol:
output:
chair
beyond
notebook
What’s the output of this code?
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.
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.
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.
Question: 11
Given the following code:
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?
Solution:
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.
Question: 15
Write a script that prints the first 10 cube numbers (x**3), starting with x=1 and ending with x=10.
Solution:
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:
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.
Solution:
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:
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.
Solution:
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.
Solution:
Question 26
Fill in the blanks of this code to print out the numbers 1 through 7.
Solution:
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.
Solution:
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.
Solution:
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
Solution:
Question 30The following code raises an error when executed. What's the reason for the error?
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 31The 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. 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. Solution: Question 33
How does this function need to be called to print yes, no,
and maybe as possible options to vote for?
a. votes("yes", "no", "maybe")
b.votes(yes, no, maybe)
c.votes([yes, no, maybe])
d. votes(['yes', 'no', 'maybe'])
Question 34What is the value of y at the end of the following code?
Question 35What is the value of x at the end of the following code? 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. Solution:
Question 37Want 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.
Solution:
Question 38Try using the index method yourself now!
Using the index method, find out the position of "x" in "supercalifragilisticexpialidocious".
Solution: 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”.
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".solution:
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. 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:Question 43If 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: 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: 45solution:
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.
Solution: 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: 46The 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.
Solution: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.
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.Solution:
Question: 48Solution:
Question: 49The 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. Solution: 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.
Solution: 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.
Solution: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).Solution:
def email_list(domains):
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.
Solution:
Question: 55The 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?
Solution: b