Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Lab #8: Iterating for-loops, while-loops, and More in CptS 111, Exercises of Advanced Computer Programming

A lab exercise for CptS 111 students, focusing on iterating for-loops, while-loops, break and continue commands, and the enumerate() function. It includes examples and explanations of how to use these features in Python, as well as tasks for students to practice.

Typology: Exercises

2021/2022

Uploaded on 09/12/2022

eklavya
eklavya 🇺🇸

4.5

(22)

266 documents

1 / 8

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
CptS 111 Lab #8
Iterating for-loops, while-loops, and More
Learning Objectives:
Write iterating for-loops with lists and dictionaries
Write while-loops
Use the break and continue commands
Use the enumerate() function
Prerequisites:
Basics of iterating for-loops
Basics of while-loops
Task 1: while-loops and break and continue with loops
In general, it’s best to minimize the use of the break and continue commands because they
can make our code more difficult to understand. This is because they can interrupt the flow of a
program. However, sometimes they can be used very effectively, e.g., in PA #5, break works
well with the while-loop used in the first part of the assignment. Let’s try some examples in an
IDLE Shell window. As usual, read the comments and type the text in boldface.
>>> # Let’s start with while-loops. It’s best to use while-loops only
>>> # when no other loop works as well, e.g., when we want a certain
>>> # set of commands to run, but we don’t know how many times.
>>> volunteers = []
>>> entry = ’-’
>>> while entry != ’’:
entry = input(’Enter the name of a volunteer [return to stop]: ’)
volunteers.append(entry)
Enter the name of a volunteer [return to stop]: Sam
Enter the name of a volunteer [return to stop]: Ann
Enter the name of a volunteer [return to stop]: Mohammed
Enter the name of a volunteer [return to stop]: Maria
Enter the name of a volunteer [return to stop]: Yan
Enter the name of a volunteer [return to stop]: Saana
Enter the name of a volunteer [return to stop]: Matt
Enter the name of a volunteer [return to stop]:
>>> volunteers
[’Sam’, ’Ann’, ’Mohammed’, ’Maria’, ’Yan’, ’Saana’, ’Matt’, ’’]
>>> len(volunteers)
8
>>>
>>> # However, as you can see from this example, our list contains an
>>> # empty string (depending on which version of Python3 you’re using
1
pf3
pf4
pf5
pf8

Partial preview of the text

Download Lab #8: Iterating for-loops, while-loops, and More in CptS 111 and more Exercises Advanced Computer Programming in PDF only on Docsity!

CptS 111 — Lab

Iterating for -loops, while -loops, and More

Learning Objectives:

• Write iterating for-loops with lists and dictionaries

• Write while-loops

• Use the break and continue commands

• Use the enumerate() function

Prerequisites:

• Basics of iterating for-loops

• Basics of while-loops

Task 1: while-loops and break and continue with loops

In general, it’s best to minimize the use of the break and continue commands because they

can make our code more difficult to understand. This is because they can interrupt the flow of a

program. However, sometimes they can be used very effectively, e.g., in PA #5, break works

well with the while-loop used in the first part of the assignment. Let’s try some examples in an

IDLE Shell window. As usual, read the comments and type the text in boldface.

Let’s start with while-loops. It’s best to use while-loops only

when no other loop works as well, e.g., when we want a certain

set of commands to run, but we don’t know how many times.

volunteers = [] entry = ’-’ while entry != ’’: entry = input(’Enter the name of a volunteer [return to stop]: ’) volunteers.append(entry)

Enter the name of a volunteer [return to stop]: Sam Enter the name of a volunteer [return to stop]: Ann Enter the name of a volunteer [return to stop]: Mohammed Enter the name of a volunteer [return to stop]: Maria Enter the name of a volunteer [return to stop]: Yan Enter the name of a volunteer [return to stop]: Saana Enter the name of a volunteer [return to stop]: Matt Enter the name of a volunteer [return to stop]:

volunteers [’Sam’, ’Ann’, ’Mohammed’, ’Maria’, ’Yan’, ’Saana’, ’Matt’, ’’] len(volunteers) 8

However, as you can see from this example, our list contains an

empty string (depending on which version of Python3 you’re using

the last command will result in 7 or 8). We’ll see how we can

fix the list shortly, but first let’s try another while-loop

example.

steps = 0 step_goal = 10000 while steps <= step_goal: if steps < step_goal: print(’Keep on moving!’) else: print(’Well done! Another step goal met.’) steps += 1000

As we see from this example, we can use a conditional in the body

of our while-loop. In fact, conditionals are often used in the

body of a while-loop. Now let’s return to our earlier example.

We can use a conditional and the break command to remove the

empty string in our list.

