I need help with my python program. I'm doing a calculator.
The numbers must be formed, but for some reason they do not add up.
It seems that I did everything right, but the program does not work.
Please help me. Picture
Code:
a = input('Enter number A \n');
d = input('Enter sign operations \n')
b = input('Enter number B \n')
c = a + b
if str(d) == "+":
int(c) == "a + b"
print('Answer: ' + c)
4 Answers 4
Please don't post screenshots. Copy and paste text and use the {} CODE markdown.
What data type is returned by input()? It's always a string. It doesn't matter what you type.
Where is the variable c actually calculated in this program? Line 4.
What types of data are used to compute c? Two strings.
What happens when you use the "+" operation on two strings instead of two numbers? Try running your program and when it prompts you to "enter number A", type "Joe". When it prompts you to "enter number B", type "Bob". What does your program do?
You need to create numerical objects from each of the strings you entered if you want to do arithmetic.
I think that you tried what you thought would do that on line 7. It doesn't work though. "==" is used to test for equality, not to assign a value. The single "=" is used to bind values to variable names. You do that correctly on lines 1 through 4. Notice that the plain variable name is always by itself on the left of the "=" sign. You do all the fancy stuff on the right side of the "=".
You can actually delete lines 6 and 7 and the output of the program will not change.
Comments
a and b are strings.
a + b concatenates strings a and b.
You need to convert the strings to int:
c = int(a) + int(b)
And remove the lines:
if str(d) == "+":
int(c) == "a + b"
Comments
Here is the complete code, that should to what you want:
a = input('Enter number A \n');
operation = input('Enter sign operations \n')
b = input('Enter number B \n')
c = a + b
if operation == "+":
c= int(a) + int(b)
print('Answer:', c)
Since it looks like you also want to enter an operation sign you might also try eval
a = input('Enter number A \n');
d = raw_input('Enter sign operations \n')
b = input('Enter number B \n')
eval_string = str(a) + d + str(b)
print ( eval(eval_string) )
You should know input accepts only integers and raw_input even if given an integer saves it as a string so it saves only strings.
int(c) == "a + b"?