I am trying to learn Python and I think sharing what I learn on my blog will not only serve as a quick reference for me in future but will also help those who are always on the lookout to find and learn fun things. So here goes my first post, a summary of a few very simple things I have learnt.
Event driven programming: This means your program will not run forever, rather it will run for sometime and then wait for an ‘event’ to occur like a mouse click or a text input or a button press and so on. The program flow then passes to a ‘handler’ specific to that event who knows what to do in case its event is fired.
Lets look at an example, this is from a module called simplegui. Yes Python functions are housed in these nifty little packages called ‘modules’. I think that’s really very cool.
So I import simplegui module saying
Then I have 3 timer functions in this module namely:
mytimer = simplegui.timer_create(delay in ms,myhandler) which will create and return a timer object
mytimer.start() which will start the timer
mytimer.stop() which will stop the timer.
So if I define a function like
print "Hello Sir"
and I create and start a timer object, I will have “Hello Sir” printed at regular intervals ! BTW printing something like “Hello Sir” is just a trivial example, I can make anything to trigger at regular timings with the power of timers in my hands. Mwahaha !
A few notes: When a handler runs, no other the event handler can be run, so if another event occurs while a handler is running, the event just gets into the event queue and waits to be pulled out of the queue after the current handler finishes executing. So the queue does the trick.