




Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
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
1 / 8
This page cannot be seen from the preview
Don't miss anything!
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
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:
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:
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.