volunteers = [] entry = ’-’ while True: entry = input(’Enter the name of a volunteer [return to stop]: ’) if entry == ’’: break volunteers.append(entry)

Enter the name of a volunteer [return to stop]: Sam Enter the name of a volunteer [return to stop]: Ann Enter the name of a volunteer [return to stop]: Mohammed Enter the name of a volunteer [return to stop]: Maria Enter the name of a volunteer [return to stop]: Yan Enter the name of a volunteer [return to stop]: Saana Enter the name of a volunteer [return to stop]: Matt Enter the name of a volunteer [return to stop]:

volunteers [’Sam’, ’Ann’, ’Mohammed’, ’Maria’, ’Yan’, ’Saana’, ’Matt’] len(volunteers) 7

The break command tells Python to ignore the remaining commands

and leave the while-loop. Thus, the empty string isn’t added to

the list. Important: Note that we reinitialized the list as

an empty list. If we hadn’t done this, Python would have added

the names to the original list of volunteers because lists are

mutable, i.e., can be changed! However, we only have to do this,

i.e., reinitialize the list, volunteers, because we’re using an

IDLE Shell window.

Care must always be used with while-loops because a simple

As you can see, the headers for counting and iterating for-loops

differ. In an iterating for-loop, there is no explicit counter.

Instead each value in the iterable (a string, list, dictionary,

tuple, or set) is used in the loop itself. It’s good practice

to give the loop variable a name that makes sense rather than

using, e.g., just ’i’. For example, we might use the following:

for name in names: <loop_body>

for num in nums: <loop_body>

for char in word: # Don’t use chr! (Why?) <loop_body>

Now let’s look at some examples. Please note that we’ll use

lists and dictionaries in these, but the same format used for

lists can be used for strings, tuples, and sets.

names = [’Sam’, ’Mohammed’, ’Maria’, ’Yan’] for name in names: print(f’Hello, {name}.’)

In this first example, we used the same list as in Lab #7, but

rather than using the range() function, we used an iterating for-

loop with the list iterable. Python used the first element from

names in its first iteration, the second element in names in its

second iteration, and so on. In Lab #7, we used ‘‘for i in

range(len(names))’’ in the header and ‘‘names[i]’’ in the print

statement which was more complicated. However, we considered

four other counting for-loop examples in Lab #7, and none of

these would work with an iterating for-loop because there is

no iterable. Let’s look at another list example.

models = [] makes = [’Tesla’, ’Ford’, ’Hyundai’, ’Toyota’, ’Honda’, ’Jaguar’] for make in makes: model = input(f’Enter a model for a {make}: ’) models.append(model)

Enter a model for a Tesla: Model Y Enter a model for a Ford: Escape Enter a model for a Hyundai: Kona Enter a model for a Toyota: RAV Enter a model for a Honda: CR-V Enter a model for a Jaguar: E-PACE

models

In the example above, we’ve used two lists, one as the iterable

and the other that we create in the iterating for-loop. Outside

the loop, we have to first initialize the list we want to create

in the loop, and we also define the ’makes’ list. Note the use

of string formatting in the input() function. Pretty cool!

Next let’s turn to dictionaries, but first let me show you

another reason why I love Python!

cars = dict(zip(makes, models)) cars

Wow! Python makes coding so easy! We can use the zip()

function to zip two iterables together to create a zip type.

res = zip(makes, models) type(res)

Then we can use list(), tuple(), set(), or dict() with the zip

file to create data structures of these types. However, we have

to create the zip file each time after it’s used or else we’ll

end up with an empty container.

res = zip(makes, models) l_cars = list(res) # That’s an ’el’, not a one! l_cars res = zip(makes, models) t_cars = tuple(res) t_cars res = zip(makes, models) s_cars = set(res) s_cars

Note that we get a list of tuples, a tuple of tuples, or a set

of tuples with a zipped object. Only dict() doesn’t result in

tuples. Now let’s use an iterating for-loop with our dictionary

’cars’. We can use three different approaches.

for key in dictionary.keys(): for key in dictionary.values(): for key, value in dictionary.items():

Let’s try each of these.

for make in cars.keys(): print(f’What do you think of {make}s?’)

for model in cars.values(): print(f’Are you familiar with the {model}?’)

