0% found this document useful (0 votes)
233 views

MSBA Prep 2 - Python Prep Home1

Uploaded by

Bharathi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
233 views

MSBA Prep 2 - Python Prep Home1

Uploaded by

Bharathi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

1/3/22, 10:05 PM MSBA Prep 2: Python Prep home

3.1 String basics

Strings and string literals

A string is a sequence of characters, like the text MARY, that can©zyBooks


be stored01/03/22 22:04 1172417

in a variable. A string literal


Bharathi Byreddy

is a string value specified in the source code of a program. ALOUISVILLEMSBAPrep2DaviesWinter2022


programmer creates a string literal by
surrounding text with single or double quotes, such as 'MARY' or "MARY".
The string type is a special construct known as a sequence type: A type that specifies a collection of
objects ordered from left to right. A string's characters are ordered from the string's first letter to the
last. A character's position in a string is called the character's index, which starts at 0. Ex: In "Trish", T
is at index 0, r at 1, etc.

PARTICIPATION
ACTIVITY
3.1.1:
String indexing.

Type a string below to see how a string is a sequence of


characters ordered by position. The numbers on top indicate
each character's index.

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 = ''.

zyDE 3.1.1: A program with strings.


Try the 'mad libs' style game below.

brother
©zyBooks 01/03/22 22:04 1172417

Load default template... Bharathi Byreddy

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.

Indicate which items are 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.

1) Which answer creates a string variable


first_name with a value 'Daniel'?
Daniel = first_name
first_name = 'Daniel'
©zyBooks 01/03/22 22:04 1172417

first_name = Daniel Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022
2) Which answer prints the value of the
first_name variable?
print(first_name)
print('first_name')
print("first_name")

3) Which answer assigns first_name with


a string read from input?
first_name = input
input('Type your name:')
first_name = input('Type
your name:')

4) Which answer assigns first_name with


an empty string?
first_name =
first_name = ''
'' = first_name

String length and indexing

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

©zyBooks 01/03/22 22:04 1172417

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.

185 characters is much too


long of a name!

26 characters is better...

3 characters is short enough.

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 3/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home

george_v = "His Majesty George V, by the Grace of


God, " \

"of the United Kingdom of Great Britain


and " \

"Ireland and of the British Dominions


beyond " \

"the Seas, King, Defender of the Faith,


Emperor of India"

gandhi = 'Mohandas Karamchand Gandhi'

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!')

print(len(gandhi), 'characters is better...')

print(len(john_f_kennedy), 'characters is short


enough.')

PARTICIPATION
ACTIVITY
3.1.4:
Using len() to find the length of a string.

1) What is the length of the string


"Santa"?

Check Show answer

2) Write a statement that prints the


length of the string variable
first_name.

Check Show answer

©zyBooks 01/03/22 22:04 1172417

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:

Figure 3.1.2: Accessing individual characters of

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'

print(alphabet[0], alphabet[1], alphabet[25])


A B Z

©zyBooks 01/03/22 22:04 1172417

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

zyDE 3.1.2: String indexing.


Try the simple program that looks up the indices of letters in the
alphabet. Try entering a negative value like -1, or -25.

Load default template...


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.

©zyBooks 01/03/22 22:04 1172417

1) What character is in index 2 of the Bharathi Byreddy

string "America"? LOUISVILLEMSBAPrep2DaviesWinter2022

Check Show answer

2) Write an expression that accesses

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 5/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home

the first character of the string


my_country.

Check Show answer

3) Assign my_var with the last ©zyBooks 01/03/22 22:04 1172417

character in my_str. Use a negative Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022
index.

Check Show answer

Changing string variables and concatenating strings

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.

Figure 3.1.3: Strings are immutable and cannot be changed.

Individual characters of a string cannot be directly changed.

alphabet =
'abcdefghijklmnopqrstuvwxyz'

# Change to upper case


Traceback (most recent call last):


File "main.py", line 5, in <module>

alphabet[0] = 'A' # Invalid: Cannot alphabet[0] = 'A' # Invalid: Cannot


change character

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
 

Instead, update the variable by assigning an entirely new string.

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 6/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home

alphabet = Alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZ


'abcdefghijklmnopqrstuvwxyz'

# Change to upper case

alphabet =
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

print('Alphabet:', alphabet)

©zyBooks 01/03/22 22:04 1172417

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.

Figure 3.1.4: String concatenation.

string_1 = 'abc'

string_2 = '123'

concatenated_string = string_1 + string_2


Easy as abc123
print('Easy as ' + concatenated_string)

PARTICIPATION
ACTIVITY 3.1.6:
String variables.

1) Python string objects are mutable,


meaning that individual characters can
be changed.
True
False

2) Executing the statements:


©zyBooks 01/03/22 22:04 1172417

address = '900 University Ave'


Bharathi Byreddy

address[0] = '6'

LOUISVILLEMSBAPrep2DaviesWinter2022
address[1] = '2'

is a valid way to change address to


'620 University Ave'.
True
False

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 7/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home

3) Executing the statements:


address = '900 University Ave'

address = '620 University Ave'

is a valid way to change address to


'620 University Ave'.
True
False ©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

4) After the following executes, the value LOUISVILLEMSBAPrep2DaviesWinter2022

of address is '500 Floral Avenue'.

street_num = '500'

street = 'Floral Avenue'

