
Code
Weigh the Cargo
A for loop can walk straight through a list, one item at a time,
no range needed:
for crate in [4, 11, 2]:
print("Crate weighs", crate)
Combine that with accumulators and if to answer questions about
your data. To find the biggest value, remember the best one
seen so far and replace it whenever you find something bigger:
biggest = crates[0]
for crate in crates:
if crate > biggest:
biggest = crate
Pip tip: Python has built-ins
sum(crates)andmax(crates)that do this for you. Writing the loop yourself once is the best way to understand what they do!
Assignment
Using one loop over crates, work out:
total: the weight of all crates added together.heavy: how many crates weigh more than 8 kg.heaviest: the weight of the heaviest crate.
The prints are already written for you.
Using one loop over crates, work out:
total: the weight of all crates added together.heavy: how many crates weigh more than 8 kg.heaviest: the weight of the heaviest crate.
The prints are already written for you.
main.py Python sleeping
Press Run to try your code, then Check to test it.