Search code examples
pythonnameerror

NameError: Name 'trys1' is not defined


In my school project I am comparing search algorithms. I don't get an error for searched numbers between 36 and 65. Above/below this number range the error occurs (NameError: name 'trys1' is not defined). I don't know why. I tried to call the def directly after the definition as it was solved for a similar question but it doesn't work. What should I do? If try1 is removed from the def diagram, the error no longer occurs.

import math
from Suche.SucheZahlen import Zahlen
import matplotlib.pyplot as plt

index1 = []
index2 = []
index3 = []
data0 = Zahlen.data
length = len(data0) - 1


def suche(number, x, right, length, data0):
    global index1
    global trys1
    runtime = int(math.log2(length))
    for i in range(runtime + 1):
        if data0[x] <= number <= data0[right]:
            median_index = int((length + x) / 2 - 1)
            index1.append(median_index)
            if number == data0[median_index]:
                print("ja")
                trys1 = i + 1
                break
            if number - 1 > data0[median_index]:
                x = median_index + 1
            elif number - 1 < data0[median_index]:
                length = median_index + 1
            elif number - 1 == data0[median_index]:
                print("ja")
                break
        else:
            print("nein")
            break


def intervallsuche(number, right, left, data0):
    global trys2
    for i in range(right):
        if data0[left] <= number <= data0[right]:
            x = left + (number - data0[left]) / (data0[right] - data0[left]) * (right - left)
            round = x % 1
            if round < 0.5:
                x = int(x)
            if round >= 0.5:
                x = int(x) + 1
            index2.append(x)
            if data0[x] == number:
                trys2 = i + 1
                print("ja")
                break
            if data0[x] > number:
                right = right - 1
            if data0[x] < number:
                left = left + 1
        else:
            print("nein")
            break


def linearesuche(number, x, right, data0):
    global trys3
    if data0[x] <= number <= data0[right]:
        for i in range(right):
            if number == data0[x]:
                trys3 = i
                print("ja")
                break
            else:
                x = x + 1
            index3.append(x)
    else:
        print("nein")


def diagramm():
    x1 = list(range(trys1))
    x2 = list(range(trys2))
    x3 = list(range(trys3))
    x4 = [0, length]
    y1 = index1
    y2 = index2
    y3 = index3
    y4 = [number, number]
    xmin = 0
    xmax = trys3
    ymin = 0
    ymax = data0[100]
    plt.axis([xmin, xmax, ymin, ymax])
    plt.scatter(x1, y1)
    plt.scatter(x2, y2)
    plt.scatter(x3, y3)
    plt.plot(x4, y4)
    plt.xlabel("X")
    plt.ylabel("Y")
    plt.show()


number = int(input("number:"))
linearesuche(number, 0, length, data0)
intervallsuche(number, length, 0, data0)
suche(number, 0, length, length, data0)
diagramm()

Solution

  • First of all, some code feedback: You should almost never use global variables for anything. It is extremely rare that you'll actually need them, and they cause all sorts of namespace problems if you aren't careful - this being an example.

    The actual issue: You haven't actually created a global variable called trys1 outside of the suche function. Global variables need to be defined on the global namespace, and then calling them inside the function simply tells Python that you're trying to modify that global variable, rather than a new local one.

    If that's confusing, hopefully the example below will clarify. The below code will return 2, because you told the foo function that you're trying to modify the c that you defined above, not a local c that you created within the confines of the function.

    c = 1
    def foo():
      global c
      c = c+1
      return c
    
    print(foo())
    

    This time, the below code should give the same NameError that you received (although I haven't tested), because you're trying to tell the foo function to modify the global variable c, but there is no global variable c.

    def foo():
      global c
      c = c+1
      return c
    
    print(foo())
    

    Now, the below code will simply modify the c variable inside the function.

    def foo():
      c = 1
      c = c+1
      return c
    
    print(foo())