address = street_num + ' ' +


street

True
False

CHALLENGE
ACTIVITY
3.1.1:
String basics.

368708.2344834.qx3zqy7

Start

Type the program's output

Aerith

print('Aerith')

1 2 3 4 5

Check Next

©zyBooks 01/03/22 22:04 1172417

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

In 5 years Amy will be 9

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

4 print('In 5 years', person_name, 'will be', person_age + 5)


LOUISVILLEMSBAPrep2DaviesWinter2022

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:

2014-07-26 02:12:18: Houston Texas

Note: Do not write a prompt for the input values.

368708.2344834.qx3zqy7
©zyBooks 01/03/22 22:04 1172417

1 current_time = '2020-07-26 02:12:18:' Bharathi Byreddy

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

3.2 List basics

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:

1. User creates a new list.


2. The interpreter creates new object for each list element.
3. 'prices' holds references to objects in list.

©zyBooks 01/03/22 22:04 1172417

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.

Load default template... Run

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 10/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home

1 names = ['Daniel', 'Roxanna',


2
3 print(names)
4

©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

PARTICIPATION
ACTIVITY
3.2.2:
Creating lists.

1) Write a statement that creates a


list called my_nums, containing the
elements 5, 10, and 20.

Check Show answer

2) Write a statement that creates a


list called my_list with the
elements -100 and the string 'lists
are fun'.

Check Show answer

3) Write a statement that creates an


empty list called class_grades. ©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

Check Show answer

Accessing list elements

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

Figure 3.2.1: Access list elements using an indexing expression.

# Some of the most expensive cars in the world

lamborghini_veneno = 3900000 # $3.9 million!

bugatti_veyron = 2400000 # $2.4 million!

aston_martin_one77 = 1850000 # $1.85 million!

Lamborghini Veneno: 3900000


prices = [lamborghini_veneno, bugatti_veyron,
dollars

aston_martin_one77]
Bugatti Veyron Super Sport:

2400000 dollars

print('Lamborghini Veneno:', prices[0], Aston Martin One-77: 1850000


'dollars')
dollars
print('Bugatti Veyron Super Sport:', prices[1],
'dollars')

print('Aston Martin One-77:', prices[2],


'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

Zoe ©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy


LOUISVILLEMSBAPrep2DaviesWinter2022

368708.2344834.qx3zqy7

1 short_names = ''' Your solution goes here '''


2
3 print(short_names[0])
4 print(short_names[1])
5 i t( h t [2])
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 12/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
5 print(short_names[2])

©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

Run

Updating list elements

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.

Figure 3.2.2: Updating list elements.

my_nums = [5, 12, 20]

print(my_nums)


[5, 12, 20]

# Update a list element


[5, -28, 20]
my_nums[1] = -28

print(my_nums)

PARTICIPATION
ACTIVITY 3.2.3:
Accessing and updating list elements.

1) Write a statement that assigns


my_var with the 3rd element of
©zyBooks 01/03/22 22:04 1172417

my_list. Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

Check Show answer

2) Write a statement that assigns the


2nd element of my_towns with

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 13/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home

'Detroit'.

Check Show answer

Adding and removing list elements ©zyBooks 01/03/22 22:04 1172417

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.

Adding elements to a list:

list.append(value): Adds value to the end of list. Ex: my_list.append('abc')

Removing elements from a list:

list.pop(i): Removes the element at index i from list. Ex: my_list.pop(1)


list.remove(v): Removes the first element whose value is v. Ex: my_list.remove('abc')

PARTICIPATION
ACTIVITY 3.2.4:
Adding and removing list elements.

Animation content:

undefined

Animation captions:

1. append() adds an element to the end of the list.


2. pop() removes the element at the given index from the list.
'bw', which is at index 1, is removed
and 'abc' is now at index 1.
3. remove() removes the first element with a given value.
'abc' is removed and now the list only
has one element. ©zyBooks 01/03/22 22:04 1172417

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.

1) Update the price of the second item


https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 14/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home

in house_prices to '$175,000'.

Check Show answer

2) Add a price to the end of the list with a value


of '$1,000,000'. ©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

Check Show answer

3) Remove the 1st element from


house_prices, using the pop()
method.

Check Show answer

4) Remove '$140,000' from


house_prices, using the remove()
method.

Check Show answer

Sequence-type methods and functions

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.

©zyBooks 01/03/22 22:04 1172417

Table 3.2.1: Some of the functions and methods useful Bharathi


to lists.Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

Operation Description

len(list) Find the length of the list.

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.

sum(list) Find the sum of all elements of a list (numbers only).


©zyBooks 01/03/22 22:04 1172417

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.

Figure 3.2.3: Using sequence-type functions with lists.

# Concatenating lists

house_prices = [380000, 900000, 875000] + [225000]

