-1

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.

1
  • 1
    Please provide meaningful title for the question next time Commented Nov 15, 2017 at 8:08

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

1 Comment

I'll be accepting this as the answer. I like the explanation you made along with your answer.
3

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) 

Comments

0

use int(raw_input('Input number: ')) instead of raw_input('Input number: ')

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.