0

I am trying to display "5 + 5 = 10" with the syntax as follows print ("2 + 2 = " + ( 2 + 2) ), what is the correct syntax to write it as i keep getting the error :

" TypeError: must be str, not int"

Appreciate the help :)

I tried : str ("2 + 2 = " + ( 2 + 2) )

2
  • 1
    try: print("2 + 2 = " + str(2 + 2)) Commented Mar 31, 2023 at 10:24
  • ...and 5s instead of the 2s. Commented Mar 31, 2023 at 10:35

5 Answers 5

4

Nobody suggested the f-strings:

print(f'2 + 2 = {2 + 2}')

Or even (since python3.8):

print(f'{2 + 2 = }')
Sign up to request clarification or add additional context in comments.

1 Comment

a little more elegant: result = 2 + 2; print(f'2 + 2 = {result}')
2

In python, it's different type,and you could not use + operator on type str and int. for your case you can write below:

1.cover int to str:

"2 + 2 = " + str( 2 + 2) 

2.use str.format method

"2+2={:d}".format(2+2)

Comments

2

You have to convert 2+2 into a string before concatenating it to "2+2".

print("2 + 2 = "+str(2+2))

or even better, with f-strings

print(f"2 + 2 = {2+2}")

If you want to avoid repeating the sum, you can use the devtools library (to be installed via pip)

from devtools import debug

debug(f"{3+5=}")
>>> '3+5=8'

Comments

1

You are trying to add a string "2 + 2 =" to an int (4). Turn the int into a string first and then add the two strings together:

"2 + 2 = " + str(2 + 2)

Comments

1

The + operand in python adds 2 items of the same type together - two strings join to become longer, or two numbers add to become a combined single number. Yuo are adding a string "2+2=" to a number (2+2)=4, which doesn't make logical sense.

Either make both strings print ("2 + 2 = " + str( 2 + 2) )

or rely on print to transform the numbers into strings for output, remove the + sign, and add a comma to show that you are printing two separate things. print ("2 + 2 = ", ( 2 + 2) )

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.