## Practice Quiz: Hello World

• Total points: 5
• Score: 100%

### Question 1

What are functions in Python?

• Functions let us to use Python as a calculator.
• Functions are pieces of code that perform a unit of work.
• Functions are only used to print messages to the screen.
• Functions are how we tell if our program is functioning or not.

Python functions encapsulate a certain action, like outputting a message to the screen in the case of print().

### Question 2

What are keywords in Python?

• Keywords are reserved words that are used to construct instructions.
• Keywords are used to calculate mathematical operations.
• Keywords are used to print messages like “Hello World!” to the screen.
• Keywords are the words that we need to memorize to program in Python.

Using the reserved words provided by the language we can construct complex instructions that will make our scripts.

### Question 3

What does the print function do in Python?

• The print function generates PDFs and sends it to the nearest printer.
• The print function stores values provided by the user.
• The print function outputs messages to the screen
• The print function calculates mathematical operations.

Using the print() we can generate output for the user of our programs.

### Question 4

Output a message that says “Programming in Python is fun!” to the screen.

print("Programming in Python is fun!")

We’re just starting but programming in Python can indeed be a lot of fun.

### Question 5

Replace the _ placeholder and calculate the Golden ratio: $\frac{1+\sqrt{5}}{2}$

ratio = (1 + 5**.5) / 2
print(ratio)

See how we can use Python to calculate complex values for us.

## Practice Quiz: Introduction to Programming

• Total points: 5
• Score: 100%

### Question 1

What’s a computer program?

• A set of languages available in the computer
• A process for getting duplicate values removed from a list
• A list of instructions that the computer has to follow to reach a goal
• A file that gets copied to all machines in the network

At a basic level, a computer program is a recipe of instructions that tells your computer what to do.

## Question 2

What’s the syntax of a language?

• The rules of how to express things in that language
• The subject of a sentence
• The difference between one language and another
• The meaning of the words

In a human language, syntax is the rules for how a sentence is constructed, and in a programming language, syntax is the rules for how each instruction is written.

## Question 3

What’s the difference between a program and a script?

• There’s not much difference, but scripts are usually simpler and shorter.
• Scripts are only written in Python.
• Scripts can only be used for simple tasks.
• Programs are written by software engineers; scripts are written by system administrators.

The line between a program and a script is blurry; scripts usually have a shorter development cycle. This means that scripts are shorter, simpler, and can be written very quickly.

## Question 4

Which of these scenarios are good candidates for automation? Select all that apply.

• Generating a sales report, split by region and product type
• Creating your own startup company
• Helping a user who’s having network troubles
• Copying a file to all computers in a company
• Interviewing a candidate for a job
• Sending personalized emails to subscribers of your website
• Investigating the root cause of a machine failing to boot

Creating a report that presents stored data in specific ways is a tedious task that can be easily automated.

A task like copying files to other computers is easily automated, and helps to reduce unnecessary manual work.

Sending out periodic emails is a time-consuming task that can be easily automated, and you won’t have to worry about forgetting to do it on a regular basis.

## Question 5

What are semantics when applied to programming code and pseudocode?

• The rules for how a programming instruction is written
• The difference in number values in one instance of a script compared to another
• The effect the programming instructions have
• The end result of a programming instruction

Like human language, the intended meaning or effect of words, or in this case instructions, are referred to as semantics.

## Practice Quiz: Introduction to Python

• Total points: 5
• Score: 100%

### Question 1

Fill in the correct Python command to put “My first Python program” onto the screen.

print("My first Python program")

Output:

My first Python program

### Question 2

Python is an example of what type of programming language?

• Platform-specific scripting language
• General purpose scripting language
• Client-side scripting language
• Machine language

Python is one of the general purpose scripting languages that are widely used for scripting and automation.

### Question 3

Convert this Bash command into Python:

# echo Have a nice day
print('Have a nice day')

Output:

Have a nice day

### Question 4

Fill in the correct Python commands to put “This is fun!” onto the screen 5 times.

for i in range(5):
print("This is fun!")

Output:

This is fun!
This is fun!
This is fun!
This is fun!
This is fun!

### Question 5

Select the Python code snippet that corresponds to the following Javascript snippet:

for (let i = 0; i < 10; i++) {
console.log(i);
}
for i in range(10):
print(i)

In Python, we use range() to initiate for loops.

## Introduction to Programming

### Video: What is programming?

Why do we need to learn the syntax and semantics of a programming language?

