Interesting math. 1 + 2 = 12. 123 + 456 = 123456
If I had this problem the first thing I would do is verify that math works correctly in Python.
print(1 + 2)
print(123 + 456)
Output:
3
579
Hmmm. It looks like Python knows how to add, so what else could be the problem? The next thing I would do is verify I was entering numbers.
a = input("Enter Number ")
print('type(a) =', type(a))
Output:
Enter Number 1
type(a) = <class 'str'>
Even though I typed a number Python says I entered a string. Guess I need to find out how "input" works. I could look this up in the documentation, but you can also ask for help from the Python terminal.
help(input)
Output:
input(prompt=None, /)
Read a string from standard input. The trailing newline is stripped.
The prompt string, if given, is printed to standard output without a
trailing newline before reading input.
If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
On *nix systems, readline is used if available.
Sure enough, Python returns a string from standard input. Actually in older versions of Python (pre 3.0), input worked differently. The old input tried to evaluate the text you typed, converting it to floats or ints if you typed a number. To read a string you had to raw_input.
To add two numbers you will have to convert the strings returned by "input" into numbers.
a = int(input("Enter Number "))
b = int(input("Enter Number "))
number = a + b
print(a, '+', b, '=', a+b)
Output:
Enter Number 1
Enter Number 2
1 + 2 = 3
Output:
Enter Number 1
Enter Number 2.3
Traceback (most recent call last):
File "...junk.py", line 2, in <module>
b = int(input("Enter Number "))
ValueError: invalid literal for int() with base 10: '2.3'
int() does not work if the string is not a valid representation of an integer. Though 2.3 is a number, it is not an integer.
a = float(input("Enter Number "))
b = float(input("Enter Number "))
number = a + b
print(a, '+', b, '=', a+b)
Output:
Enter Number 1
Enter Number 2.3
1.0 + 2.3 = 3.3
Output:
Enter Number one
Traceback (most recent call last):
File "C:\Users\djhys\Documents\python\musings\junk.py", line 1, in <module>
a = float(input("Enter Number "))
ValueError: could not convert string to float: 'one'
The program works for floats and ints, but it throws an exception for anything that is not a float or int. This may be acceptable, but maybe you would like a simpler error message.
try:
a = float(input("Enter Number "))
b = float(input("Enter Number "))
number = a + b
print(a, '+', b, '=', a+b)
except ValueError as errmsg:
print(errmsg)
Output:
Enter Number 1
Enter Number two
could not convert string to float: 'two'
Even simple programs are surprisingly complex.