|
It all starts here! Every language has its "Hello, world"! The idea of such an application is to test the most basic functions; initialize, print something out in human readable format to prove that it works, and exit cleanly. It all started with the B language, and has been a standard since the first C tutorial. So, here goes for a Python "Hello, world!" Right from the very start, we will learn one of the big differences between Python and almost any other language, the Python interpreter. All languages require a file containing the source code. Depending on the language, the source code is either compiled into machine format, pre-compiled into something the interpreter understands, or run as-is. Python is slightly different. It does, of course, require a source file for most operations, but it can be run straight from the command line, and ask you to enter each line of code, which is then executed immediately. Bear with me. Running Python from the command line, on Linux: jlangbridge@vadrouille:~$ python Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> This means that the interpreter is running, and is awaiting some code. Well, let's give it some! >>> print "Hello, world!" Hello, world! >>>
Simple enough, wasn't it? Our very first hello world. The same applies to Windows and to Mac, and indeed any other OS. Fire up the interpreter, and let it run. When we quit our interpreter, all of our work is lost, so let's put all our hard work into a text file. Python files can be edited with any text editor, notepad.exe or gedit spring to mind. Let's create a file now, and call it "hello.py". Python source code (normally) has the extension .py. There are a few exceptions, but we'll go over those later. For the time being, assume that all source code files have the .py extension. In this file, we will add a single line of text: print "Hello, world!" Save the file, and run it with Python. On a Linux machine: jlangbridge@vadrouille:/tmp$ python ./hello.py Which, of course, prints out "Hello, world!". We have now used the Python interpreter to run a file. However, there are other ways to run files, and .py files can me run straight from the command line, without feeding it to the interpreter. To do this (on a Linux machine), we need to add the hash-bang line, and make the file executable. Add the following line to the beginning of your file: #!/usr/bin/env python And make the file executable: chmod +x ./hello.py Now run it straight from the command line: ./hello.py What this does is tell Linux that the file is to be run with Python. Essentialy, it is the same as before. Instead of specifying the Python executable, the shell does that for you. Congratulations! Your first Python program! Stay tuned for some more Python articles.
|