• To be able to easily switch to a different programming language
• So that we know which part is the subject and which one is the predicate
• To allow us to clearly express what we want the computer to do
• To understand why our computer crashes

Knowing the syntax and understanding the semantics of a programming language allows us to tell the computer what we want it to do.

### Video: What is automation?

What’s automation?

• The process of telling a computer what to do
• The process of installing traffic lights
• The process of getting a haircut
• The process of replacing a manual step with one that happens automatically

By replacing a manual step with an automatic one we create automation that helps us reduce unnecessary manual work.

### Video: Getting Computers to Work for You

Which of the following tasks do you think are good candidates for automation? Check all that apply.

• Periodically scanning the disk usage of a group of fileservers
• Installing software on laptops given to new employees when they are hired
• Investigating reports that customers are having difficulty accessing your company’s external website
• Designing a configuration management system for deploying software patches

Scanning the disk usage is a task that can be easily automated. By letting the computer do it, you won’t have to worry about forgetting to do it whenever it’s needed.

Installing and configuring software is a task that can be automated. Ensuring that everyone gets the exact same setup and reducing the amount of manual work needed for each new employee.

## Introduction to Python

### Video: What is Python?

Execute the following code and see what happens. Feel free to change it and run it as many times as you want.

friends = ['Taylor', 'Alex', 'Pat', 'Eli']
for friend in friends:
print("Hi " + friend)

Output:

Hi Taylor
Hi Alex
Hi Pat
Hi Eli

### Video: Why is Python relevant to IT?

Select all options that explain why Python is relevant to today’s IT industry.

• Python scripts are easy to write, understand, and maintain.
• There are many system administration tools built with Python.
• Python was written by Guido van Rossum in 1991.
• Python is available on a wide variety of platforms.
• There have been multiple major version releases over the years which incorporate significant changes to the language.

Python is a language that tries to mimic our natural language and so Python scripts are generally easy to write, understand and maintain.

Over the years, the Python community has developed a lot of additional tools that can be used by system administrators to get their job done.

Python is available on Windows, Linux, MacOS and even on mobile devices, making it a great tool for IT specialist looking to create scripts that can work across platforms.

### Video: Other Languages

Here’s how printing “Hello, World” 10 times looks in Bash and Powershell:

Bash:

for i in {1..10}; do
echo Hello, World!
done

Powershell:

for ($i=1;$i -le 10; \$i++) {
Write-Host "Hello, World!"
}

Now try out the Python example yourself:

for i in range(10):
print("Hello, World!")

Output:

Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!

## Hello World

### Video: Hello, World!

Write a Python script that outputs “I’m programming in Python!” to the screen. Remember that you need to use the print() function and use quotation marks to delimiter the string.

print("I'm programming in Python!")

Output:

I'm programming in Python!

### Video: Getting Information from the User

In the following script, change the values of color and thing to have the computer output a different statement than the initial one.

color = "Blue"
thing = "Sky"
print(color + " is the color of " + thing)

Output:

Blue is the color of Sky

### Video: Python Can Be Your Calculator

Use Python to calculate (((1+2)*3)/4)5

Tip: remember that you can use a**b to calculate a to the power of b.

print((((1+2)*3)/4)**5)

Output:

57.6650390625

## Practice Quiz: Conditionals

• Total points: 5

### Question 1

What’s the value of this Python expression: (2**2) == 4?

• 4
• 2**2
• True
• False

The conditional operator == checks if two values are equal. The result of that operation is a boolean: either True or False.

### Question 2

Complete the script by filling in the missing parts. The function receives a name, then returns a greeting based on whether or not that name is “Taylor”.

def greeting(name):
if name == "Taylor":
return "Welcome back Taylor!"
else:
return "Hello there, " + name

print(greeting("Taylor"))
print(greeting("John"))

Output:

Welcome back Taylor!
Hello there, John

### Question 3

What’s the output of this code if number equals 10?

if number > 11:
print(0)
elif number != 10:
print(1)
elif number >= 20 or number < 12:
print(2)
else:
print(3)

Output:

2

### Question 4

Is “A dog” smaller or larger than “A mouse”? Is 9999+8888 smaller or larger than 100*100? Replace the plus sign in the following code to let Python check it for you and then answer.

print(len("A dog") > len("A mouse"))
print(9999+8888 > 100*100)
• “A dog” is larger than “A mouse” and 9999+8888 is larger than 100*100
• “A dog” is smaller than “A mouse” and 9999+8888 is larger than 100*100
• “A dog” is larger than “A mouse” and 9999+8888 is smaller than 100*100
• “A dog” is smaller than “A mouse” and 9999+8888 is smaller than 100*100

