0% found this document useful (0 votes)
5 views23 pages

Programming ZyBooks3

The document provides an overview of lists in Python, explaining how to create, access, and modify them. It covers the mutability of lists, methods for adding and removing elements, and introduces sequence-type functions. Additionally, it briefly mentions tuples as immutable sequences similar to lists.

Uploaded by

cadabradanny
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)
5 views23 pages

Programming ZyBooks3

The document provides an overview of lists in Python, explaining how to create, access, and modify them. It covers the mutability of lists, methods for adding and removing elements, and introduces sequence-type functions. Additionally, it briefly mentions tuples as immutable sequences similar to lists.

Uploaded by

cadabradanny
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/ 23

2/27/24, 8:07 PM zyBooks 2/27/24, 8:07 PM zyBooks

Load default template... Run


3.1 List basics
1 names = ['Daniel', 'Roxanna',
2
3 print(names)
Creating a list 4

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

Python interpreter 1) Write a statement that creates a list


>>> prices = ['$20', 14.99, 5] prices = ['$20', 14.99, 5]
called my_nums, containing the
>>> elements 5, 10, and 20.

prices 0 1 2

'$20' Check Show answer


Python (command line) 14.99
5
2) Write a statement that creates a list
called my_list with the elements
-100 and the string 'lists are fun'.
Animation captions:

1. User creates a new list.


Check Show answer
2. The interpreter creates new object for each list element. ©zyBooks 02/27/24 20:07 1927475 ©zyBooks 02/27/24 20:07 1927475
3. 'prices' holds references to objects in list. Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A 3) Write a statement that creates an CS119-2402A-06-2402A

empty list called class_grades.

zyDE 3.1.1: Creating lists.


Check Show answer
The following program prints a list of names. Try adding your name to
the list, and run the program again.
https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 1/45 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 2/45
2/27/24, 8:07 PM zyBooks 2/27/24, 8:07 PM zyBooks
4 print(short_names[1])
Accessing list elements 5 print(short_names[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')

my_nums = [5, 12, 20]


print(my_nums)
[5, 12,
# Update a list 20]
element [5, -28,
my_nums[1] = -28 20]
CHALLENGE
ACTIVITY
3.1.1: Initialize a list. print(my_nums)

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

2) Write a statement that assigns the


2nd element of my_towns with Animation captions:
'Detroit'.
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.
Check Show answer
3. remove() removes the first element with a given value. 'abc' is removed and now the list only
©zyBooks 02/27/24 20:07 1927475 ©zyBooks 02/27/24 20:07 1927475
Daniel Reyes has one element. Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
Adding and removing list elements

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.

Adding elements to a list: 1) Update the price of the second item


in house_prices to '$175,000'.
list.append(value): Adds value to the end of list. Ex: my_list.append('abc')

Removing elements from a list:


Check Show answer
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')
2) Add a price to the end of the list with a value
of '$1,000,000'.
PARTICIPATION
ACTIVITY
3.1.4: Adding and removing list elements.

Check Show answer

my_list = [10, 'bw']


print(my_list) 3) Remove the 1st element from
my_list:
my_list.append('abc') house_prices, using the pop()
print('After append:', my_list) 10 method.
my_list.pop(1)
print('After pop:', my_list)

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]

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 5/45 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 6/45


2/27/24, 8:07 PM zyBooks 2/27/24, 8:07 PM zyBooks

4) Remove '$140,000' from


house_prices, using the remove() # Concatenating lists
method. 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
# Finding min, max Most expensive house: 900000
print('Cheapest house:', min(house_prices))
Check Show answer print('Most expensive house:', max(house_prices))
©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
Sequence-type methods and functions
Note that lists can contain mixed types of objects. Ex: x = [1, 2.5, 'abc'] creates a new list x
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. that contains an integer, a floating-point number, and a string. Later material explores lists in detail,
A subset of such functions and methods is provided below. including how lists can even contain other lists as elements.

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

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 7/45 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 8/45


2/27/24, 8:07 PM zyBooks 2/27/24, 8:07 PM zyBooks
PARTICIPATION
ACTIVITY 3.1.6: Using sequence-type functions. Tuples

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.

