Parenthesis in User-Defined Functions - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Parenthesis in User-Defined Functions (/thread-20371.html) |
Parenthesis in User-Defined Functions - giorgitsu - Aug-07-2019 I have the following question regarding using parenthesis when calling use defined function. This is the code proposed by the book to simulate white noise process for 100 periods using User-Defined Function. def generate_data(n, generator_type): ϵ_values = [] for i in range(n): e = generator_type() ϵ_values.append(e) return ϵ_values data = generate_data(100, np.random.uniform) plt.plot(data) plt.show()I am trying to change this code in the following way: def generate_data(n, generator_type): ϵ_values = [] for i in range(n): e = generator_type ϵ_values.append(e) return ϵ_values data = generate_data(100, np.random.uniform()) plt.plot(data) plt.show()So, instead of having parenthesis inside the body of the function (e=generator_type()) I provide it as the name of the second variable in the function generate_data. But the code does not run in the second case. I wonder what is the difference and why it fails to provide the same results as the first version. The call should just take np.random.uniform() instead of generator_type and produce the same result should not it? Why should I put generator_type() parenthesis in the body and then put np.random.uniform as the variable? why does it make a difference where to put ()? RE: Parenthesis in User-Defined Functions - Gribouillis - Aug-07-2019 The difference is that in the first case the function generator_type() is called for every index in the loop for i in ramge... while in the second case it is called only once.
RE: Parenthesis in User-Defined Functions - ThomasL - Aug-07-2019 data = generate_data(100, np.random.uniform)Here the function np.random.uniform is given as a parameter to the function and inside the function the according argument name generator_type can be used to call the function by adding () data = generate_data(100, np.random.uniform())Here you are CALLING the function np.random.uniform once and that call returns a random value and that value is passed as a parameter to the function and then assigned to e and then to the ϵ_values list. So your 2nd code snippet runs but all values are the same. |