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:

5 Comments

  1. Moustafa said,

    Wednesday, 11th Apr 2012 at 10:25

    Thank you.

  2. mickymoose said,

    Friday, 13th Nov 2009 at 10:41

    Wow. I just learned Python in 10 minutes. I want to laminate a wallet-size copy of this :-P

    • sysblog said,

      Saturday, 14th Nov 2009 at 00:54

      Feel free to do so. Thanks for the feedback, mate.

  3. Merlin81 said,

    Friday, 23rd Oct 2009 at 16:00

    EPA does not test or certify these treatment units. ,

  4. pythonisms said,

    Saturday, 7th Mar 2009 at 19:12

    this is wicked !


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: