 # This seems really dumb, because I'm converting to int but it still doesn't recognize

``````operator = ['+', '-', '/', '*', '']

class calculator:
def subtraction(x,y):
sub = int(x) - int(y)
print(sub)
def multiplication(x,y):
mult = int(x)*int(y)
print(mult)
def division(x,y):
#Doing a try on the division function in calculator class
try:
y = int(y)
x = int(x)
except ValueError:
print("Cannot divide, because either first or second number \
is not an integer.")
div = int(x)/int(y)
print(div)

while True:
'''See if input is a number.  Inputs are turned into integers at assignment
for math that follows.'''
x = input("Enter first number")
y = input("Enter second number")

z = input("Enter an operator. (*, /, +, -)")

#Check if z in the list operator, if not then
if z not in operator:
print("No valid operator detected.")
for n in operator:
if z == '+':
if x == 0 and y == 0:
print("Answer is 0, because either first or second \
number was incorrect type.")
print(x)
print(y)
break
elif z == '*':
calculator.multiplication(x,y)
if x == 0 and y == 0:
print("Answer is 0, because either first or second \
number was not an integer.")
print(x)
print(y)
break
elif z == '/':
#the if statement was removed on this elif, but it now says that y is not defined
print(x)
print(y)
calculator.division(x,y)
break
elif z == '-':
calculator.subtraction(x,y)
if x == 0 and y == 0:
print("Answer is 0, because either first or second \
number was not an integer.")
break

``````

Error with input ‘asfasd’ for second number input

``````Traceback (most recent call last):
File "D:\Documents\Python Scripts\class example.py", line 62, in <module>
calculator.division(x,y)
File "D:\Documents\Python Scripts\class example.py", line 22, in division
div = int(x)/int(y)
ValueError: invalid literal for int() with base 10: 'asfasd'
``````

I want it to be able to do try and except within each function of the calculator class, and give a unique message if it errors within those functions. For now, I’ve been testing divide, but it apparently doesn’t want to make the number into an integer, even though I told it to convert when it arrived at the class.

If I convert it at input, it still just errors ‘invalid literal’ if I were to input a non-int. I don’t want the program to crash, but tell the user to put proper input in.

2 Likes

Note: Zero(0) is an integer too. You don’t want a ZeroDivisionError.

Found this on the internet. It uses more more general `except`, maybe this could help you.

def is_float(value):
try:
float(value)
return True
except:
return False

2 Likes
``````operator = ['+', '-', '/', '*', '']

def is_float(value):
try:
float(value)
return True
except:
return False

class calculator:
def subtraction(x,y):
sub = int(x) - int(y)
print(sub)
def multiplication(x,y):
mult = int(x)*int(y)
print(mult)
def division(x,y):
#Doing a try on the division function in calculator class
is_float(x)
is_float(y)
if x or y == False:
print("Cannot divide, because either first or second value \
is not an integer.")
div = int(x)/int(y)
print(div)

while True:
'''See if input is a number.  Inputs are turned into integers at assignment
for math that follows.'''
x = input("Enter first number")
y = input("Enter second number")

z = input("Enter an operator. (*, /, +, -)")

#Check if z in the list operator, if not then
if z not in operator:
print("No valid operator detected.")
for n in operator:
if z == '+':
if x == 0 and y == 0:
print("Answer is 0, because either first or second \
number was incorrect type.")
print(x)
print(y)
break
elif z == '*':
calculator.multiplication(x,y)
if x == 0 and y == 0:
print("Answer is 0, because either first or second \
number was not an integer.")
print(x)
print(y)
break
elif z == '/':
#the if statement was removed on this elif, but it now says that y is not defined
print(x)
print(y)
calculator.division(x,y)
break
elif z == '-':
calculator.subtraction(x,y)
if x == 0 and y == 0:
print("Answer is 0, because either first or second \
number was not an integer.")
break
``````

There’s no error when I divide, but it still calls the print statement that was written in the calculator class field for divide.

2 Likes

It looks like your treating ‘x’ and ‘y’ as booleans here, and I’m betting they’re not.

Did you define is_float() somewhere? And the is_float function I found earlier returns a boolean, but it looks like your dropping the value, and those lines do nothing.

If you divide by zero you will get a divide by zero error (“ZeroDivisionError: integer division or modulo by zero”) In mathematics division by zero is considered undefined.

“The” so only one?, and

probably isn’t right.

Do you have operator defined somewhere?
Looks your combining a `for` loop and an `if` statement when you don’t need to.

Zero is an integer. You might want to learn more about the number types like: integer, natural, whole, real, imaginary, quotients, …

1 Like

Why would I be dropping the value if I stored is_float(x) and is_float(y) in vars a and z?

``````operator = ['+', '-', '/', '*', '']

def is_float(value):
try:
float(value)
return True
except:
return False

class calculator:
def subtraction(x,y):
sub = int(x) - int(y)
print(sub)
def multiplication(x,y):
mult = int(x)*int(y)
print(mult)
def division(x,y):
#Doing a try on the division function in calculator class
z = is_float(x)
a = is_float(y)
if a or z == False:
print("Cannot divide, because either first or second value \
is not an integer.")
div = int(x)/int(y)
print(div)
``````
2 Likes

