Product SiteDocumentation Site

Chapter 2. The Beginning

2.1. helloworld.py
2.2. Whitespaces and indentation
2.3. Comments
2.4. Modules

So we are going to look at our first code. As python is an interpreted language , you can directly write the code into the python interpreter or write in a file and then run the file. First we are going to do that using the interpreter, to start type python in the command prompt (shell or terminal).
[kd@kdlappy ~]$ python
Python 2.5.1 (r251:54863, Oct 30 2007, 13:54:11)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-33)] on linux2
Type "help", "copyright", "credits" or "license" for more information. 
>>>

In our first code we are going to print "Hello World!" , so do it as below,
>>> print "Hello World!"
Hello World!

2.1. helloworld.py

Now as a serious programmer you may want to write the above code into a source file. We will create a helloworld.py. Use any text editor you like to create the file. I used vi, you can even use GUI based tools like Kate, gedit too.
#!/usr/bin/env python
print "Hello World!"

To run the code first you have to make the file executable, in GNU/Linux you can do that by giving the command in a shell or terminal
$ chmod +x helloworld.py

Then
$ ./helloworld.py
Hello World!

On the first line you can #! , we call it sha-bang. Using this we are telling that use python interpreter to run this code. In the next line we are printing a text message. In python we call all the line of texts as strings.