#!/usr/bin/env python def main(): print "Hello World!" name = raw_input("What is your name?\n> ") print "Hello", name + "." if __name__ == "__main__": main()
Running the above code should output something like this:
$ ./hello.py Hello World! What is your Name? > David Hello David. $
Let us walk through this program line by line.
#!/usr/bin/env python
This opening statement is an attempt at cross-platform coding. In a linux environment, it will tell the shell you are using to run python as the interpreter. Windows will simply execute whatever program you have associated with the ".py" extension
def main():
This line begins a new function called "main" with no parameters. As python structures its syntax around indentation, all lines following this one which are indented will be a part of this function.
print "Hello World!"
The "print" command in python will output whatever follows it to the console, appending a newline at the end.
name = raw_input("What is your name?\n> ")
The "raw_input" function will print a prompt to the console, then await input until a newline is received (enter is pressed). The results will then be stored in a variable called "name" for use later in our program.
print "Hello", name + "."
You may provide "print" with a comma-separated list of strings. The function will print these strings to the same line on the console, separated by a single space. In the case of the period at the end, we do not wish for there to be a space, so we simply concatenate it with the name variable.
if __name__ == "__main__": main()
These two lines are designed to make your python code more re-usable. Suffice to say that they will cause your 'main' function to be called when your file is run directly, without causing problems when it is loaded as a module. We will learn about modules in a later tutorial, and hopefully the purpose of these lines will become more clear.
This example illustrates a basic form which you can apply to most of the python files that you write which are intended to be run directly.