The program asks for two numbers, adds them with + and prints the sum. The one step that beginners often miss is converting the typed text into numbers first.
The program
first = float(input("Enter the first number: ")) second = float(input("Enter the second number: ")) total = first + second print(f"{first} + {second} = {total}")
Typed in this example: 12.5, 7.25. Press Run to type your own.
Enter the first number: 12.5 Enter the second number: 7.25 12.5 + 7.25 = 19.75
How it works
input()always gives back a string, even when the user types digits.float(...)turns that string into a number that can have a decimal point.+on two numbers adds them. The f-string puts the three values into one line.
Why you must convert
+ on two strings does not add them. It joins them end to end:
a = "12" b = "30" print(a + b) print(int(a) + int(b))
1230 42
int or float
Use int() when the user must type whole numbers. Then 7 prints as 7 and not 7.0:
first = int(input("First whole number: ")) second = int(input("Second whole number: ")) print("Sum:", first + second)
Typed in this example: 25, 17. Press Run to type your own.
First whole number: 25 Second whole number: 17 Sum: 42
int("7.5") raises a ValueError, so use float() if decimals are allowed. The type conversion page shows what each conversion accepts.
Without input
If the numbers are already in your code, add them directly. sum() adds every number in a list:
a = 15 b = 27 print("Sum:", a + b) print(sum([3, 4.5, 10])) print(0.1 + 0.2) print(round(0.1 + 0.2, 2))
Sum: 42 17.5 0.30000000000000004 0.3
The last two lines show a normal property of floats: most decimal fractions cannot be stored exactly in binary, so a tiny error can appear. Use round() or an f-string such as f"{total:.2f}" when you print the result.