print('There are', len(house_prices), 'prices in the There are 4 prices in the


list.')
list.


Cheapest house: 225000

Most expensive house:


# Finding min, max

900000
print('Cheapest house:', min(house_prices))

print('Most expensive house:', max(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.

zyDE 3.2.2: Student grade statistics.


The following program calculates some information regarding final and
midterm scores. Try enhancing the program by calculating the average
midterm and final scores.
©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

Load default template...


LOUISVILLEMSBAPrep2DaviesWinter2022
 
1 #Program to calculate statistics from student test scores
2 midterm_scores = [99.5, 78.25, 76, 58.5, 100, 87.5, 91, 6
3 final_scores = [55, 62, 100, 98.75, 80, 76.5, 85.25]
4
5 #Combine the scores into a single list
6 all_scores = midterm_scores + final_scores
7
8 num midterm scores = len(midterm scores)
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 16/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
8 num_midterm_scores = len(midterm_scores)
9 num_final_scores = len(final_scores)
10
11 print(num_midterm_scores, 'students took the midterm.')
12 print(num_final_scores, 'students took the final.')
13
14 #Calculate the number of students that took the midterm b
15 dropped_students = num_midterm_scores - num_final_scores
16 print(dropped_students, 'students must have dropped the c
17 ©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

Run LOUISVILLEMSBAPrep2DaviesWinter2022

PARTICIPATION
ACTIVITY 3.2.6:
Using sequence-type functions.

1) Write an expression that


concatenates the list feb_temps to
the end of jan_temps.

Check Show answer

2) Write an expression that finds the


minimum value in the list
total_prices.

Check Show answer

3) Write a statement that assigns the


variable avg_price with the average
of the elements of prices.
©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

Check Show answer

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 ]

©zyBooks 01/03/22 22:04 1172417

What is the value of len(user_ages)? Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

1 2 3 4 5

Check Next

3.3 Tuple basics

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.

©zyBooks 01/03/22 22:04 1172417

Figure 3.3.1: Using tuples. Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 18/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home

white_house_coordinates = (38.8977, Coordinates: (38.8977, 77.0366)

77.0366)
Tuple length: 2

print('Coordinates:',

Latitude: 38.8977 north

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>

# Access tuples via index


TypeError: 'tuple' object does not
print('\nLatitude:', support item assignment
white_house_coordinates[0], 'north')
©zyBooks 01/03/22 22:04 1172417

print('Longitude:', Bharathi Byreddy

white_house_coordinates[1], 'west\n')
LOUISVILLEMSBAPrep2DaviesWinter2022

# Error. Tuples are immutable

white_house_coordinates[1] = 50

PARTICIPATION
ACTIVITY 3.3.1:
Tuples.

1) Create a new variable point that is


a tuple containing the strings 'X
string' and 'Y string'.

Check Show answer

2) If the value of variable friends is


the tuple ('Cleopatra',
'Marc', 'Seneca'), then what is
the result of len(friends)?

Check Show answer

©zyBooks 01/03/22 22:04 1172417

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

©zyBooks 01/03/22 22:04 1172417

368708.2344834.qx3zqy7 Bharathi Byreddy

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.

Figure 3.3.2: Creating named tuples.

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 20/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home

from collections import namedtuple

Car = namedtuple('Car', ['make','model','price','horsepower','seats']) # Create


the named tuple

chevy_blazer = Car('Chevrolet', 'Blazer', 32000, 275, 8) # Use the named tuple


to describe a car

chevy_impala = Car('Chevrolet', 'Impala', 37495, 305, 5) # Use the named tuple


to describe a different car


©zyBooks 01/03/22 22:04 1172417

print(chevy_blazer)
Bharathi Byreddy

print(chevy_impala)
LOUISVILLEMSBAPrep2DaviesWinter2022

Car(make='Chevrolet', model='Blazer', price=32000, horsepower=275, seats=8)

Car(make='Chevrolet', model='Impala', price=37495, horsepower=305, seats=5)

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.

1) Complete the following named


tuple definition that describes a
house.
House =
('House', ['street', ©zyBooks 01/03/22 22:04 1172417

'postal_code', 'country'])
Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022
Check Show answer

2) Create a new named tuple Dog that has the attributes


name, breed, and color.

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

3) Let Address = namedtuple('Address', ['street',


'city', 'country']). Create a new address object house
where house.street is "221B Baker Street", house.city is
"London", and house.country is "England".
©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

Check Show answer LOUISVILLEMSBAPrep2DaviesWinter2022

4) Given the following named tuple


Car = namedtuple('Car',
['make', 'model', 'price',
'horsepower', 'seats']), and
data objects car1 and car2, write
an expression that computes the
sum of the price of both cars.

Check Show answer

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

1 from collections import namedtuple


2
3 Player = ''' Your solution goes here '''
4
5 cam = Player('Cam Newton', '1', 'Quarterback', 'Carolina Panthers')
6 lebron = Player('Lebron James', '23', 'Small forward', 'Los Angeles Lakers')
7 ©zyBooks 01/03/22 22:04 1172417

8 print(cam.name + '(#' + cam.number + ')' + ' is a ' + cam.position + ' for


Bharathi Byreddy
the ' + c
9 LOUISVILLEMSBAPrep2DaviesWinter2022
print(lebron.name + '(#' + lebron.number + ')' + ' is a ' + lebron.position + ' for

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 22/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home

Run

3.4 Set basics ©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

info This section has been set as optional by your instructor.

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().

Figure 3.4.1: Creating sets.

# Create a set using the set() function.

nums1 = set([1, 2, 3])

# Create a set using a set literal.

nums2 = { 7, 8, 9 }
{1, 2, 3}

{7, 8, 9}

# Print the contents of the sets.

print(nums1)

print(nums2)

©zyBooks 01/03/22 22:04 1172417

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

zyDE 3.4.1: Creating sets.

Load default template... Run

1 # Initial list contains some


2 first_names = [ 'Alba', 'Hema
3 ©zyBooks 01/03/22 22:04 1172417

4 # Creating a set removes any Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022
5 names_set = set(first_names)
6
7 print(names_set)
8

PARTICIPATION
ACTIVITY
3.4.1:
Basic sets.

1) What's the result of set(['A',


'Z'])?
A set that contains 'A' and 'Z'.
A list with the following
elements: ['A', 'Z'].
Error: invalid syntax.

