Python3 If Else statement SyntaxError and IndentationError [duplicate]

  if-statement, python, python-3.x, stdin, windows

I am new to Python and Stackoverflow. I tried looking at some of the already existing questions, but I could not see where I was messing up. Sorry in advance for the repeated question.

I am trying to figure out what I did wrong with my if-else statement.

Here is what I wrote:

myFavoriteFood = "Ice Cream"
userGuess = input("What is my favorite food? ")

if myFavoriteFood == userGuess:
    print("nice!")

else:
    print("Sorry, that's not right. Try again!")

Here is the Error I am getting:

>>> else:
  File "<stdin>", line 1
    else:
    ^^^^
SyntaxError: invalid syntax
>>>     print("Sorry, that's not right. Try again!")
  File "<stdin>", line 1
    print("Sorry, that's not right. Try again!")
IndentationError: unexpected indent
>>>
>>>

What I have tried so far:

  • To avoid any more spacing issues, I just let Visual Studio Code add the indent.
    I tried with 4 space only. I tried with tab. I never mixed the two. I still ran into the issue.
  • I didn’t realize I needed ":", so I added those.
  • I tried "else :" but that errored.
  • I made sure there was no extra space in front of if or else.
  • I tried enclosing the codeblock in parentheses but that errored.
  • VSC says Line 5 Col 1-5 is 4 spaces; as well as, Line 8 Col 1-5 is 4 spaces.

What I am confused about:

  • Why are the line numbers off from the error? Am I reading this wrong?
  • What am I doing wrong in the if-else part?
  • Did I do something wrong with input? Maybe that’s causing an issue? I only ask because of the stdin in the error log. I am assuming/guessing that’s something long like "standard text something input". Idk.

General Info:
I am working on Windows 10 at the moment. I am using Visual Studio Code with the terminal that is built inside. My program is saved as .py. I am running Python. 3.10.0 64bit. I have selected Python because I work on both Mac and Windows, and I wanted something that could work on both platforms.

(I hope this is info is helpful and not even more confusing.)

Source: Windows Questions

LEAVE A COMMENT