In this program, we are given two numeric values by the user, and our task is to calculate their sum and display the result on the screen. The program first accepts input from the keyboard, converts the entered values into numbers (such as integers or floating-point values), performs the addition using the + operator, and then prints the final output. For example, if the user enters 10 and 20, the program should display 30 as the result. Below, you will find a simple implementation, followed by a few alternative approaches to handle different types of inputs and improve robustness.
Add Two Numbers in Python :
# Simple (straightforward) program to add two numbers
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
result = num1 + num2
print("Sum:", result)Output :
Enter first number: 12.5
Enter second number: 3.4
Sum: 15.9
Code language: CSS (css)
input() reads a line of text typed by the user.float() converts that text into a floating-point number so the program can add decimals as well as integers.+ operator performs arithmetic addition on the two numeric values.print() displays the result on the screen.If you expect only integers, use int() instead of float():
num1 = int(input("Enter first integer: "))
num2 = int(input("Enter second integer: "))
print("Sum:", num1 + num2)This will raise a ValueError if the user types a non-integer (for example 3.5 or abc).
You can accept two space-separated numbers and convert them with map().
Code:
num1, num2 = map(float, input("Enter two numbers separated by space: ").split())
print("Sum:", num1 + num2)Note: This expects exactly two values; otherwise, Python raises a ValueError.
If you want the program to handle invalid input gracefully, use a helper function that keeps prompting until a valid number is entered.
Code :
def read_number(prompt):
while True:
s = input(prompt).strip()
try:
if '.' in s or 'e' in s.lower():
return float(s)
return int(s)
except ValueError:
print("Invalid number. Please try again.")
n1 = read_number("Enter first number: ")
n2 = read_number("Enter second number: ")
print("Sum:", n1 + n2)
This approach keeps integers as int when possible and falls back to float for decimal input.
int() when you only want integers — it will truncate decimals and raise errors for non-integers.float() when decimals are required.map() with split() is compact but less user-friendly for errors; wrap it in try/except if you expect bad input.format() or f-strings, for example: print(f"Sum: {result:.4f}").Constant time — O(1). The program performs a fixed number of operations regardless of input size.
Copy the Simple program snippet into a file called sum_two_numbers.py and run:
python3 sum_two_numbers.pyCode language: CSS (css)
Enter different inputs (integers, floats, invalid strings) to see how each variant behaves.