MSBA Prep 2 - Python Prep Home1
MSBA Prep 2 - Python Prep Home1
PARTICIPATION
ACTIVITY
3.1.1:
String indexing.
Type a string
0 1 2 3 4 5
(up to 6 characters)
T r i s h
Trish
A programmer can assign a string just as with other types. Ex: str1 = 'Hello', or str1 = str2. The input()
function can also be used to get strings from the user.
An empty string is a sequence type with 0 elements, created with two quotes. Ex: my_str = ''.
brother
©zyBooks 01/03/22 22:04 1172417
burritos
macho
LOUISVILLEMSBAPrep2DaviesWinter2022
1 #A 'Mad Libs' style game w d
2 #verbs, etc., and then a s
Run
3
4 #Get user's words
5 relative = input('Enter a
6 print()
7
8 food = input('Enter a type
9 i t()
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 1/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
9 print()
10
11 adjective = input('Enter a
12 print()
13
14 period = input('Enter a ti
15 print()
16
17 # Tell the story
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
PARTICIPATION
ACTIVITY
3.1.2:
String literals.
1) 'Hey'
Yes
No
2) 'Hey there.'
Yes
No
3) 674
Yes
No
4) '674'
Yes
No
5) "ok"
Yes
No ©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
6) "a"
Yes
No
PARTICIPATION
313 S i b i
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 2/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
ACTIVITY 3.1.3:
String basics.
LOUISVILLEMSBAPrep2DaviesWinter2022
2) Which answer prints the value of the
first_name variable?
print(first_name)
print('first_name')
print("first_name")
A common operation is to find the length, or the number of characters, in a string. The len() built-in
function can be used to find the length of a string (and any other sequence type).
Figure 3.1.1: Using len() to get the length of a string. Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
The \ character after the string literal extends the string to the following line.
26 characters is better...
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 3/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
john_f_kennedy = 'JFK'
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
print(len(george_v), 'characters is much too long
of a name!')
PARTICIPATION
ACTIVITY
3.1.4:
Using len() to find the length of a string.
Bharathi Byreddy
Programs commonly access an individual character of a string. As a sequence type, every character in
LOUISVILLEMSBAPrep2DaviesWinter2022
a string has an index, or position, starting at 0 from the leftmost character. For example, the 'A' in
string 'ABC' is at index 0, 'B' is at index 1, and 'C' is at index 2. A programmer can access a character at
a specific index by appending brackets [ ] containing the index:
a string
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 4/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
a string.
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
Note that negative indices can be used to access characters starting from the rightmost
Bharathi Byreddy
character of
the string, instead of the leftmost. Ex: alphabet[-1] is 'Z'. LOUISVILLEMSBAPrep2DaviesWinter2022
1 alphabet = "ABCDEFGHIJKLMNOPQ
2 Run
3 user_number = int(input('Ente
4 print()
5
6 print('\nThe letter at index'
7
8
PARTICIPATION
ACTIVITY
3.1.5:
String indexing.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 5/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
LOUISVILLEMSBAPrep2DaviesWinter2022
index.
Writing or altering individual characters of a string variable is not allowed. Strings are immutable
objects, meaning that string values cannot change once created. Instead, an assignment statement
must be used to update an entire string variable.
alphabet =
'abcdefghijklmnopqrstuvwxyz'
File "main.py", line 5, in <module>
change character
TypeError: 'str' object does not support
alphabet[1] = 'B' # Invalid: Cannot item assignment
change character
print('Alphabet:', alphabet)
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 6/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
alphabet =
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
print('Alphabet:', alphabet)
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
A program can add new characters to the end of a string in a process known as string concatenation.
The expression "New" + "York" concatenates the strings New and York to create a new string
NewYork. Most sequence types support concatenation. String concatenation does not contradict the
immutability of strings, because the result of concatenation is a new string; the original strings are not
altered.
string_1 = 'abc'
string_2 = '123'
PARTICIPATION
ACTIVITY 3.1.6:
String variables.
address[0] = '6'
LOUISVILLEMSBAPrep2DaviesWinter2022
address[1] = '2'
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 7/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
Bharathi Byreddy
street_num = '500'
True
False
CHALLENGE
ACTIVITY
3.1.1:
String basics.
368708.2344834.qx3zqy7
Start
Aerith
print('Aerith')
1 2 3 4 5
Check Next
Bharathi Byreddy
CHALLENGE LOUISVILLEMSBAPrep2DaviesWinter2022
ACTIVITY
3.1.2:
Reading multiple data types.
Type two statements. The first reads user input into person_name. The second reads user
input into person_age. Use the int() function to convert person_age into an integer. Below is a
sample output for the given program if the user's input is: Amy 4
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 8/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
Note: Do not write a prompt for the input values, use the format: variable_name = input()
368708.2344834.qx3zqy7
1
2 ''' Your solution goes here '''
©zyBooks 01/03/22 22:04 1172417
3 Bharathi Byreddy
Run
CHALLENGE
ACTIVITY
3.1.3:
Concatenating strings.
Write two statements to read in values for my_city followed by my_state. Do not provide a
prompt. Assign log_entry with current_time, my_city, and my_state. Values should be
separated by a space. Sample output for given program if my_city is Houston and my_state
is Texas:
368708.2344834.qx3zqy7
©zyBooks 01/03/22 22:04 1172417
2 LOUISVILLEMSBAPrep2DaviesWinter2022
3 ''' Your solution goes here '''
4
5 print(log_entry)
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 9/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
Run
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Creating a list
A container is a construct used to group related values together and contains references to other
objects instead of data. A list is a container created by surrounding a sequence of variables or literals
with brackets [ ]. Ex: my_list = [10, 'abc'] creates a new list variable my_list that contains the
two items: 10 and 'abc'. A list item is called an element .
A list is also a sequence, meaning the contained elements are ordered by position in the list, known as
the element's index, starting with 0. my_list = [ ] creates an empty list.
The animation below shows how a list is created and managed by the interpreter. A list itself is an
object, and its value is a sequence of references to the list's elements.
PARTICIPATION
ACTIVITY 3.2.1:
Creating lists.
Animation captions:
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
zyDE 3.2.1: Creating lists.
The following program prints a list of names. Try adding your name to
the list, and run the program again.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 10/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
PARTICIPATION
ACTIVITY
3.2.2:
Creating lists.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 11/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
Lists are useful for reducing the number of variables in a program. Instead of having a separate
variable for the name of every student in a class, or for every word in an email, a single list can store
an entire collection of related variables.
Individual list elements can be accessed using an indexing expression by using brackets as in
my_list[i], where i is an integer. This allows a programmer to quickly find the i'th element in a list.
A list's index must be an integer. The index cannot be a floating-point type, even if the value is a whole
©zyBooks 01/03/22 22:04 1172417
number like 0.0 or 1.0. Using any type besides an integer will produce a runtime error and
Bharathi Byreddy
the program
will terminate. LOUISVILLEMSBAPrep2DaviesWinter2022
aston_martin_one77]
Bugatti Veyron Super Sport:
2400000 dollars
CHALLENGE
ACTIVITY
3.2.1:
Initialize a list.
Initialize the list short_names with strings 'Gus', 'Bob', and 'Zoe'. Sample output for the given
program:
Gus
Bob
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
368708.2344834.qx3zqy7
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Run
Lists are mutable, meaning that a programmer can change a list's contents. An element can be
updated with a new value by performing an assignment to a position in the list.
print(my_nums)
[5, 12, 20]
print(my_nums)
PARTICIPATION
ACTIVITY 3.2.3:
Accessing and updating list elements.
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 13/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
'Detroit'.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Since lists are mutable, a programmer can also use methods to add and remove elements. A method
instructs an object to perform some action, and is executed by specifying the method name following
a "." symbol and an object. The append() list method is used to add new elements to a list. Elements
can be removed using the pop() or remove() methods. Methods are covered in greater detail in
another section.
PARTICIPATION
ACTIVITY 3.2.4:
Adding and removing list elements.
Animation content:
undefined
Animation captions:
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
PARTICIPATION
ACTIVITY
3.2.5:
List modification.
Write a statement that performs the desired action. Assume the list
house_prices = ['$140,000', '$550,000', '$480,000'] exists.
in house_prices to '$175,000'.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Sequence-type functions are built-in functions that operate on sequences like lists and strings.
Sequence-type methods are methods built into the class definitions of sequences like lists and
strings. A subset of such functions and methods is provided below.
LOUISVILLEMSBAPrep2DaviesWinter2022
Operation Description
list1 + list2 Produce a new list by concatenating list2 to the end of list1.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 15/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
min(list) Find the element in list with the smallest value. All elements must be of
the same type.
Find the element in list with the largest value. All elements must be of the
max(list)
same type.
list.index(val) Find the index of the first element in list whose valueBharathi
matches Byreddy
val.
LOUISVILLEMSBAPrep2DaviesWinter2022
list.count(val) Count the number of occurrences of the value val in list.
# Concatenating lists
Cheapest house: 225000
900000
print('Cheapest house:', min(house_prices))
Note that lists can contain mixed types of objects. Ex: x = [1, 2.5, 'abc'] creates a new list x
that contains an integer, a floating-point number, and a string. Later material explores lists in detail,
including how lists can even contain other lists as elements.
Bharathi Byreddy
Bharathi Byreddy
Run LOUISVILLEMSBAPrep2DaviesWinter2022
PARTICIPATION
ACTIVITY 3.2.6:
Using sequence-type functions.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
CHALLENGE
ACTIVITY
3.2.2:
List functions and methods.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 17/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
368708.2344834.qx3zqy7
Start
user_ages = [ 9, 7, 8 ]
LOUISVILLEMSBAPrep2DaviesWinter2022
1 2 3 4 5
Check Next
Tuples
A tuple, usually pronounced "tuhple" or "toople", behaves similar to a list but is immutable – once
created the tuple's elements cannot be changed. A tuple is also a sequence type, supporting len(),
indexing, and other sequence type functions. A new tuple is generated by creating a list of comma-
separated values, such as 5, 15, 20. Typically, tuples are surrounded with parentheses, as in
(5, 15, 20). Note that printing a tuple always displays surrounding parentheses.
A tuple is not as common as a list in practical usage, but can be useful when a programmer wants to
ensure that values do not change. Tuples are typically used when element position, and not just the
relative ordering of elements, is important. Ex: A tuple might store the latitude and longitude of a
landmark because a programmer knows that the first element should be the latitude, the second
element should be the longitude, and the landmark will never move from those coordinates.
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 18/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
77.0366)
Tuple length: 2
print('Coordinates:',
white_house_coordinates)
Longitude: 77.0366 west
print('Tuple length:',
len(white_house_coordinates))
Traceback (most recent call last):
File "<stdin>", line 10, in <module>
white_house_coordinates[1], 'west\n')
LOUISVILLEMSBAPrep2DaviesWinter2022
white_house_coordinates[1] = 50
PARTICIPATION
ACTIVITY 3.3.1:
Tuples.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
CHALLENGE
ACTIVITY
3.3.1:
Initialize a tuple.
Initialize the tuple team_names with the strings 'Rockets', 'Raptors', 'Warriors', and 'Celtics'
(The top-4 2018 NBA teams at the end of the regular season in order). Sample output for the
given program:
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 19/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
Rockets
Raptors
Warriors
Celtics
LOUISVILLEMSBAPrep2DaviesWinter2022
1 team_names = ''' Your solution goes here '''
2
3 print(team_names[0])
4 print(team_names[1])
5 print(team_names[2])
6 print(team_names[3])
Run
Named tuples
A program commonly captures collections of data; for example, a car could be described using a
series of variables describing the make, model, retail price, horsepower, and number of seats. A
named tuple allows the programmer to define a new simple data type that consists of named
attributes. A Car named tuple with fields like Car.price and Car.horsepower would more clearly
represent a car object than a list with index positions correlating to some attributes.
The namedtuple container must be imported to create a new named tuple. Once the container is
imported, the named tuple should be created like in the example below, where the name and attribute
©zyBooks 01/03/22 22:04 1172417
names of the named tuple are provided as arguments to the namedtuple constructor. Note that the
Bharathi Byreddy
fields to include in the named tuple are found in a list, but may also be a single string with space or
LOUISVILLEMSBAPrep2DaviesWinter2022
comma separated values.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 20/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
©zyBooks 01/03/22 22:04 1172417
print(chevy_blazer)
Bharathi Byreddy
print(chevy_impala)
LOUISVILLEMSBAPrep2DaviesWinter2022
namedtuple() only creates the new simple data type, and does not create new data objects. Above, a
new data object is not created until Car() is called with appropriate values. A data object's attributes
can be accessed using dot notation, as in chevy_blazer.price. This "named" attribute is simpler to
read than if using a list or tuple referenced via index like chevy_blazer[2].
Like normal tuples, named tuples are immutable. A programmer wishing to edit a named tuple would
replace the named tuple with a new object.
PARTICIPATION
ACTIVITY 3.3.2:
Named tuples.
Assume namedtuple has been imported. Use a list of strings in the namedtuple()
constructor where applicable.
'postal_code', 'country'])
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Check Show answer
Ch k Sh
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 21/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
Check Show answer
Bharathi Byreddy
CHALLENGE
ACTIVITY 3.3.2:
Creating a named tuple
Define a named tuple Player that describes an athlete on a sports team. Include the fields
name, number, position, and team.
368708.2344834.qx3zqy7
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 22/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
Run
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Set basics
A set is an unordered collection of unique elements. Sets have the following properties:
Elements are unordered: Elements in the set do not have a position or index.
Elements are unique: No elements in the set share the same value.
A set can be created using the set() function, which accepts a sequence-type iterable object (list,
tuple, string, etc.) whose elements are inserted into the set. A set literal can be written using curly
braces { } with commas separating set elements. Note that an empty set can only be created using
set().
nums2 = { 7, 8, 9 }
{1, 2, 3}
{7, 8, 9}
print(nums1)
print(nums2)
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Because the elements of a set are unordered and have no meaningful position in the collection, the
index operator is not valid. Attempting to access the element of a set by position, for example
nums1[2] to access the element at index 2, is invalid and will produce a runtime error.
A set is often used to reduce a list of items that potentially contains duplicates into a collection of
unique values. Simply passing a list into set() will cause any duplicates to be omitted in the created
set.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 23/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
LOUISVILLEMSBAPrep2DaviesWinter2022
5 names_set = set(first_names)
6
7 print(names_set)
8
PARTICIPATION
ACTIVITY
3.4.1:
Basic sets.
LOUISVILLEMSBAPrep2DaviesWinter2022
25.
Error: invalid syntax.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 24/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
LOUISVILLEMSBAPrep2DaviesWinter2022
Modifying sets
Sets are mutable – elements can be added or removed using set methods. The add() method places
a new element into the set if the set does not contain an element with the provided value. The
remove() and pop() methods remove an element from the set.
Additionally, sets support the len() function to return the number of elements in a set. To check if a
specific value exists in a set, a membership test such as value in set (discussed in another
section) can be used.
set.remove(value): Remove the element with given value from the set. Raises KeyError if value is
not found. Ex: my_set.remove('abc')
set.pop(): Remove a random element from the set. Ex: my_set.pop()
Operation Description
Bharathi Byreddy
set.remove(value) Removes value from the set. Raises KeyError if value is not found.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 25/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
PARTICIPATION
ACTIVITY
3.4.2:
Modifying sets.
Animation content:
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Animation captions:
1. Sets can be created using braces {} with commas separating the elements.
2. The add() method adds a single element to a set.
3. The update() method adds the elements of one set to another set.
4. The remove() method removes a single element from a set.
5. The clear() method removes all elements from a set, leaving the set with a length of 0.
PARTICIPATION
ACTIVITY
3.4.3:
Modifying sets.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 26/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
CHALLENGE
ACTIVITY 3.4.1:
Creating and modifying sets.
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
The top 3 most popular male names of 2017 are Oliver, Declan, and Henry according to
LOUISVILLEMSBAPrep2DaviesWinter2022
babynames.com.
Write a program that modifies the male_names set by removing a name and adding a
different name.
NOTE: Because sets are unordered, the order in which the names in male_names appear
may differ from above.
368708.2344834.qx3zqy7
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Run
Set operations
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 27/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
Python set objects support typical set theory operations like intersections and unions. A brief overview
of common set operations supported in Python are provided below:
Description
LOUISVILLEMSBAPrep2DaviesWinter2022
set.intersection(set_a, set_b, Returns a new set containing only the elements in
set_c...) common between set and all provided sets.
PARTICIPATION
ACTIVITY
3.4.4:
Set theory operations.
Animation content:
Animation captions:
1. The union() method builds a set containing the unique elements from names1 and names2.
'Corrin' only appears once in the resulting set.
2. The intersection() method builds a set that contains all common elements between result_set
and names3.
3. The difference() method builds a set that contains elements only found
©zyBooks in result_set
01/03/22 that are
22:04 1172417
LOUISVILLEMSBAPrep2DaviesWinter2022
PARTICIPATION
ACTIVITY
3.4.5:
Set theory operations.
Assume that:
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 28/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
Fill in the code to complete the line that would produce the given set.
Bharathi Byreddy
monsters. (trolls)
LOUISVILLEMSBAPrep2DaviesWinter2022
2) {'Gorgon'}
monsters. (horde)
CHALLENGE
ACTIVITY 3.4.2:
Set theory methods.
The following program includes fictional sets of the top 10 male and female baby names for
the current year. Write a program that creates:
1. A set all_names that contains all of the top 10 male and all of the top 10 female
names.
2. A set neutral_names that contains only names found in both male_names and
female_names.
3. A set specific_names that contains only gender specific names.
©zyBooks 01/03/22 22:04 1172417
LOUISVILLEMSBAPrep2DaviesWinter2022
{'Michael', 'Henry', 'Jayden', 'Bailey', 'Lucas', 'Chuck', 'Aiden',
'Khloe', 'Elizabeth', 'Maria', 'Veronica', 'Meghan', 'John', 'Samuel',
'Britney', 'Charlie', 'Kim'}
NOTE: Because sets are unordered, they are printed using the sorted() function here for
comparison.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 29/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
368708.2344834.qx3zqy7
7 Bharathi Byreddy
8 print(sorted(all_names)) LOUISVILLEMSBAPrep2DaviesWinter2022
9 print(sorted(neutral_names))
10 print(sorted(specific_names))
Run
Creating a dictionary
Consider a normal English language dictionary – a reader looks up the word "cat" and finds the
definition, "A small, domesticated carnivore." The relationship between "cat" and its definition is
associative, i.e., "cat" is associated with some words describing "cat."
Bharathi Byreddy
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 30/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
Dictionaries are typically used in place of lists when an associative relationship exists. Ex: If a program
contains a collection of anonymous student test scores, those scores should be stored in a list.
However, if each score is associated with a student name, a dictionary could be used to associate
student names to their score. Other examples of associative relationships include last names and
addresses, car models and price, or student ID number and university email address.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
players = {
'Cristiano Ronaldo': 7
}
{'Lionel Messi': 10, 'Cristiano Ronaldo': 7}
print(players)
Note that formatting list or dictionary entries like in the above example, where elements appear on
consecutive lines, helps to improve the readability of the code. The behavior of the code is not
changed.
1 caffeine_content_mg = {
2 'Mr. Goodbar chocolate': ©zyBooks 01/03/22 22:04 1172417
PARTICIPATION
ACTIVITY
3.5.1:
Create a dictionary. ©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
1) Use braces to create a dictionary
called ages that maps the names
'Bob' and 'Frank' to their ages, 27
and 75, respectively. For this
exercise, make 'Bob' the first entry
in the dict.
ages =
Traceback (most recent call last):
prices['lemons'])
KeyError: 'lemons'
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
PARTICIPATION
ACTIVITY 3.5.2:
Accessing dictionary entries.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 32/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
False
Bharathi Byreddy
dict[k] = v: Adds the new key-value pair k-v, if dict[k] does not already exist.
print(prices)
©zyBooks 01/03/22 22:04 1172417
Bharathi1.49}
{'banana': Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
{'banana': 1.69}
print(prices)
{}
print(prices)
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 33/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
PARTICIPATION
ACTIVITY 3.5.3:
Modifying dictionaries.
LOUISVILLEMSBAPrep2DaviesWinter2022
prices['pears': 1.79]
del prices['limes']
True
False
prices['oranges'] = 1.29
True
False
CHALLENGE
ACTIVITY 3.5.1:
Modify and add to dictionary.
Write a statement to add the key Tesla with value USA to car_makers. Modify the car maker
of Fiat to Italy. Sample output for the given program:
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
368708.2344834.qx3zqy7
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Run
Numeric types int and float represent the most common types used to store data. All numeric types
support the normal mathematical operations such as addition, subtraction, multiplication, and
division, among others.
Type Notes
Sequence types string, list, and tuple are all containers for collections ofBharathi
objectsByreddy
ordered
by position in
LOUISVILLEMSBAPrep2DaviesWinter2022
the sequence, where the first object has an index of 0 and subsequent elements have indices 1, 2, etc.
A list and a tuple are very similar, except that a list is mutable and individual elements may be edited
or removed. Conversely, a tuple is immutable and individual elements may not be edited or removed.
Lists and tuples can contain any type, whereas a string contains only single-characters. Sequence-
type functions such as len() and element indexing using brackets [ ] can be applied to any sequence
type.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 35/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
The only mapping type in Python is the dict type. Like a sequence type, a dict serves as a container.
However, each element of a dict is independent, having no special ordering or relation to other
elements. A dictionary uses key-value pairs to associate a key with a value.
LOUISVILLEMSBAPrep2DaviesWinter2022
string Sequence type: Used for text.
set Set type: A mutable container with unordered and unique elements.
PARTICIPATION
ACTIVITY
3.6.1:
Common data types.
Bharathi Byreddy
True LOUISVILLEMSBAPrep2DaviesWinter2022
False
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 36/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
New programmers often struggle with choosing the types that best fit their needs, such as choosing
whether to store particular data using a list, tuple, or dict. In general, a programmer might use a list
when data has an order, such as lines of text on a page. A programmer might use a tuple instead of a
list if the contained data should not change. If order is not important, a programmer might use a
dictionary to capture relationships between elements, such as student names and grades.
PARTICIPATION
ACTIVITY
3.6.2:
Choosing among different container types.
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Choose the container that best fits the described data.
PARTICIPATION
ACTIVITY 3.6.3:
Finding errors in container code.
Bharathi Byreddy
'Amy']
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 37/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
grades = {}
name = input('name:')
grades.append(name) = grade
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
2)
workers = ('Jo', 'Amy')
del workers[1]
print('Jo:', workers[0])
The following program calculates an overall grade in a course based on three equally weighted
exams.
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
70
75
91
Run
1. Calculates the overall grade for four equally weighted programming assignments, where each
assignment is graded out of 50 points. Hint: First calculate the percentage for each assignment
(e.g., score / 50), then calculate the overall grade percentage (be sure to multiply the result by
100).
2. Calculates the overall grade for four equally weighted programming assignments, where
assignments 1 and 2 are graded out of 50 points and assignments 3 and 4 are graded out of 75
points.
3. Calculates the overall grade for a course with three equally weighted exams (graded out of 100)
that account for 60% of the overall grade and four equally weighted programming assignments
(graded out of 50) that account for 40% of the overall grade. Hint: The overall grade can be
calculated as 0.6 * averageExamScore + 0.4 * averageProgScore.
LOUISVILLEMSBAPrep2DaviesWinter2022
Type conversions
A calculation sometimes must mix integer and floating-point numbers. For example, given that about
50.4% of human births are males, then 0.504 * num_births calculates the number of expected
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 39/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
males in num_births births. If num_births is an integer type, then the expression combines a floating-
point and integer.
A type conversion is a conversion of one type to another, such as an int to a float. An implicit
conversion is a type conversion automatically made by the interpreter, usually between numeric types.
For example, the result of an arithmetic operation like + or * will be a float only if either operand of the
operation is a float.
©zyBooks 01/03/22 22:04 1172417
PARTICIPATION
ACTIVITY 3.8.1:
Implicit conversions between float and int.
Type the value held in the variable after the assignment statement, given:
num_items = 5
item_weight = 0.5
For any floating-point answer, type answer to tenths. Ex: 8.0, 6.5, or 0.1
1) num_items + num_items
2) item_weight * num_items
3) (num_items + num_items) *
item_weight ©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Conversion functions
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 40/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
Sometimes a programmer needs to explicitly convert an item's type. Conversion can be explicitly
performed using the below conversion functions:
Bharathi Byreddy
Converting a float to an int will truncate the floating-point number's fraction. For example, the variable
temperature might have a value of 18.75232, but can be converted to an integer expression
int(temperature). The result would have the value 18, with the fractional part removed.
Conversion of types is very common. In fact, all user input obtained using input() is initially a string
and a programmer must explicitly convert the input to a numeric type.
Strings can also be converted to numeric types, if the strings follow the correct formatting, i.e. using
only numbers and possibly a decimal point. For example, int('500') yields an integer with a value of
500, and float('1.75') yields the floating-point value 1.75.
18
1 input_text = input('Enter a n
2 float_variable = float(input_ Run
3 int_variable = int(float_vari ©zyBooks 01/03/22 22:04 1172417
4 Bharathi Byreddy
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 41/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
PARTICIPATION
ACTIVITY
3.8.2:
Type conversions.
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
1) int(1.55)
1.55
1
'1.55'
2) float("7.99")
7.0
8.0
7.99
3) str(99)
99
99.0
'99'
CHALLENGE
ACTIVITY
3.8.1:
Type conversions.
368708.2344834.qx3zqy7
Start
number = 3
Bharathi Byreddy
new_number = number * 5
LOUISVILLEMSBAPrep2DaviesWinter2022
print(new_number)
1 2 3 4 5
Check Next
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 42/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
CHALLENGE
ACTIVITY 3.8.2:
Type casting: Computing average owls per zoo.
Assign avg_owls with the average owls per zoo. Print avg_owls as an integer.
Bharathi Byreddy
368708.2344834.qx3zqy7
1 avg_owls = 0.0
2
3 num_owls_zooA = int(input())
4 num_owls_zooB = int(input())
5 num_owls_zooC = int(input())
6
7 ''' Your solution goes here '''
8
9 print('Average owls per zoo:', int(avg_owls))
Run
CHALLENGE
ACTIVITY
3.8.3:
Type casting: Reading and adding values.
LOUISVILLEMSBAPrep2DaviesWinter2022
Number of owls: 7
368708.2344834.qx3zqy7
1 total_owls = 0
2
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 43/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
2
3 num_owls_A = input()
4 num_owls_B = input()
5
6 ''' Your solution goes here '''
7
8 print('Number of owls:', total_owls)
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Run
Program output commonly includes expressions, like variables or other calculations, as a part of the
output text. A formatted string literal, or f-string, allows a programmer to create a string with
placeholder expressions that are evaluated as the program executes. An f-string starts with a f
character before the starting quote, and uses curly braces { } to denote the placeholder expressions.
A placeholder expression is also called a replacement field, as its value replaces the expression in the
final output.
PARTICIPATION
ACTIVITY
3.9.1:
Creating literal strings with embedded expressions.
Animation content:
©zyBooks 01/03/22 22:04 1172417
Animation captions:
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 44/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
1. The first expression, {number}, is replaced with the value of the number variable.
2. The second expression, {amount}, is replaced with the value of the number amount.
PARTICIPATION
ACTIVITY
3.9.2:
Identify the output of f-strings.
Bharathi Byreddy
num_items = 3
LOUISVILLEMSBAPrep2DaviesWinter2022
cost_taco = 1.25
print('{num_items} tacos
cost {cost_taco * 3}')
print(f'{num_items} tacos
cost {cost_taco}')
print(f'{num_items} tacos
cost {cost_taco *
num_items}')
print(f'(num_items) tacos
cost (cost_taco *
num_items)')
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
An = sign can be provided after the expression in a replacement field to print both the expression and
its result which is a useful debugging technique when dynamically generating lots of strings and
output. Ex: f'{2*4=}' produces the string "2*4=8".
Additionally, double braces {{ and }} can be used to place an actual curly brace into an f-string. Ex:
f'{{Jeff Bezos}}: Amazon' produces the string "{Jeff Bezos}: Amazon".
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 45/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
Example Output
print(f'{2**2=}')
2**2=4
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
two_power_two = 2**2
LOUISVILLEMSBAPrep2DaviesWinter2022
print(f'{two_power_two=}')
two_power_two=4
print(f'{2**2=},{2**4=}')
2**2=4,2**4=16
print(f'{{2**2}}')
{2**2}
print(f'{{{2**2=}}}')
{2**2=4}
PARTICIPATION
ACTIVITY
3.9.3:
Output of f-strings using debug features and escape characters.
1) output = f'{2*2}'
2) output = f'{2*2=}'
3) kids = 4
Bharathi Byreddy
adults = 2
LOUISVILLEMSBAPrep2DaviesWinter2022
output = f'{kids+adults}
total'
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 46/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
4) kids = 4
adults = 2
output = f'{kids+adults=}
total'
Bharathi Byreddy
Format specifications
A format specification inside a replacement field allows a value's formatting in the string to be
customized. Ex: Using a format specification, a variable with the integer value 4 can be output as a
floating-point number (4.0), with leading zeros (004), aligned to the left or right, etc.
A format specification is introduced with a colon : in the replacement field. The colon separates the
"what" on the left from the "how" on the right. The left "what" side is an expression to be evaluated,
perhaps just a variable name or a value. The right "how" side is the format specification that
determines how to show that value using special characters. Ex: {4:.2f} formats 4 as 4.00.
A presentation type is a part of a format specification that determines how to represent a value in text
form, such as integer (4), floating point (4.0), fixed precision decimal (4.000), percentage (4%), binary
(100), etc. A presentation type can be set in a replacement field by inserting a colon : and providing
one of the presentation type characters described below.
More advanced format specifications, like fill and alignment, are provided in a later section.
'
©zyBooks 01/03/22 22:04 1172417
Output
LOUISVILLEMSBAPrep2DaviesWinter2022
String (default presentation name = 'Aiden'
s print(f'{name:s}')
Aiden
type - can be omitted)
number = 4
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 47/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
number = 44
Bharathi Byreddy
f print(f'{number:f}')
4.000000
of precision)
Fixed-point notation
number = 4
number = 4
PARTICIPATION
ACTIVITY 3.9.4:
Format specifications and presentation types.
Enter the most appropriate format specification to produce the desired output.
print(f'{num: }')
num = 31
Bharathi Byreddy
print('{num: }')
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 48/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
num = 31
print('{num: }')
CHALLENGE
ACTIVITY
3.9.1:
String formatting with f-strings.
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
368708.2344834.qx3zqy7
LOUISVILLEMSBAPrep2DaviesWinter2022
Start
name = 'Ron'
1 2 3 4 5
Check Next
CHALLENGE
ACTIVITY 3.9.2:
Printing an f-string.
Amy,5
Bharathi Byreddy
1 user_word = input()
LOUISVILLEMSBAPrep2DaviesWinter2022
2 user_number = int(input())
3
4 ''' Your solution goes here '''
5
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 49/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
CHALLENGE
ACTIVITY
3.9.3:
String formatting.
368708.2344834.qx3zqy7
Start
num_students = 90
The math class has 90 students.
1 2 3
Check Next
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Binary numbers
Normally, a programmer can think in terms of base ten numbers. However, a computer must allocate
some finite quantity of bits (e.g., 32 bits) for a variable, and that quantity
©zyBooksof01/03/22
bits limits the1172417
22:04 range of
numbers that the variable can represent. Python allocates additional memory Bharathi
toByreddy
accommodate
LOUISVILLEMSBAPrep2DaviesWinter2022
numbers of very large sizes (past a typical 32 or 64 bit size), and a Python programmer need not think
of such low level details. However, binary base computation is a common and important part of
computer science, so some background on how the quantity of bits influences a variable's number
range is helpful.
Because each memory location is composed of bits (0s and 1s), a processor stores a number using
base 2, known as a binary number.
For a number in the more familiar base 10, known as a decimal number, each digit must be 0-9 and
each digit's place is weighed by increasing powers of 10.
212 2 1 0
= 2 ⋅ 10 + 1 ⋅ 10 + 2 ⋅ 10
= 2 ⋅ 100 + 1 ⋅ 10 + 2 ⋅ 1
= 200 + 10 + 2
= 212
In base 2, each digit must be 0-1 and each digit's place is weighed by increasing powers of 2.
Table 3.10.2: Binary numbers use weighed powers of 2. 01/03/22 22:04 1172417
©zyBooks
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Binary number with
Representation
4 bits
1101
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 51/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
3 2 1 0
= 1 ⋅ 2 + 1 ⋅ 2 + 0 ⋅ 2 + 1 ⋅ 2
= 1 ⋅ 8 + 1 ⋅ 4 + 0 ⋅ 2 + 1 ⋅ 1
= 8 + 4 + 0 + 1
= 13
Bharathi Byreddy
PARTICIPATION LOUISVILLEMSBAPrep2DaviesWinter2022
ACTIVITY 3.10.1:
Binary number tool.
Set each binary digit for the unsigned binary number below to 1 or 0 to obtain the decimal
equivalents of 9, then 50, then 212, then 255. Note also that 255 is the largest integer that the
8 bits can represent.
0 0 0 0 0 0 0 0
0
128 64 32 16 8 4 2 1 (decimal value)
27 26 25 24 23 22 21 20
PARTICIPATION
ACTIVITY 3.10.2:
Binary numbers.
LOUISVILLEMSBAPrep2DaviesWinter2022
an 8-bit binary number.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 52/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
ACTIVITY
3.10.1:
Create a binary number. Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
368708.2344834.qx3zqy7
Start
0 0 0
0
1 2 3
Check Next
Bharathi Byreddy
The following is a sample programming lab activity; not all classes using a zyBook require students to
fully complete this activity. No auto-checking is performed. Users planning to fully complete this
program may consider first developing their code in a separate programming environment.
The following calculates a user's age in days based on the user's age in years.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 53/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
22
Load default template...
1 user_age_years = int(input('e
2
Run ©zyBooks 01/03/22 22:04 1172417
3 user_age_days = user_age_year
Bharathi Byreddy
4
LOUISVILLEMSBAPrep2DaviesWinter2022
5 print(f'You are at least {use
6
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
(1) Prompt the user to enter two words and a number, storing each into separate variables. Then,
output those three values on a single line separated by a space. (Submit for 1 point)
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 54/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
yellow
Daisy
Bharathi Byreddy
(2) Output two passwords using a combination of the user input. Format the passwords as shown
below. (Submit for 2 points, so 3 points total).
yellow
Daisy
(3) Output the length of each password (the number of characters in the strings). (Submit for 2 points,
so 5 points total).
Ex: If the input is:
yellow
Daisy
the output after the prompts is: ©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
You entered: yellow Daisy 6
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 55/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
NaN.2344834.qx3zqy7
LAB
ACTIVITY
3.12.1:
LAB: Warm up: Creating passwords 0/5
Bharathi Byreddy
1 # FIXME (1): Finish reading another word and an integer into variables.
2 # Output all the values on a single line
3 favorite_color = input('Enter favorite color:\n')
4
5
6 # FIXME (2): Output two password options
7 password1 = favorite_color
8 print('\nFirst password:')
9
10
11 # FIXME (3): Output the length of the two password options
12
trending_flat trending_flat
main.py
Run program Input (from above) Outp
(Your program)
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
History of your effort will appear here once you begin working
on this zyLab.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 56/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
A half-life is the amount of time it takes for a substance or entity to fall to half its original value.
Caffeine has a half-life of about 6 hours in humans. Given caffeine amount (in mg) as input, output the
caffeine level after 6, 12, and 24 hours. Use a string formatting expression with conversion specifiers
to output the caffeine amount as floating-point numbers.
Output each floating-point value with two digits after the decimal point, which can be achieved as
follows:
print(f'{your_value:.2f}')
Ex: If the input is:
100
Note: A cup of coffee has about 100 mg. A soda has about 40 mg. An "energy" drink (a misnomer) has
between 100 mg and 200 mg.
NaN.2344834.qx3zqy7
LAB
ACTIVITY
3.13.1:
LAB: Input and formatted output: Caffeine levels 0 / 10
Bharathi Byreddy
2
LOUISVILLEMSBAPrep2DaviesWinter2022
3 ''' Type your code here. '''
4
5
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 57/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
for grading. Below, type any needed input values in the first
Bharathi Byreddy
trending_flat trending_flat
main.py
Run program Input (from above)
(Your program)
Outp
History of your effort will appear here once you begin working
on this zyLab.
LOUISVILLEMSBAPrep2DaviesWinter2022
Output each floating-point value with three digits after the decimal point, which can be achieved as
follows:
print(f'{your_value:.3f}')
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 58/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
8.3
10.4
5.0
4.8
2072 7
Bharathi Byreddy
2071.680 7.125
LOUISVILLEMSBAPrep2DaviesWinter2022
NaN.2344834.qx3zqy7
LAB
ACTIVITY
3.14.1:
LAB: Simple statistics 0 / 10
1 num1 = float(input())
2 num2 = float(input())
3 num3 = float(input())
4 num4 = float(input())
5
6 ''' Type your code here. '''
7
Bharathi Byreddy
trending_flat trending_flat
main.py
Run program Input (from above) Outp
(Your program)
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 59/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
History of your effort will appear here once you begin working
on this zyLab.
©zyBooks 01/03/22 22:04 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
print(f'{your_value:.2f}')
(1) Prompt the user to input a wall's height and width. Calculate and output the wall's area (integer).
(Submit for 2 points).
12
Enter wall width (feet):
15
Wall area: 180 square feet
(2) Extend to also calculate and output the amount of paint in gallons needed to paint the wall
(floating point). Assume a gallon of paint covers 350 square feet. Store this value in a variable. Output
the amount of paint needed using the %f conversion specifier. (Submit for 2 points, so 4 points total).
12
Enter wall width (feet):
LOUISVILLEMSBAPrep2DaviesWinter2022
Paint needed: 0.51 gallons
(3) Extend to also calculate and output the number of 1 gallon cans needed to paint the wall. Hint: Use
a math function to round up to the nearest gallon. (Submit for 2 points, so 6 points total).
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 60/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
12
Enter wall width (feet):
15
Wall area: 180 square feet
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
(4) Extend by prompting the user for a color they want to paint the walls. Calculate and output the
total cost of the paint cans depending on which color is chosen. Hint: Use a dictionary to associate
each paint color with its respective cost. Red paint costs $35 per gallon can, blue paint costs $25 per
gallon can, and green paint costs $23 per gallon can. (Submit for 2 points, so 8 points total).
12
Enter wall width (feet):
15
Wall area: 180 square feet
red
NaN.2344834.qx3zqy7
LAB
ACTIVITY
3.15.1:
LAB*: Program: Painting a wall 0/8
1 import math
2
3 # Dictionary of paint colors and cost per gallon
4 paint_colors = { ©zyBooks 01/03/22 22:04 1172417
LOUISVILLEMSBAPrep2DaviesWinter2022
If your code requires input values, provide them here.
trending_flat trending_flat
main.py
Run program Input (from above) Outp
(Your program)
History of your effort will appear here once you begin working
on this zyLab.
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 62/62