Random numbers and uppercase result instead of a number -> - python

I'm working on this calculator but the output that I keep getting is function ops at 0x03B0B858 instead of it being a number, and i'm not really sure what i'm doing wrong....
The calculator asks three questions, first number, operator, and the second number. if you type in letters or anything other than numbers when asked the first number and the second number, it will tell you that what you typed in was invalid and asks you to enter a valid number again, the problem is that I'm trying to do that with the operator as well which is defined inside the function ops() but it doesn't matter what I typed in the operator the result will always be random letters and numbers.... This is the code below, you can copy past it and try it and see what I mean by all of this..
try:
num1 = float(input('Enter the first number: '))
except ValueError:
print('Invalid number')
num1 = float(input('Enter first number again: '))
op = input('Enter operator: ')
try:
num2 = float(input('Enter the second number: '))
except ValueError:
print('Invalid number')
num2 = float(input('Enter second number again: '))
def ops():
if op != '+' or '-' or '/' or '*':
op = input('Invalid Operator, please enter operator: ')
elif op == '+':
return num1 + num2
elif op == '-':
return num1 - num2
elif op == '*':
return num1 * num2
elif op == '/':
return num1 / num2
print(ops)

First:
- to run the function 'ops' you should call print(ops()) , do not forget the parentheses
- try putting the code inside the function, otherwise, your function won't recognize the variable 'op'
- you cannot check the content of the variable 'op' like that
op != '+' or '-' or '/' or '*'
this will be evaluated as a single boolean 'OR',
your code should go like that instead:
if op not in ['+' , '-' , '/' , '*']:
do smthg...
Edit 2:
Complete solution:
def ops():
try:
num1 = float(input('Enter the first number: '))
except ValueError:
print('Invalid number')
num1 = float(input('Enter first number again: '))
op = input('Enter operator:')
try:
num2 = float(input('Enter the second number: '))
except ValueError:
print('Invalid number')
num2 = float(input('Enter second number again: '))
if op not in ['+' , '-' , '/' , '*']:
op = input('Invalid Operator, please enter operator: ')
if op == '+':
return num1 + num2
elif op == '-':
return num1 - num2
elif op == '*':
return num1 * num2
elif op == '/':
return num1 / num2
print(ops())

Related

Trying to break in a while loop for a calculator program while accepting int and str values

I am making a calculator program while I'm learning python, I learned Java in high school and don't know any advanced python functions yet, so try not to use anything too advanced, but lets get to my problem. Sorry if this question isnt organized properly I have never posted on here. the entire program will be at the bottom.
where I'm getting stuck is I have the user enter the operator that they want to use and then it asks for number 1 and number 2. If the user types 'exit' or 'stop' at anytime then the program exits, for the operator part it exits fine and displays the exit message. But when typing exit for num1 or num2 I don't get the response I want, i get many errors playing with it but mainly like num is int cant have string value, num is str cant have int, or it accepts 'exit'/'stop' but then goes onto num2 and then throws an error after anything is entered into num2
operator = (input("Would you like to add(+), subtract(-), multiply(*), divide(/) or use exponents(**)? "))
if operator.lower() == 'exit' or operator.lower() == 'stop':
break #this part works fine and as intended
num1 = eval(input("Enter number 1: "))
if num1 == str() and (num1.lower() == 'exit' or num1.lower() == 'stop'):
break #this part however doesnt work because i have int and str in the same variable
num2 = eval(input("Enter number 2: "))
if num2 == str() and (num2.lower() == 'exit' or num2.lower() == 'stop'):
break
ive tried things from using float, str, or int for nums, messing around with the if statements positions, I want to be able to accept 'exit' or 'stop' as a value for num and then exit the while loop, which ends the program but ive tried for an hour or so and cant figure it out. so again my problem is i need the num1 and num2 values to be able to accept str and int and end the program when they are equal to 'stop' or 'exit'
operator = ''
num1 = ''
num2 = ''
while True:
operator = (input("Would you like to add(+), subtract(-), multiply(*), divide(/) or use exponents(**)? "))
if operator.lower() == 'exit' or operator.lower() == 'stop':
break
num1 = eval(input("Enter number 1: "))
if num1 == str() and (num1.lower() == 'exit' or num1.lower() == 'stop'):
break
num2 = eval(input("Enter number 2: "))
if num2 == str() and (num2.lower() == 'exit' or num2.lower() == 'stop'):
break
oldNum2 = num2
if operator == 'add' or operator == '+':
answer = num1 + num2
print(num1, '+', num2, '=', answer)
elif operator == 'subtract' or operator == '-':
answer = num1 - num2
print(num1, '-', num2, '=', answer)
elif operator == 'multiply' or operator == '*':
answer = num1 * num2
print(num1, '*', num2, '=', answer)
elif operator == 'divide' or operator == '/':
answer = num1 / num2
print(num1, '/', num2, '=', answer)
elif operator == 'exponents' or operator == '**':
answer = num1 ** num2
print(num1, '**', num2, '=', answer)
else:
print('Please type a valid operator...')
print('Program has exited due to user input.')
Basically just treat num1 and num2 as strings until you know they are not stop or exit and then parse the number out of them:
def isExitCommand(userInput):
return userInput.lower() == 'exit' or userInput.lower() == 'stop'
while True:
operator = str(input("Would you like to add(+), subtract(-), multiply(*), divide(/) or use exponents(**)? "))
if isExitCommand(operator):
break #this part works fine and as intended
num1 = input("Enter number 1: ")
if isExitCommand(num1):
break
else:
num1 = float(num1)
num2 = input("Enter number 2: ")
if isExitCommand(num2):
break
else:
num2 = float(num2)
print("You entered {} {} {}".format(num1, operator, num2))
Also there's no need to check if the input is a string, but if you do want to then num1 == str() is incorrect. str() just gives a blank string. You want to do isinstance(s, str) instead for Python 3.x
There are probably many answers to your question, but what I would do is get rid of eval() and just treat the input() since it will always be in a string format.
num1 = input("Enter number 1: ")
if num1.lower() == 'exit' or num1.lower() == 'stop':
break
num2 = input("Enter number 2: ")
if num2.lower() == 'exit' or num2.lower() == 'stop':
break
But since num1 and num2 are both in a string format after the if statements, make sure to cast them to an integer (or float)
num1 = int(num1)
num2 = int(num2)
Your functional problem is at the start of those validation checks:
if num1 == str() and ...
You just failed the check, right there. I think you're trying to check the type of the input after the eval (which, by the way, is a baaaaaad function to use).
str() is a call to convert the empty argument to a string. This returns an empty string. Since this will not be equal to any non-empty input, you fail.
Instead, use the function supplied for this purpose:
if isinstance(num1, str)
Better yet, check the values before you try a conversion:
user_input = input("What would you like to do?")
if user_input in ("stop", "exit"):
break

