Home | Help | Sign In 

Hello world in Python

By

Sebastian Bassi

DNALinux.com
Article rating:
Your rating:

A "Hello world" program is the customary way to show how to program in a new language. Although the Python's hello world is trivially simple, there is always something to learn from it

Installing Python

Depending on your operating system, you may need to download Python.  Most Linux distributions come with Python as does Mac OS X.  Windows does not ship with Python.  To test if Python is installed, open a command prompt and enter:
python
If Python is installed you will see the Python interactive interpreter, if not you will receive an error message.  To install Python go to http://www.python.org/download/ and download the appropriate file.  Follow the instructions to install Python.

Hello world in Python (prior version 3):


Writing a "Hello word" program in Python is trivial:
print "Hello world"
In the interactive interpreter, it looks like this:


This Knol also introduces the print command:

The print command

A print command in Python adds a line feed, so with two prints you will get two lines:

print "Hello"
print "world"

Hello
world

This can be avoided by using a period (,) at the end:

print "Hello",
print "world"  

Hello world

Hello world using variables:

>>> h = "Hello"
>>> w = "world"
>>> print h+' '+w
Hello world

Note that the "+" operation concatenates three strings: Hello, a "space" character and "world".

Printing with placeholders


>>> print "%s %s" %(h,w)
Hello world
By using "%s" you don't have to concatenate strings, just use one string and put a placeholder (the %s) where the variable


Python 3

In Python 3, the print statement is transformed into a function, so a basic hello world, is:

print("Hello world")

x

Videos


Introduction to Python (from download to "Hello world")


Contributors


Share what you know
Write a Knol
Moderated collaboration
All signed in users can suggest edits to the knol, but these need approval from an author before being published
Version: 13 Last edited: Jul 31, 2008 11:03 PM.

Reviews

  • There are no reviews for this knol.

Comments

Comments are disabled for this knol.