Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Collection of numbers

Write a program that processes a collection of numbers using a for loop. The program should end immediately, printing only the word "Done", when a zero is encountered (use a break for this). Negative numbers should be ignored (use a continue for this; I know you can also easily do this with a condition, but I want you to practice with continue). If no zero is encountered, the program should display the sum of all numbers (do this in an else clause). Always display "Done" at the end of the program.

I tried the code below :

total = 0
for num in ( 12, 4, 3, 33, -2, -5, 7, 0, 22, 4 ):
    if num < 0:
        continue 
    if num == 0:
        print("Done")
        break
    else:
        total += num
        print(total)
if num > 0:
    print(total)
print("D0ne")

It returns:
12
16
19
52
59
Done
D0ne

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But With the numbers provided, the program should display only "Done". If you remove the zero, it should display 85 (and "Done").

>Solution :

The for/else pattern is ideal for this:

total = 0
for num in ( 12, 4, 3, 33, -2, -5, 7, 0, 22, 4 ):
    if num < 0:
        continue
    if num == 0:
        break
    total += num
else:
    print(total)
print('Done')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading