0

I'm having this annoying problem in Python 2.7, it won't let me do this

numbers = raw_input(numbers + 1 + ': ')

I want it to print out 'numbers + 1' as a number in the console but.. It comes up with this error message:

Traceback (most recent call last):
  File "F:/Python/Conversation", line 25, in <module>
    numbers = raw_input(numbers + 1 + ': ')
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Is there a solution or just another thing that I can use instead of this? Thanks in advance!

3 Answers 3

2

As the error message points out, you cannot add a number and a string. You can add two strings, so try this:

raw_input( str(numbers+1) + ':' )
Sign up to request clarification or add additional context in comments.

Comments

2

You need to put + and numbers inside a single/double quote; or else, it will be treated as a string concatenation. You got the error because you tried to concatenate/add numbers with 1.

So, you need to cast 1 to a string, using str( ). Then, concatenate it with 'numbers + ' and ':'. Like so:

>>> numbers = raw_input('numbers + ' + str(1) + ': ')
numbers + 1: 

However, If you want to replace numbers with number:

>>> numbers = 3
>>> numbers = raw_input(str(numbers + 1) + ': ')
4:

It works because you add the numbers's value with 1 first. Then, cast the result to string later.

Comments

0

You need to turn the 1 int value into a string:

numbers = raw_input(numbers + str(1) + ': ')

Alternatively, use string formatting:

numbers = raw_input('{}{}: '.format(numbers, 1))

Or perhaps you wanted to turn numbers into an int first, then the result into a string:

sum = int(numbers) + 1
numbers = raw_input(str(sum) + ': ')

4 Comments

if numbers is initialised as 6, it prints 61.. So this doesn't give the correct output
@Aswin: Which could have been what the OP wanted. In any case, my last guess turned out to be the correct one.
OP wanter it to be numbers+1 (ie) if numbers is 5, it should print 6
@Aswin: We probably have to agree to disagree here, but the question was ambiguous. There are several different answers here now, for instance.

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.