SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Tony Gaddis
Chapter:
Repetition Structures
Exercise:
Algorithm Workbench
Question:2 | ISBN:9780132576376 | Edition: 2

Question

Write a while loop that asks the user to enter two numbers. The numbers should be added and the sum displayed. The loop should ask the user if he or she wishes to perform the operation again. If so, the loop should repeat, otherwise it should terminate.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

repeat = True
#Prompt and read the two numbers
while repeat:
    firstNumber = float(input("Enter the first number: "))
    secondNumber = float(input("Enter the second number: "))
    #Calculate the sum
    sum = firstNumber + secondNumber
    print("The sum is:", sum)
    #The loop should ask the user if he or she wishes to 
    #perform the operation again. If so, the loop should
    #repeat, otherwise it should terminate.
    userChoice = input("Do you want to perform the operation again? (y/n): ")
    if userChoice.lower() != 'y':
        repeat = False

Executed Output:

Enter the first number: 20
Enter the second number: 300
The sum is: 320.0
Do you want to perform the operation again? (y/n): y
Enter the first number: 25
Enter the second number: -5
The sum is: 20.0
Do you want to perform the operation again? (y/n): n

 

0 0

Discussions

Post the discussion to improve the above solution.