2

I am relatively new at programming and working through LPTHW. I want to build a function that will check if a raw_input() is a number and and then return either float(input) or simply the original input if not a number.

I have determined that input.isdigit() is an acceptable function to use, but now I am struggling building the function that will actually return the variable after the if statement compiles. I believe using the global function will help me, but after reading some posts, it doesn't sound like global is very "effective" tool.

This is what I have thus far.

def Number_Check(input):
    global input
    if input.isdigit():
        input = float(input)
    else:
        input = input

Running this in the shell gives me the error:

SyntaxError: name 'input' is local and global (ex36.py, line 19)

Any help on this is greatly appreciated.

2
  • change the signature from def Number_Check(input) to def Number_Check(), or if it is a different variable, just rename it. Commented Aug 17, 2013 at 5:12
  • 1
    you definitely do not need global for this Commented Aug 17, 2013 at 5:22

2 Answers 2

2

Forget global, you do not need it here; global is only needed sometimes when you want to share state between different function calls. As the value of input is always new to the call, global is definitely what you should be using. Try the following instead

def number_check(input):
    """
    if the given input can be converted to a float, return
    the float, otherwise return the input as a string unchanged.
    """
    try:
        return float(input)
    except ValueError:
        return input

# and use like this:

string = raw_input()
number_or_string = number_check(input)
Sign up to request clarification or add additional context in comments.

Comments

1

You have two input in your code. One is a parameter and the other one is a global variable. The compiler doesn't know which one is the one you are referring to. Maybe change name of one of those?

input = input

This doesn't make any sense. Are you trying to say that input remains the same? then simply remove the else part! And you dont need the global variable. You can directly return the value !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.