-1

I am trying to do a simple math function which will sum up two variables. However, if string is entered into the function everything goes crazy. Try/Except for some reason is not working:

def addtwo(a,b):
    if int(a) and int(b):
        added=a+b
    else:
        added=print("Insert a number!")
    return added
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Monk
  • 1
  • 2
  • You are mentioning try/except in your question, but you are not using it in the code you've shown. Is the code you have shown not the same you are talking about? – mkrieger1 Sep 15 '18 at 14:24
  • And where is the NameError you mention in the title? – mkrieger1 Sep 15 '18 at 14:25
  • This looks like it could be a Python 2 vs Python 3 issue, specifically around the behaviour of the `input` function. Do you think we could get the full script you are using? – Quinn Mortimer Sep 15 '18 at 14:29
  • See https://stackoverflow.com/questions/21122540/input-error-nameerror-name-is-not-defined – Quinn Mortimer Sep 15 '18 at 14:29

2 Answers2

0

NameErrors are raised when variables are called before being set. This means that your a and b variables are probably not set correctly.

https://airbrake.io/blog/python-exception-handling/python-nameerror

A string being entered in to the function would result in an invalid literal and is a completely different problem. That can be handled using a try and except.

fileinsert
  • 431
  • 4
  • 22
  • You call the procedure with two arguments, but where are those two arguments pulled from? For example, of you are calling this def like this: `output = addtwo(var1, var2)` where are those variables set? – fileinsert Sep 15 '18 at 15:03
-1

NameError is not coming due to this function. Also, your function is written wrongly. NameError will not be solved(because that part you didn't share). But other error which comes to you by addtwo function will be solved by this:-

    >>> def addtwo(a,b):
    ...     if isinstance(a, int) and isinstance(b,int):
    ...             added = a+b
    ...     else:
    ...             added = "Insert a number!"
    ...     return added
    >>> print(addtwo(7,5))
    12
    >>> print(addtwo("str",5))
    Insert a number!

In your code if int(a) and int(b): is creating problem while checking for integer value. It will give this error ValueError: invalid literal for int() with base 10: 'str'. So use isinstance instead of int. And also added=print("Insert a number!") is completely wrong.

Vineet Jain
  • 1,515
  • 4
  • 21
  • 31
  • Despite the lack of information in the original post, this just isn't the problem the original poster is having. A more useful answer would address possible causes for the NameError the OP references. – Quinn Mortimer Sep 15 '18 at 16:17