Figure 3.1.4: Using tuples.


Check Show answer

3) Write a statement that assigns the white_house_coordinates = (38.8977, 77.0366)


print('Coordinates:',
variable avg_price with the average white_house_coordinates) Coordinates: (38.8977, 77.0366)
of the elements of prices. print('Tuple length:', Tuple length: 2
len(white_house_coordinates))
Latitude: 38.8977 north
# Access tuples via index Longitude: 77.0366 west
print('\nLatitude:',
white_house_coordinates[0], 'north') Traceback (most recent call last):
Check Show answer print('Longitude:', File "<stdin>", line 10, in <module>
white_house_coordinates[1], 'west\n') TypeError: 'tuple' object does not
support item assignment
# Error. Tuples are immutable
white_house_coordinates[1] = 50
CHALLENGE
ACTIVITY
3.1.2: List functions and methods.

550678.3854950.qx3zqy7

Start PARTICIPATION
ACTIVITY
3.1.7: Tuples.

user_ages = [ 2, 6, 8, 5, 3, 1 ] 1) Create a new variable point that is


a tuple containing the strings 'X
©zyBooks 02/27/24 20:07 1927475 string' and 'Y string'. ©zyBooks 02/27/24 20:07 1927475
What is the value of len(user_ages)? Daniel Reyes Daniel Reyes
Select CS119-2402A-06-2402A CS119-2402A-06-2402A

Check Show answer


1 2 3

Check Next

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 9/45 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 10/45


2/27/24, 8:07 PM zyBooks 2/27/24, 8:07 PM zyBooks

2) If the value of variable friends is


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

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

Learn how our autograder works

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

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 11/45 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 12/45


2/27/24, 8:07 PM zyBooks 2/27/24, 8:07 PM zyBooks

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

Check Show answer print('Goodbye.\n')


Enter a character ('q' for
quit): q
Goodbye.
3) Assume user would enter 'a', then 'b',
then 'n'.
# Get character from user here ©zyBooks 02/27/24 20:07 1927475 ©zyBooks 02/27/24 20:07 1927475
while user_char != 'n': Daniel Reyes Daniel Reyes
# Do something CS119-2402A-06-2402A CS119-2402A-06-2402A
# Get character from user here
PARTICIPATION
ACTIVITY 3.2.3: Loop expressions.

Complete the loop expressions, using a single operator in your expression. Use the most
Check Show answer
straightforward translation of English to an expression.

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 13/45 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 14/45


2/27/24, 8:07 PM zyBooks 2/27/24, 8:07 PM zyBooks

1) Iterate while x is less than 100.


Iteration num Output
while : ....
# Read num from user …. 902
# Loop body statements go
# Print each digit 1 2
here while num > 0:
print(num % 10) 90
num = num // 10
Check Show answer 2 0
©zyBooks 02/27/24 20:07 1927475 9©zyBooks 02/27/24 20:07 1927475
Daniel Reyes Daniel Reyes
2) Iterate while x is greater than or CS119-2402A-06-2402A 3 9
CS119-2402A-06-2402A
equal to 0. 0

while :

# Loop body statements go


here

Check Show answer


Animation captions:

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.

Check Show answer


Example: While loop: Iterations
4) Iterate until c equals 'z'. Each iteration of the program below prints one line with the year and the number of ancestors in that
while : year. (Note: the program's output numbers are large due to not considering breeding among distant
# Loop body statements go relatives, but nevertheless, a person has many ancestors.)
here
The program checks for year_considered >= user_year rather than for
year_considered != user_year, because year_considered might be reduced past user_year
Check Show answer without equaling it, causing an infinite loop. An infinite loop is a loop that will always execute because
the loop's expression is always True. A common error is to accidentally create an infinite loop by
assuming equality will be reached. Good practice is to include greater than or less than along with
Stepping through a while loop equality in a loop expression to help avoid infinite loops.

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.

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 15/45 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 16/45


2/27/24, 8:07 PM zyBooks 2/27/24, 8:07 PM zyBooks

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

Check Show answer

1945
4) x = 1
y = 3
z = 5
while not (y < x < z):
print(x, end=' ')
Run x = x + 1

