Python's a ridiculously easy language to learn. Here are a few examples of bits of syntax.<p><pre><code> # comments start with a "#" symbol
[1,2,3,4] # that's a list
{"x":1, "y":2, "z":3} # that's a dictionary
blah = 6 # you can assign things to variables
asdf = [3,6,1,2] # including lists, dictionaries, etc.
def foo(x,y,z):
if x > y:
print "X is greater than Y"
else:
print "X < Y!"
return z - 1
</code></pre>
That's a function called foo taking parameters x,y,z. "def" defines a function. Notice that you indent where you normally would (after the def, after the if and else). Python code is typically very readable because of this.<p>Here's an example of a class in Python (I assume you're familiar with classes?):<p><pre><code> class Foo:
def __init__(self, x, y):
"""The __init__ function is basically like a constructor.
This thing here is a docstring, it's used to document a function
or class."""
self.x = x
self.y = y
def sum(self):
# The pointer to the instance is the first parameter.
# It's usually called 'self', but the name can be anything.
return self.x + self.y #note: self.<whatever> for member variables
def __str__(self):
"""This function is used to make a human readable representation."""
# there are various ways to do this, but % should be familiar to
# programmers of C-like languages. (it's like printf)
return "Foo(%d, %d)" % (self.x, self.y)
foo = Foo(1,2) # note: Python is case-sensitive
print foo # calls foo.__str__() and displays the result -- "Foo(1, 2)"
print foo.sum() # prints 3
</code></pre>
Python allows functions to be passed to functions and returned from functions, for example:<p><pre><code> def makeAFunctionThatAddsXtoY(x):
def myNewFunction(y):
return x + y # x gets stored in the new function for later use
return myNewFunction
f = makeAFunctionThatAddsXtoY(5) # f is a function
print f(10) # prints 15, as expected
</code></pre>
Some people care about this ability more than other people. Python's an easy way to start learning about functional programming if you're not familiar with it yet.<p>There's also some other fairly handy things to learn, like list comprehensions:<p><pre><code> foo = [3,1,6,206,24,1230,0,1,112,30, 96]
bar = [x for x in foo if x % 2 == 0] # all even numbers in foo
baz = [3*x for x in foo if x % 3 == 0] # triple everything divisible by 3
</code></pre>
You can access list elements with familiar array syntax:<p><pre><code> foo[0] == 3 # evaluates to True (note: True and False are capitalized!)
</code></pre>
You can also take "slices" of lists to get a range of elements:<p><pre><code> foo[0:2] == [3,1] # this statement also evaluates to True
</code></pre>
You can get a description of most functions and classes by typing help(name_of_thing_you_want_to_know_about) into the Python interpreter.<p>The best way to learn Python is to read the tutorial (<a href="http://docs.python.org/tutorial/" rel="nofollow">http://docs.python.org/tutorial/</a>) and play around with it. Have fun!