3 ms·
Python's a ridiculously easy language to learn. Here are a few examples of bits of syntax. # comments start with a "#" symbol [1,2,3,4] # that's a lis
by Figs 16y ago
Python's a ridiculously easy language to learn. Here are a few examples of bits of syntax.
# 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
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.
Here's an example of a class in Python (I assume you're familiar with classes?):
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
Python allows functions to be passed to functions and returned from functions, for example:
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
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.
There's also some other fairly handy things to learn, like list comprehensions:
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
You can access list elements with familiar array syntax:
foo[0] == 3 # evaluates to True (note: True and False are capitalized!)
You can also take "slices" of lists to get a range of elements:
foo[0:2] == [3,1] # this statement also evaluates to True
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.
The best way to learn Python is to read the tutorial (http://docs.python.org/tutorial/ http://docs.python.org/tutorial/) and play around with it. Have fun!
- andre 16y agothat, that looks manageable