-4

was making some code and i ran into the error here is the code

import random
foo = ['sad', 'mad', 'happy ', 'inbetween', 'bored']
print("hello answer 1 or 2 or 3")
e = input(str)


if e == '1' : print("ok give me a sentence and ill tell you how i feel about it") ;a = input("please enter a sentence ")  ;a == ('i hate you')  :print(" i feel sad and mad that you hate me") ;a == ('I hate you') :print("i feel sad and mad that you hate me")
elif e == '2' :print("ok ill give you advice")
elif e == '3' :print("so you want to have a converstation")
else :print(" thats not an option") 
  • 1
    Have the body of the `if` block indented and spanning multiple lines. What you are trying to do doesn't look like Python. The `elif` blocks should also be indented in their own lines. There is a place for a 1-line `if` statement. This isn't it. – John Coleman Jan 23 '23 at 01:37
  • Maybe https://stackoverflow.com/questions/53734530 is a close enough duplicate? There are a few questions about this error message, but without a really clear canonical. – Karl Knechtel Jan 23 '23 at 01:54

1 Answers1

1

A minimal reproducible example for this:

>>> if True: True: print('x')
... 
  File "<stdin>", line 1
SyntaxError: illegal target for annotation

The problem is that the second True was intended to be another if condition, but is instead just an expression. The parser treats : print('x') as a type annotation for True; but type annotations have to be applied to individual variable names, not expressions.

The specific error is only possible because print('x') is an expression, and thus a valid type annotation. If it were another kind of statement, this would cause a generic syntax error:

>>> if True: True: pass
  File "<stdin>", line 1
    if True: True: pass
                   ^
SyntaxError: invalid syntax

Either way, there was a typo here - the second True: was meant to be if True:. However, this does not fix the problem by itself:

>>> if True: if True: pass
  File "<stdin>", line 1
    if True: if True: pass
             ^
SyntaxError: invalid syntax

It is not permitted to put multiple ifs on the same line; nor can elif and else be paired with the matching if on the same line:

>>> if True: pass; else: pass
  File "<stdin>", line 1
    if True: pass; else: pass
                   ^
SyntaxError: invalid syntax

Putting multiple statements on a line - by using semicolons, and/or by putting the "suite" of an if etc. statement on the same line - is strongly discouraged in Python. It has multiple limitations, and makes the code much harder to read.

To make the example work, use indented blocks in the normal way:

if True:
    if True:
        pass
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • 1
    Technically, `True: print('x')` reproduces the error message, so this example is not *quite* minimal; but the point here is to highlight the issue with trying to nest `if`s. – Karl Knechtel Jan 23 '23 at 01:50