Search code examples
pythonconsolespyder

Why it keeps returning me "theIndentationError: unexpected indent" and when i put the same code in the terminal is everything fine?


this is my first attempt with python and I'm using the spider enviroment.. I'm trying to execute a very simple code

# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""
import numpy as np
 x = np.array([1,2,3])
 y = np.array([4,5,6])
 z= x+y
 print (z)

When I type this code as a .py file, I get the following error

    x = np.array([1,2,3])
    ^
IndentationError: unexpected indent

Why do I get this error? I did not have the same problem when using the console.


Solution

  • All the 5 lines of code you showed have to be at the same indentation level, meaning, you should remove the spaces (or tabs) that are in front of the last 4 lines, or add spaces in front of the first line (the import statement).

    You code (with the error):

    import numpy as np
     x = np.array([1,2,3])
     y = np.array([4,5,6])
     z= x+y
     print (z)
    

    But it should look like this (all 5 lines starting at the same position):

    import numpy as np
    x = np.array([1, 2, 3])
    y = np.array([4, 5, 6])
    z = x + y
    print(z)