Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Name 'x' is parameter and global [Python]

Tags:

python

I was wondering why this won't work? I'm fairly new to programming and I'm learning Python.

def convert(x,y):
    while True:
        try:
            global x
            x = int(input("Number: "))
        except ValueError:
            print("Make sure it is a number.")
    while True:
        try:
            global y
            y = int(input("Number: "))
        except ValueError:
            print("Make sure it is a number.")


convert(x,y)

Please tell me how to make this work.

Also, the error I get when I run this is name 'x' is parameter and global.

Ok, I fixed it. This is the correct code.

def convert():
    while True:
        try:
            global number
            number = int(input("Number: "))
            break
        except ValueError:
            print("Make sure it is a number.")
    while True:
        try:
            global number2
            number2 = int(input("Number: "))
            break
        except ValueError:
            print("Make sure it is a number.")


convert()
like image 987
Suds2 Avatar asked Sep 15 '13 00:09

Suds2


4 Answers

In Python, parameters to functions (the things in parentheses next to the definition) are added as local variables to the scope of the function within the code. The Python interpreter makes a few major scans of your code. The first is a syntax scan in which it tests to see if your program is syntactically correct according to Python's rules. One of these rules is that, for a given block of code with its own scope, you can't have variables that are both in the local namespace and the global namespace.

In this scan, it does some special checks for you before even running the code. It stores the names of all global variables and local variables and checks them against one another. Since parameters to functions MUST be considered 'local' within the scope of the function, they cannot be declared as 'global' inside the function definition as that creates a contradiction.

What you could do is declare x and y to be global before your function definitions and that would work.

like image 125
Shashank Avatar answered Sep 20 '22 11:09

Shashank


Haidro explains the problem well, here is a solution!

You seem to want to read two values from the user, and save them to x and y. To do so, you can return multiple values from your function (python supports this).

Example:

def convert():
    x = 0
    y = 0
    while True:
        try:
            x = int(input("Number: "))
            break
        except ValueError:
            print("Make sure it is a number.")
    while True:
        try:
            y = int(input("Number: "))
            break
        except ValueError:
            print("Make sure it is a number.")

    return x, y # magic 

a, b = convert() # you could name these any way you want, even x/y, no collisions anymore

It would be better of course to clean up the code a little to remove the duplicated stuff:

def readNumber():
    while True:
        try:
             x = int(input("Number: "))
             return x
        except ValueError:
             print("Make sure it is a number!")

# and then
a = readNumber()
b = readNumber()

# or:
def convert():
    return readNumber(), readNumber()
a, b = convert()
like image 22
opatut Avatar answered Sep 17 '22 11:09

opatut


It's because you're trying to override the parameter x, but you can't. Here's a related question

To fix this, don't name variables that. You're code is pretty much:

x = 'hi'
x = 5
print(x)
# Why isn't this 'hi'?

By the way, your while loops are going to be running indefinitely. After x = int(input("Number: ")), you may want to add a break. Same for the other loop.

like image 28
TerryA Avatar answered Sep 19 '22 11:09

TerryA


well, let's see the python3's API, Here are the description of the global key word:

The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global. Names listed in a global statement must not be used in the same code block textually preceding that global statement. Names listed in a global statement must not be defined as formal parameters or in a for loop control target, class definition, function definition, or import statement.

Names listed in a global statement must not be defined as formal parameters

Names listed in a global statement must not be defined as formal parameters

Names listed in a global statement must not be defined as formal parameters

so, you can not name x and y both as formal parameters and as global

like image 30
Guo.Jia Avatar answered Sep 18 '22 11:09

Guo.Jia