Beginner python: Rerunning a function automatically after getting the return value

I'm programming a beginner calculator in Python.
I'm stuck trying to rerun the function automatically after getting the return value.
So far it reruns when the except block is triggered.
However, it does not rerun when a sum is entered correctly.
def better_calc():
num1 = float(input("please enter your first number: "))
op = input("please enter an operator: ")
num2 = float(input("please enter your second number: "))
try:
if op == "+":
result = num1+num2
elif op == "-":
result = num1-num2
elif op == "*":
result = num1*num2
elif op == "/":
result = num1/num2
print()
print(num1, op, num2, "=")
return result
better_calc()
print()
except UnboundLocalError:
print("\nError: please enter an established operator")
print()
except ZeroDivisionError:
print("\nError: Can not divide by zero")
print()
better_calc()
print(better_calc())
So I have two questions.
(1) How do I rerun the function after getting the return value?
(2) Should I bother trying to get a return value (is there any benefit?), or just print the answer without a return?
As someone stated in the comments, anything below a return statement is not run because it ends the function, bearing this in mind, my answer to your second question would be no, there is no benefit (in this case) to getting a return value. Instead, I would change your function to this:
def better_calc():
num1 = float(input("please enter your first number: "))
op = input("please enter an operator: ")
num2 = float(input("please enter your second number: "))
try:
if op == "+":
result = num1+num2
elif op == "-":
result = num1-num2
elif op == "*":
result = num1*num2
elif op == "/":
result = num1/num2
print()
print(str(num1)+" "+ str(op)+" "+ str(num2)+ " = " + str(result))
#You just print the result of the calculation above
except UnboundLocalError:
print("\nError: please enter an established operator")
print()
except ZeroDivisionError:
print("\nError: Can not divide by zero")
print()
answer = input("Would you like to enter another calculation?(type \"yes\" if so): ")
return answer
#You are using this return statement to either continue or end the while loop
I would also recommend encasing your file in a while loop like so:
#start of file
#have your better_calc function definition here
startingAnswer = "yes"
while(startingAnswer = "yes"):
startingAnswer = better_calc()
#end of file
This way, you are able to continue doing calculations as long as you want (while not running into infinite loop issues).

How to store result of simple python calculator in variable