Check Show answer

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

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 17/45 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 18/45


2/27/24, 8:07 PM zyBooks 2/27/24, 8:07 PM zyBooks

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.

Sample outputs with inputs: 9 5 2 -1


Note: If the submitted code has an infinite loop, the system will stop running the code after a
Body few seconds and report "Program end never reached." The system doesn't print the test case
Body that caused the reported message.
Body
Done. Learn how our autograder works
550678.3854950.qx3zqy7

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

©zyBooks 02/27/24 20:07 1927475


View your last submission keyboard_arrow_down ©zyBooks 02/27/24 20:07 1927475
Daniel Reyes Daniel Reyes
Run CS119-2402A-06-2402A CS119-2402A-06-2402A

View your last submission keyboard_arrow_down


3.3 For loops
CHALLENGE
ACTIVITY
3.2.3: Basic while loop expression.
Basics
https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 19/45 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 20/45
2/27/24, 8:07 PM zyBooks 2/27/24, 8:07 PM zyBooks

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

Figure 3.3.2: Using a for loop to access each character of a string.

Hi Bill! my_str = ''


Hi Nicole! for character in "Take me to the
moon.": T_a_k_e_ _m_e_ _t_o_ _t_h_e_
Hi John! _m_o_o_n_._
my_str += character + '_'
print(my_str)

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

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 21/45 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 22/45


2/27/24, 8:07 PM zyBooks 2/27/24, 8:07 PM zyBooks

1) Iterate over the given list using a


variable called my_pet. daily_revenues = [
2356.23, # Monday
for in ['Scooter', 1800.12, # Tuesday
1792.50, # Wednesday
'Kobe', 'Bella']: 2058.10, # Thursday
# Loop body statements 1988.00, # Friday
2002.99, # Saturday
1890.75 # Sunday
Check Show answer
]
©zyBooks 02/27/24 20:07 1927475 Weekly revenue:02/27/24
©zyBooks $13888.69
20:07 1927475
Daily average revenue:
Daniel Reyes total = 0 Daniel Reyes
$1984.10
2) Iterate over the list my_prices using CS119-2402A-06-2402A for day in daily_revenues: CS119-2402A-06-2402A
total += day
a variable called price.
average = total / len(daily_revenues)
for :
print('Weekly revenue: ${:.2f}'.format(total))
# Loop body statements print('Daily average revenue:
${:.2f}'.format(average))
Check Show answer

3) Iterate the string '911' using a


variable called number.
A for loop may also iterate backwards over a sequence, starting at the last element and ending with the
for :
first element, by using the reversed() function to reverse the order of the elements.
# Loop body statements

Check Show answer


Figure 3.3.4: For loop example: Looping over a sequence in reverse.

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.

Fill in the missing code to perform the desired calculation.

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 23/45 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 24/45


2/27/24, 8:07 PM zyBooks 2/27/24, 8:07 PM zyBooks

1) Compute the average number of 4) Print scores in order from highest to


kids. lowest. Note: List is pre-sorted from
# Each list item is the number lowest to highest.
of kids in a family. scores = [75, 77, 80, 85, 90,
num_kids = [1, 1, 2, 2, 1, 4, 3, 95, 99]
1]
for scr in :
total = 0
for num in num_kids: ©zyBooks 02/27/24 20:07 1927475 print(scr, end=' ') ©zyBooks 02/27/24 20:07 1927475
total += Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
Check Show answer
average = total / len(num_kids)

CHALLENGE
Check Show answer 3.3.1: Looping over strings, lists, and dictionaries.
ACTIVITY

2) Assign num_neg with the number of 550678.3854950.qx3zqy7

below-freezing Celsius temperatures Start


in the list.
temperatures = [30, 20, 2, -5, Type the program's output
-15, -8, -1, 0, 5, 35]

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

3) Print scores higher than 80, in order 1 2


from highest to lowest. Note: list is
pre-sorted from lowest to highest.
Check Next
scores = [75, 77, 80, 85, 90,
95, 99]

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

Check Show answer


While loop and for loop correspondence

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

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 25/45 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 26/45


2/27/24, 8:07 PM zyBooks 2/27/24, 8:07 PM zyBooks

