Adding two numbers

The provided Python code is a simple program that performs the addition of two numbers. The user is prompted to input two numeric values, and the program converts these inputs into floating-point numbers to handle decimal values. The addition of the two numbers is then carried out using the + operator, and the result is stored in a variable called sum_result. Finally, the program prints a message displaying the sum of the input numbers in a formatted string using the print function and the format method. This program serves as a basic illustration of user input, data type conversion, arithmetic operations, and output display in Python.


Source code

# Taking input from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

# Adding the two numbers
sum_result = num1 + num2

# Displaying the result
print("The sum of {} and {} is: {}".format(num1, num2, sum_result))

Description

  1. Taking Input from the User:

num1 = float(input("Enter the first number: ")) num2 = float(input("Enter the second number: "))

  • input("Enter the first number: "): This line prompts the user to enter the first number. The input function is used to read a line from the user, and the text inside the parentheses is the prompt displayed to the user.
  • float(...): This is used to convert the user input (which is initially a string) into a floating-point number. The float function is used for this conversion. This is important because the + operator is used for addition, and it works with numeric types.
  1. Adding the Two Numbers:

sum_result = num1 + num2

  • The + operator is used to add the values stored in the variables num1 and num2. The result is then stored in the variable sum_result.
  1. Displaying the Result:
  1. print("The sum of {} and {} is: {}".format(num1, num2, sum_result))
    • The print function is used to display the result. The format method is used to insert the values of num1, num2, and sum_result into the string. The curly braces {} act as placeholders for these values.

So, when you run this code, it will ask the user to enter two numbers, add them together, and then print the result in a formatted string.


Screenshot


Download

By Admin

Leave a Reply

Your email address will not be published. Required fields are marked *