2) What's the result of set(10, 20,


25)?
A list with the following
elements: [10, 20, 25].
©zyBooks 01/03/22 22:04 1172417

A set that contains 10, 20, and Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022
25.
Error: invalid syntax.

3) What's the result of set([100, 200,


100, 200, 300])?
A list with the following

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 24/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home

elements: [100, 200, 100,


200, 300].
A set that contains 100, 200, and
300.
A set that contains 100, 200, 300,
another 100, and another 200.
©zyBooks 01/03/22 22:04 1172417

Error: invalid syntax. Bharathi Byreddy

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.

Adding elements to a set:

set.add(value): Add value into the set. Ex: my_set.add('abc')

Remove elements from a set:

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

Table 3.4.1: Some of the methods useful to sets.

Operation Description

len(set) Find the length (number of elements) of the set.

set1.update(set2) Adds the elements in set2 to set1.


©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

set.add(value) Adds value into the set. LOUISVILLEMSBAPrep2DaviesWinter2022

set.remove(value) Removes value from the set. Raises KeyError if value is not found.

set.pop() Removes a random element from the set.

set.clear() Clears all elements from the set.

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.

Write a line of code to complete the following operations.

1) Add the literal 'Ryder' to the set


names.

Check Show answer

2) Add all of the elements of set


goblins into set monsters.

Check Show answer

3) Remove all of the elements from


the trolls set. ©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

Check Show answer

4) Get the number of elements in the


set elves.

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 26/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home

Check Show answer

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.

Sample output with inputs: 'Oliver' 'Atlas'

{ 'Atlas', 'Declan', 'Henry' }

NOTE: Because sets are unordered, the order in which the names in male_names appear
may differ from above.

368708.2344834.qx3zqy7

1 male_names = { 'Oliver', 'Declan', 'Henry' }


2 name_to_remove = input()
3 name_to_add = input()
4
5 ''' Your solution goes here '''
6
7 print(male_names)

©zyBooks 01/03/22 22:04 1172417

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:

Table 3.4.2: Common set theory operations.

. ©zyBooks 01/03/22 22:04 1172417

Operation Bharathi Byreddy

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.

Returns a new set containing all of the unique


set.union(set_a, set_b, set_c...)
elements in all sets.

set.difference(set_a, set_b, Returns a set containing only the elements of set


set_c...) that are not found in any of the provided sets.

Returns a set containing only elements that appear


set_a.symmetric_difference(set_b)
in exactly one of set_a or set_b

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

not in names4. Bharathi Byreddy

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

monsters = {'Gorgon', 'Medusa'}


trolls = {'William', 'Bert', 'Tom'}
horde = {'Gorgon', 'Bert', 'Tom'}

Fill in the code to complete the line that would produce the given set.

1) {'Gorgon', 'Bert', 'Tom',


'Medusa', 'William'} ©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

monsters. (trolls)
LOUISVILLEMSBAPrep2DaviesWinter2022

Check Show answer

2) {'Gorgon'}
monsters. (horde)

Check Show answer

3) {'Medusa', 'Bert', 'Tom'}


monsters.symmetric_difference(
)

Check Show answer

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

Sample output for all_names: Bharathi Byreddy

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

