First my codes are from this link
https://www.programiz.com/python-programming/examples/calculator
When i open the program whatever choice I make it prints me invalid input. Am I missing something?
However when I do it on Codeskulptor I do not get it but get the answer i am looking for?
Note: I am using ubuntu and I am trying on Terminal.
Using the built-in eval() is probably the easiest approach:
while True:
data = input('Enter operation: ')
print(eval(data))
use this code
num1 = float(input('Enter a number: '))
the_operation = str(input('choose operator: '))
num2 = float(input('Enter an anathor number: '))
if the_operation == '*':
print(num1 * num2)
elif the_operation == '+':
print(num1 + num2)
elif the_operation == '-':
print(num1 - num2)
elif the_operation == '/':
print(num1 / num2)
print("There must be a space between the number and the operator!!\nBlank to continue\n")
def calc(a,b,c):
if b in '+-*/':
if b=='+':
d=a+c
if b=='-':
d=a-c
if b=='*':
d=a*c
if b=='/':
if c==0:
d="undefind"
else:
d=a/c
return "Answer:- {}".format(d)
else:
return "Invalid operator '{}' !".format(b)
while True:
cal=input("Type here:- ").split()
if len(cal)!=3:
print("Try again!")
continue
num1,op,num2=cal[:]
print(calc(float(num1),op,float(num2)))
if input("Going to next calculation or not\n::- ").strip()!='':
break
Related
I'm trying to build a calculator with a loop until I choose to break it or end it.
Can you please suggest?
Thank you in advance,
Max
new_operation = input("press enter to make a new operation or type the word exit to finish")
num1 = int(input("Enter a number: "))
op = input("Enter the operator: ")
num2 = int(input("Enter a second number: "))
while new_operation != ("no"):
if op == ("+"):
print (num1 + num2)
elif op == ("-"):
print (num1 - num2)
elif op == ("*"):
print (num1 * num2)
elif op == ("/"):\
print (num1 / num2)
else:
print ("Invalid operation")
new_operation = input("make a new operation")
Your code looks good, but need some tweak to make it "do while" loop kind of implementation.
while True:
num1 = int(input("Enter a number: "))
op = input("Enter the operator: ")
num2 = int(input("Enter a second number: "))
if op == ("+"):
print (num1 + num2)
elif op == ("-"):
print (num1 - num2)
elif op == ("*"):
print (num1 * num2)
elif op == ("/"):\
print (num1 / num2)
else:
print ("Invalid operation")
new_operation = input("press enter to make a new operation or type the word exit to finish")
if(new_operation == ("no")):
break
Some suggestions:
Check your indentation, as commented above. Python is sensitive to that.
Make sure your inputs and outputs are more consistent and useful. Your prompt says I should type exit, but your code requires them to type no...
Your looping structure is a bit broken. This is to be expected for somebody new to coding. One of my favorites for this case is:
print('Welcome to the calculator!')
do_run = True
while do_run:
...
do_run = input('Would you like to continue [y/n]: ')[0].lower() == 'y'
I am building a calculator and I want to know if i can make num2 input be skipped when "root" option is chosen.
This is my code:
num1 = float(input("Enter a number: "))
op = input("Enter a operator: ")
if op not in operators:
print("Invalid operator")
start()
num2 = float(input("Enter a 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 == "root":
print(math.sqrt(num1))
restart = input("Continue?: ")
if restart == "yes":
start()
else:
sys.exit(0)
I want this to get ignored:
num2 = float(input("Enter a number: "))
When this is the case:
elif op == "root":
print(math.sqrt(num1))
Put the second number input statement behind an if:
op = input("Enter a operator: ")
if op != "root":
num2 = float(input("Enter a number: "))
To do this, you could do:
if op != "root":
num2 = float(input("Enter a number: "))
This would skip the num2 input if op == "root"
There can be many different ways. One suggestion would be as below.
num1 = float(input("Enter a number: "))
op = input("Enter a operator: ")
# HERE
if op != "root" and op in operators:
num2 = float(input("Enter a number: "))
elif op not in operators:
print("Invalid operator")
start()
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 == "root":
print(math.sqrt(num1))
restart = input("Continue?: ")
if restart == "yes":
start()
else:
sys.exit(0)
or
# HERE
if op in operators:
if op != "root":
num2 = float(input("Enter a number: "))
else:
print("Invalid operator")
start()
I'm new to coding. I would like to understand why something like this happens, and of couse how I could fix it.
When I run the .PY script, it works fine. But when I run it in CMD, or compile it to an EXE, it opens, or starts. I can fill in my first number. But when I want to fill in the operator, it stops working and gives me this error: Syntax error: Unexpected EOF while parsing.
Screenshot of the Error in the CMD:
The full code of this file:
i = 1
print("------------------CALCULATOR------------------")
print("-------- Valid operators: +, -, /, * --------")
print("----------------------------------------------")
while i <= 2:
num1 = float(input("Enter your first number: "))
op = input("Enter the operator: ")
num2 = float(input("Enter your second number: "))
if op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "/":
print(num1 / num2)
elif op == "*":
print(num1 * num2)
else:
print("You need to enter a valid operator!")
more_calc = input("Do you want to do another calculation?\n---> ")
if more_calc == "yes":
print("----------------------------------------------\nOk!")
elif more_calc == "no":
i += 2
input("\n----------------------------------------------\nThank you for using my Calculator!\nPress enter to exit.\n----------------------------------------------")
I got to do this calculator on python 3 that must execute on loop until the user types exit. Besides, programming ahead of the user typing invalid characters, such as letters when asked to type an operator or a number.
I must use while, if... However, I cannot use import.
while True:
operator = input("Give me an operator or \"exit\" to stop : ")
if operator == "exit":
break
if operator != "+" or "-" or "*" or "/":
print ("You must enter an operator")
break
no1 = input("Enter a number: ")
no2 = input("Enter a number: ")
if operator == "+":
output = int(num1) + int(num2)
elif operator == "-":
output = int(num1) - int(num2)
elif operator == "*":
output = int(num1) * int(num2)
else :
output = int(num1) / int(num2)
print("The result is " + str(result))
print("See you soon!")
I expect it to actually not stop when we enter anything but an operator, I want it to loop back to:
operator = input("Give me an operator or \"exit\" to stop : ")
You will find below this your code that work as expected, however lets start with general rules.
Be attentif, when you declare a variable, use the same elsewhere in your code.
Test, simple part of your code before trying to do a script. You condition to test operator was totally broken.
while True:
operator = input("Give me an operator or \"exit\" to stop : ")
if operator == "exit":
break
if operator not in [ "+", "-", "*" , "/"]: #<== here you condition is wrong ,do this instead
print ("You must enter an operator")
continue
try:
num1 = int(input("Enter a number: ")) #
num2 = int(input("Enter a number: ")) # <== both of this variable are not use else where ,rename to be consitdnt with the rest of your code
except ValueError:
print("Please enter an integer")
if operator == "+":
output = num1 + num2
elif operator == "-":
output = num1 - num2
elif operator == "*":
output = num1 * num2
else :
output = num1 / num2
print("The result is " + str(output)) #<=== here also, results was not defined
print("See you soon!")
Put a generic else statement which will continue with the next iteration.
if condition1 :
//logic
elif condition2 :
//logic
else:
continue
Your problem is that you are doing:
if operator != "+" or "-" or "*" or "/":
And what that is really doing, is that:
if operator != "+" or 45 or 42 or 47: (ASCII representation of these characters)
What this means, is that the condition is true no matter what, because or n where N is not 0, would pass any time.
You want:
if operator != "+" and operator != "-" and operator != "*" and operator != "/":
You want an AND gate.
Also, I noticed you are saying no1 = input(...) then doing int(num1) instead of int(no1).
As for jumping back to input, you use continue
Final code:
while True:
operator = input("Give me an operator or \"exit\" to stop : ")
if operator == "exit":
break
if operator not in [ "+", "-", "*" , "/"]: # credit to Florian Bernard for this line :)
print ("You must enter an operator")
continue
num1 = input("Enter a number: ")
num2 = input("Enter a number: ")
if operator == "+":
output = int(num1) + int(num2)
elif operator == "-":
output = int(num1) - int(num2)
elif operator == "*":
output = int(num1) * int(num2)
else:
output = int(num1) / int(num2)
print("The result is " + str(output)) # this was previously str(result) but result is was not defined
print("See you soon!")
BUT! if you are feeling new today, you can use the walrus operator introduced in PEP 572 and available from python 3.8
while (operator := input("Give me an operator or \"exit\" to stop : ")) != "exit":
if operator not in [ "+", "-", "*" , "/"]: # credit to Florian Bernard for this line :)
print ("You must enter an operator")
continue
num1 = input("Enter a number: ")
num2 = input("Enter a number: ")
if operator == "+":
output = int(num1) + int(num2)
elif operator == "-":
output = int(num1) - int(num2)
elif operator == "*":
output = int(num1) * int(num2)
else:
output = int(num1) / int(num2)
print("The result is " + str(output))
print("See you soon!")
EDIT:
Edited the final code to use continue, previous version was.
Also added a python 3.8 implementation.
EDIT2:
Just correcting some stuff, making sentences truer.
I'm trying to program a simple Python calculator but always when I run the code the Atom editor has a problem with reading this line:
while True:
user_input = input(":")
Under this line of code I entered the methods for Python and told it what it should do:
if userinput == "quit":
break
elif userinput == "add":
num1 = float(input("Enter a number"))
num2 = float(input("Enter another number"))
result = str(num1 + num2)
print("The answer is:" + result)
So now when I run this code the Atom editor says that it has a problem with reading this code and it won't ask me for an input as it should.
I think I didn't miss out any code.
This is most likely either mixed tabs and spaces or a missing parenthesis somewhere in your code. also the code has a few mistakes including indentation errors:
while True:
user_input = input(":")
if user_input == "quit":
break
elif user_input == "add":
num1 = float(input("Enter a number"))
num2 = float(input("Enter another number"))
result = str(num1 + num2)
print("The answer is:", result)