Write a Python algorithm which asks the user to enter two numbers 'a' and 'b' and display their sum: a + b.


# Ask the user to enter values of 'a' and 'b'
a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))

# compute the sum of 'a' and 'b'
sum = a + b

# display sum
print("The sum of", a, "and", b, "is", sum)

Here's how it works:

  1. input() function: used to asks the user to enter the first number and second number and stores them in the variables a and b, respectively.
  2. The float() function: is used to convert the user input to floating-point numbers, since the input() function always returns a string.
  3. The sum of a and b: is calculated and stored in the variable sum.
  4. The print() function: is used to display the sum of a and b, along with a descriptive message.
  5. The values of a, b, and sum: are inserted into the message using string concatenation.
One thought on “Solution Exercise 2: compute the sum of two numbers”

Leave a Reply