1 male_names = { 'John', 'Bailey', 'Charlie', 'Chuck', 'Michael', 'Samuel', 'Jayden',


2 female_names = { 'Elizabeth', 'Meghan', 'Kim', 'Khloe', 'Bailey', 'Jayden', 'Aiden'
3
4 # Use set methods to create sets all_names, neutral_names, and specific_names.
5
6 ''' Your solution goes here ''' ©zyBooks 01/03/22 22:04 1172417

7 Bharathi Byreddy

8 print(sorted(all_names)) LOUISVILLEMSBAPrep2DaviesWinter2022
9 print(sorted(neutral_names))
10 print(sorted(specific_names))

Run

3.5 Dictionary basics

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

A dictionary is a Python container used to describe associative relationships. A dictionary is


represented by the dict object type. A dictionary associates (or "maps") keys with values. A key is a
term that can be located in a dictionary, such as the word "cat" in the English dictionary. A value
describes some data associated with a key, such as a definition. A key can be any immutable type,
such as a number, string, or tuple; a value can be any type. ©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

A dict object is created using curly braces { } to surround theLOUISVILLEMSBAPrep2DaviesWinter2022


key:value pairs that comprise the
dictionary contents. Ex: players = {'Lionel Messi': 10, 'Cristiano Ronaldo': 7} creates a
dictionary called players with two keys: 'Lionel Messi' and 'Cristiano Ronaldo', associated with the
values 10 and 7 (their respective jersey numbers). An empty dictionary is created with the expression
players = { }.

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.

Figure 3.5.1: Creating a dictionary. ©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

players = {

'Lionel Messi': 10,

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

zyDE 3.5.1: Creating dictionaries.


Run the program below that displays the caffeine content in milligrams
for 100 ml/grams of some popular foods. The indentation and spacing
of the caffeine_content_mg key-value pairs simply provides more
readability. Note that order is maintained in the dict when printed (not
standard before Python 3.7).
Try adding new items into the dictionary, using this U.S. federal
government report on caffeine content.

Load default template... Run

1 caffeine_content_mg = {
2 'Mr. Goodbar chocolate': ©zyBooks 01/03/22 22:04 1172417

3 'Red Bull': 33, Bharathi Byreddy

4 'Monster Hitman Sniper e LOUISVILLEMSBAPrep2DaviesWinter2022


5 'Lipton Brisk iced tea -
6 'dark chocolate coated c
7 'Regular drip or percola
8 'Buzz Bites Chocolate Ch
9 }
10
11 print(caffeine_content_mg)
12
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 31/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home

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 =

Check Show answer

Accessing dictionary entries

Though dictionaries maintain a left-to-right ordering, dictionary entries cannot be accessed by


indexing. To access an entry, the key is specified in brackets [ ]. If no entry with a matching key exists
in the dictionary, then a KeyError runtime error occurs and the program is terminated.

Figure 3.5.2: Accessing dictionary entries.

prices = {'apples': 1.99, 'oranges': 1.49}

The price of apples is 1.99


Traceback (most recent call last):

print('The price of apples is', prices['apples'])


File "<stdin>", line 3, in
print('\nThe price of lemons is', <module>

prices['lemons'])
KeyError: 'lemons'

©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022
PARTICIPATION
ACTIVITY 3.5.2:
Accessing dictionary entries.

1) A dictionary entry is accessed by


placing a key in curly braces { }.
True

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 32/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home

False

2) Dictionary entries are ordered by


position.
True
False
©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

Adding, modifying, and removing dictionary entries


LOUISVILLEMSBAPrep2DaviesWinter2022

A dictionary is mutable, so entries can be added, modified, and deleted as necessary by a


programmer. A new dictionary entry is added by using brackets to specify the key:
prices['banana'] = 1.49. A dictionary key is unique – attempting to create a new entry with a key
that already exists in the dictionary replaces the existing entry. The del keyword is used to remove
entries from a dictionary: del prices['papaya'] removes the entry whose key is 'papaya'. If the
requested key to delete does not exist then a KeyError occurs.

Adding new entries to a dictionary:

dict[k] = v: Adds the new key-value pair k-v, if dict[k] does not already exist.

Example: students['John'] = 'A+'

Modifying existing entries in a dictionary:

dict[k] = v: Updates the existing entry dict[k], if dict[k] already exists.

Example: students['Jessica'] = 'A+'

Removing entries from a dictionary:

del dict[k]: Deletes the entry dict[k].

Example: del students['Rachel']

Figure 3.5.3: Adding and editing dictionary entries.

prices = {} # Create empty dictionary

prices['banana'] = 1.49 # Add new entry

print(prices)
©zyBooks 01/03/22 22:04 1172417


Bharathi1.49}

{'banana': Byreddy

prices['banana'] = 1.69 # Modify entry

LOUISVILLEMSBAPrep2DaviesWinter2022
{'banana': 1.69}

print(prices)
{}

del prices['banana'] # Remove entry

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.

1) Which statement adds 'pears' to the


following dictionary?

prices = {'apples': 1.99,


'oranges': 1.49, 'kiwi': 0.79}

©zyBooks 01/03/22 22:04 1172417

prices['pears'] = 1.79 Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022
prices['pears': 1.79]

2) Executing the following statements


produces a KeyError:

prices = {'apples': 1.99,


'oranges': 1.49, 'kiwi': 0.79}

del prices['limes']

True
False

3) Executing the following statements


adds a new entry to the dictionary:

prices = {'apples': 1.99,


'oranges': 1.49, 'kiwi': 0.79}

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:

Acura made in Japan

Fiat made in Italy

Tesla made in USA


©zyBooks 01/03/22 22:04 1172417


Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

368708.2344834.qx3zqy7

1 car_makers = {'Acura': 'Japan', 'Fiat': 'Egypt'}


2
3 # Add the key Tesla with value USA to car_makers
4 # Modify the car maker of Fiat to Italy
5
6 ''' Your solution goes here '''
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 34/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
6 Your solution goes here
7
8 print('Acura made in', car_makers['Acura'])
9 print('Fiat made in', car_makers['Fiat'])
10 print('Tesla made in', car_makers['Tesla'])

©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

Run

3.6 Common data types summary


The most common Python types are presented below.

Common data types

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.

Table 3.6.1: Common data types.

Type Notes

int Numeric type: Used for variable-width integers.

float Numeric type: Used for floating-point numbers.

©zyBooks 01/03/22 22:04 1172417

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.

Table 3.6.2: Containers: sequence and mapping types.


©zyBooks 01/03/22 22:04 1172417

Type Notes Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022
string Sequence type: Used for text.

list Sequence type: A mutable container with ordered elements.

tuple Sequence type: An immutable container with ordered elements.

set Set type: A mutable container with unordered and unique elements.

dict Mapping type: A container with key-values associated elements.

PARTICIPATION
ACTIVITY
3.6.1:
Common data types.

1) The list ['a', 'b', 3] is invalid


