0

I was wondering if anyone could help me. I'm really new to this and I need to convert my input into a string?

# Python program to calculate the Fibonacci numbers
def fibR(n):
    if n == 1 or n == 2:
        return 1
    else:
        return fibR(n - 1) + fibR(n - 2)

# Request input from the user
num = int(input("Please enter the number in the Fibonacci sequence you wish to calculate: "))

#
if num == 1:
    print("The Fibonacci number you have requested is" + 1 + ".")
else :
    print("The Fibonacci number you have requested is" + fibR(num) + ".")
Patryk
  • 22,602
  • 44
  • 128
  • 244
Kate Wylie
  • 11
  • 3
  • Your input is a string already. You convert it into an `int`.. – Avihoo Mamka Feb 20 '16 at 14:28
  • Did you google "TypeError: cannot concatenate 'str' and 'int' objects"? Possible duplicate of [Python: TypeError: cannot concatenate 'str' and 'int' objects](http://stackoverflow.com/questions/11844072/python-typeerror-cannot-concatenate-str-and-int-objects) – martijnn2008 Feb 20 '16 at 14:36
  • Why do you avoid calling your `fibR` function in the `n == 1` case? It's not like it will cause a performance issue for 1. (It will for large `n`, though.) – das-g Feb 20 '16 at 14:52

5 Answers5

3

You are already converting your input into an int correctly. However, in your print statement...

print("The Fibonacci number you have requested is" + fibR(num) + ".")

....the function fibR(num) is returning an integer. When you try and concatenate the returned integer with the string, it causes an error. What you need to do instead is use format strings:

print("The Fibonacci number you have requested is {}.".format(fibR(num))) 
gtlambert
  • 11,711
  • 2
  • 30
  • 48
1

Do str(number) to convert a number to string.

JulienD
  • 7,102
  • 9
  • 50
  • 84
1

In else statement use %:

print("The Fibonacci number you have requested is %d." % fibR(num))
Kenly
  • 24,317
  • 7
  • 44
  • 60
1

If you

import this

you'll learn that the makers of Python think

Explicit is better than implicit.

Thus, in Python you can just 'add' strings and ints as you try to do in your two print statements. Either explicitly convert the number to a string by using the return value of str(fibR(num)), or, even better, look into string's format() method. Some examples on how to use it have already be given by the other answers here.

das-g
  • 9,718
  • 4
  • 38
  • 80
0

Just use the str() method:

print("The Fibonacci number you have requested is" + str(fibR(num)) + ".")
Mark Skelton
  • 3,663
  • 4
  • 27
  • 47