FREE E LEARNING PLATFORM
HOMEEXCEPTIONSOOPSJVMINTRO
 

Python Program to Add Two Numbers




In this post we will see how to add two numbers in Python. In the first program we have the values assigned to the numbers that we are going to add. In the second program we are adding the numbers entered by user.

Example: Adding two numbers in Python

Here we have hardcoded the values of two numbers in the source code.

# two float values
val1 = 100.99
val2 = 76.15

# Adding the two given numbers
sum = float(val1) + float(val2)

# Displaying the addition result
print("The sum of given numbers is: ", sum)

Output

The sum of given numbers is : 177.14

Example 2: Adding the numbers entered by User

Here we are taking the values from user and then performing the addition on the input numbers. The reason we are using the float() function over the input() function is because the input() function receives the value as String, so to convert it into a number we are using the float().

# Getting the values of two numbers from user
val1 = float(input("Enter first number: "))
val2 = float(input("Enter second number: "))

# Adding the numbers
sum = val1 + val2

# Displaying the result
print("The sum of input numbers is: ", sum)

Output

Enter first number : 10
Enter Second number : 9.9
The sum of input numbers is 19.9






Leave Comment