because the list contains a mix of
strings and integers.
True
False

2) int and float types can always hold the


exact same values.
True
False

3) A sorted collection of integers might


best be contained in a list. ©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

True LOUISVILLEMSBAPrep2DaviesWinter2022

False

Choosing a container type

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.

1) Student test scores that may later be


adjusted, ordered from best to worst.
list
tuple
dict

2) A single student's name and their final


grade in the class.
list
tuple
dict

3) Names and current grades for all


students in the class.
list
tuple
dict

PARTICIPATION
ACTIVITY 3.6.3:
Finding errors in container code.

Click on the error.


©zyBooks 01/03/22 22:04 1172417


Bharathi Byreddy

1) # Student grade program LOUISVILLEMSBAPrep2DaviesWinter2022

students = ['Jo', 'Bob',

'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 = {}

# Get student name, grade

name = input('name:')

grade = input('grade:')# Assign grade

©zyBooks 01/03/22 22:04 1172417

grades.append(name) = grade
Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

2)
workers = ('Jo', 'Amy')

# Remove Amy from workers

del workers[1]

# Print worker at index 0

print('Jo:', workers[0])

3.7 Additional practice: Grade calculation

info This section has been set as optional by your instructor.

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

zyDE 3.7.1: Grade calculator: Average score onLOUISVILLEMSBAPrep2DaviesWinter2022


three exams.

Load default template...

1 exam1_grade = float(input('Enter score on Exam 1 (out of 100


2 exam2_grade = float(input('Enter score on Exam 2 (out of 100
3 exam3_grade = float(input('Enter score on Exam 3 (out of 100
4
5 ll d ( 1 d 2
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print
d 3 d ) / 38/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
5 overall_grade = (exam1_grade + exam2_grade + exam3_grade) /
6
7 print('Your overall grade is:', overall_grade)
8

©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

70

75

91

Run

Create a different version of the program that:

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.

©zyBooks 01/03/22 22:04 1172417

3.8 Type conversions Bharathi Byreddy

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

1 + 2 returns an integer type. Bharathi Byreddy

1 + 2.0 returns a float type. LOUISVILLEMSBAPrep2DaviesWinter2022

1.0 + 2.0 returns a float type.

int-to-float conversion is straightforward: 25 becomes 25.0.


float-to-int conversion just drops the fraction: 4.9 becomes 4.

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

Check Show answer

2) item_weight * num_items

Check Show answer

3) (num_items + num_items) *
item_weight ©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

Check Show answer

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:

Table 3.8.1: Conversion functions for some common types.

Function Notes Can ©zyBooks


convert: 01/03/22 22:04 1172417

Bharathi Byreddy

int() Creates integers LOUISVILLEMSBAPrep2DaviesWinter2022


int, float, strings w/ integers only

float() Creates floats int, float, strings w/ integers or fractions

str() Creates strings Any

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.

zyDE 3.8.1: Simple example of converting float and int types.


Run the below program. Observe how the type conversion affects the
entered number. Change the input to 18.552 and run the program
again.

18

Load default template...


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

5 print('original input text:', LOUISVILLEMSBAPrep2DaviesWinter2022


6 print('input text converted t
7 print('float variable convert
8

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

What is the result of each expression? LOUISVILLEMSBAPrep2DaviesWinter2022

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

Type the program's output


©zyBooks 01/03/22 22:04 1172417

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.

Sample output for inputs: 1 2 4


©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

Average owls per zoo: 2 LOUISVILLEMSBAPrep2DaviesWinter2022

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.

Assign total_owls with the sum of num_owls_A and num_owls_B.

©zyBooks 01/03/22 22:04 1172417

Sample output with inputs: 3 4 Bharathi Byreddy

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)

©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

Run

3.9 String formatting

Formatted string literals (f-strings)

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

The first expression is evaluated and the value of the Bharathi


number Byreddy
variable

6 is
substituted into the string.
LOUISVILLEMSBAPrep2DaviesWinter2022
The second expression is evaluated and the value of the amount variable 32 is
substituted into the string. The resulting string literal is '6 burritos cost
$32'.

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.

Select the option that correctly prints the given output.


Assume the following
©zyBooks code
01/03/22 is defined.
22:04 1172417

Bharathi Byreddy

num_items = 3
LOUISVILLEMSBAPrep2DaviesWinter2022
cost_taco = 1.25

1) I need 3 items please.

print(f'I need {num_items}


please')

print(f'{I need num_items


items please}')

print('I need {num_items}


items please')

print(f'I need {num_items}


items please')

2) 3 tacos cost 3.75

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

Additional f-string features ©zyBooks 01/03/22 22:04 1172417

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

Table 3.9.1: f-string examples.

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.

Enter the final value of output.

1) output = f'{2*2}'

Check Show answer

2) output = f'{2*2=}'

Check Show answer

©zyBooks 01/03/22 22:04 1172417

3) kids = 4
Bharathi Byreddy

adults = 2
LOUISVILLEMSBAPrep2DaviesWinter2022
output = f'{kids+adults}
total'

Check Show answer

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'

Check Show answer


©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

5) output = f'{{2}} + {{3}} = LOUISVILLEMSBAPrep2DaviesWinter2022


{{5}}'

Check Show answer

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.

Table 3.9.2: Common format specification presentation types.

'
©zyBooks 01/03/22 22:04 1172417

Type Description Example Bharathi Byreddy

Output
LOUISVILLEMSBAPrep2DaviesWinter2022
String (default presentation name = 'Aiden'

s print(f'{name:s}')
Aiden
type - can be omitted)

number = 4

d Decimal (integer values only) print(f'{number:d}')


4

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 47/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home

b Binary (integer values only) number = 4


100
print(f'{number:b}')

Hexadecimal in lowercase (x)


number = 31

x, X and uppercase (X) (integer print(f'{number:x}')


1f
values only)
©zyBooks 01/03/22 22:04 1172417

number = 44
Bharathi Byreddy

e Exponent notation print(f'{number:e}')


4.400000e+01
LOUISVILLEMSBAPrep2DaviesWinter2022

Fixed-point notation (6 places number = 4

f print(f'{number:f}')
4.000000
of precision)

Fixed-point notation
number = 4

.[precision]f (programmer-defined print(f'{number:.2f}')


4.00
precision)

number = 4

0[precision]d Leading 0 notation print(f'{number:03d}')


004

PARTICIPATION
ACTIVITY 3.9.4:
Format specifications and presentation types.

Enter the most appropriate format specification to produce the desired output.

1) The value of num as a decimal


(base 10) integer: 31
num = 31

print(f'{num: }')

Check Show answer

2) The value of num as a hexadecimal


(base 16) integer: 1f
©zyBooks 01/03/22 22:04 1172417

num = 31
Bharathi Byreddy

print('{num: }')
LOUISVILLEMSBAPrep2DaviesWinter2022

Check Show answer

3) The value of num as a binary (base


2) integer: 11111

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

