mitra
mitra

Reputation: 37

Repetition of function call

import numpy as np
import matplotlib.pyplot as plt

pi = np.pi


def draw_first():
    x = np.arange(-3, 3, 0.1)
    y = x**3 - 3*x
    plt.plot(x, y)


def draw_second():
    x = np.arange(0, 2*pi, 0.1)
    y = 3*x*np.cos(2*x)
    plt.plot(x, y)


def draw_third():
    x = np.arange(-8*pi, 8*pi, 0.1)
    y = np.sin(x) / x
    plt.plot(x, y)


switch = {
    "1": draw_first,
    "2": draw_second,
    "3": draw_third
}

while True:
    try:
        choice = input("Enter a number [1-3]: ")
        function_called = switch[choice]()
        break
    except:
        print("Try again!")

plt.show()

Is there a way not to repeat plt.plot(x,y) in every function? I was thinking about something like plt.plot(function_called.x,function_called.y), but i don't think that's right

Upvotes: 1

Views: 57

Answers (2)

madbird
madbird

Reputation: 1379

function_called is None here:

function_called = switch[choice]()

But you could return x and y from functions and plot them in the loop:

def draw_first():
    x = np.arange(-3, 3, 0.1)
    y = x**3 - 3*x
    return x, y

...

while True:
    try:
        choice = input("Enter a number [1-3]: ")
        x, y = switch[choice]()
        plt.plot(x, y)
    except:
        print("Try again!")

plt.show()

Upvotes: 3

Jiří Baum
Jiří Baum

Reputation: 6930

You could have each function return the x, y then call plt.plot(x, y) in the caller:

def draw_first():
    x = np.arange(-3, 3, 0.1)
    y = x**3 - 3*x
    return x, y

and then

        x, y = switch[choice]()
        plt.plot(x, y)

Note that the two pairs of x, y are completely separate variables that just happen to have the same names; you could use a different name in each place:

        a, b = switch[choice]()
        plt.plot(a, b)

Upvotes: 3

Related Questions