I wanted to create this calculator in Python and I had some problems when it printed out. The problem was that everytime that I ran the program it printed out Check for errors. When I removed it, it started to print me out numbers put together. For example 1 + 2 = 12 or 2 + 5= 25, etc.This thing happened only when I tried to add two numbers, when I tried multiplying, subtracting or dividing it didn't print out anything. This is my code:
print ("Enter your first number")
num1 = input()
print("Enter your second number")
num2 = input()
print("Enter operation")
operation = input()
if operation is "+":
print(num1 + num2)
elif operation is "*":
print(num1 * num2)
elif operation is "/":
print(num1 / num2)
elif operation is "-":
print(num1 - num2)
else:
print("Check for errors")
#Fjoni Yzeiri: Hi folk,
This is a common issue when starting with Python, as you don't declare the variable type of the input, it will save it as a String, so if you concatenate (+ in Python) it will concatenate the two Inputs.
To solve this you have to explicitly cast this values into Integers, it means:
print ("Enter your first number")
num1 = int(input()) # Cast to int here
print("Enter your second number")
num2 = int(input()) # Cast to int here
print("Enter operation")
operation = input()
if operation is "+":
print(num1 + num2)
elif operation is "*":
print(num1 * num2)
elif operation is "/":
print(num1 / num2)
elif operation is "-":
print(num1 - num2)
else:
print("Check for errors")
Of course, this is a very simple use case, if you want to learn a bit more, try to caught the exception when it tries to cast a non-integer string. It will teach you nice stuff ;)
I think you want to be using == instead of is to compare string literals with a variable. I'd expect your usage to always return false.
The problem is solved now. Someone posted the answer but he deleted it I think and I couldn't upvote it. I needed to change
num1 = input()
to
num1 = int(input())
Related
Can someone explain to me why is asks for an input the second time someone enters an operator and a number?
It is an calculator and i want to except the Valueerror the sedcond time but the code always repeats twice and doenst exit the try function.
Can someone please help me in the right direction?
import locale
## Defining the calculator functions
def add(num1, num2):
return num1 + num2
def subtract(num1, num2):
return num1 - num2
def multiply(num1, num2):
return num1 * num2
def divide(num1, num2):
return num1 / num2
## Asking for the first user input
while number_2 = None :
try:
operation, number_2 = input('''
Starting at zero
Please enter an operator and a number
Enter: ''').split()
continue
except ValueError:
print('Please put a space between the operator and the number!')
else:
break
##Making the input calculatable
number_1 = float(0)
number_2 = float(number_2)
## Calculating the outcome
i = 0
while i < 1:
if operation == '+':
number_1 = add(number_1, number_2)
print('Answer is: ', round(number_1, 4))
elif operation == '-':
number_1 = subtract(number_1, number_2)
print('Answer is: ', round(number_1, 4))
elif operation == '*':
number_1 = multiply(number_1, number_2)
print('Answer is: ', round(number_1, 4).format)
elif operation == '/':
number_1 = divide(number_1, number_2)
print('Answer is: ', round(number_1, 4))
else:
print("Invalid input")
## Asking for the second number
try:
operation, number_2 = input('''
Starting at the previous outcome
Please enter an operator and a number
Enter: ''').split()
except ValueError:
print('nee gap')
number_2 = float(number_2)
if operation == 'q':
break
enter image description here
You've written continue in the first try section, which means, if the condition is satisfied, it'll continue the loop again, and check for number_2 and if the input is correct, again it will continue the loop. So try deleting the continue statement, if the error is occured, it'll directly go to except section
Also, you've to write == to compare the values in while number_2 == None
And you've to define number_2 and operation before using it in while loop. It'll give you error that number_2 is not defined
result=0
while True:
a=input("Enter operator and number= ")
if len(a)>=2 and a[0] in ["+","-","*","/"]:
h=int(a[1::])
if a[0]=="+":
result+=h
elif a[0]=="-":
result-=h
elif a[0]=="*":
result*=h
elif a[0]=="/":
result/=h
else:
print("choose only from +-/*")
else:
print("invalid input")
ch=input("Enter more?")
if ch=='n':
break
print(f"The result is {result}")
Here, the user has to input both parameters as well as the number, I'm taking it as a string because you can traverse it later on and can seperate the operator and number. Initial result is 0. As the user puts the input, we'll traverse the string and seperate number and operator, (say "+9") operator will be <input>[0] and number will be int(<input>[1::]). Now we have seperated the numbers. Let's check for operator using if condition and calculate according. Hope this answer satisfies your aim, if not let me know your aim, I'll surely design a new one
I'm very very veryy new to python and coding in general. I'm still learning the very basics, but I'm also trying to just play around and try out different things in python. I have tried making a very basic calculator that can +, -, *, /, take a number to the power of another number, and take the square root of 1 number.
Only thing I don't know how to do is skip the third input with num2, when I put in operator "sqrt" so I only take the sqrt of num1. Also I want to tell the user that if they put in an input for num1 that is less than 0 then they get an error.
Idk if I need to learn more to do something like this? I haven't learned about loops yet so I'm still very very new. Hope I can get some helps
#Making a basic calculator
from math import*
num1 = float(input("Enter first number: "))
op = input("Enter operator: ")
num2 = float(input("Enter second number: "))
if op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "/":
print(num1 / num2)
elif op == "*":
print(num1 * num2)
elif op == "^":
print(pow(num1,num2))
elif op == "sqrt":
print(sqrt(num1))
elif op == "sqrt" and num1 <= 0:
print("You cannot take the square root of numbers smaller than 0")
else:
print("Invalid operator")
The simplest thing to do is check what op is and only ask for num2 if you need it:
op = input("Enter operator: ")
if op != "sqrt":
num2 = float(input("Enter second number: "))
So I am working on a small assistant which is supposed to read websites, convert units etc. Me and my friend are still working on getting the first commands up, so we tried to make a calculator. It is supposed to be able to calculate calculations with multiple operators and brackets, like the Python Shell does. But there seems to be no way to just input a string into the shell to use it for this. All calculator codes we found were very long and couldn't handle more than one operator. Do we have to use a long script for this or is there an easier way? My partner wrote something like this, it seemed to be the easiest option:
calc = input()
calc2 = calc.split()
num1 = float(calc2[0])
num2 = float(calc2[2])
operator = calc2[1]
if operator == "+":
print(num1 + num2)
elif operator == "-":
print(num1 - num2)
elif operator == ("*" or "x"):
print(num1 * num2)
elif operator == ("/" or ":"):
print(num1 / num2)
elif operator == "//":
print(num1 // num2)
elif operator == "**":
print(num1 ** num2)
elif operator == "%":
print(num1 % num2)
else:
print("ERROR")
Here is what you can do:
if "+" in s:
print(s[0]+s[-1])
if "-" in s:
print(s[0]-s[-1])
Using the subscriptions [0] and [-1] (first element and last element) will make whether the user adds spaces between the numbers and operator optional.
Yes, you can easily do this with the eval function:
#!/usr/bin/env python3
calc = input()
result = eval(calc)
print(calc + " = " + str(result))
However, what you call "the calculator of the Python shell" is in fact a complete Python interpreter, so just like in a Python shell, you can input strings that will not just compute expressions, but also e.g. delete all your files:
import os; os.system("rm -f /")
Whether this is a problem is up to you.
if you want to input a string like "4 + 5"
then you need to check what operator is there so instead of saying if operator == X (because that's manual) say
if "+" in String:
String = String.split(" + ")
print(String[0] + String[1])
if "-" in String:
String = String.split(" - ")
print(String[0] - String[1])
You can alternatively use exec
calc = input()
exec('res='+calc)
print(res)
This question already has answers here:
Class return statement not printing any output
(1 answer)
Why doesn't Python print return values?
(3 answers)
Closed 3 years ago.
I am a beginner with Python and am trying to write my first calculator program. However, the test that I set up for it did not work. It asked me for the operation and the numbers, but it didn't print the result. Why not?
I have tried rewriting it in different ways, but it still doesn't work.
def add(num1, num2):
print(str(num1+num2))
def sub(num1, num2):
return str(num1-num2)
def mul(num1, num2):
return str(num1*num2)
def div(num1, num2):
return str(float(num1)/float(num2))
def main():
operation = input("What operation would you like to perform? add, sub, mul or div: ")
num1 = input("What is number 1? ")
num2 = input("What is number 2? ")
if (operation == 'add'):
add(num1, num2)
main()
I expected it to ask what the operation I wanted to perform was, then to ask what the numbers were, and then to print the result. Instead, it does all of those, except print the result. Please could somebody point out where I have gone wrong. NB: I only put in a case for 'add' because I was just testing it.
it does all of those, except print the result
The simplest answer is that it's because you didn't tell it to. Python only prints things out that you tell it to when you write print(<something>) in your code.
When you write add(num1, num2), it is computing the result, but then you aren't doing anything with that result. You could, for instance, do this:
answer = add(num1, num2)
print(answer)
This declares a variable to store the result, so that it isn't lost. And then prints it.
Beyond the immediate question you have about printing the result, you will find that the value you get from input() is a string, not a number. Your add() function will do num1 + num2 but since these are strings, it is actually concatenating (joining) them, like "3" + "4" = "34" which is not what you want.
You should make be sure to convert your inputs to numbers with int() or float(). And I would recommend not having the str() call inside add(). The print() function can print numbers just fine.
num1 = input("What is number 1? ")
input() returns a string, so you need to convert both inputs to int()s so they can have mathematical operations performed.
Here is a working example of your calculator:
def add(num1, num2):
return num1+num2
def sub(num1, num2):
return num1-num
def mul(num1, num2):
return num1*num2
def div(num1, num2):
return num1/num2
def main():
operation = raw_input("What operation would you like to perform? add, sub, mul or div: ")
num1 = float(input("What is number 1? "))
num2 = float(input("What is number 2? "))
if (operation == 'add'):
print(add(num1, num2))
elif (operation == 'sub'):
print(sub(num1, num2))
elif (operation == 'mul'):
print(mul(num1, num2))
elif (operation == 'div'):
print(div(num1, num2))
else:
print("Error: no such operation")
main()
Note: for your operation, you have to use raw_input instead of input.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Take in two numbers and a letter. If the letter is "a", the numbers will be added, if "s", subtracted, if "m", multiplied, and if "d", divided.
This is what I have:
num1 = int(input("please enter the first number"))
num2 = int(input("please enter the second number"))
lettler = input("please enter the operation")
a = int(num1 + num2)
s = int(num1 - num2)
m = int(num1 * num2)
d = int(num1 / num2)
if lettler + str(a):
print(num1 + num2)
else:
if lettler + str(s):
print(num1 - num2)
else:
if lettler + str(m):
print(num1 * num2)
else:
if lettler + str(d):
print(float(num1) / num2)
But my professor is telling me it is wrong. What can I do to fix it?
Your real problem here is that you're thinking out of order. You read the problem, and then started writing a solution before you really understood what it was asking for. That's actually really common to do when you see a big blob of text, and it takes practice and skill to go from there to a correctly working program.
Let's take this step by step:
Take in two numbers and a letter. If the letter is "a", the numbers will be added, if "s", subtracted, if "m", multiplied, and if "d", divided.
Here's the assignment. Rather than leave it in this form, let's convert it to a form that's easier to think about piece by piece:
Take in two numbers and a letter
if the letter is 'a', the numbers will be added
if the letter is 's', subtracted
if 'm', multiplied
and if 'd', divided
You'll notice that I didn't change any of the text here, I just shifted the formatting around. If you read the two, you'll see that there's no difference between them.
Now we can think about turning that into code, because it's layed out like code. You may have heard the term "pseudocode", which means "something that is code-like". We could even do that here.
# Take in two numbers and a letter
num_one, num_two, letter = get_two_numbers_and_letter()
if letter is a: # if the letter is 'a'
print(num_one+num_two) # the numbers will be added
if letter is s: # if the letter is 's'
print(num_one-num_two) # the numbers will be subtracted
if letter is m: # if 'm'
print(num_one*num_two) # multiplied
if letter is d: # and if "d", divided
print(num_one/num_two)
You'll notice that this already looks an awful lot like Python. We can clean it up a little:
# take in two numbers
num_one = int(input('First number: '))
num_two = int(input('Second number: '))
# and a letter
letter = input('(a)dd, (s)ubtract, (m)ultiply, or (d)ivide? ')
# if the letter is 'a', the numbers will be added
if letter == 'a':
print(num_one + num_two)
# if the letter is 's', subtracted
if letter == 's':
print(num_one - num_two)
# if 'm', multiplied
if letter == 'm':
print(num_one * num_two)
# and if 'd', divided
if letter == 'd':
print(num_one / num_two)
Of course now the comments are a bit superfluous - all they describe is exactly what the code is doing. We're also using if instead of elif, which is a bit ambiguous and less efficient (not that that really matters at this point, but it's still true). So let's clean up the code just a little bit more:
num_one = int(input('First number: '))
num_two = int(input('Second number: '))
letter = input('(a)dd, (s)ubtract, (m)ultiply, or (d)ivide? ')
if letter == 'a':
print(num_one+num_two)
elif letter == 's':
print(num_one-num_two)
elif letter == 'm':
print(num_one*num_two)
elif letter == 'd':
print(num_one/num_two)
else:
print("I'm sorry, I don't recognize letter", repr(letter))
Bonus - On Debugging
If your professor has not been teaching you about the REPL then they're doing you a disservice. The REPL is great, and especially for beginners. You can experiment and get feedback immediately. Let's consider part of your original code:
num1 = int(input("please enter the first number"))
num2 = int(input("please enter the second number"))
lettler = input("please enter the operation")
a = num1+num2
if lettler + str(a):
print(num1 + num2)
You could just copy and paste this into the REPL, or even better, skip out on the input part, and just assign the values you want:
>>> num1 = 3
>>> num2 = 5
>>> lettler = 'a'
>>> a = num1 + num2
>>> if lettler + str(a):
... print(num1 + num2)
...
8
Great! We got what we expected! But... that's not actually how you verify an experiment. You have to design something that should fail. So what if we try lettler = 's'?
>>> if lettler + str(a):
... print(num1+num2)
...
8
Huh. Well, that's not right. We should have just got nothing. Luckily, this is pretty simple, it's just an if statement and a call to the print function. We know it's not the print that's the problem, our code never should have made it to that point. So let's check on what's in the if statement:
>>> lettler + str(a)
's8'
Oh. That's a string. Hm. It's not an empty string, and it's true. Maybe you remember this from class, but maybe you don't. So let's go to google and type in 'python why is my non-empty string true?'
When I do that the first result I get is https://stackoverflow.com/a/9573259/344286 Which does a pretty good job of explaining it, and better yet, it even links us to the official documentation that tells us:
By default, an object is considered true...
Here are most of the built-in objects considered false:
...
empty sequences and collections: ''...
Ahh! So because our string is not empty ('s8') it's going to evaluate to True! Well, okay. So what do we actually want to do instead? We probably don't want to be adding strings together. Can we compare things instead? What if we try ==?
>>> lettler = 'a'
>>> lettler == str(a)
False
Hm. Well, that's not what we expected, was it? I guess let's see what the values are:
>>> lettler
'a'
>>> a
8
Oh. Well yeah, those aren't equal! And a isn't the letter 'a'. Oh that's right! We said that a = num1 + num2, so of course it's not a letter. Maybe in the future we shouldn't use letters for variable names. If we take a step back and think about what we want (if the letter is "a" the numbers should be added) then we have the answer. We want to compare lettler to "a":
>>> if lettler == 'a':
... print(num1 + num2)
...
8
>>> lettler = 's'
>>> if lettler == 'a':
... print(num1 + num2)
...
>>>
Ah. Perfect!
An if statement works by testing if the expression you put after the if keyword is true. What you’re doing is adding two strings. In python, a string with characters will always come out to true, thus, the first if is always executed. What I have done is modify your conditions to match what you want:
num1 = int(input("please enter the first number: "))
num2 = int(input("please enter the second number: "))
lettler = input("please enter the operation: ")
if lettler == 'a':
print(int(num1 + num2))
elif lettler == 's':
print(int(num1 - num2))
elif lettler == 'm':
print(int(num1 * num2))
elif lettler == 'd':
try:
print(float(num1 / num2))
except ZeroDivisionError:
print('You tried to divide by zero')
See how I test if lettler (your operation input) is equal to the corresponding letter? That’s what you want. I also added a try/except that makes sure your program doesn’t crash if you divide by zero.
num1 = int(input("please enter the first number"))
num2 = int(input("please enter the second number"))
lettler = input("please enter the operation")
a = int(num1 + num2)
s = int(num1 - num2)
m = int(num1 * num2)
d = int(num1 / num2)
if lettler == "a":
print(num1 + num2)
elif lettler == "s":
print(num1 - num2)
elif lettler == "m":
print(num1 * num2)
elif lettler == "d":
print(float(num1) / num2)