Check Show answer

CHALLENGE
ACTIVITY
3.9.1:
String formatting with f-strings.
©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

368708.2344834.qx3zqy7
LOUISVILLEMSBAPrep2DaviesWinter2022

Start

Type the program's output

name = 'Ron'

print(f'My name is {name}')

1 2 3 4 5

Check Next

CHALLENGE
ACTIVITY 3.9.2:
Printing an f-string.

Write a single statement to print: user_word,user_number. Note that there is no space


between the comma and user_number.

Sample output with inputs: Amy 5

Amy,5

368708.2344834.qx3zqy7 ©zyBooks 01/03/22 22:04 1172417

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

Run ©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

CHALLENGE
ACTIVITY
3.9.3:
String formatting.

368708.2344834.qx3zqy7

Start

Select the most appropriate replacement field definitions.

num_students = 90

print(f'The math class has students.')


The math class has 90 students.

1 2 3

Check Next
©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

3.10 Binary numbers


https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 50/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home

info This section has been set as optional by your instructor.

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.

Table 3.10.1: Decimal numbers use weighed powers of 10.

Decimal number with 3


Representation
digits

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

©zyBooks 01/03/22 22:04 1172417

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.

1) Convert the binary number


00001111 to a decimal number.

Check Show answer

2) Convert the binary number


10001000 to a decimal number.

Check Show answer

©zyBooks 01/03/22 22:04 1172417

3) Convert the decimal number 17 to Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022
an 8-bit binary number.

Check Show answer

4) Convert the decimal number 51 to

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 52/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home

an 8-bit binary number.

Check Show answer

CHALLENGE ©zyBooks 01/03/22 22:04 1172417

ACTIVITY
3.10.1:
Create a binary number. Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022
368708.2344834.qx3zqy7

Start

Match the decimal value in binary.

0 0 0
0

1 2 3

Check Next

3.11 Additional practice: Health data


©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

info This section has been set as optional by your instructor.


LOUISVILLEMSBAPrep2DaviesWinter2022

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

zyDE 3.11.1: Health data: Age in days.

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

Create a different version of the program that:

1. Calculates the user's age in minutes and seconds.


2. Estimates the approximate number of times the user's heart has beat in his/her lifetime using
an average heart rate of 72 beats per minute.
3. Estimates the number of times the person has sneezed in his/her lifetime.
4. Estimates the number of calories that the person has expended in his/her lifetime (research on
the Internet to obtain a daily estimate). Also calculate the number of sandwiches (or other
common food item) that equals that number of calories.
5. Be creative: Pick several other interesting health-related statistics. Try searching the Internet to
determine how to calculate that data, and create a program to perform that calculation. The
program can ask the user to enter any information needed to perform the calculation.

3.12 LAB: Warm up: Creating passwords


©zyBooks 01/03/22 22:04 1172417

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)

Ex: If the input is:

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

the output after the prompts is:

You entered: yellow Daisy 6


©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

Note: User input is not part of the program output. LOUISVILLEMSBAPrep2DaviesWinter2022

(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).

Ex: If the input is:

yellow

Daisy

the output after the prompts is:

You entered: yellow Daisy 6

First password: yellow_Daisy

Second password: 6yellow6