### Question 5

If a filesystem has a block size of 4096 bytes, this means that a file comprised of only one byte will still use 4096 bytes of storage. A file made up of 4097 bytes will use 4096*2=8192 bytes of storage. Knowing this, can you fill in the gaps in the calculate_storage function below, which calculates the total number of bytes needed to store a file of a given size?

def calculate_storage(filesize):
block_size = 4096
# Use floor division to calculate how many blocks are fully occupied
full_blocks = filesize // block_size
# Use the modulo operator to check whether there's any remainder
partial_block_remainder = filesize % block_size
# Depending on whether there's a remainder or not, return
# the total number of bytes required to allocate enough blocks
if partial_block_remainder > 0:
return 4096 * (full_blocks + 1)
return 4096

print(calculate_storage(1))    # Should be 4096
print(calculate_storage(4096)) # Should be 4096
print(calculate_storage(4097)) # Should be 8192
print(calculate_storage(6000)) # Should be 8192

Output:

4096
4096
8192
8192

## Practice Quiz: Expressions and Variables

• Total points: 5

### Question 1

In this scenario, two friends are eating dinner at a restaurant. The bill comes in the amount of 47.28 dollars. The friends decide to split the bill evenly between them, after adding 15% tip for the service. Calculate the tip, the total amount to pay, and each friend’s share, then output a message saying “Each person needs to pay: ” followed by the resulting number.

bill = 47.28
tip = bill * .15
total = bill + tip
share = total / 2
print("Each person needs to pay: " + str(share))

Output:

Each person needs to pay: 27.186

### Question 2

This code is supposed to take two numbers, divide one by another so that the result is equal to 1, and display the result on the screen. Unfortunately, there is an error in the code. Find the error and fix it, so that the output is correct.

numerator = 10
denominator = 10
result = numerator // denominator
print(result)

Output:

1

### Question 3

Combine the variables to display the sentence “How do you like Python so far?”

word1 = "How"
word2 = "do"
word3 = "you"
word4 = "like"
word5 = "Python"
word6 = "so"
word7 = "far?"

print(' '.join([eval(str('word'+str(i+1))) for i in range(7)]))

Output:

How do you like Python so far?

### Question 4

This code is supposed to display “2 + 2 = 4” on the screen, but there is an error. Find the error in the code and fix it, so that the output is correct.

print("2 + 2 = " + str(2 + 2))

Output:

2 + 2 = 4   

### Question 5

What do you call a combination of numbers, symbols, or other values that produce a result when evaluated?

• An explicit conversion
• An expression
• A variable
• An implicit conversion

An expression is a combination of values, variables, operators, and calls to functions.

## Practice Quiz: Functions

• Total points: 5

### Question 1

This function converts miles to kilometers (km).

1. Complete the function to return the result of the conversion
2. Call the function to convert the trip distance from miles to kilometers
3. Fill in the blank to print the result of the conversion
4. Calculate the round-trip in kilometers by doubling the result, and fill in the blank to print the result
# 1) Complete the function to return the result of the conversion
def convert_distance(miles):
return miles * 1.6  # approximately 1.6 km in 1 mile

my_trip_miles = 55

# 2) Convert my_trip_miles to kilometers by calling the function above
my_trip_km = convert_distance(my_trip_miles)

# 3) Fill in the blank to print the result of the conversion
print("The distance in kilometers is " + str(my_trip_km))

# 4) Calculate the round-trip in kilometers by doubling the result,
#    and fill in the blank to print the result
print("The round-trip in kilometers is " + str(2 * my_trip_km))

Output:

The distance in kilometers is 88.0
The round-trip in kilometers is 176.0

### Question 2

This function compares two numbers and returns them in increasing order.

1. Fill in the blanks, so the print statement displays the result of the function call in order.

Hint: if a function returns multiple values, don’t forget to store these values in multiple variables

# This function compares two numbers and returns them
# in increasing order.
def order_numbers(number1, number2):
if number2 > number1:
return number1, number2
else:
return number2, number1

# 1) Fill in the blanks so the print statement displays the result
#    of the function call
smaller, bigger = order_numbers(100, 99)
print(smaller, bigger)

Output:

99 100

### Question 3

What are the values passed into functions as input called?

• Variables
• Return values
• Parameters
• Data types

