0

I am Trying to execute a script in which if non integer value is enter is should catch with except but it doesn't seem to work ..in my case print(message) in except block is showing in output while executing but errors also come

print('Answer is :', add(num1, num2))

NameError: name 'num1' is not defined

I'm using python 3.8... kindly assist :

def add(num1, num2):
    return num1 + num2    

def subtract(num1, num2):
    return num1 - num2

def into(num1, num2):
    return num1 * num2

def by(num1, num2):
    return num1 / num2

print("Select operation :")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

choice = input("Enter choice(1/2/3/4): ")

if choice in ["1", "2", "3", "4"]:
    try:
        num1 = float(input("Enter first number: "))
        num2 = float(input("Enter second number: "))

    except NameError:
        print('Only Integers Allowed')
    except ValueError:
        print('Only Integers Allowed ')

else:
    print("Invalid Input")
    exit()

def calci():
    if choice == "1":
        print('Answer is :', add(num1, num2))

    elif choice == "2":
        print('Answer is :', subtract(num1, num2))

    elif choice == "3":
        print('Answer is :', into(num1, num2))

    elif choice == "4":
        print('Answer is :', by(num1, num2)) 

calci()
  • Where do you call `calci`? – Thomas Schillaci Jun 23 '20 at 09:39
  • its at the end just after sample code as asked in question –  Jun 23 '20 at 09:40
  • Your code runs fine on my machine – Thomas Schillaci Jun 23 '20 at 09:45
  • Nothing guarantees that all or *any* line of code in a `try` block is executed, that's even the point of them (attempting to do something that might fail for some reason, and providing a way to solve the issue). Since you're defining `num1` and `num2` in a `try` block, this means that *maybe* they are defined (in this case your code should run), or *maybe* not (in this case it fails). You need to [ask the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response). – Unatiel Jun 23 '20 at 09:46
  • Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Unatiel Jun 23 '20 at 09:47
  • thanks for the reply .. my question here was why except block is not working when i enter a non integer value for example below i enter alphabet a and got the below error...Enter second number: >? a Only Integers Allowed calci.py", line 76, in calci(num1,num2) NameError: name 'num2' is not defined –  Jun 23 '20 at 09:49
  • Then you may want to call `calci` inside your `try` – Thomas Schillaci Jun 23 '20 at 09:51
  • It's not working because it not might be exception that's getting raised? Even if it's working, the code flow will continue to execute the next lines, and when it does, it doesn't find num1, num2 etc – Aditya Jun 23 '20 at 09:51
  • @user13531614 If you input an invalid `float`, then `float(input("..."))` will still try to convert your invalid float to a float. This will raise a `ValueError`, which should end the program, but since the failing line of code is in a `try` block, the `except ValueError:` gets executed instead. – Unatiel Jun 23 '20 at 09:52
  • yes that's what i needed ..but it is giving error if you see in my code above u can see i have added print('only intergers allowed ') when any exception is there like if i enter a alphabet it should only print('only integers allowed') but in my case in console i am able to see print statement but value error is also raised though i have not added raise in expect block –  Jun 23 '20 at 09:57
  • 1
    @user13531614 The `NameError` isn't raised in the `try` block. It is raised when you try to use the variables in `calci()`. Since they're not defined because of the `ValueError`, you cannot use them. You need to use a loop until your variables are properly defined, and then `break`. This is explained in details in the question I linked earlier. – Unatiel Jun 23 '20 at 10:06
  • @ Unateil7..Thanks buddy My requirement was filled by adding : except : print('Only Integers Allowed') exit() –  Jun 23 '20 at 10:11

1 Answers1

0

You have to exit() the if statement block so that the program doesn't call the calc() function. If you don't exit the if statement block the program calls the calc() function which is responsible for the error message.

Also, you have to pass the parameters choice, num1 and num2 to the calc() function. I have edited the code a little bit, which might be useful. You can iterate the input() statement so that the user can give it another try after entering an invalid input.

print("Select operation :")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

choice = input("Enter choice(1/2/3/4): ")


if choice in ["1", "2", "3", "4"] :
    try:
        num1 = float(input("Enter first number: "))
        num2 = float(input("Enter second number: "))
    except(TypeError, NameError, ValueError):
        print('Only Numbers Allowed !!!')
        exit()
else:
    print("Invalid Input")
    exit()

def add(a, b):
    return a+b


def subtract(a,b):
    return a-b


def multiply(a,b):
    return a*b


def divide(a,b):
    try:
        return a/b
    except ZeroDivisionError:
        print("Undefined (Can't be divided by zero)")


def calc(choice, num1, num2):
    if choice == "1":
        print('Answer is :', add(num1, num2))
    elif choice == "2":
        print('Answer is :', subtract(num1, num2))
    elif choice == "3":
        print('Answer is :', multiply(num1, num2))
    else:
        print('Answer is :', divide(num1, num2))


calc(choice, num1, num2)
suravshrestha
  • 329
  • 1
  • 5
  • 14