-1

I am trying to make it so that if either input value is not a number, it will print an error message saying that an integer must be entered. And whenever no error is caught, it will multiply x by y. How would I do this?

Here is what I have so far:

def main():
    try:
        x = int(input("Please enter a number: "))
        y = int(input("Please enter another number: "))
    except:
Woody1193
  • 4,413
  • 1
  • 28
  • 58

4 Answers4

0

It's good practice to not have empty except as it makes debugging difficult

def main():
    try:
        
        x = int(input("Please enter a number: "))
        y = int(input("Please enter another number: "))
        print(x*y)
    
    except ValueError:
        print("An integer must be entered. ")
main()
Mark
  • 84,957
  • 6
  • 91
  • 136
TheRavenSpectre
  • 161
  • 1
  • 9
0

you could try this:

def main():
    while True:
        try:
        
            x = int(input("Please enter a number: "))
            y = int(input("Please enter another number: "))
            print(x*y)
            break
        except:
            print("Please input an integer")
Pwuurple
  • 312
  • 1
  • 10
0
while True:            
    try:
        x, y = map(int, input("Please enter two number: ").strip().split())
        return x * y
    except:
        print("two integer must be entered")
eness
  • 1
0

Try, except, finally is the most pythonic way of doing this. Note that the code below will only raise an error if the value entered isn't a base 10 integer (which is probably what you want, but worth noting).

try:
     x = int(input("Please enter a number: "))
     y = int(input("Please enter another number: "))
except ValueError:
    print("Entered values must be a base 10 integer")
finally:
    print(x*y)
I break things
  • 337
  • 3
  • 11
  • From [python docs](https://docs.python.org/3/tutorial/errors.html#defining-clean-up-actions): "The finally clause runs whether or not the try statement produces an exception". This means that `print(x*y)` will run even when the `try` block fails, which will generate another, uncaught exception: `name 'x' is not defined` – Mark May 20 '22 at 16:58