tags:

views:

263

answers:

9

I have just started learning python and am getting caught up. I come from mostly C background.

class Alarm:

    def timer():

    def main():
     print ("Timer has Started")

    main()

I always get a silly error when I try to run this code::

alarm > python alarm.py 
  File "alarm.py", line 5
    def main():
      ^
IndentationError: expected an indented block

What am I doing wrong?

+11  A: 

You have an empty def

def timer():

use

def timer():
    pass

instead.

Chen Levy
interesting observation in how all the early answers had this incorporated yet this one has the highest # of upvotes because it just mentions that excerpt :p
meder
+1  A: 

try deindent main() and add pass to timer and define an init method:

class Alarm():

    def __init__(self):
        print ("Timer has Started")

<shell>$  Alarm()
DrFalk3n
wouldn't this error out because main is undefined? well, I guess that's what the OP was intending for.
meder
main is totally a non-sense in this implementation, you are already using __init__() with the same intent of the original main()
AlberT
You were right!
DrFalk3n
+1  A: 

Your timer function is not defined. (And your space/tab indentation may be mixed)

See the tutorial (classes) for more details on classes.

class Alarm:

    def timer(self):
        pass
    def main(self):
        print ("Timer has Started")

if __name__ == '__main__':
    class_inst = Alarm()
    class_inst.main()

If you getting into python read PEP8.
Also, using pylint helps, it will point out indentation and many other errors you'll run across before you 'execute' your code.

monkut
If you would had used pylint it would had told you that main() is undefined, in fact.
AlberT
+3  A: 

Learn about the pass statement, main is usually not part of the class.

A global (module level) main() function is simpler than an Alarm.main() class method. Usually, main() functions come at module level.

class Alarm:

    def timer():
        pass

def main():
    print ("Timer has Started")

main()
gimel
Can I ask why it is not part of the class?
Recursion
You can use methods (in a class) or functions (outside class), it's your choice. As opposed to C/C++/C#/Java, Python does not need a main method. It simply executes all code in the file (that means that it reads the classes and then executes the code that follows class definition.)
Roman Plášil
Well, the question was obviously a beginner's, and a global (module level) main() function is simpler than an Alarm.main() class method.Usually, main() functions come at module level.
gimel
+1  A: 

I think you want to use __init__ though, which is the constructor...

class Alarm:

    def timer(self): 
        print('timer has started')

    def __init__(self): 
        print('constructor')
        self.timer()


x = Alarm()

constructor

timer has started

My example differs from the others in that I'm actually instantiating a new object.

Notes:

  • specify self as the first argument to any method defined in the class
  • __init__ is the method to define for the constructor
  • invoke the class by doing variableName = className() like you would invoke a function, no new keyword
  • if you have an empty function, use the pass keyword like def foo(self): pass
meder
So in python a new instance is not automatically instantiated as in java or C#. You must instantiate it manually?
Recursion
As far as I know, that's the only practical way to do it.
meder
I recommend reading about `__init__` and `self` @ http://docs.python.org/tutorial/classes.html
meder
@Recursion: No object is automatically instantiated in Java/C#. It's the same in Python. Maybe you meant the static method main in the startup class?
Roman Plášil
@Roman: I was refering to Classes. In Java you dont need to instantiate your first class, it is done for you. You then have a constructor to start off with. From my reading python has no instructor.
Recursion
Are you looking to use `__init__`? http://docs.python.org/reference/datamodel.html#object.__init__
meder
I updated my solution so it contains a constructor example.
meder
__init__ has to be the forst method
DrFalk3n
The first method defined you mean? It works perfectly locally, so I do not think that is the case. I don't get why you have to downvote when I was the first one to actually mention init and use it in an example, which you later adjusted your answer to :p
meder
+1  A: 

Invoking main() will give an undefined function error, as it is a Alarm method.

IMHO the right form you should use is the following:

class Alarm:
    def timer():
      pass

    @staticmethod
    def main():
      print ("Timer has Started")

if __name__ == "__main__" :
    Alarm.main()
AlberT
I get the following errorpython alarm.py File "alarm.py", line 12 Alarm::main() ^SyntaxError: invalid syntax
Recursion
Sorry, too many languages at the same time for me, corrected :)
AlberT
A: 

As others have pointed out, you have a syntax error because timer() has no body.

You don't need to use main() in python at all. Usually people use it to indicate that the file is the top level program and not a module to be imported, but it is just by convention

You may also see this idiom

def main():
    blah blah

if __name__ == "__main__":
    main()

Here __name__ is a special variable. If the file has been imported it will contain the module name, so the comparison fails and main does not run.

For the top level program __name__ contains "__main__" so the main() function will be run.

This is useful because sometimes your module might run tests when it is loaded as a program but you don't want those test to run if you are importing it into a larger program

gnibbler
A: 

In Python, you don't need to define everything as a class. There's nothing to encapsulate in this code, so there's no reason to define an Alarm class. Just have the functions in a module.

Daniel Roseman
A: 

Thanks for all the help everybody. I was making a little alarm/timer to remind me to get up and take a walk every now and then. I got most of it working, and it works great. Checked it against a stop watch and it works great.

import time

def timer(num):
    seconds = num*60
    print (num , "minutes", seconds , "seconds")

    while (seconds > 0):
     print (seconds, "seconds")
     time.sleep(1)
     seconds = seconds-1

    print ("Time to get up and take a WALK!!!!")
    main()


def main():
    number = input("Input time : ")
    int(number)
    timer(number)


if __name__ == '__main__':
    main()
Recursion
next exercise: make main a loop that repeats forever (e.g., while True), and break out of the loop if the user just hits 'enter' rather than inputting a number.
foosion