**for make, model in cars.items(): cars = dict(zip(makes, models)) >>> cars >>> >>> # Wow! Python makes coding so easy! We can use the zip() >>> # function to zip two iterables together to create a zip type. >>> res = zip(makes, models) >>> type(res) >>> >>> # Then we can use list(), tuple(), set(), or dict() with the zip >>> # file to create data structures of these types. However, we have >>> # to create the zip file each time after it’s used or else we’ll >>> # end up with an empty container. >>> res = zip(makes, models) >>> l_cars = list(res) # That’s an ’el’, not a one! >>> l_cars >>> res = zip(makes, models) >>> t_cars = tuple(res) >>> t_cars >>> res = zip(makes, models) >>> s_cars = set(res) >>> s_cars >>> >>> # Note that we get a list of tuples, a tuple of tuples, or a set >>> # of tuples with a zipped object. Only dict() doesn’t result in >>> # tuples. Now let’s use an iterating for-loop with our dictionary >>> # ’cars’. We can use three different approaches. for key in dictionary.keys(): for key in dictionary.values(): for key, value in dictionary.items(): >>> # Let’s try each of these. >>> for make in cars.keys(): print(f’What do you think of {make}s?’) >>> >>> for model in cars.values(): print(f’Are you familiar with the {model}?’) >>> >>> for make, model in cars.items(): print(f‘‘I’m thinking of buying a {make} {model}.’’)

So using dictionaries as iterables is a little more complicated

than using lists, but it’s still not difficult. However, you

have to expend some effort to memorize these concepts or at

least enough effort to know what you can do even if you can’t

  • get steps() : This non-void function has a single parameter, the list of days in the week.

It initializes an empty list and then uses an iterating for-loop to prompt and obtain the

number of steps a user walked as shown in the examples below. It appends each number to

the list that was initialized and returns this list to main(). Hint: Recall that you can use

string formatting in the argument of the input() function.

  • max steps day() : This non-void function has one parameter, the dictionary of days

(keys) and number of steps (values). It initializes values for the maximum number of steps

(see example before on previous page!). and the day of the maximum number of steps. It

then finds the actual maximum number of steps and the day of the maximum number of

steps using an iterating for-loop with the dictionary as the iterable and returns both values

to main().

  • print results() : This void function has five parameters: the dictionary of days (keys)

and number of steps (values), the total number of steps, the average number of steps, the

maximum number of steps, and the day the maximum number of steps occurred, and prints

an itemized list of the days of the week and the number of steps walked that day using

the enumerate() function, the total number of steps, the average number of steps, the

maximum number of steps walked in a day, and the day which this occurred as shown in

the examples below. Recall that commas in numbers can be obtained using a comma in the

replacement field:

This will work nicely for your output sentences as shown in the examples below, but it’s a

little bit trickier to obtain the commas with the formatting for each day. Try

{:>n,}

where I’ll let you figure out the value of n. You’ll also need to provide the number of spaces

occurring before the colons in the output. Hint: Which day has the most letters?

  • main() : This void function has no parameters. It creates a list of the days of the week (Sun-

day through Saturday) and uses this list as the argument to the non-void function get steps()

which returns a list of the steps walked in the week. It finds the total number of steps by

summing this list and the average number of steps walked using this total and then creates

a dictionary by zipping together the lists of the days of the week (keys) and the number of

steps walked each day (values). The non-void function max steps day() is called with

the dictionary as its argument, and it returns the maximum number of steps and the day

which this occurred. Finally, the void function print results() is called with the dic-

tionary, total number of steps, average number of steps, maximum number of steps, and day

which maximum number of steps occurred as the arguments.

Enter the number of steps you walked on Sunday: 14426 Enter the number of steps you walked on Monday: 2011 Enter the number of steps you walked on Tuesday: 14544 Enter the number of steps you walked on Wednesday: 1437 Enter the number of steps you walked on Thursday: 13937 Enter the number of steps you walked on Friday: 2286 Enter the number of steps you walked on Saturday: 14276

Your weekly steps:

  1. Sunday : 14,
  1. Monday : 2,
  2. Tuesday : 14,
  3. Wednesday: 1,
  4. Thursday : 13,
  5. Friday : 2,
  6. Saturday : 14,

You walked a total of 62,917 steps. The average number of steps you walked was 8,988. The maximum number of steps you walked (14,544) occurred on Tuesday.

Enter the number of steps you walked on Sunday: 16126 Enter the number of steps you walked on Monday: 2647 Enter the number of steps you walked on Tuesday: 13940 Enter the number of steps you walked on Wednesday: 947 Enter the number of steps you walked on Thursday: 13944 Enter the number of steps you walked on Friday: 1519 Enter the number of steps you walked on Saturday: 18966

Your weekly steps:

  1. Sunday : 16,
  2. Monday : 2,
  3. Tuesday : 13,
  4. Wednesday: 947
  5. Thursday : 13,
  6. Friday : 1,
  7. Saturday : 18,

You walked a total of 68,089 steps. The average number of steps you walked was 9,727. The maximum number of steps you walked (18,966) occurred on Saturday.

When your program is working properly, demonstrate it to your TA to get credit.

There are only three tasks in this week’s lab, because the last task was pretty challenging. You

should feel really good about yourself and your coding, especially if you finished everything! You

may want to use the program you wrote in the last task!