188k views
5 votes
4. Fill in the code so it adds all integers inputted by the user until the number -1 is inputted & then displays that sum (without the -1 added to the sum.) Also trace your code assuming the user inputs the values 4, 3, 1, -1

sum = 0 sum num
num = __________________
while (_______________________ ):
num = int(input(""Enter a positive integer (-1 to quit): ""))
_________________________
print(________________________

User Yetunde
by
7.4k points

1 Answer

4 votes

Final answer:

To add integers inputted by the user until -1 is entered and then display the sum (excluding the -1), initialize 'sum' to 0, read user input into 'num', use a while loop that adds 'num' to 'sum' if 'num' is not -1, and prints the sum after the loop exits.

Step-by-step explanation:

Python Code Completion for Summation Task

To complete the given code so that it adds all integers inputted by the user until the number -1 is inputted (without adding the -1), the following Python code structure can be used:

sum = 0
num = int(input("Enter a positive integer (-1 to quit): "))
while num != -1:
sum += num
num = int(input("Enter a positive integer (-1 to quit): "))
print("The sum is:", sum)

In this code:

  1. The variable sum is initialized to 0 to start the summation.
  2. The variable num is used to store the user input.
  3. The while loop continues as long as num is not equal to -1.
  4. Inside the loop, num is added to sum using the += operator, and then a new num is read from the user.
  5. Once -1 is inputted, the loop exits, and the sum (which does not include the -1) is printed.

For the provided sequence of inputs (4, 3, 1, -1), this code will output:

The sum is: 8

It's important to understand that when adding numbers:

  1. If both are positive or both are negative, they reinforce each other, and the sum takes their common sign.
  2. If they have opposite signs, the smaller magnitude subtracts from the larger, resulting in the sign of the larger magnitude number.
User Vineet Kasat
by
8.5k points