Skip to content
Programs · Program 6-13

Q.Program 6-13: Find the sum of all the positive numbers entered by the user. As soon as the user enters a negative number, stop taking in any further input from the user and display the sum.

Yanam CbseNCERTSubjective· 3mImportance★★★★★est
44% · 17/39 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

A sentinel-controlled while True: loop reads numbers, adds each positive one to a running total, and breaks the moment a negative number arrives — then prints the sum (e.g. inputs 3, 5, 6, −1 give 14).

The idea. The number of inputs is not known in advance — the user decides when to stop by entering a special value (a sentinel, here any negative number). That is exactly the shape for while True: + break: loop indefinitely, and exit from inside when the sentinel appears. A separate variable (total) accumulates the sum, and crucially the sentinel itself is never added.

# Program 6-13: sum positive numbers until a negative number is entered
total = 0
print("Enter numbers to be summed; a negative number stops the input.")
while True:
    entry = int(input("Enter a number: "))
    if entry < 0:
        break
    total += entry
print("Sum of the positive numbers entered =", total)

Sample run (user enters 3, 5, 6, then −1)

Enter numbers to be summed; a negative number stops the input.
Enter a number: 3
Enter a number: 5
Enter a number: 6
Enter a number: -1
Sum of the positive numbers entered = 14

Dry run of that sample

Input entryentry < 0?Actiontotal after
3noadd3
5noadd8

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.