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) + ".")
3
  • Your input is a string already. You convert it into an int.. Commented Feb 20, 2016 at 14:28
  • Did you google "TypeError: cannot concatenate 'str' and 'int' objects"? Possible duplicate of Python: TypeError: cannot concatenate 'str' and 'int' objects Commented Feb 20, 2016 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.) Commented Feb 20, 2016 at 14:52

5 Answers 5

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))) 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!!! I'm really trying to improve myself. Oh and by the way it's she not he.
1

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

Comments

1

In else statement use %:

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

Comments

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.

Comments

0

Just use the str() method:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.