Syntaxerror: invalid syntax, what happened?

Asked

Viewed 1,999 times

2

I am using Python 3.7.4, I tried to write 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

1 answer

3


This code is almost random. There are rules to be followed to write a code, can not write the way you want. So it works:

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

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Some problems there:

  • There was an addition operator, which in this case would be considered concatenation right at the beginning of the expression within the parentheses of the function, and this makes no sense, this operator is binary and waits for one operand on the left and one on the right, can have nothing on the left (in this case he is even working as an unary operator which is only to confirm that something is positive and can only be used with numbers, not with texts).
  • Then you seem to want to concatenate a variable with a literal string, and you don’t have the operator, probably because you used him in the wrong place.
  • Then he didn’t even use the operator to concatenate the variable with the strings, have to have operators.
  • The ideal is to use an interpolation form than concatenate in most situations.

You can read more on How to interpolate string in Python?.

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

  • It is worth commenting that there is the operator + unary also, only does not apply natively in strings, as is the case.

  • @Andersoncarloswoss the most meaningless operator ever created before a language had the bad idea to do and the others copied

Browser other questions tagged

You are not signed in. Login or sign up in order to post.