(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

First password: yellow_Daisy

Second password: 6yellow6

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 55/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home

Number of characters in yellow_Daisy: 12

Number of characters in 6yellow6: 8

NaN.2344834.qx3zqy7

LAB
ACTIVITY
3.12.1:
LAB: Warm up: Creating passwords 0/5

©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

main.py Load default template...


LOUISVILLEMSBAPrep2DaviesWinter2022

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

Run your program as often as you'd like, before submitting


Develop mode Submit mode
for grading. Below, type any needed input values in the first
box, then click Run program and observe the program's
output in the second box.
Enter program input (optional)
If your code requires input values, provide them here.

trending_flat trending_flat
main.py
Run program Input (from above) Outp
(Your program)

Program output displayed here ©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

Coding trail of your work What is this?

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

3.13 LAB: Input and formatted output: Caffeine


levels ©zyBooks 01/03/22 22:04 1172417

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

the output is:

After 6 hours: 50.00 mg

After 12 hours: 25.00 mg

After 24 hours: 6.25 mg

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

main.py Load default template...

1 caffeine_mg = float(input()) ©zyBooks 01/03/22 22:04 1172417

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

Run your program as often as you'd like, before submitting


Develop mode Submit mode ©zyBooks 01/03/22 22:04 1172417

for grading. Below, type any needed input values in the first
Bharathi Byreddy

box, then click Run program and observe the program's


LOUISVILLEMSBAPrep2DaviesWinter2022
output in the second box.
Enter program input (optional)
If your code requires input values, provide them here.

trending_flat trending_flat
main.py
Run program Input (from above)
(Your program)
Outp

Program output displayed here

Coding trail of your work What is this?

History of your effort will appear here once you begin working
on this zyLab.

3.14 LAB: Simple statistics


Given 4 floating-point numbers. Use a string formatting expression with conversion specifiers to
output their product and their average as integers (rounded), then as floating-point numbers.

Output each rounded integer using the following:


©zyBooks 01/03/22 22:04 1172417

print(f'{your_value:.0f}') Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022
Output each floating-point value with three digits after the decimal point, which can be achieved as
follows:

print(f'{your_value:.3f}')

Ex: If the input is:

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

the output is:


©zyBooks 01/03/22 22:04 1172417

2072 7
Bharathi Byreddy

2071.680 7.125
LOUISVILLEMSBAPrep2DaviesWinter2022

NaN.2344834.qx3zqy7

LAB
ACTIVITY
3.14.1:
LAB: Simple statistics 0 / 10

main.py Load default template...

1 num1 = float(input())
2 num2 = float(input())
3 num3 = float(input())
4 num4 = float(input())
5
6 ''' Type your code here. '''
7

Run your program as often as you'd like, before submitting


Develop mode Submit mode
for grading. Below, type any needed input values in the first
box, then click Run program and observe the program's
output in the second box.
Enter program input (optional) ©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

If your code requires input values, provide them here. LOUISVILLEMSBAPrep2DaviesWinter2022

trending_flat trending_flat
main.py
Run program Input (from above) Outp
(Your program)

Program output displayed here

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 59/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home

Coding trail of your work What is this?

History of your effort will appear here once you begin working
on this zyLab.
©zyBooks 01/03/22 22:04 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

3.15 LAB*: Program: Painting a wall


Output each floating-point value with two digits after the decimal point, which can be achieved as
follows:

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

Enter wall height (feet):

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

Enter wall height (feet):

12
Enter wall width (feet):

15 ©zyBooks 01/03/22 22:04 1172417

Wall area: 180 square feet


Bharathi Byreddy

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

Enter wall height (feet):

12
Enter wall width (feet):

15
Wall area: 180 square feet

Paint needed: 0.51 gallons

Cans needed: 1 can(s)


©zyBooks 01/03/22 22:04 1172417

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

Enter wall height (feet):

12
Enter wall width (feet):

15
Wall area: 180 square feet

Paint needed: 0.51 gallons

Cans needed: 1 can(s)

Choose a color to paint the wall:

red

Cost of purchasing red paint: $35

NaN.2344834.qx3zqy7

LAB
ACTIVITY
3.15.1:
LAB*: Program: Painting a wall 0/8

main.py Load default template...

 
1 import math
2
3 # Dictionary of paint colors and cost per gallon
4 paint_colors = { ©zyBooks 01/03/22 22:04 1172417

5 'red': 35, Bharathi Byreddy

6 'blue': 25, LOUISVILLEMSBAPrep2DaviesWinter2022


7 'green': 23
8 }
9
10 # FIXME (1): Prompt user to input wall's width
11 # Calculate and output wall area
12 wall_height = int(input('Enter wall height (feet):\n'))
13 print('Wall area:')
14
15 # FIXME (2): Calculate and output the amount of paint in gallons needed to paint th
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 61/62
1/3/22, 10:05 PM MSBA Prep 2: Python Prep home
15 # FIXME (2): Calculate and output the amount of paint in gallons needed to paint th
16
17 # FIXME (3): Calculate and output the number of 1 gallon cans needed to paint the w

Run your program as often as you'd like, before submitting


Develop mode Submit mode
for grading. Below, type any needed input values in the first
box, then click Run program and observe the program's
output in the second box.
©zyBooks 01/03/22 22:04 1172417

Enter program input (optional) Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022
If your code requires input values, provide them here.

trending_flat trending_flat
main.py
Run program Input (from above) Outp
(Your program)

Program output displayed here

Coding trail of your work What is this?

History of your effort will appear here once you begin working
on this zyLab.

3.16 LAB: List basics

visibility_off This section's content is not available for print.

©zyBooks 01/03/22 22:04 1172417

3.17 LAB: Set basics Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

visibility_off This section's content is not available for print.

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/3/print 62/62

You might also like