(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

2) Iterate until the values of x and y are


©zyBooks 02/27/24 20:07 1927475 equal, where x and y are changed in the ©zyBooks 02/27/24 20:07 1927475
Daniel Reyes loop body. Daniel Reyes
i = 0 for i in range( 100,CS119-2402A-06-2402A
): CS119-2402A-06-2402A
while i < 100 :
while
# Loop body statements
# Loop body statements
i += 1 for

3) Iterate 1500 times


i=0 while
while i < 100 : for i in range( 100, ):
#Loop body statements #Loop body statements for
i += 1

3.5 Nested loops


Animation captions:

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:

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 27/45 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 28/45


2/27/24, 8:07 PM zyBooks 2/27/24, 8:07 PM zyBooks

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

thousand or millions of dollars. Source: dnjournal.com, 2012.)

zyDE 3.5.1: Nested loop example: Histogram. Check Show answer

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

Check Show answer

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 29/45 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 30/45


2/27/24, 8:07 PM zyBooks 2/27/24, 8:07 PM zyBooks
7 print()
3) What is the output of the following
code?
c1 = 'a'
while c1 < 'b':
c2 = 'a'
while c2 <= 'c':
print('{}{}'.format(c1,
c2), end=' ')
c2 = chr(ord(c2) + 1)
c1 = chr(ord(c1) + 1) ©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
Run
Check Show answer
View your last submission keyboard_arrow_down
4) What is the output of the following
code?
i1 = 1

3.6 Developing programs incrementally


