Exercise2
Write a Python algorithm which asks the user to enter two numbers 'a' and 'b' and display their sum: a + b.
Solution
# 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:
- 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.
- The float() function: is used to convert the user input to floating-point numbers, since the input() function always returns a string.
- The sum of a and b: is calculated and stored in the variable sum.
- The print() function: is used to display the sum of a and b, along with a descriptive message.
- The values of a, b, and sum: are inserted into the message using string concatenation.
[…] Exercise 2 || Solution […]