Python hello world tutorial
From GMpedia.org Wiki
c4tela
[edit] Basic Python Syntax
People would disagree about C++ coding styles, some think that the following way is better:
void foo ( void )
{
/* Body of Foo */
}
While other's believe writing code like this would be beter:
void bar ( void ) {
/* Body of Bar */
}
The creators of Python thought they could skirt the whole argument by attempting to allow only "THE ONE WAY": indentation!
[edit] Indentation?
Yep, and it's suprisingly elegant too(although the forthcoming example is nothing to write home about). I'm going to throw some code here, don't worry, we'll cover the specifics of these structures and more later on.
# Example of some needlessly complicated loops and other control
# structures to illustrate how indentation is used to make
# blocks of code.
# Indentation works like { and } in C or Java.
if "hello" == "world": #Colons are used at the end of control statements a lot
# Notice the indent here
print "hello" + "world" + "!!!"
elif type(a) == type(1):
newlist = []
while a < 100: # Everything below here is part of this while
list.append(a)
for value in list: # Everything below here is part of this for
try:
newlist.append[math.sqrt(value)]
except:
print "value just happened to be negative!!!"
print "I'm melting!"
# The for loop ends here
a += 1
# The while loop ends here
print newlist
# The if else structure (and in this case, the "program") ends here.
Now let's try the only example you'll ever need when attempting to teach a programming language: Hello World! Notice this is mostly comments, and I'm actually doing hello world in several different ways.
One of the ways not shown is using modules (although this file could also be a module). All python source is also a module (and modules can be gathered into packages for convenience and logical organization). We'll cover this more later. Suffice it to say you can execute hello world within the python interpreter by "importing" this python file ("hello.py").
You can download this Python file and try it yourself very quickly.
# Intro to Python
# THROUGH:
# The _Sacred_ Hello World Program
# At the interpreter
print "Hello World!" # Note that the "\n" is automagic after each print.
# As a function
def hello():
print "Hello World!"
return # This is optional, since you aren't returning anything.
# From the commandline (A one liner, immediate execution)
import os
os.popen("python -c \"print 'Hello World!'\"")
# Just python -c "print 'hello world!'" at the commandline.
[edit] Resources
Feel free to continue to modify and expand this page, but please leave this notice and any licence notices in-tact.