A parameter, also sometimes called an argument, is a value passed into a function for use within the function.

### Question 4

Let’s revisit our lucky_number function. We want to change it, so that instead of printing the message, it returns the message. This way, the calling line can print the message, or do something else with it if needed. Fill in the blanks to complete the code to make it work.

def lucky_number(name):
number = len(name) * 9
greet = "Hello " + name + ". Your lucky number is " + str(number)
return greet

print(lucky_number("Kay"))
print(lucky_number("Cameron"))

Output:

Hello Kay. Your lucky number is 27
Hello Cameron. Your lucky number is 63

### Question 5

What is the purpose of the def keyword?

• Used to define a new function
• Used to define a return value
• Used to define a new variable
• Used to define a new parameter

When defining a new function, we must use the def keyword followed by the function name and properly indented body.

## Practice Quiz: For Loops

• Total points: 5

### Question 1

How are while loops and for loops different in Python?

• While loops can be used with all data types, for loops can only be used with numbers.
• For loops can be nested, but while loops can’t.
• While loops iterate while a condition is true, for loops iterate through a sequence of elements.
• While loops can be interrupted using break, for loops using continue.

We can use while loops when we want our code to execute repeatedly while a condition is true, and for loops when we want to execute a block of code for each element of a sequence.

### Question 2

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):
result *= x
return result

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

Output:

0 1
1 1
2 2
3 6
4 24
5 120
6 720
7 5040
8 40320
9 362880

The pieces of code you’re tackling keep getting more complex, you’re doing a great job!

### Question 3

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

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

Output:

1
8
27
64
125
216
343
512
729
1000

### Question 4

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.

num = 0
mult = 7
while num <= 100:
print(num)
num += mult

Output:

0
7
14
21
28
35
42
49
56
63
70
77
84
91
98

### Question 5

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")
break
else:
print("Attempt " + str(n) + " failed")

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

Output:

Attempt 0 failed
Attempt 1 failed
Attempt 2 succeeded
Attempt 0 succeeded
Attempt 0 failed
Attempt 1 failed
Attempt 2 failed
Attempt 3 succeeded
None

## Practice Quiz: Recursion

• Total points: 5

### Question 1

What is recursion used for?

• Recursion is used to create loops in languages where other loops are not available.
• We use recursion only to implement mathematical formulas in code.
• Recursion is used to iterate through sequences of files and directories.
• Recursion lets us tackle complex problems by reducing the problem to a simpler one.

By reducing the problem to a smaller one each time a recursive function is called, we can tackle complex problems in simple steps.

### Question 2

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

• Going through a file system collecting information related to directories and files.
• Creating a user account.
• Installing or upgrading software on the computer.
• Managing permissions assigned to groups inside a company, when each group can contain both subgroups and users.
• Checking if a computer is connected to the local network.

Because directories can contain subdirectories that can contain more subdirectories, going through these contents is a good use case for a recursive program.

As the groups can contain both groups and users, this is the kind of problem that is a great use case for a recursive solution.

### Question 3

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

Output:

True
True
False

### Question 4

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

Output:

3
8
18

### Question 5

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

Output:

6
15

## Practice Quiz: While Loops

• Total points: 5

## Question 1

What are while loops in Python?

• While loops let the computer execute a set of instructions while a condition is true.
• While loops instruct the computer to execute a piece of code a set number of times.
• While loops let us branch execution on whether or not a condition is true.
• While loops are how we initialize variables in Python.

Using while loops we can keep executing the same group of instructions until the condition stops being true.

## Question 2

Fill in the blanks to make the print_prime_factors function print all the prime factors of a number. A prime factor is a number that is prime and divides another without a remainder.

def print_prime_factors(number):
factor = 2
# Keep going until the factor is larger than the number
while factor <= number:
# Check if factor is a divisor of number
if number % factor == 0:
# If it is, print it and divide the original number
print(factor)
number = number / factor
else:
# If it's not, increment the factor by one
factor += 1
return "Done"

print_prime_factors(100) # Should print 2,2,5,5

Output:

2
2
5
5

## Question 3

The following code can lead to an infinite loop. Fix the code so that it can finish successfully for all numbers.

Note: Try running your function with the number 0 as the input, and see what you get!

def is_power_of_two(n):
# Check if the number can be divided by two without a remainder
while n % 2 == 0 and n != 0:
n = n / 2
# If after dividing by two the number is 1, it's a power of two
if n == 1:
return True
return False

