Learn Python in 100 Python Session Log Lines: A Python Demo

Well, not exactly 100, but sort of 😉 For a quick and dirty overlook to learn python from (valid) source code:

>>> myvar = 3
>>> myvar += 2 # no myvar++
>>> myvar -= 1
"""This is a multiline comment.
The following lines concatenate the two strings."""
>>> mystring = "Hello"
# Concatenate strings:
>>> mystring += " world."
>>> print mystring
Hello world.
# This swaps the variables in one line(!).
>> myvar, mystring = mystring, myvar
# List with number, list, tupel as elements:
>>> sample = [1, ["another", "list"], ("a", "tuple")]
# List with string, int, float as elements:
>>> mylist = ["List item 1", 2, 3.14]
# Change first element:
>>> mylist[0] = "List item 1 again"
# Dereference the last element (second last would be -2):
>>> mylist[-1] = 3.14
# Dictionary; known as hash in perl:
>>> mydict = {"Key 1": "Value 1", 2: 3, "pi": 3.14}
>>> mydict["pi"] = 3.15
# Tupel a.k.a. int array:
>>> mytuple = (1, 2, 3)
# Pointer to function len:
>>> myfunction = len
>>> print myfunction(mylist)
3
>>> mylist = ["List item 1", 2, 3.14]
# List ranges, called slicing. Range = [a, b):
>>> print mylist[:]
['List item 1', 2, 3.1400000000000001]
>>> print mylist[0:2]
['List item 1', 2]
>>> print mylist[-3:-1]
['List item 1', 2]
>>> print mylist[1:]
[2, 3.14]
>>> print "He said 'hello'."
He said 'hello'.
>>> print 'He said "hello".'
He said "hello".
>>> unicodestring =  u"This is a unicode string"
>>> strString = """This is
>>> a multiline
>>> string."""
""" %s get replaced with items from a given tuple | dict,
left to right (borrowed from printf()):"""
>>>print "Name: %s\nNumber: %s\nString: %s" % (myclass.name, 3, 3 * "-")
Name: Poromenos
Number: 3
String: ---
""" % is a string creation operator. Watch out for the
trailing s in "%(key)s", like printf's modifiers:"""
>>> print "This %(verb)s a %(noun)s." % {"noun": "test", "verb": "is"}
This is a test.
# If you prefer C syntax just define your own function
# ('*' means to wrap parameters up in a tuple and ',' adds no \n):
def printf(format, params): print format % params,
"""controling flow by if, for, while. Use if instead of case/switch.
Blocks are marked by indention!"""
rangelist = range(10)
>>> print rangelist
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in rangelist:
    # Check if number is one of
    # the numbers in the tuple.
    if number in (3, 4, 7, 9):
        # "Break" terminates a for without
        # executing the "else" clause.
        break
    else:
        # "Continue" starts the next iteration
        # of the loop. It's rather useless here,
        # as it's the last statement of the loop.
        continue
else:
    # The "else" clause is optional and is
    # executed only if the loop didn't "break".
    pass # Do nothing

if rangelist[1] == 2:
    print "The second item (lists are 0-based) is 2"
elif rangelist[1] == 3:
    print "The second item (lists are 0-based) is 3"
else:
    print "Dunno"
while rangelist[1] == 1:
    pass
# Declare functions with def; optional arguments have default value assigned:
def myfunction(arg1, arg2 = 100, arg3 = "test"):
    # multiple returns, i.e. multidimentional function.
    # '\' is line continuation character:
    return arg3, \
    arg2, arg1
>>>ret1, ret2, ret3 = myfunction("Argument 1", arg3 = "Named argument")
# notice = doing a multi-assignement here!
>>>print ret1, ret2, ret3
Named argument 100 Argument 1
# We can do easy value swapping:
>>>ret1, ret3 = ret3, ret1
>>>print ret1, ret3
Argument 1 Named argument
# Same as def f(x): return x + 1 but without a function's name:
functionvar = lambda x: x + 1
>>> print functionvar(1)
2
# Private vars and methods start by >= 2 underscores and
# <2 ones ppended (by convention only). __spam is
# replaced by _classname__spam literally.
# __init__() is the closest python gets to a constructor
# (instance already exists when it's called:
class MyClass:
    common = 10
    def __init__(self, n=3):
        self.myvariable = n
    def myfunction(self, arg1, arg2):
        return self.myvariable
