Home > Uncategorized > Getting started with Python (part 3 – for programmers)

Getting started with Python (part 3 – for programmers)

In this tutorial, I’m going to go over writing your first Python program for C style language developers.

In most C style languages, a program starts execution in a main function. Python is a little different. To allow Python programs to act either as runnable programs, or as modules (similar to a class library), there’s a special way that you call the main function (source). In fact, it doesn’t have to be called main at all; you can name it whatever you want.

First, let’s define a simple main function:

def main():
	print 'Hello World'

	return 0

Similar to C languages, the main function returns a numeric code, indicating the exit state.

This code should go right below your main function:

# Run main
if __name__ == "__main__":
    sys.exit(main())

The if statement asks if we are the main program, and if so, run our main function. We’ll pass it’s return value to sys.exit().

Pretty simple right?

In the next tutorial, I’ll talk about IDLE (the interactive Python shell and IDE), and how to access an interactive Python shell from PyScripter.

Categories: Uncategorized Tags: ,
  1. No comments yet.
  1. No trackbacks yet.