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.
raw_input() returns a string, as you've surmised. However, int(n) doesn't change the value of n to an integer, instead it returns the converted value. You need to do:
n = int(n)
instead.
The problem is that raw_input is providing a string, not an integer. Can I suggest just putting the integer value into n
in the first place:
n = int(raw_input('Input numver: '))
fib(n)
Avoid n = int(n)
as in a longer section of code it would be unclear when you came back to it what type n
is, 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 n
could 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 of raw_input
into n
, Python knows it is a string, so multiplying that string by a number makes no sense and returns an error.
Just make a small change :
n = raw_input('Input number: ')
n = int(n)
fib(n)
The int conversion takes a string which you obtained from raw_input and returns a integer. You need to pass the return value to fib(..).
int_obj = int(str_obj)
use int(raw_input('Input number: '))
instead of raw_input('Input number: ')
精彩评论