Programming ZyBooks3
Programming ZyBooks3
©zyBooksreferences
A container is a construct used to group related values together and contains 02/27/24 20:07 1927475
to other ©zyBooks 02/27/24 20:07 1927475
Daniel Reyes Daniel Reyes
objects instead of data. A list is a container created by surrounding a sequence of variables or
CS119-2402A-06-2402A literals CS119-2402A-06-2402A
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.1.1: Creating lists.
PARTICIPATION
ACTIVITY
3.1.2: Creating lists.
prices 0 1 2
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©zyBooks
element in a list. 20:07 1927475
02/27/24 ©zyBooks 02/27/24 20:07 1927475
Daniel Reyes Daniel Reyes
A list's index must be an integer. The index cannot be a floating-point type, CS119-2402A-06-2402A
even if the value is a whole CS119-2402A-06-2402A
number like 0.0 or 1.0. Using any type besides an integer will produce a runtime error and the program
will terminate.
Run
Figure 3.1.1: Access list elements using an indexing expression.
View your last submission keyboard_arrow_down
# Some of the most expensive cars in the world
lamborghini_veneno = 3900000 # $3.9 million! Updating list elements
bugatti_veyron = 2400000 # $2.4 million!
aston_martin_one77 = 1850000 # $1.85 million!
Lamborghini Veneno: 3900000 Lists are mutable, meaning that a programmer can change a list's contents. An element can be updated
prices = [lamborghini_veneno, bugatti_veyron, dollars
aston_martin_one77] Bugatti Veyron Super Sport: with a new value by performing an assignment to a position in the list.
2400000 dollars
print('Lamborghini Veneno:', prices[0], 'dollars') Aston Martin One-77: 1850000
print('Bugatti Veyron Super Sport:', prices[1], dollars
'dollars') Figure 3.1.2: Updating list elements.
print('Aston Martin One-77:', prices[2],
'dollars')
Initialize the list short_names with strings 'Gus', 'Bob', and 'Zoe'. Sample output for the given
program:
Gus PARTICIPATION
ACTIVITY
3.1.3: Accessing and updating list elements.
Bob
Zoe ©zyBooks 02/27/24 20:07 1927475 ©zyBooks 02/27/24 20:07 1927475
Daniel Reyes 1) Write a statement that assigns Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
my_var with the 3rd element of
my_list.
Learn how our autograder works
550678.3854950.qx3zqy7
1 short_names = ''' Your solution goes here ''' Check Show answer
2
3 print(short_names[0])
( )
https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 3/45 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 4/45
2/27/24, 8:07 PM zyBooks 2/27/24, 8:07 PM zyBooks
Since lists are mutable, a programmer can also use methods to add and remove elements. A method PARTICIPATION
ACTIVITY 3.1.5: List modification.
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
Write a statement that performs the desired action. Assume the list
be removed using the pop() or remove() methods. Methods are covered in greater detail in another
house_prices = ['$140,000', '$550,000', '$480,000'] exists.
section.
my_list.remove('abc')
print('After remove:', my_list) ©zyBooks 02/27/24 20:07 1927475 Check Show answer ©zyBooks 02/27/24 20:07 1927475
Daniel Reyes Daniel Reyes
[10, 'bw'] CS119-2402A-06-2402A CS119-2402A-06-2402A
After append: [10, 'bw', 'abc']
After pop: [10, 'abc']
After remove: [10]
Table 3.1.1: Some of the functions and methods useful to lists. zyDE 3.1.2: Student grade statistics.
The following program calculates some information regarding final and
Operation Description midterm scores. Try enhancing the program by calculating the average
midterm and final scores.
len(list) Find the length of the list.
Load default template...
list1 + list2 Produce a new list by concatenating list2 to the end of list1.
1 #Program to calculate statistics from student test scores.
min(list) Find the element in list with the smallest value. 2 midterm_scores = [99.5, 78.25, 76, 58.5, 100, 87.5, 91, 68
3 final_scores = [55, 62, 100, 98.75, 80, 76.5, 85.25]
max(list) Find the element in list with the largest value. 4
5 #Combine the scores into a single list
6 all_scores = midterm_scores + final_scores
sum(list) Find the sum of all elements of a list (numbers only). 7
8 num_midterm_scores = len(midterm_scores)
Find the index of the first element in list whose value 9 num_final_scores = len(final_scores)
list.index(val) 10
matches val.
11 print(num_midterm_scores, 'students took the midterm.')
12 print(num_final_scores, 'students took the final.')
list.count(val) Count the number of occurrences of the value val in list. 13
14 #Calculate the number of students that took the midterm bu
15 dropped_students = num_midterm_scores - num_final_scores
16 print(dropped_students, 'students must have dropped the cl
17
©zyBooks 02/27/24 20:07 1927475 ©zyBooks 02/27/24 20:07 1927475
Daniel Reyes Run Daniel Reyes
Figure 3.1.3: Using sequence-type functions with lists. CS119-2402A-06-2402A CS119-2402A-06-2402A
A tuple, usually pronounced "tuhple" or "toople", behaves similar to a list but is immutable – once
1) Write an expression that
created the tuple's elements cannot be changed. A tuple is also a sequence type, supporting len(),
concatenates the list feb_temps to
indexing, and other sequence type functions. A new tuple is generated by creating a list of comma-
the end of jan_temps.
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.
©zyBooks 02/27/24 20:07 1927475 ©zyBooks 02/27/24 20:07 1927475
Daniel Reyes Daniel Reyes
A tuple is not as common as a list in practical usage, but can be useful when a programmer wants to
Check Show answer CS119-2402A-06-2402A CS119-2402A-06-2402A
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
2) Write an expression that finds the landmark because a programmer knows that the first element should be the latitude, the second
minimum value in the list prices. element should be the longitude, and the landmark will never move from those coordinates.
550678.3854950.qx3zqy7
Start PARTICIPATION
ACTIVITY
3.1.7: Tuples.
Check Next
Check Show answer ©zyBooks 02/27/24 20:07 1927475 While loop: Basics ©zyBooks 02/27/24 20:07 1927475
Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
A while loop is a construct that repeatedly executes an indented block of code (known as the loop body)
as long as the loop's expression is True. At the end of the loop body, execution goes back to the while
CHALLENGE
ACTIVITY 3.1.3: Initialize a tuple. loop statement and the loop expression is evaluated again. If the loop expression is True, the loop body
is executed again. But, if the expression evaluates to False, then execution instead proceeds to below
Initialize the tuple team_names with the strings 'Rockets', 'Raptors', 'Warriors', and 'Celtics' the loop body. Each execution of the loop body is called an iteration, and looping is also called iterating.
(The top-4 2018 NBA teams at the end of the regular season in order). Sample output for the
given program:
Construct 3.2.1: While loop.
Rockets
Raptors while expression: # Loop expression
# Loop body: Sub-statements to execute
Warriors
# if the loop expression evaluates to True
Celtics
# Statements to execute after the expression evaluates to
False
550678.3854950.qx3zqy7
PARTICIPATION
1 team_names = ''' Your solution goes here ''' ACTIVITY 3.2.1: While loop.
2
3 print(team_names[0])
4 print(team_names[1])
5 print(team_names[2])
6 print(team_names[3]) Input Python interpreter
curr_power = 2 yyn 8 curr_power
user_char = 'y'
'n' user_char
while user_char == 'y': Output
print(curr_power)
curr_power = curr_power * 2 2
user_char = input() 4
8
©zyBooks 02/27/24 20:07 1927475 print('Done') Done ©zyBooks 02/27/24 20:07 1927475
Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
Run
Animation captions:
View your last submission keyboard_arrow_down
1. When encountered, a while loop's expression is evaluated. If true, the loop's body is entered. Example: While loop with a sentinel value
Here, user_char was initialized with 'y', so user_char == 'y' is true.
2. Thus, the loop body is executed, which outputs curr_power's current value of 2, doubles The following example uses the statement while user_value != 'q': to allow a user to end a
curr_power, and gets the next input. face-drawing program by entering the character 'q'. The letter 'q' in this case is a sentinel value, a value
3. Execution jumps back to the while part. user_char is 'y' (the first input), so user_char == 'y' is that when evaluated by the loop expression causes the loop to terminate.
true, and the loop body executes (again), outputting 4.
The code print(user_value*5) produces a new string, which repeats the value of user_value 5
4. user_char is 'y' (the second user input), so user_char == 'y' is true, and the loop body executes (a
©zyBooks 02/27/24 20:07 1927475 times. In this case, the value of user_value may be "-", thus the result of the multiplication
©zyBooks is "-----".
02/27/24 20:07 1927475
third time), outputting 8. Daniel Reyes Daniel Reyes
Another valid (but long and visually unappealing) method is the statement
5. user_char is now 'n', so user_char == 'y' is false. Thus, execution jumps to after the loop, which
CS119-2402A-06-2402A CS119-2402A-06-2402A
print('{}{}{}{}{}'.format(user_value, user_value, user_value, user_value, us
outputs "Done".
Note that input may read in a multi-character string from the user, so only the first character is
extracted from user_input with user_value = user_input[0].
PARTICIPATION
ACTIVITY
3.2.2: Basic while loops.
Once execution enters the loop body, execution continues to the body's end even if the expression
becomes False midway through.
How many times will the loop body execute?
1) x = 3
Figure 3.2.1: While loop example: Face-printing program that ends when
while x >= 1:
# Do something
x = x - 1
user enters 'q'.
- -
0
Check Show answer
-----
nose = '0' # Looks a little like a nose
user_value = '-'
Enter a character ('q' for
2) Assume user would enter 'n', then 'n', while user_value != 'q': quit): x
print(' {} {} '.format(user_value, user_value)) # x x
then 'y'. Print eyes 0
print(' {} '.format(nose)) # Print nose xxxxx
# Get character from user here
while user_char != 'n': print(user_value*5) # Print mouth
# Do something print('\n')
# Get character from user here Enter a character ('q' for
# Get new character for eyes and mouth quit): @
user_input = input("Enter a character ('q' for @ @
quit): \n") 0
user_value = user_input[0] @@@@@
Complete the loop expressions, using a single operator in your expression. Use the most
Check Show answer
straightforward translation of English to an expression.
while :
3) Iterate while c equals 'g'. 1. User enters the number 902. The first iteration prints "2".
while : 2. The second iteration prints "0".
3. The third iteration prints "9", so every digit has been printed. The loop condition is checked one
# Loop body statements go
here more time, and since num is 0, the loop stops.
A program with an infinite loop may print output excessively, or just seem to stall (if the loop contains
The following program animation provides another loop example. First, the user
©zyBooks enters an
02/27/24 integer.
20:07 Then,
1927475 ©zyBooks 02/27/24 20:07 1927475
Daniel Reyes no printing). A user can halt a program by pressing Control-C in the command prompt running the
Daniel Reyes
the loop prints each digit one at a time starting from the right, using "% 10" to get the rightmost digit and
CS119-2402A-06-2402A Python program. Alternatively, some IDEs have a "Stop" button. CS119-2402A-06-2402A
"// 10" to remove that digit. The loop is only entered while num is greater than 0; once num reaches 0,
the loop will have printed all digits.
zyDE 3.2.1: While loop example: Ancestors printing program.
PARTICIPATION
ACTIVITY
3.2.4: While loop step-by-step.
Run the program below.
2) x = 5
Load default template... y = 18
while y >= x:
print(y, end=' ')
1 year_considered = 2020 # Year being considered y = y - x
2 num_ancestors = 2 # Approx. ancestors in considered year
3 years_per_generation = 20 # Approx. years per generation
4
5 user_year = int(input('Enter a past year (neg. for B.C.): ')
6 print() Check Show answer
7 ©zyBooks 02/27/24 20:07 1927475 ©zyBooks 02/27/24 20:07 1927475
Daniel Reyes Daniel Reyes
8 while year_considered >= user_year:
CS119-2402A-06-2402A CS119-2402A-06-2402A
9 print('Ancestors in {}: {}'.format(year_considered, num_ 3) x = 10
10 while x != 3:
11 num_ancestors = num_ancestors * 2 print(x, end=' ')
x = x / 2
12 year_considered = year_considered - years_per_generation
13
1945
4) x = 1
y = 3
z = 5
while not (y < x < z):
print(x, end=' ')
Run x = x + 1
CHALLENGE
PARTICIPATION 3.2.1: Enter the output of the while loop.
ACTIVITY 3.2.5: While loop iterations. ACTIVITY
550678.3854950.qx3zqy7
What is the output of the following code? (Use "IL" for infinite loops.)
Start
1) x = 0
while x > 0:
print(x, end=' ') Type the program's output
x = x - 1
print('Bye')
g = 0
0
©zyBooks 02/27/24 20:07 1927475 ©zyBooks 02/27/24 20:07 1927475
Daniel Reyes
1 Daniel Reyes
while g <= 2:
Check Show answer CS119-2402A-06-2402A print(g) 2 CS119-2402A-06-2402A
g += 1
1 2
Check Next
Write a while loop that repeats while user_num ≥ 1. In each loop iteration, divide user_num by
2, then print user_num.
CHALLENGE
ACTIVITY
3.2.2: Basic while loop with user input.
Sample output with input: 20
Write an expression that executes the loop body as long as the user enters a non-negative 10.0
number. 5.0
©zyBooks 02/27/24 20:07 1927475 2.5 ©zyBooks 02/27/24 20:07 1927475
Daniel Reyes Daniel Reyes
Note: If the submitted code has an infinite loop, the system will stop running the code after a
CS119-2402A-06-2402A 1.25 CS119-2402A-06-2402A
few seconds and report "Program end never reached." The system doesn't print the test case 0.625
that caused the reported message.
1 user_num = int(input())
2
Learn how our autograder works
3 ''' Your solution goes here '''
550678.3854950.qx3zqy7
4
1 user_num = int(input())
2 while ''' Your solution goes here ''':
3 print('Body')
4 user_num = int(input())
5
6 print('Done.')
Run
A common programming task is to access all of the elements in a container. Ex: Printing every item in a position of the elements in the container, starting with position 0 (the leftmost element) and continuing
list. A for loop statement loops over each element in a container one at a time, assigning a variable with until the last element is reached.
the next element that can then be used in the loop body. The container in the for loop statement is
Iterating over a dictionary using a for loop assigns the loop variable with the keys of the dictionary. The
typically a list, tuple, or string. Each iteration of the loop assigns the name given in the for loop
values can then be accessed using the key.
statement with the next element in the container.
Figure 3.3.1: A for loop assigns the loop variable with ©zyBooks
a dictionary's keys.
Construct 3.3.1 ©zyBooks 02/27/24 20:07 1927475 02/27/24 20:07 1927475
Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
for variable in container: channels = {
# Loop body: Sub-statements to execute 'MTV': 35, MTV is on channel
# for each item in the container 'CNN': 28, 35
'FOX': 11, CNN is on channel
# Statements to execute after the for loop is 'NBC': 4, 28
complete 'CBS': 12 FOX is on channel
} 11
NBC is on channel 4
for c in channels: CBS is on channel
print('{} is on channel {}'.format(c, 12
channels[c]))
PARTICIPATION
ACTIVITY
3.3.1: Iterating over a list using a for loop.
A for loop can also iterate over a string. Each iteration assigns the loop variable with the next character
of the string. Strings are sequence types just like lists, so the behavior is identical (leftmost character
name: 'John' first, then each following character).
for name in ['Bill', 'Nicole', 'John']:
print('Hi {}!'.format(name))
Animation captions:
©zyBooks
1. The first iteration assigns the variable name with 'Bill' and prints 'Hi Bill!'02/27/24 20:07 1927475
to the screen. ©zyBooks 02/27/24 20:07 1927475
PARTICIPATION
Daniel Reyes 3.3.2: Creating for loops. Daniel Reyes
2. The second iteration assigns the variable name with 'Nicole' and prints 'Hi Nicole!'.
CS119-2402A-06-2402A
ACTIVITY
CS119-2402A-06-2402A
3. The third iteration assigns the variable name with 'John' and prints 'Hi John!'.
Complete the for loop statement by giving the loop variable and container.
The for loop above iterates over the list ['Bill', 'Nicole', 'John']. The first iteration assigns
the variable name with 'Bill', the second iteration assigns name with 'Nicole', and the final iteration
assigns name with 'John'. For sequence types like lists and tuples, the assignment order follows the
The following program first prints a list that is ordered alphabetically, then prints the same list
For loop examples
in reverse order.
For loops can be used to perform some action during each loop iteration. A simple example would be
names = [
printing the value, as above examples demonstrated. The program below uses an additional variable to 'Biffle',
sum list elements to calculate weekly revenue and an average daily revenue. 'Bowyer',
'Busch',
'Gordon',
'Patrick'
Biffle | Bowyer | Busch | Gordon | Patrick |
Figure 3.3.3: For loop example: Calculating shop revenue. ]
Printing in reverse:
for name in names: Patrick | Gordon | Busch | Bowyer | Biffle |
print(name, '|', end=' ')
print('\nPrinting in reverse:')
for name in reversed(names):
print(name, '|', end=' ')
©zyBooks 02/27/24 20:07 1927475 ©zyBooks 02/27/24 20:07 1927475
Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
PARTICIPATION
ACTIVITY
3.3.3: For loops.
CHALLENGE
Check Show answer 3.3.1: Looping over strings, lists, and dictionaries.
ACTIVITY
num_neg = 0
for temp in temperatures: grey
if temp < 0: gold
colors = ['grey', 'gold', 'blue', 'red']
for color in colors: blue
print(color)
red
Check Show answer
for scr in
:
if scr > 80:
print scr
©zyBooks 02/27/24 20:07 1927475
Daniel Reyes 3.4 While vs. for loops
©zyBooks 02/27/24 20:07 1927475
Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
Both for loops and while loops can be used to count a specific number of loop iterations. A for loop
combined with range() is generally preferred over while loops, since for loops are less likely to become
stuck in an infinite loop situation. A programmer may easily forget to increment a while loop's variable
(causing an infinite loop), but for loops iterate over a finite number of elements in a container and are 1) Iterate as long as the user-entered
thus guaranteed to complete. string c is not q.
while
PARTICIPATION
ACTIVITY
3.4.1: While/for loop correspondence. for
1. A for loop and range function can replace a while loop. Nested loops
2. A more concise for loop uses a single argument for range().
A nested loop is a loop that appears as part of the body of another loop. The nested loops are
commonly referred to as the outer loop and inner loop.
As a general rule:
Nested loops have various uses. One use is to generate all combinations of some items. Ex: The
1. Use a for loop when the number of iterations is computable before entering the loop, as when following program generates all two letter .com Internet domain names. Recall that ord() converts a
counting down from X to 0, printing a string N times, etc. 1-character string into an integer, and chr() converts an integer into a character. Thus,
2. Use a for loop when accessing the elements of a container, as when adding 1 to every element in chr(ord('a') + 1) results in 'b'.
a list, or printing the key of every entry in a dict, etc.
3. Use a while loop when the number of iterations is not computable before entering the loop, as
when iterating until a user enters a particular character. Figure 3.5.1: Nested loops example: Two-letter domain name printing
program.
These are not hard rules, just general guidelines.
©zyBooks 02/27/24 20:07 1927475 ©zyBooks 02/27/24 20:07 1927475
Daniel Reyes Daniel Reyes
PARTICIPATION
3.4.2: While loops and for loops. CS119-2402A-06-2402A CS119-2402A-06-2402A
ACTIVITY
Indicate whether a while loop or for loop should be used in the following scenarios:
5
Load default template...
Two-letter domain 10
names: -1
aa.com 1 num = 0
ab.com 2 while num >= 0:
ac.com Run
3 num = int(input('Enter a
ad.com
ae.com 4
""" af.com 5 if num >= 0:
Program to print all 2-letter domain names. ag.com 6 print('Depicted grap
©zyBooks 02/27/24 20:07 1927475 ©zyBooks 02/27/24 20:07 1927475
ah.com 7 for i in range(num):
Note that ord() and chr() convert between text and the ASCII or Daniel Reyes
ai.com
Daniel Reyes
Unicode encoding: CS119-2402A-06-2402A 8 print('*', end=' CS119-2402A-06-2402A
aj.com
- ord('a') yields the encoded value of 'a', the number 97. ak.com 9 print('\n')
- ord('a')+1 adds 1 to the encoded value of 'a', giving 98. al.com 10
- chr(ord('a')+1) converts 98 back into a letter, producing 'b' am.com 11 print('Goodbye.')
""" an.com 12
print('Two-letter domain names:') ao.com
ap.com
letter1 = 'a' aq.com
letter2 = '?' ar.com
while letter1 <= 'z': # Outer loop as.com
letter2 = 'a' at.com
while letter2 <= 'z': # Inner loop au.com
print('{}{}.com'.format(letter1, letter2)) av.com
letter2 = chr(ord(letter2) + 1) aw.com
letter1 = chr(ord(letter1) + 1) ax.com
ay.com
az.com
ba.com PARTICIPATION
ACTIVITY
3.5.1: Nested loops.
bb.com
….
zy.com
zz.com 1) Given the following code, how many
times will the inner loop body
execute?
for i in range(2):
for j in range(3):
(Forget about buying a two-letter domain name: They are all taken, and each sells for several hundred # Inner loop body
Here is a nested loop example that graphically depicts an integer's 2) Given the following code, how many
magnitude by using asterisks, creating what is commonly called a times will the print statement
histogram: execute?
Run the program below and observe the output. Modify the program to for i in range(5):
©zyBooks 02/27/24 20:07 1927475 for j in range(10, 12): ©zyBooks 02/27/24 20:07 1927475
print one asterisk per 5 units. So if the user enters 40, print 8 asterisks.
Daniel Reyes
print('{}{}'.format(i, j))
Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
* * * The following program allows the user to enter a phone number that includes letters, which appear on
* * * phone keypads along with numbers and are commonly used by companies as a marketing tactic (e.g.,
1-555-HOLIDAY). The program then outputs the phone number using numbers only.
©zyBooks 02/27/24 20:07 1927475 The first program version simply prints each element of the string to ensure the02/27/24
©zyBooks loop iterates
20:07 properly
1927475
Daniel Reyes through each string element. Daniel Reyes
Learn how our autograder works CS119-2402A-06-2402A CS119-2402A-06-2402A
550678.3854950.qx3zqy7
1 num_rows = int(input()) Figure 3.6.1: First version echoes input phone number string.
2 num_cols = int(input())
3
4 ''' Your solution goes here '''
5
6 print('*', end=' ')
7 print()
https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 31/45 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 32/45
2/27/24, 8:07 PM zyBooks 2/27/24, 8:07 PM zyBooks
The fourth version can be created by filling in the if-else branches similarly for other letters and adding
The second program version outputs the numbers (0 - 9) of the phone number and outputs a '?' for all
more instructions for handling unexpected characters. The code is not shown below, but sample
other characters. A FIXME comment attracts attention to code that needs to be fixed in the future. Many
input/output is provided.
editors automatically highlight FIXME comments. Large projects with multiple programmers might also
include a username and date, as in FIXME(01/22/2018, John).
Figure 3.6.4: Fourth and final version sample input/output.
Figure 3.6.2: Second version echoes numbers, and has FIXME comment.
Enter phone number (letters/- OK, no spaces): 1-555-HOLIDAY
Numbers only: 1-555-4654329
...
user_input = input('Enter phone number: ') Enter phone number (letters/- OK, no spaces): 1-555-holiday
phone_number = '' Numbers only: 1-555-4654329
...
for character in user_input: Enter phone number (letters/- OK, no spaces): 999-9999
if '0' <= character <= '9': Numbers only: 999-9999
phone_number += character Enter phone number: 1-555- ...
else: HOLIDAY Enter phone number (letters/- OK, no spaces): 9876zywx%$#@
#FIXME: Add elif branches for letters and Numbers only: 1?555???????? Numbers only: 98769999????
hyphen
phone_number += '?'
1 import random
2
Run
3 num_sixes = 0
4 num_sevens = 0
5 num_rolls = int(input('Ent
6
PARTICIPATION
3.6.1: Incremental programming. 7 if num_rolls >= 1:
ACTIVITY 8 for i in range(num_rol
9 die1 = random.rand
10 die2 = random.rand
1) Incremental programming may help
11 roll_total = die1
reduce the number of errors in a 12
program. 13 #Count number of s
14 if roll_total == 6
True 15 num_sixes = nu
16 if roll_total == 7
False 17 num_sevens = n
2s: **
3s: ****
4s: ***
5s: ********
6s: *************
7s: *****************
8s: *************
9s: *********
10s: ********** ©zyBooks 02/27/24 20:07 1927475 Run your program as often©zyBooks
as you'd 02/27/24 20:07
like, before 1927475
submitting
11s: *****
Daniel Reyes Develop mode Submit mode Daniel Reyes
12s: **
CS119-2402A-06-2402A for grading. Below, type any needed input values in
CS119-2402A-06-2402A
the first
box, then click Run program and observe the program's
output in the second box.
3.8 LAB: Read values into a list Enter program input (optional)
10
Write a program that reads a list of integers into a list as long as the integers are greater than zero, then 5
3
outputs the values of the list.
21
Ex: If the input is:
trending_flat trending_flat
main.py
Run program Input (from above)
(Your program)
Output
10
5
Program output displayed here
3
21
2
-6
2/20 T------------0,0-------------------------------------------
[10, 5, 3, 21, 2]
You can assume that the list of integers will have at least 2 values.
550678.3854950.qx3zqy7
LAB
ACTIVITY 3.8.1: LAB: Read values into a list 10 / 10 3.9 LAB: Smallest and largest numbers in a list
using min and max built-in functions
main.py Load default template...
©zyBooks 02/27/24 20:07 1927475 ©zyBooks 02/27/24 20:07 1927475
Daniel Reyes NOTE1: Please make sure you complete previous lab successfully before you proceed with this Lab
Daniel Reyes
1 user_numbers = [] CS119-2402A-06-2402A assignment CS119-2402A-06-2402A
2 user_input = int(input())
3 while user_input > 0: NOTE2: Make sure to copy and past your code from previous lab into here and update it to complete
4 user_numbers.append(user_input)
this lab
5 user_input = int(input())
6 print(user_numbers) Write a program that reads a list of integers into a list as long as the integers are greater than zero, then
outputs the list values and the smallest and largest integers in the list using min and max built-in
functions .
trending_flat trending_flat
main.py
21 Run program Input (from above) Output
(Your program)
2
©zyBooks 02/27/24 20:07 1927475 ©zyBooks 02/27/24 20:07 1927475
-6 Daniel Reyes Program output displayed here Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
the output is:
[10, 5, 3, 21, 2]
2 and 21
Coding trail of your work What is this?
You can assume that the list of integers will have at least 2 values. Note: Please make sure you 2/20 T------------------ W----------10,10-10 min:16
complete this lab successfully before you process with the next Lab assignment
550678.3854950.qx3zqy7
10 /
LAB 3.9.1: LAB: Smallest and largest numbers in a list using min and max built-in
ACTIVITY
functions
10
3.10 End of Unit 3 Assignments
If you have gotten here, you have gone through all of the sections within the two zyBook assignments.
main.py Load default template... Check your grades for (1) Interactive Assignment and (2) Lab Assignment in the VC gradebook for
accuracy.
1 user_numbers = []
2 Remember, you can always continue practicing to improve your score on the assignments.
3 user_numbers = []
4 user_input = int(input()) If you scroll up, you can look for incomplete activities. A check mark will appear to the right of
5 while user_input > 0: each activity that has been completed.
6 user_numbers.append(user_input)
7 user_input = int(input())
View your 'My Activity' tab to see the assignment completion from a birds eye view. (Get there by
8 print(user_numbers) clicking on the course name at the top of this page --> My Activity on the bottom right)
9
10 print(f'{min(user_numbers)} and {max(user_numbers)}')
To ensure your grades and scores sync with the VC gradebook, close out of this zyBook and click on
11
12 the next assignment link in Virtual Campus rather than clicking the next section in the zyBook now.
-15
30
-15 -5 5 15 25
For coding simplicity, output a space after every integer, including the last.
550678.3854950.qx3zqy7
LAB
ACTIVITY
3.11.1: LAB: Output range with increment of 10 0 / 10
trending_flat trending_flat
main.py The 5 indicates that there are five integers in the list, namely 50, 60, 140, 200, and 75. The 100 indicates
Run program Input (from above) Output
(Your program) that the program should output all integers less than or equal to 100, so the program outputs 50, 60,
©zyBooks 02/27/24 20:07 1927475
and 75. ©zyBooks 02/27/24 20:07 1927475
Program output displayed here Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A
Such functionality is common on sites like Amazon, where a user can filterCS119-2402A-06-2402A
results.
550678.3854950.qx3zqy7
LAB
ACTIVITY
3.12.1: LAB: Output values in a list below a user defined amount 0 / 10
Write a program that first gets a list of integers from input. The input begins with an integer indicating
the number of integers that follow. Then, get the last value from the input, which indicates a threshold.
Output all integers less than or equal to that last threshold value. 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
Ex: If the input is: box, then click Run program and observe the program's
output in the second box.
5
50 Enter program input (optional)
60 ©zyBooks 02/27/24 20:07 1927475 If your code requires input values, provide them here. ©zyBooks 02/27/24 20:07 1927475
140 Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
200
75
trending_flat trending_flat
100 main.py
Run program Input (from above)
(Your program)
Output
History of your effort will appear here once you begin working
on this zyLab.
©zyBooks 02/27/24 20:07 1927475
Daniel Reyes
CS119-2402A-06-2402A
https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 45/45