Home > Back-end >  UnboundLocalError: local variable 'y' referenced before assignment
UnboundLocalError: local variable 'y' referenced before assignment

Time:12-28

import matplotlib.pyplot as plt
import numpy as np

#F(x;y) = a · x   b · y
def F1(a, b):
    x = np.linspace(-6,9,100)
    y = a*x   b
    return x, y

#F(x; y) = a · x - b · y
def F2(a, b):
    x = np.linspace(-6,9,100)
    y = a*x - b
    return x, y

#F(x; y) = a · x · b · y
def F3(a, b):
    x = np.linspace(-6,9,100)
    y = a*x*b
    return x, y

#F(x; y) = (a · x) / (b · y)
def F4(a, b):
    x = np.linspace(-6,9,100)
    y = (a*x)/(b*y)
    return x, y

plt.title("Euler's method")
plt.xlabel("x")
plt.ylabel("y")

a = 5
b = 1

x, y = F1(a, b)
plt.plot(x, y, label="F1(x,y): a · x   b · y")

x, y = F2(a, b)
plt.plot(x, y, label="F2(x,y): a · x - b · y")

x, y = F3(a, b)
plt.plot(x, y, label="F3(x,y): a · x · b · y")

x, y = F4(a, b)
plt.plot(x, y, label="F4(x,y): (a · x) / (b · y)")


plt.legend()
plt.show()

I am receiving the following error in Python (I'm using Jupyter):

UnboundLocalError: local variable 'y' referenced before assignment

in line 25 and 44

25 line y = (a*x)/(b*y)

44 line x, y = F4(a, b)

How to fix it?

CodePudding user response:

In your F4 function you need to change your equation to get y value .. You can not have y on right hand side before assigning value to it.

def F4(a, b):
    x = np.linspace(-6,9,100)
    y = (a*x)/(b)
    return x, y

CodePudding user response:

In the function F4 you are trying to assing a value to the variable y that is dependent on the variable y itself without assigning it a value before.

def F4(a, b):
    x = np.linspace(-6,9,100)
    y = (a*x)/(b*y)
    return x, y

In the line y = (a*x)/(b*y) the denominator is dependent on y but you never specify what y is before this instruction.

  • Related