Loops#
Exercise 1: Printing using a for loop#
Use a for loop to each list element in a separate line:
weights = [1243891290, 1234129401, 14910395130, 1340981394]
# your solution here
1243891290
1234129401
14910395130
1340981394
Exercise 2: Convert units#
We have a list of weights in grams. Use a for loop to convert the weights to tons and print them one by one.
grams = [1243891290, 1234129401, 14910395130, 1340981394]
# your solution here
1243.89129
1234.129401
14910.39513
1340.981394
Exercise 3: Convert units and append the results to a new list#
We have a list of weights in grams - create a new list, called tons
that contains the weights in tons.
grams = [1243891290, 1234129401, 14910395130, 1340981394]
# your solution here
tons= []
for gram in grams:
tons.append(gram/1000000)
print(tons)
[1243.89129, 1234.129401, 14910.39513, 1340.981394]
Exercise 4: Filtering a list (1)#
Print all list elements greater than 10:
a = [34,5, 432, 3, 780]
# your solution here
for number in a:
if number > 10:
print(number)
34
432
780
Exercise 5: Filtering a list (2)#
Create a new list that contains all elements greater than 10:
a = [34,5, 432, 3, 780]
# your solution here
big_a = []
for number in a:
if number > 10:
big_a.append(number)
big_a
[34, 432, 780]
Exercise 6: Filtering a list (3)#
Create a new list that contains all elements greater than 10 and less than 100:
a = [34, 5, 11, 83, 432, 3, 50, 780]
# your solution here
big_a = []
for number in a:
if number > 10 and number < 100:
big_a.append(number)
big_a
[34, 11, 83, 50]
Exercise 7: Slice indexing#
The following code is supposed to generate a list that only contains the even values from the list all_values
.
Does it produce the correct result? If not, fix it!
even_values = list(range(0, 10, 2))
print(even_values)
[0, 2, 4, 6, 8]
Exercise 8: Updating a variable#
The following code is supposed to compute the sum of the values in the list all_values
.
Does it produce the correct result? If not, fix it!
all_values = list(range(10))
print(all_values)
# fix this code:
sum_of_values = 0
for value in all_values:
sum_of_values = sum_of_values + value
print(sum_of_values, value)
print('after loop:', sum_of_values, value)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0 0
1 1
3 2
6 3
10 4
15 5
21 6
28 7
36 8
45 9
after loop: 45 9