Question: Listing 5.4 (addnonnegatives.py) is a program that allows a user to enter any number of nonnegative integers. When the user enters a negative value, the



Listing 5.4 (addnonnegatives.py) is a program that allows a user to enter any number of nonnegative integers. When the user enters a negative value, the program no longer accepts input, and it displays the sum of all the nonnegative values. If a negative number is the first entry, the sum is zero. Listing 5.4: addnonnegatives.py # Allow the user to enter a sequence of nonnegative # integers. The user ends the list with a negative # integer. At the end the sum of the nonnegative # numbers entered is displayed. The program prints # zero if the user provides no nonnegative numbers. entry = 0 sum = 0 # Ensure the loop is entered # Initialize sum # Request input from the user print("Enter numbers to sum, negative number ends list:") while entry >= 0 : # A negative number exits the loop entry = int(input() # Get the value if entry >= 0 # Is number nonnegative? sum += entry # Only add it if it is nonnegative print("Sum=", sum) # Display the sum 1. In Listing 5.4 (addnonnegatives.py) could the condition of the if statement have used > instead of >= and achieved the same results? Why? 2. In Listing 5.4 (addnonnegatives.py) could the condition of the while statement have used > instead of >= and achieved the same results? Why? 3. In Listing 5.4 (addnonnegatives.py) what would happen if the statement entry = int(input()) # Get the value were moved out of the loop? Is moving the assignment out of the loop a good or bad thing to do? Why? 4. How many asterisks does the following code fragment print? 2019 Richard L. Halterman Draft date: June 26, 2019 5.9. EXERCISES a = 0 while a
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
