dutchballa
dutchballa

Reputation: 79

Python using "global" in function to return new variable

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.

Upvotes: 2

Views: 134

Answers (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)

Upvotes: 2

A M
A M

Reputation: 448

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 !

Upvotes: 1

Related Questions