I’m completely new to Python and I’ve been trying to make a fibonacci program with it.
def fib(n):
print 'n =', n
if n > 1:
return n * fib(n - 1)
else:
print 'end of the line'
return 1
n = raw_input('Input number: ')
int(n)
fib(n)
When I try to run this program, I get the following error after entering the number:
Input number: 5
n = 5
Traceback (most recent call last):
File “fibonacci.py”, line 11, in
fib(n)File “fibonacci.py”, line 4, in fib
return n * fib(n - 1)TypeError: unsupported operand type(s)
for -: ‘str’ and ‘int’
If I run the interpreter and import just the function (without the code after it), supply the value for n and call the function with the value as the parameter, it works.
I tried converting the input to int since I thought it was a string problem but no dice. I don’t really know where I went wrong so if you could please shed some light on the subject, it’ll be much appreciated.
I’d love to change the problem title to something specific but I don’t really know what the problem is.
The problem is that raw_input is providing a string, not an integer. Can I suggest just putting the integer value into
nin the first place:Avoid
n = int(n)as in a longer section of code it would be unclear when you came back to it what typenis, and you have no need for the original string value.The deeper understanding you need is that Python is strongly typed – it cares what type everything is, but it is also dynamically typed, so
ncould change from holding a string value to holding an integer value. But Python is still keeping track of what is held, so when you put the return value ofraw_inputinton, Python knows it is a string, so multiplying that string by a number makes no sense and returns an error.