Variable assignment in nested function | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Variable assignment in nested function

My function has another purpose, I simplified it. def addSquares(x,y): def squareX(): x = x**2 def squareY(): y = y**2 squareX() squareY() return x+y print(addSquares(3,5)) --- To my logic, i assgined a value to y and x in addSquares(3,5). So x = 3 and y = 5. "UnboundLocalError: local variable 'x' referenced before assignment" So how can I make such a nested function using an outer parameter in inner functon? If i try to define x and y as global at the start of the outer function, i get "SyntaxError: name 'x' is parameter and global", at the start of the inner function "NameError: name 'x' is not defined". Please help! Thanks in advance.

23rd Oct 2020, 12:01 PM
Alex Snaidars
Alex Snaidars - avatar
6 Answers
+ 1
Try this to see what is happening inside the functions: https://code.sololearn.com/cHft055cl79E/?ref=app
23rd Oct 2020, 12:24 PM
QTWizard
+ 1
Don't use global here, use nonlocal keyword. And even better, simply store the result of the function calls to x and y, it will be better than using some nonlocal (or global) tricks.
23rd Oct 2020, 4:46 PM
Théophile
Théophile - avatar
0
@NotAPythonNinja x = 3 y = 5 def square(): global x x = x**3 square() sum = x+y print(sum) Although square() does not take any parameters or return any values, it does change the value of x. The only difference in this case and the other is that assignement is done here using x = 3, but above using addSquares(3,5). Is my idea impossible to implement?
23rd Oct 2020, 1:05 PM
Alex Snaidars
Alex Snaidars - avatar
0
@NotAPythonNinja def addSquares(x,y): def squareX(x): global x x = x**2 def squareY(y): global y y = y**2 squareX() squareY() return x+y print(addSquares(3,5)) this gives "SyntaxError: name 'x' is parameter and global". Btw x and y are only to be used inside the addSquares() function.
23rd Oct 2020, 1:19 PM
Alex Snaidars
Alex Snaidars - avatar
0
@NotAPythonNinja So that means i cannot implement the code without defining x and y outside of the function?
23rd Oct 2020, 1:37 PM
Alex Snaidars
Alex Snaidars - avatar
0
Yes, i did. I want something a little bit different. But if no choices left, i might as well use your option. Thanks.
23rd Oct 2020, 2:06 PM
Alex Snaidars
Alex Snaidars - avatar