[Python] Build a Basic Calculator !
Hello ~ In this chapter, we're going to make a basic calculator by Python !
in Python, we can calculate numbers; for instance..
print(5+4)
you'll get "9"
print(6*4)
you get 24
Now ! Let's make a calculator;
num1 = input("Enter a number: ")
num2 = input("Enter another number:")
result = num1 + num2
print(result)
---------------------------------------------------------------
Enter a number: 10
Enter another number: 2
result: 102
What !? I expected 10 + 2 = 12, but it got 102 as a result.
Why it happened is .. Python accepts num1+num2 as a string.!
What we have to do is let Python know those are numbers by putting int (integer)
num1 = input("Enter a number: ")
num2 = input("Enter another number:")
result = int(num1) + int(num2)
print(result)
and Put the same numbers
Enter a number: 10
Enter another number:2
result : 12
we got the number we want :)
However, you're gonna see the problems here; when you type the decimal numbers;
Enter a number: 10.2
Enter another number:11
Traceback (most recent call last):
File "c:\Users\j\Desktop\pythonwork\practice.py", line 3, in <module>
result = int(num1) + int(num2)
ValueError: invalid literal for int() with base 10: '10.2'
Because we gave Python Int(integer) so the Python doesn't react decimal numbers.
what we're going to do is type "float" instead of "int"
num1 = input("Enter a number: ")
num2 = input("Enter another number:")
result = float(num1) + float(num2)
print(result)
Let's run again
Enter a number: 10.2
Enter another number:11.5
result : 21.7
Now we can handle with decimal numbers too :) EASY!