This

isn’t the same code that was posted earlier:

When you do

it doesn’t change what `value` is. it returns to the line the closest ‘float’ representation of what `value` is, since this line does nothing with that, this line does nothing.

If `y` is zero you will get an error.

2 Likes

How do I best use the is_float function? Other ways of implementing try except haven’t worked.

2 Likes

Experiment with something like: (‘int’ is short for ‘integer’)

``````if int(x) == x:
``````

p.s.

Ops… somehow I missed this, looks like you did define it somewhere.

1 Like

Can we trust this function?

All we’ve really done is shown that an input CAN BE cast as a float, not that it IS a float.

2 Likes

I since deleted it, and coming up with another solution…

2 Likes

If this is to satisfy a lesson, then abide by what it expects; otherwise, write a piece of code that does what it is expected to do, and leverage whatever comes to hand.

``````isinstance(x, float)
``````

As in…

``````>>> isinstance(5.0, float)
True
>>> isinstance(5, float)
False
>>>
``````

In Python 2 we could divide by `1` to determine if a decimal was attached or not.

``````5.0 / 1  => 5
5 / 1    => 5
``````

If the string representations don’t match, then it’s a float.

In Python 3 we have to step up the division process using the, `//` operator. Some will call it floor division while others will call it integer division. There are no remainders, in any case.

``````5.0 // 1  =>  5
``````

We can still use a snapshot of each side for comparison.

If we wanted to use the exception handling approach that too would be easy.

``````try:
a = [x]
except TypeError:
# something
``````

Consider,

``````>>> x = []
>>> x[0.0]
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
x[0.0]
TypeError: list indices must be integers or slices, not float
>>>
``````

Notice that it didn’t even conceive of an index other that to choke on a float. Follow this up with,

``````>>> x
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
x
IndexError: list index out of range
>>>
``````

and we zero in on two exceptions to flag, and their order.

2 Likes
``````operator = ['+', '-', '/', '*', '']

#This is calculator (a class), with fields for four basic math operations
class calculator:
def subtraction(x,y):
sub = int(x) - int(y)
print(sub)
def multiplication(x,y):
mult = int(x)*int(y)
print(mult)
def division(x,y):
#Using if and else on the division field of calculator class
if int(x) == x and int(y) == y:
div = int(x)/int(y)
print(div)
else:
print("ERROR!  Either x or y is not an integer.")

'''The inputs x, y and z are given below.  They're kept going with a while loop, so that
I can test each possible input combination, without having to restart the program every
time.'''

while True:
x = input("Enter first number")
y = input("Enter second number")

z = input("Enter an operator. (*, /, +, -)")

#Check if z in operator (a list).  If not, then it will print 'not there'
if z not in operator:
print("No valid operator detected.")

#Loop through operator (list defined at line 1)
for n in operator:
if z == '+':
print(x)
print(y)
break
elif z == '*':
calculator.multiplication(x,y)
print(x)
print(y)
break
elif z == '/':
#the if statement was removed on this elif. It now says that y is not defined
#print(x)
#print(y)
calculator.division(x,y)
break
elif z == '-':
calculator.subtraction(x,y)
break
``````

I’m only testing division at the moment.

It works when I put a string (eg. ajdfa) as second input, but then errors when the string is first input.

It doesn’t error when I input integers for both first and second input, but it still returns my else statement for division.

Here’s the error test

``````Enter first numberasdfasd
Enter second number1
Enter an operator. (*, /, +, -)/
Traceback (most recent call last):
File "D:\Documents\Python Scripts\class example.py", line 61, in <module>
calculator.division(x,y)
File "D:\Documents\Python Scripts\class example.py", line 18, in division
if int(x) == x and int(y) == y:
ValueError: invalid literal for int() with base 10: 'asdfasd'
``````

The semi-error test

``````Enter first number12
Enter second number1
Enter an operator. (*, /, +, -)/
ERROR!  Either x or y is not an integer.  <--- (THIS SHOULD NOT BE HERE, BUT IT IS FOR SOME REASON)
``````

And then successful test

``````Enter first number12
Enter second numberasdfasdf
Enter an operator. (*, /, +, -)/
ERROR!  Either x or y is not an integer.
``````

Fourth test, to make sure, which passes

``````Enter first number 12
Enter second number 1
Enter an operator. (*, /, +, -) asfasd
No valid operator detected.
``````

And a fifth test, to make sure input values don’t stick around in memory

``````Enter first number 12
Enter second number 1
Enter an operator. (*, /, +, -) /
ERROR!  Either x or y is not an integer.
Enter first number
Enter second number
Enter an operator. (*, /, +, -) /
Traceback (most recent call last):
File "D:\Documents\Python Scripts\class example.py", line 61, in <module>
calculator.division(x,y)
File "D:\Documents\Python Scripts\class example.py", line 18, in division
if int(x) == x and int(y) == y:
ValueError: invalid literal for int() with base 10: ''
``````
2 Likes

Try surrounding this with a `try` `except ValueError`. If `int(input)` errors then the input wasn’t an number that can be converted to an int.

1 Like

Did you add spaces to the end of your prompt? or put in spaces before your number?

1 Like

Yeah I included a space at end of prompt in most recent edit

1 Like