print(is_power_of_two(0)) # Should be False
print(is_power_of_two(1)) # Should be True
print(is_power_of_two(8)) # Should be True
print(is_power_of_two(9)) # Should be False

Output:

False
True
True
False

## Question 4

Fill in the empty function so that it returns the sum of all the divisors of a number, without including it. A divisor is a number that divides into another without a remainder.

def sum_divisors(n):
sum, num = 0, 1
while num < n:
if n % num == 0:
sum += num
if num > n//2:
pass
num += 1
# Return the sum of all divisors of n, not including n
return sum

print(sum_divisors(0))
# 0
print(sum_divisors(3)) # Should sum of 1
# 1
print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18
# 55
print(sum_divisors(102)) # Should be sum of 2+3+6+17+34+51
# 114

Output:

0
1
55
114

## Question 5

The multiplication_table function prints the results of a number passed to it multiplied by 1 through 5. An additional requirement is that the result is not to exceed 25, which is done with the break statement. Fill in the blanks to complete the function to satisfy these conditions.

def multiplication_table(number):
# Initialize the starting point of the multiplication table
multiplier = 1
# Only want to loop through 5
while multiplier <= 5:
result = number * multiplier
# What is the additional condition to exit out of the loop?
if result > 25 :
break
print(str(number) + "x" + str(multiplier) + "=" + str(result))
# Increment the variable for the loop
multiplier += 1

multiplication_table(3)
# Should print: 3x1=3 3x2=6 3x3=9 3x4=12 3x5=15

multiplication_table(5)
# Should print: 5x1=5 5x2=10 5x3=15 5x4=20 5x5=25

multiplication_table(8)
# Should print: 8x1=8 8x2=16 8x3=24

Output:

3x1=3
3x2=6
3x3=9
3x4=12
3x5=15
5x1=5
5x2=10
5x3=15
5x4=20
5x5=25
8x1=8
8x2=16
8x3=24

## Practice Quiz: Dictionaries

• Total points: 5

### Question 1

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 domain, users in domains.items():
for user in users:
emails.append(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"]}))

Output:

['clark.kent@gmail.com', 'diana.prince@gmail.com', 'peter.parker@gmail.com', 'barbara.gordon@yahoo.com', 'jean.grey@yahoo.com', 'bruce.wayne@hotmail.com']

### Question 2

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 group, users in group_dictionary.items():
# Now go through the users in the group
for user in users:
# Now add the group to the the list of
# groups for this user, creating the entry
# in the dictionary if necessary
user_groups[user] = user_groups.get(user,[]) + [group]
return(user_groups)

"administrator": ["admin"] }))

Output:

{'admin': ['local', 'public', 'administrator'], 'userA': ['local'], 'userB': ['public']}

### Question 3

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)
• {'jeans': ['white'], 'scarf': ['yellow'], 'socks': ['black', 'brown']}
• {'shirt': ['red', 'blue', 'white'], 'jeans': ['white'], 'scarf': ['yellow'], 'socks': ['black', 'brown']}
• {'shirt': ['red', 'blue', 'white'], 'jeans': ['blue', 'black', 'white'], 'scarf': ['yellow'], 'socks': ['black', 'brown']}
• {'shirt': ['red', 'blue', 'white'], 'jeans': ['blue', 'black'], 'jeans': ['white'], 'scarf': ['yellow'], 'socks': ['black', 'brown']}

The dict.update method updates the dictionary (wardrobe) with the items coming from the other dictionary (new_items), adding new entries and replacing existing entries.

### Question 4

What’s a major advantage of using dictionaries over lists?

• Dictionaries are ordered sets
• Dictionaries can be accessed by the index number of the element
• Elements can be removed and inserted into dictionaries
• It’s quicker and easier to find a specific element in a dictionary

Because of their unordered nature and use of key value pairs, searching a dictionary takes the same amount of time no matter how many elements it contains

### Question 5

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
# Add each price to the total calculation
# Hint: how do you access the values of
# dictionary items?
# 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

Output:

28.44

## Practice Quiz: Lists

• Total points: 6

### Question 1

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.
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"]

Output:

['program.c', 'stdio.h', 'sample.h', 'a.out', 'math.h', 'hpp.out']

### Question 2

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 = text.split()
for word in words:
# Create the pig latin word and add it to the list
pig_latin_word = word[1:] + word + '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"

Output:

 ellohay owhay reaay ouyay
rogrammingpay niay ythonpay siay unfay

### Question 3

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

Output:

