SyntaxError: invalid syntax, what happened? [duplicate]

this question already has answers here : How to concatenate multiple Strings in Python? (2 responses) Closed 1 year ago .

I'm using Python 3.7.4, tried writing in several different ways and nothing worked.

character_name = "Johnny"
character_age = "64"
print(+character_name "is cool.")
print("And he is " character_age " years old.")

Error:

    print(+character_name "is cool.")
                                   ^
SyntaxError: invalid syntax

Process finished with exit code 1
Author: Maniero, 2019-08-30

1 answers

This code is almost random. There are rules to follow to write a code, you can not write the way you well understand. So it works:

character_name = "Johnny"
character_age = "64"
print(character_name + " is cool.")
print("And he is " + character_age + " years old.")

See working on ideone. E no repl.it. also I put on GitHub for future reference .

Some problems there:

  • had an addition operator, which in this case would be considered concatenation at the very beginning of the expression within the parentheses of the function, and this does not make sense, this operator is binary and expects one operand on the left and another on the right, it can not have anything on the left (in this case it is even working as a unary operator that is just to confirm that something is positive and can only be used with numbers, not
  • then you seem to want to concatenate a variable with a literal string, and you don't have the operator, probably because you used it in the wrong place.
  • then nor did you use the operator to concatenate the variable with the strings , it has to have operators.
  • the ideal is to use a form of interpolation than concatenate in most situations.

You can read more in How To Do string interpolation in Python?.

It would be nice to study how syntax works and understand what each part does, do not try to join random snippets in the code, this is not programming.

 3
Author: Maniero, 2019-09-02 13:54:23