I am a beginner to Python and have just started learning recently.
After learning about if, elif and else statements I decided to try and make a simple calculator.
Now, a few hours later I was wondering how I could improve it and make it more complex.
I am trying to store the result of the addition, subtraction, divison or multiplication of the first two numbers in a variable. After doing this I want to Re-create the calculator only I already have the first number.
I am also running into problems with my continue1 if statement, for some reason even if the user inputs "no" the script continues instead of displaying a message.
I'd really appreciate any help at all, Thank you!
Python code:
num1 = float(input("Please enter your first number: "))
num2 = float(input("Please enter your second number: "))
operator = input("Please enter operator: ")
if operator == "/":
print(num1 / num2)
elif operator == "+":
print(num1 + num2)
elif operator == "-":
print(num1 - num2)
elif operator == "*":
print(num1 * num2)
else:
print("FATAL ERROR")
num3 = num1 / num2
num3 = num1 - num2
num3 = num1 + num2
num3 = num1 * num2
continue1 = input ("Would you like too continue? [Yes/No]")
if continue1 == "yes" or "Yes":
operator1 = num4 = float(input("Please enter second number: "))
else:
print("Fatal error")
input("please enter operator")
if operator == "/":
print(num3 / num4)
elif operator == "+":
print(num3 + num4)
elif operator == "-":
print(num3 - num4)
elif operator == "*":
print(num3 * num4)
else:
print("Please press enter to close.")
input("Press Enter to Exit")
In the first part, just assign to a variable (and then print it if you want):
if operator == "/":
num3 = num1 / num2
elif operator == "+":
num3 = num1 + num2
elif operator == "-":
num3 = num1 - num2
elif operator == "*":
num3 = num1 * num2
else:
print("FATAL ERROR")
print(num3)
Regarding the second part of your question, in your statement:
if continue1 == "yes" or "Yes":
this is wrong because or is an operator which will combine the two things on either side of it (typically used where each of these two things is something that evaluates to True or False), so you could have for example:
if continue1 == "yes" or continue1 == "Yes":
You can also add brackets to control the order of execution, as shown below. In this case they do not affect the result, because it is already the case that the == operators are evaluated before the or, but they may make it clearer to read.
if (continue1 == "yes") or (continue1 == "Yes"):
You can also do this instead:
if continue1 in ("yes", "Yes"):
The details of what is going wrong with your original form of the conditional statement are perhaps not important at this stage, but I mention them for sake of completeness. If you enter "No" then the whole expression will actually evaluate to "Yes" (the continue1 == "yes" evaluates to False, and then False or "Yes" evalues to "Yes"). The if statement then treats the value "Yes" (a non-empty string) as a true value and so executes the code which depends on the condition.
num1 = float(input("Please enter your first number: "))
num2 = float(input("Please enter your second number: "))
keepCalculate=True
while keepCalculate:
operator = input("Please enter operator: ")
if operator == "/":
print(num1 / num2)
elif operator == "+":
print(num1 + num2)
elif operator == "-":
print(num1 - num2)
elif operator == "*":
print(num1 * num2)
else:
print("FATAL ERROR")
continue1 = input ("Would you like too continue? [Yes/No]")
if continue1== "yes" or "Yes":
keepCalculate=True
else:
keepCalculate=False
The most simple way todo what you want
simply use
num3 = num1 + num2
to store the codes
"or" in programming doesn't work like or in rel life, it is ussed to separate 2 different conditions, hence use:
if continue1 == "yes" or continue1 == "Yes":
I recreated your code now it's working:
def op(operator,num1,num2):
global num3
if operator == "/":
num3 = num1 / num2
elif operator == "+":
num3 = num1 + num2
elif operator == "-":
num3 = num1 - num2
elif operator == "*":
num3 = num1 * num2
else:
print("FATAL ERROR")
num1 = float(input("Please enter your first number: "))
num2 = float(input("Please enter your second number: "))
operator = input("Please enter operator: ")
op(operator,num1,num2)
print(num3)
continue1 = input ("Would you like too continue? [Yes/No]").lower()
if continue1 in ["yes", "y"]:
num4 = float(input("Please enter second number: "))
operator = input("please enter operator")
op(operator,num3,num4)
print(num3)
else:
print("Fatal error")
input("Press Enter to Exit")
Whatever you do, this code will keep as result, the value of num3 = num1 * num2. You should put these lines in each if, elif

