"Name 'x' is parameter and global" error in Python

Question:

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()
Asked By: Suds2

||

Answers:

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.

Answered By: TerryA

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()
Answered By: opatut

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.

Answered By: Shashank

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

Answered By: Guo.Jia

So, if i’m right, to use global, the variable must not be in the function: fun([HERE]) and instead the brackets must be left empty !

Then we have to do global var and do whatever we need to do to it !

Answered By: Doot

I got the same error below:

SyntaxError: name ‘num’ is parameter and global

When I defined num global variable in test() which has num parameter as shown below:

num = 10
        # Here
def test(num):
    global num # Here

So, I removed num parameter from test() as shown below:

num = 10
      # ↓↓ "num" is removed
def test():
    global num

Or, I renamed num parameter to number parameter in test() as shown below:

num = 10
         # ↓↓ "num" is renamed to "number"
def test(number):
    global num

Then, the error was solved.

Answered By: Kai – Kazuya Ito