2

I am trying to learn to define a function in Python.

I tried this syntax

>>> def hello():
... print("Hello")

but when I press the enter key after "Hello" I get the expected an indented block error.

Actually I am trying to write this code

>>> def hello():
... print("Hello")
... print("Computers are Fun")

but I cannot because of the error message.

What is going wrong? How can I fix it?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
user1705029
  • 21
  • 1
  • 1
  • 2

4 Answers4

5

Check your indentation. Unlike C, Java, C++, there are no {} to enclose a function, code segment. Indentation is what defines a code section, loop, function etc.

>>> def hello():
...     print "hello"
...
>>> hello()
hello
>>>

Note the indentation from the def line and print line. Your code is missing correct formatting.

powerrox
  • 1,334
  • 11
  • 21
3

You need to indent (4 spaces recommended) the commands that go in a function, like this:

>>> def hello():
...     print 'hello'
... 
>>> hello()
hello
Matthew Adams
  • 9,426
  • 3
  • 27
  • 43
  • @WaleedKhan for sure; I was just following [PEP8](http://www.python.org/dev/peps/pep-0008/#tabs-or-spaces) – Matthew Adams Sep 28 '12 at 02:07
  • 1
    @WaleedKhan: 1 space is also acceptable, as is 2 spaces, 5 spaces, 3 tabs, or a complex interleaving of 47 tabs and 79 spaces, so long as you're consistent. Introducing 4 spaces as the standard is still a good idea. – Ben Sep 28 '12 at 02:24
1

You need to properly format your functions. Python has very specific spacing requirements.

def hello():
    print "Hello"
Andy
  • 49,085
  • 60
  • 166
  • 233
1

´expected an Indented block´ means that your indentation is not correct, try following code:

def hello():
    print "Hello"

def hello2():
    print "Hello"
    print "Computers are Fun"

hello()
hello2()
mawueth
  • 2,668
  • 1
  • 14
  • 12