while i1 < 19:
i2 = 3
while i2 <= 9:
print('{}
{}'.format(i1,i2), end=' ')
i2 = i2 + 3
i1 = i1 + 10 Incremental programming

As programs increase in complexity, a programmer's development process


becomes more important. A programmer should not write the entire program
Check Show answer
and then run the program—hoping the program works. If, as is often the case,
the program does not work on the first try, debugging at that point can be extra
difficult because the program may have many distinct bugs.
CHALLENGE
ACTIVITY
3.5.1: Nested loops: Print rectangle Experienced programmers practice incremental programming, starting with a
simple version of the program, and then growing the program little-by-little into a
Given the number of rows and the number of columns, write nested loops to print a rectangle. complete version.

Sample output with inputs: 2 3 Example: Phone number program

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

Enter phone number: 1-555- user_input = input('Enter phone number: ')


HOLIDAY phone_number = ''
Element 0 is: 1
Element 1 is: - for character in user_input:
user_input = input('Enter phone number: ') Element 2 is: 5 if ('0' <= character <= '9') or (character == '-'):
Element 3 is: 5 phone_number += character
index = 0 Element 4 is: 5 elif ('a' <= character <= 'c') or ('A' <= character Enter phone number: 1-555-
for character in user_input: Element 5 is: - <= 'C'): HOLIDAY
print('Element {} is: {}'.format(index, Element 6 is: H phone_number += '2' Numbers only: 1-555-?????2?
character)) ©zyBooks 02/27/24 20:07 1927475
Element 7 is: O #FIXME: Add remaining elif branches
©zyBooks 02/27/24 20:07 1927475
Element 8 is: L Daniel Reyes
index += 1 else: Daniel Reyes
CS119-2402A-06-2402A
Element 9 is: I phone_number += '?' CS119-2402A-06-2402A
Element 10 is: D
Element 11 is: A print('Numbers only: {}'.format(phone_number))
Element 12 is: Y

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 += '?'

print('Numbers only: {}'.format(phone_number))

zyDE 3.6.1: Complete the phone number program.


Complete the program by providing the additional if-else branches for
The third version completes the elif branch for the letters A-C (lowercase and uppercase, per a standard
©zyBooks 02/27/24 20:07 1927475 decoding other letters in a phone number. Try incrementally writing02/27/24
©zyBooks the 20:07 1927475
phone keypad). The code also modifies the if branch to echo a hyphen in addition to numbers.
Daniel Reyes Daniel Reyes
program by adding one "else if" branch at a time, testing that each added
CS119-2402A-06-2402A CS119-2402A-06-2402A
branch works as intended.
Figure 3.6.3: Third version echoes hyphens too, and handles first three
letters.

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 33/45 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 34/45


2/27/24, 8:07 PM zyBooks 2/27/24, 8:07 PM zyBooks

Load default template...


1-555-HOLIDAY
3.7 Additional practice: Dice statistics
1 user_input = input('Enter ph
2 phone_number = '' The following is a sample programming lab activity; not all classes using a zyBook require students to
Run
3 fully complete this activity. No auto-checking is performed. Users planning to fully complete this program
4 for character in user_input: may consider first developing their code in a separate programming environment.
5 if ('0' <= character <=
6 phone_number += char ©zyBooks 02/27/24 20:07 1927475 Analyzing dice rolls is a common example in understanding probability and statistics.
©zyBooks 02/27/24 The following
20:07 1927475
7 elif ('a' <= character < Daniel Reyes Daniel Reyes
8 phone_number += '2'
program calculates the number of times the sum of two dice (randomly rolled) is equal to six or seven.
CS119-2402A-06-2402A CS119-2402A-06-2402A
9 #FIXME: Add remaining el
10 else:
11 phone_number += '?' zyDE 3.7.1: Dice statistics.
12
13 print('Numbers only: {}'.for
14
6
Load default template...

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

2) FIXME comments provide a way for a


programmer to remember what needs
to be added.
Create a different version of the program that:
True
1. Calculates the number of times the sum of the randomly rolled dice equals each possible value
False
from 2 to 12.
3) Once a program is complete, one would 2. Repeatedly asks the user for the number of times to roll the dice, quitting only when the user-
expect to see several FIXME entered number is less than 1. Hint: Use a while loop that will execute as long as num_rolls is
©zyBooks 02/27/24 20:07 1927475 ©zyBooks 02/27/24 20:07 1927475
comments. Daniel Reyes greater than 1. Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
3. Prints a histogram in which the total number of times the dice rolls equals each possible value is
True
displayed by printing a character, such as *, that number of times. The following provides an
False
example:

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 35/45 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 36/45


2/27/24, 8:07 PM zyBooks 2/27/24, 8:07 PM zyBooks

Dice roll histogram:

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

the output is: Coding trail of your work What is this?

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 .

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 37/45 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 38/45


2/27/24, 8:07 PM zyBooks 2/27/24, 8:07 PM zyBooks

Ex: If the input is: 10


5
10 3
5 21
3

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.

©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

Develop mode Submit mode


Run your program as often as you'd like, before submitting Figure 3.10.1: Stop Sign
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)

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 39/45 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 40/45


2/27/24, 8:07 PM zyBooks 2/27/24, 8:07 PM zyBooks

-15
30

the output is:

-15 -5 5 15 25

©zyBooks 02/27/24 20:07 1927475 ©zyBooks 02/27/24 20:07 1927475


Daniel Reyes Ex: If the second integer is less than the first as in: Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
20
5

the output is:

Second integer can't be less than the first.

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

main.py Load default template...

1 ''' Type your code here. '''

3.11 LAB: Output range with increment of20:07


©zyBooks 02/27/24 10 1927475 ©zyBooks 02/27/24 20:07 1927475
Daniel Reyes Daniel Reyes
CS119-2402A-06-2402A CS119-2402A-06-2402A
Run your program as often as you'd like, before submitting
info This section has been set as optional by your instructor. 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
Write a program whose input is two integers. Output the first integer and subsequent increments of 10 output in the second box.
as long as the value is less than or equal to the second integer. Enter program input (optional)
Ex: If the input is:
https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 41/45 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 42/45
2/27/24, 8:07 PM zyBooks 2/27/24, 8:07 PM zyBooks

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


60
75

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

Coding trail of your work What is this?


main.py Load default template...
History of your effort will appear here once you begin working
on this zyLab.
1 ''' Type your code here. '''
2

3.12 LAB: Output values in a list below a user


defined amount

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

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

the output is:


Program output displayed here

https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 43/45 https://learn.zybooks.com/zybook/CS119-2402A-06-2402A/chapter/3/print 44/45


2/27/24, 8:07 PM zyBooks

Coding trail of your work What is this?

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

©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

You might also like