Reputation: 31
I ran this code for an exercise in python 2.7 but I get the same error everytime, no matter how I call the function fib(n) and I don't know why it doesnt get it. here's the code :
#!/usr/bin/python
class fibonacci:
def fib(self,n):
a=1
b=0
c=0
count=0
fibo=list()
while count < n:
c = a + b
fibo.append(n)
fibo.append(c)
a = b
b = c
count += 1
return fibo
n=int(raw_input("ingrese n: "))
s = fib(n)
print s
when I run it I get this error:
Traceback (most recent call last):
File "./fib.py", line 22, in <module>
s=fib(n)
NameError: name 'fib' is not defined
user@debian:~/Documents$
help please
Upvotes: 3
Views: 2172
Reputation: 6428
class fibonacci:
def fib(self,n):
a=1
b=0
c=0
count=0
fibo=list()
while count < n:
c = a + b
fibo.append(n)
fibo.append(c)
a = b
b = c
count += 1
return fibo
n=int(raw_input("ingrese n: "))
s =fibonacci().fib(n)#<-- make sure to have fibonacci() before you call .fib() otherwise it will throw an error
print s
What you needed was to call the fib
function from the class it was in. It was looking at the global scope in which a regular function would be in (one not in a class).
Upvotes: 1
Reputation: 494
fib()
is a method of the class fibonacci
, so you have to call it as such:
s = fibonnaci.fib(n)
If you just do fib(n)
, then the interpreter is looking for a global function named 'fib', outside of any class. In this case, because putting it in a class doesn't provide any specific utility to the function, you could just do this:
def fib(n):
...
s = fib(n)
(If you are putting it in a class as a way of namespacing it, keep in mind that Python uses modules to simplify that very thing.)
Upvotes: 1