Repeating a function loop in python
Question:
How to make the code calculate not one number, but several? That is, so that the user can enter several times a different number of the number from which we subtract? and so that later it would be possible to build a graph from the obtained numbers.
f1 = 1
f2 = 1
n = int(input("Enter the number from which we subtract the previous one:"))
for i in range(n - 1):
f2,f1 = f2+f1, f2
print(f2**2 - f1**2)
Answers:
I’m not sure I fully understand what you are trying to do but why not input a list of input numbers to a function which does the processing and return a list of results which is then usable for graph plotting.
import matplotlib.pyplot as plt
numbers = input("enter a series of numbers separated by a space ")
listnumbers = [int(i) for i in numbers.split(" ") if i.isdigit()]
def f(mynums):
result = []
for n in mynums:
f1 = 1
f2 = 1
for i in range(n - 1):
f2, f1 = f2 + f1, f2
result.append(f2**2 - f1**2)
return result
x = f(listnumbers)
plt.plot(listnumbers, x)
plt.show()
How to make the code calculate not one number, but several? That is, so that the user can enter several times a different number of the number from which we subtract? and so that later it would be possible to build a graph from the obtained numbers.
f1 = 1
f2 = 1
n = int(input("Enter the number from which we subtract the previous one:"))
for i in range(n - 1):
f2,f1 = f2+f1, f2
print(f2**2 - f1**2)
I’m not sure I fully understand what you are trying to do but why not input a list of input numbers to a function which does the processing and return a list of results which is then usable for graph plotting.
import matplotlib.pyplot as plt
numbers = input("enter a series of numbers separated by a space ")
listnumbers = [int(i) for i in numbers.split(" ") if i.isdigit()]
def f(mynums):
result = []
for n in mynums:
f1 = 1
f2 = 1
for i in range(n - 1):
f2, f1 = f2 + f1, f2
result.append(f2**2 - f1**2)
return result
x = f(listnumbers)
plt.plot(listnumbers, x)
plt.show()