# Initiate:
>>> instance = MyClass()
>>> instance.myfunction(1, 2)
3
>>> instance2 = MyClass()
# variable 'common' is shared by all instances via their class:
>>> instance.common
10
>>> instance2.common
10
# Note how we use the class name instead of the instance:
>>> MyClass.common = 30
>>> instance.common
30
>>> instance2.common
30
# by explicitly declaring a value it becomes
# an instance variable (called data attribute):
>>> instance.common = 10
>>> instance.common
10
>>> instance2.common
30
>>> MyClass.common = 50
# This doesn't chance this:
>>> instance.common
10
# but this
>>> instance2.common
50
# This class inherits from MyClass which is just a special
# case for multiple inheritance as in
# class OtherClass(MyClass1, MyClass2, ..., MyClassN)
class OtherClass(MyClass):
    def __init__(self, arg1):
        self.myvariable = 3
        print arg1
>>> instance = OtherClass("hello")
hello
>>> instance.myfunction(1, 2)
3
# Add (instance) members 'on-the-fly':
>>> instance.test = 10
>>> instance.test
10
# this throws an error
>>> instance2.test
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute 'test'
def somefunction():
    try:
        # Division by zero raises an exception
        10 / 0
    except ZeroDivisionError:
        print "Oops, invalid."
    else:
        # Exception didn't occur, we're fine.
        pass
>>> fnExcept()
Oops, invalid.
# Import external libraries:
import random
# This will instead import the desired function only:
from random import randint
randomint = random.randint(1, 100)
>>> print randomint
42
# convert data structures to strings using prickle library.
import pickle
mylist = ["This", "is", 4, 13327]
# Open C:\binary.dat for writing. 'r' prevents backslash escaping:
myfile = file(r"C:\binary.dat", "w")
pickle.dump(mylist, myfile)
myfile.close()
#remove, i.e. free, variable. works on list items, too:
del mylist
myfile = file(r"C:\text.txt", "w")
myfile.write("This is a sample string")
myfile.close()
myfile = file(r"C:\text.txt")
>>> print myfile.read()
'This is a sample string'
myfile.close()
# Open the file for reading.
myfile = file(r"C:\binary.dat")
loadedlist = pickle.load(myfile)
myfile.close()
>>> print loadedlist
['This', 'is', 4, 13327]
# some hints:
# chain conditions (a must be 2):
1 < a < 3
# list comprehensions are powerfull:
>>> lst1 = [1, 2, 3]
>>> lst2 = [3, 4, 5]
>>> print [x * y for x in lst1 for y in lst2]
[3, 4, 5, 6, 8, 10, 9, 12, 15]
>>> print [x for x in lst1 if 4 > x > 1]
[2, 3]
# "any" returns true if any item in the list is true.
>>> any(i % 3 for i in [3, 3, 4, 4, 3])
True
# Check how many items have this property.
>>> sum(1 for i in [3, 3, 4, 4, 3] if i == 3)
3
>>> del lst1[0]
>>> print lst1
[2, 3]
# variables outside functions are global but need to be pointed out for writing:
number = 5
def myfunc():
    # This will print 5.
    print number
def anotherfunc():
    # This raises an exception because the variable has not
    # been assigned to before printing. Python knows that it a
    # value will be assigned to it later and creates a new, local
    # number instead of accessing the global one.
    print number
    number = 3
def yetanotherfunc():
    global number
    # This will correctly change the global.
    number = 3

As with any language, even natural ones, you need to practice it for a longer while to really get to know it. So what are you waiting for? Dive into Python, now! 😉

References and Further Reading:

Were you ever in the desperate need to know all primes below 1000?

In Python calculating primes can be done with a one-liner using functional programming concepts lambda function, map(), reduce() and filter():

# Primes <1000
print filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,map(lambda x,y=y: y%x, range(2,int(pow(y,0.5)+1))),1), range(2, 1000)))&#91;/sourcecode&#93;

To try this out on a system with python installed in a terminal/console/... type python. In the command prompt showing up paste the line, hit enter and you'll get:
<code>[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]</code>Update: Thanks to <a href="http://wordpress.com/blog/2007/09/03/posting-source-code/">Matt</a> and <a href="http://en.forums.wordpress.com/topic.php?id=6435&amp;page&amp;replies=9#post-111641">Mark</a> the code snippet now can look much <a href="http://faq.wordpress.com/2007/09/03/how-do-i-post-source-code/">nicer</a>:


# Primes <1000
print filter(None, map(lambda y: y*reduce(lambda x,y: x*y!=0, map(lambda x,y=y: y%x, range(2, int(pow(y, 0.5)+1))),1),range(2,1000)))&#91;/sourcecode&#93;

Update: Not quite as accurate (compare start of the sequence, 3 is missing) but <a href="http://www.python.org/doc/current/tut/node7.html#SECTION007130000000000000000">much shorter</a> using another formula and filter() and lambda techniques only:


filter(lambda x: x % 2 != 0 and x % 3 != 0, range(2, 1000))

[5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]