Created
April 30, 2021 14:51
-
-
Save IvanFrecia/c01d636526e033ca1d2388ae12fa8d53 to your computer and use it in GitHub Desktop.
Coursera - Python 3 Programming Specialization - Course 2 - Week 4 - 14.2. The while Statement
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Here is a new version of the summation program that uses a while statement. | |
def sumTo(aBound): | |
""" Return the sum of 1+2+3 ... n """ | |
theSum = 0 | |
aNumber = 1 | |
while aNumber <= aBound: | |
theSum = theSum + aNumber | |
aNumber = aNumber + 1 | |
return theSum | |
print(sumTo(4)) | |
print(sumTo(1000)) | |
# 1) Write a while loop that is initialized at 0 and stops at 15. If the counter is an even number, | |
# append the counter to a list called eve_nums. | |
# Answer: | |
count = 0 | |
eve_nums = [] | |
while count <= 15: | |
if count % 2 == 0: | |
eve_nums.append(count) | |
count = count + 1 | |
# 2) Below, we’ve provided a for loop that sums all the elements of list1. | |
# Write code that accomplishes the same task, but instead uses a while loop. | |
# Assign the accumulator variable to the name accum. | |
# Answer: | |
list1 = [8, 3, 4, 5, 6, 7, 9] | |
tot = 0 | |
for elem in list1: | |
tot = tot + elem | |
index = 0 | |
accum = 0 | |
while index < len(list1): | |
accum = accum + list1[index] | |
index = index + 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment