Calculator code problems: 10 + 5 results in 105 - python

I'm new to this forum and new to python after c++.
I have a problem with a python calculator. When I run it and I do it with + for example : 10 + 5 gives 105, but I wanted to get 15.
Other operations don't even work (I get an error).
print("\nCalculator In Python")
print("\nChose The Operation :")
print("\na)+\n\nb)-\n\nc)/\n\nd)*")
answer = input("\n\n: ")
result = int
if answer == 'a':
a = input("\n\nFirst Number : ")
b = input("\n\nSecond Number : ")
print(a, "+", b, "=", a+b)
elif answer == 'b':
a = input("\n\nFirst Number : ")
b = input("\n\nSecond Number : ")
print(a, "-", b, "=", a-b)
elif answer == 'c':
a = input("\n\nFirst Number : ")
b = input("\n\nSecond Number : ")
print(a, "/", b, "=", a/b)
elif answer == 'd':
a = input("\n\nFirst Number : ")
b = input("\n\nSecond Number : ")
print(a, "*", b, "=", a*a)

a+b is actually '10'+'5', which is '105'. This is happening because
input() gives a string. So you need to convert it to a number first.
float(input())
Additionally, to ensure the user gives only valid numbers, you can use:
while True:
a = input('\nGive a:')
try:
a = float(a)
break
except ValueError:
print('Try again.')

The 'input' functions return a string that contains "10" and "5". Conducting a + operator on two strings concatenates them (i.e. "10" + "5" = "105").
If you convert the input to an float or integer you'll get the result you're looking for:
>>> a = "5" + "5"
>>> a
'55'
>>>
>>> b = float("5") + float("5")
>>> b
10.0

Python is setting your input to strings.
You could check this with the "type(a)" function.
You would need to convert the input to either a float or integer.
integer = int(a)
FloatingPoint = float(a)

Related

Errors pertaining to the "!==" function in Python

I'm currently trying to make a program in Python that basically asks you math problems. For some reason, there's a lot of errors, and I have no idea why, such as the "!==" function, which seems to be incorrect. There might also be some other issues as I've only just started Python. Could someone direct me to how to use the !== function correctly and also my other issue: Making my input for "addition, subtraction, or multiplication" into a possible command?
# import random
import time
choice = 0
counterright = 0
counterwrong = 0
def add_question_to_file(a, b):
with open("wrong_answers.txt", 'a') as f:
f.write(f"{a} {operation} {b}\n")
def test(a,operation,b):
user_input = int(input(f"{a} {operation} {b} = "))
if user_input == a + b:
print("You got it right!")
counterright += 1
while user_input != a + b:
if user_input == a + b:
print("You got it right!")
counterwrong += 1
break
else:
add_question_to_file(a, b)
print("Try Again!")
user_input = int(input(f"{a} + {b} = "))
def get_question():
a = random.randint(1, 10)
b = random.randint(1, 10)
with open("calc_log.txt", 'a') as f:
if a<b: #insures a is always greater than b
a, b = b, a
f.write(f"{a} {operation} {b}\n")
def check_operation():
if operation !==t "+" or "-" or "*"
print("Sorry, that's invalid. You have to choose of the three operations!")
t1=time.perf_counter() #
m = input("What mode would you like to use? Review/Normal. Choose Normal if this is your first time!")
operat ion = input("Which operation would you like to use? +,-,or *?")
if m == "review":
with open("wrong_answers.txt", 'r') as f:
for line in f:
a, operation, b = line.split()
test(int(a), int(b))
elif m == "normal":
num_questions = int(input("How many questions would you like to do? "))
for i in range(num_questions):
print(f"You are on question {i + 1}: ")
get_question()
t2=time.perf_counter() #
print("It took you", t2-t1, "seconds for you to solve this problemset") #
print ("You got",counterright,"correct and",counterwrong,"wrong.")
The reason !== isn't working is because this is not an operator in python. Try using !=. It means not equal too.
The does not equal function in python is !=. The double equal sign (==) is only used when you want to check for equality. I hope this helps!

how to get out from loop with a single word

I have to make a program using while that:
Will ask for user to put 2 integer numbers
and give back the addition and multiplication
of those 2.
Will check if the numbers are integers.
Will close if the user uses the word stop.
I have made 1 and 2 but am stuck on 3. Here is what I wrote:
while True:
try:
x = int(input("Give an integer for x"))
c = int(input("Give an integer for c"))
if x=="stop":
break
except:
print(" Try again and use an integer please ")
continue
t = x + c
f = x * c
print("the result is:", t, f)
Your code isn't working because you are starting off by defining x as an integer, and for it to equal "stop", it needs to be a string.
What you therefore want to do is allow x to be input as a string, and then convert it to an integer if it isn't stop:
while True:
try:
x = input("Give an integer for x")
if x=="stop":
break
else:
x = int(x)
c = int(input("Give an integer for c"))
except:
print(" Try again and use an integer please ")
continue
t = x + c
f = x * c
print("the result is:", t, f)
Just a slight change is required (and you can be slightly more structured using else in your try block.
You need to input the first value as a string so that you can first test it for "stop" and only then try to convert it to an integer:
while True:
try:
inp = input("Give an integer for x: ")
if inp == "stop":
break
x = int(inp)
c = int(input("Give an integer for c: "))
except:
print("Try again and use an integer please!")
else:
t = x + c
f = x * c
print("the results are", t, f)
I have also fixed up some spacing issues (i.e. extra spaces and missing spaces in your strings).

Python Formatting With Math In Print()

To print strings with math addition numbers in Python, what is the correct way doing something like:
# Read two inputs from users
a = input("Enter your First Number")
b = input("Enter your Second Number")
# perform type conversion
a = int(a)
b = int(b)
print (f"Result: {a}+{b}")
Output:
Enter your First Number10
Enter your Second Number10
Result: 10+10
Desired output: Result: 20
Your current format string Result: {a}+{b} prints out a and b individually as Result: 10+10 and doesn't perform the addition.
To achieve that, you need to change the f-string to f"Result: {a+b}" so that the addition happens within the formatting curly braces and the result gets printed
print (f"Result: {a+b}")
The output will be
Result: 20
a = input("Enter your First Number")
b = input("Enter your Second Number")
# perform type conversion
a = int(a)
b = int(b)
print (f"Result: {a + b}")
You should change
print (f"Result: {a} + {b}")
to
print (f"Result: {a + b}")
# Read two inputs from users
a = int(input("Enter your First Number"))
b = int(input("Enter your Second Number"))
print ("Result: {}".format(a+b))

If statements printing after a variable is entered

I'm new to programming/coding and I'm using Python in my course. I have been asked to create a calculator that can add, subtract, divide and multiply. I'm trying to get the program to receive the numbers through input, then ask for what to do with it (eg. plus or minus) through a number entered and then give a result. I have the input stages of the code working but when I get to the last part I cant get it to work. This is the code
FirstNumber = "blank1"
SecondNumber = "blank2"
Device = "blank3"
FirstNumber = input("First number?")
SecondNumber = input("Second number?")
Device = input("Select a Number. Options are; 1.Plus, 2.Minus, 3.Times, 4.Divide.")
if "Device" == 1:
print("FirstNumber"+"SecondNumber")
When it gets the the end it does nothing, help please.
The condition "Device" == 1 will always be False because no string is equal to an integer. You probably want to change it to Device == 1, but this will (likely) still fail because on python3.x, input returns a string. You probably want something like:
Device = int(input("Select a Number. Options are; 1.Plus, 2.Minus, 3.Times, 4.Divide."))
if Device == 1:
print(FirstNumber + SecondNumber)
Of course, for the same reason, you'll probably also want to convert FirstNumber and SecondNumber into some numeric type ...
ops = {
"+": lambda a,b: a+b,
"-": lambda a,b: a-b,
"*": lambda a,b: a*b,
"/": lambda a,b: a/b
}
a = int(input("Please enter the first number: "))
op = input("Please enter an operator: ")
b = int(input("Please enter the second number: "))
print("{} {} {} == {}".format(a, op, b, ops[op](a,b)))

input from user

It's a very basic doubt in Python in getting user input, does Python takes any input as string and to use it for calculation we have to change it to integer or what? In the following code:
a = raw_input("Enter the first no:")
b = raw_input("Enter the second no:")
c = a + b
d = a - b
p = a * b
print "sum =", c
print "difference = ", d
print "product = ", p
Python gives following error:
Enter the first no:2
Enter the second no:4
Traceback (most recent call last):
File "C:\Python27\CTE Python Practise\SumDiffProduct.py", line 7, in <module>
d=a-b
TypeError: unsupported operand type(s) for -: 'str' and 'str'
Can someone tell please why am I getting this error?
Yes, every input is string. But just try:
a = int(a)
b = int(b)
before your code.
But be aware of the fact, that user can pass any string he likes with raw_input. The safe method is try/except block.
try:
a = int(a)
b = int(b)
except ValueError:
raise Exception("Please, insert a number") #or any other handling
So it could be like:
try:
a = int(a)
b = int(b)
except ValueError:
raise Exception("Please, insert a number") #or any other handling
c=a+b
d=a-b
p=a*b
print "sum =", c
print "difference = ", d
print "product = ", p
From the documentaion:
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
Yes, you are correct thinking you need to change the input from string to integer.
Replace a = raw_input("Enter the first no: ") with a = int(raw_input("Enter the first no: ")).
Note that this will raise a ValueError if the input given is not an integer. See this for how to handle exceptions like this (or use isnumeric() for checking if a string is a number).
Also, beware that you although you might find that replacing raw_input with input might work, it is a bad and unsafe method because in Python 2.x it evaluates the input (although in Python 3.x raw_input is replaced with input).
Example code could therefore be:
try:
a = int(raw_input("Enter the first no: "))
b = int(raw_input("Enter the second no: "))
except ValueError:
a = default_value1
b = default_value2
print "Invalid input"
c = a+b
d = a-b
p = a*b
print "sum = ", c
print "difference = ", d
print "product = ", p
a = input("Enter integer 1: ")
b = input("Enter integer 2: ")
c=a+b
d=a-b
p=a*b
print "sum =", c
print "difference = ", d
print "product = ", p
Just use input() and you will get the right results. raw_input take input as String.
And one more i Would Like to Add..
why to use 3 extra variables ?
Just try:
print "Sum =", a + b
print "Difference = ", a - b
print "Product = ", a * b
Don't make the Code complex.
raw_input() stores the inputted string from user as a "string format" after stripping the trailing new line character (when you hit enter). You are using mathematical operations on string format that's why getting these errors, first cast your input string into some int variable by using a = int(a) and b = int(b) then apply these operations.

Categories