"Name 'x' is parameter and global" exception
Asked Answered
D

6

9

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()
Delaney answered 15/9, 2013 at 0:29 Comment(2)
What x and y are you passing the function when you call it? Also, you don't appear to be using them in the function, so what their purpose?Lawless
What's the point of declaring x and y global? They're not used outside of the enclosing scope.Octant
L
3

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.

Lauber answered 15/9, 2013 at 0:32 Comment(0)
G
12

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.

Glister answered 15/9, 2013 at 0:42 Comment(0)
T
4

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()
Trainband answered 15/9, 2013 at 0:40 Comment(2)
What does the return do? I've never used "return" in my code yet.Delaney
#7129785... basically, it gives the value back to where the function called from, e.g. return 123 inside def foo() would put 123 into bar when calling bar = foo(). This is a basic principle in most any programming language. You should do some basic tutorials or read a book for beginners, really.Trainband
L
3

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.

Lauber answered 15/9, 2013 at 0:32 Comment(0)
M
1

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

Metaphysic answered 14/8, 2018 at 16:25 Comment(0)
P
1

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 !

Pamulapan answered 4/3, 2020 at 23:28 Comment(0)
D
0

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.

Dominance answered 26/11, 2022 at 15:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.