rwxr-xr-x
rw-r--r--
rwxr-x---
rw-------

### Question 4

Tuples and lists are very similar types of sequences. What is the main thing that makes a tuple different from a list?

• A tuple is mutable
• A tuple contains only numeric characters
• A tuple is immutable
• A tuple can contain only one type of data at a time

Unlike lists, tuples are immutable, meaning they can’t be changed.

### Question 5

The group_list function accepts a group name and a list of members, and returns a string with the format: group_name: member1, member2, … For example, group_list(“g”, [“a”,”b”,”c”]) returns “g: a, b, c”. Fill in the gaps in this function to do that.

def group_list(group, users):
members = ', '.join(users)
return '{}:{}'.format(group, ' ' + members)

print(group_list("Marketing", ["Mike", "Karen", "Jake", "Tasha"])) # Should be "Marketing: Mike, Karen, Jake, Tasha"
print(group_list("Engineering", ["Kim", "Jay", "Tom"])) # Should be "Engineering: Kim, Jay, Tom"
print(group_list("Users", "")) # Should be "Users:"

Output:

Marketing: Mike, Karen, Jake, Tasha
Engineering: Kim, Jay, Tom
Users: 

### Question 6

The guest_list function reads in a list of tuples with the name, age, and profession of each party guest, and prints the sentence “Guest is X years old and works as __.” for each one. For example, guest_list((‘Ken’, 30, “Chef”), (“Pat”, 35, ‘Lawyer’), (‘Amanda’, 25, “Engineer”)) should print out: Ken is 30 years old and works as Chef. Pat is 35 years old and works as Lawyer. Amanda is 25 years old and works as Engineer. Fill in the gaps in this function to do that.

def guest_list(guests):
for person in guests:
name, age, profession = person
print('{} is {} years old and works as {}'.format(name, age, profession))

guest_list([('Ken', 30, "Chef"), ("Pat", 35, 'Lawyer'), ('Amanda', 25, "Engineer")])

"""
Output should match:
Ken is 30 years old and works as Chef
Pat is 35 years old and works as Lawyer
Amanda is 25 years old and works as Engineer
"""

Output:

Ken is 30 years old and works as Chef
Pat is 35 years old and works as Lawyer
Amanda is 25 years old and works as Engineer

## Practice Quiz: Strings

• Total points: 5

### Question 1

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 letter in input_string.lower():
# Add any non-blank letters to the
# end of one string, and to the front
# of the other string.
if letter.isalpha():
new_string = new_string + letter
reverse_string = letter + reverse_string
# Compare the strings
if new_string == 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

Output:

True
False
True

### Question 2

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”.

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

Output:

12 miles equals 19.2 km
5.5 miles equals 8.8 km
11 miles equals 17.6 km

### Question 3

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

• print(Weather[:4])
• print(Weather[4:])
• print(Weather[1:4])
• print(Weather[:”f”])

Formatted this way, the substring preceding the character “f”, which is indexed by 4, will be printed.

### Question 4

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.”

def nametag(first_name, last_name):
return("{} {}.".format(first_name, last_name))

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

Output:

Jane S.
Francesco R.
Jean-Luc G.

### Question 5

The replace_ending function replaces the old string in a sentence with the new string, but only if the sentence ends with the old string. If there is more than one occurrence of the old string in the sentence, only the one at the end is replaced, not all of them. For example, replace_ending(“abcabc”, “abc”, “xyz”) should return abcxyz, not xyzxyz or xyzabc. The string comparison is case-sensitive, so replace_ending(“abcabc”, “ABC”, “xyz”) should return abcabc (no changes made).

def replace_ending(sentence, old, new):
# Check if the old string is at the end of the sentence
if sentence.endswith(old):
# Using i as the slicing index, combine the part
# of the sentence up to the matched string at the
# end with the new string
i = len(old)
new_sentence = sentence[:-i] + new
return new_sentence

# Return the original sentence if there is no match
return sentence

print(replace_ending("It's raining cats and cats", "cats", "dogs"))
# Should display "It's raining cats and dogs"
print(replace_ending("She sells seashells by the seashore", "seashells", "donuts"))
# Should display "She sells seashells by the seashore"
print(replace_ending("The weather is nice in May", "may", "april"))
# Should display "The weather is nice in May"
print(replace_ending("The weather is nice in May", "May", "April"))
# Should display "The weather is nice in April"

Output:

It's raining cats and dogs
She sells seashells by the seashore
The weather is nice in May
The weather is nice in April