Basic calculator will only add values [duplicate]

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 3 years ago.
I'm new to python and am trying to make a basic calculator that takes two numbers and performs the operation specified by the user, but regardless of the operation I enter, the numbers always add.
num1 = int(input("Enter a number. "))
print(" ")
num2 = int(input("Enter another number. "))
print(" ")
operation = input("Type Add, Subtract, Multiply, or Divide" )
if operation == "Add" or "add":
add = num1 + num2
print(add)
elif operation == "Subtract" or "subtract":
sub = num1 - num2
print(sub)
elif operation == "Multiply" or "multiply":
mult = num1 * num2
print(mult)
elif operation == "Divide" or "divide":
div = num1 / num2
print(div)
else:
print("Enter a valid operation: ")
With what I have, if num1 = 10 and num2 = 5 and I enter "multiply" the result I get is 15, not 50.
if operation == "Add" or "add"
These are two conditions:
if operation == "Add" which does what you expect.
if "add" - Always evaluates to True because it's a constant string.
So you could just as well have written:
if True. You need to replace it with:
if operation == "Add" or operation == "add"
Anyway, I would like to suggest a few things.
Lowercase then check only once
You should lowercase your input string instead of double checking "Add" or "add":
num1 = int(input("Enter a number. "))
print(" ")
num2 = int(input("Enter another number. "))
print(" ")
operation = input("Type Add, Subtract, Multiply, or Divide" ).lower() # Notice the `lower` here
if operation == "add":
add = num1 + num2
print(add)
elif operation == "subtract":
sub = num1 - num2
print(sub)
elif operation "multiply":
mult = num1 * num2
print(mult)
elif operation "divide":
div = num1 / num2
print(div)
else:
print("Enter a valid operation: ")
Use the built-in operator module
The operator module contains exactly the methods that you seek for. You could use it for convenience (haven't tested, should work):
import operator
keywords = {"add": "add", "subtract": "sub", "multiply": "mul", "divide": "truediv"}
num1 = int(input("Enter a number. "))
print(" ")
num2 = int(input("Enter another number. "))
print(" ")
operation = input("Type Add, Subtract, Multiply, or Divide" )
op_func = keywords.get(operation.lower(), "add") # defaults to add
print(getattr(operator, op_func)(num1, num2))
def fun(operation, num1,num2):
operation = operation.lower()
if operation == "add":
add = num1 + num2
print(add)
elif operation == "subtract":
sub = num1 - num2
print(sub)
elif operation == "multiply":
mult = num1 * num2
print(mult)
elif operation == "divide":
div = num1 / num2
print(div)
else:
print("Enter a valid operation: ")
fun('multiply', 10,5)
Why:
if operation == "add" or "Add": this is always True
We can use if operation == "add" or operation == "Add":
You have to do like this:
num1 = int(input("Enter a number. "))
print(" ")
num2 = int(input("Enter another number. "))
print(" ")
operation = str(input("Type Add, Subtract, Multiply, or Divide" ))
if operation == "Add" or operation =="add":
add = num1 + num2
print(add)
elif operation == "Subtract" or operation =="subtract":
sub = num1 - num2
print(sub)
elif operation == "Multiply" or operation =="multiply":
mult = num1 * num2
print(mult)
elif operation == "Divide" or operation =="divide":
div = num1 / num2
print(div)
else:
print("Enter a valid operation: ")
Because of or operation with string, all your conditions will be true.
That's why it will only go to first condition no matter what you give in the input.

what's wrong with my simple calculator, it doesn't error and doesn't execute

I can't quite figure out why my code won't work.
Whenever I click run, it doesn't follow back with a traceback error, it just says process finished with exit code 0.
I thought it might be the casefold but then when I applied it to "Y". casefold it wouldn't work full stop.
def calculate():
operator = input("please select the kind of maths you would like to do")
if operator == "+":
num1 = int(input('Enter first number: '))
num2 = int(input('Enter second number: '))
print('{} + {} ='.format(num1, num2))
print(num1 + num2)
elif operator == "-":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} - {} =".format(num1, num2))
print(num1 - num2)
elif operator == "*":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} * {} =".format(num1, num2))
print(num1 * num2)
elif operator == "/":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} / {} =".format(num1, num2))
print(num1 / num2)
else:
_exit = input("would you like to exit? type Y for YES and N for NO")
if _exit.casefold() == "y":
sys.exit()
else:
calculate()
Just add calculate() at the very end to call the function.
Put function calling calculate() at the end without any indent. Your function isn't even getting called, thus giving no error.
You need to call this calculate() function first (at least it's not being executed in your code sample).
def calculate()
# func code here
#Exec this function
calculate()
I guess it should be like this:
def calculate():
operator = input("please select the kind of maths you would like to do")
if operator == "+":
num1 = int(input('Enter first number: '))
num2 = int(input('Enter second number: '))
print('{} + {} ='.format(num1, num2))
print(num1 + num2)
elif operator == "-":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} - {} =".format(num1, num2))
print(num1 - num2)
elif operator == "*":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} * {} =".format(num1, num2))
print(num1 * num2)
elif operator == "/":
num1 = int(input("enter first number: "))
num2 = int(input("enter second number: "))
print("{} / {} =".format(num1, num2))
print(num1 / num2)
else:
_exit = input("would you like to exit? type Y for YES and N for NO")
if _exit.casefold() == "y":
sys.exit()
else:
calculate()
calculate()

Categories

Resources