Python in 48 hours

2012 April 28 at 05:27 » Tagged as :python, ruby, vargs,

Spurred on by my recent success in quickly learning ruby,  I am about to embark on a (crash) course on python. Consider the following to be my study note. It may or may not be useful to you. If you are coming from a PHP, Java or C background it's perhaps more likely to be of use. Anyway, let's get started.

Strings

At first glance Python's print is like a cross between the good old printf  and puts from C.  It seems like you can even use printf style formatting in print but make sure that your variable like starts with a %

print "my height is  %d  and weight is %s ." % (my_height, my_weight)

 But looks can be deceiving. What you have just seen is a feature of python strings and not of print! you can instead do

s = "my height is  %d  and weight is %s ." % (my_height, my_weight)

Python also provides an alternative to C like formatting via the String.format function. The approach is similiar but I suppose format is more readable. Also worth note are a set of functions like rjust, ljust, center and also zfill Their names should be self explainatory.

In ruby if you write “#{‘hello’ * n}” it will produce hellohellohellohello. Python can play that game too, in fact it's even easier: "hello"*10 . If you know of someone anywhere in the world to have found this feature to be usefull please drop me a line.

Another odd thing about python strings is that they can be triple quoted with """ or ''' (Wordpress will surely mess up the display). Triple quoted strings are used to create multiline strings.  String concatenation is not so wierd, just use a + as in javascript. Even the '+' can be omitted if you are dealing with  string literals eg 'Hello' 'World'. Look ma no plus.

You cannot add a number or any other object to a String to create another string. You are supposed to call the str() function, this is like the Ruby to_s or java toString()

Strings as lists.

"Strings can be subscripted (indexed); like in C, the first character of a string has subscript (index) 0. There is no separate character type; a character is simply a string of size one." (python tutorial). This feature makes fetching a Substring easier than in most other  languages; str[2:4] also possible is to create slices like  str[2:] or str[:2]  meaning first two characters and last two characters respectively.

It's important to note that even though this notation looks pretty much like the array notation in many other langauges what's actually being returned here is a string.

IO

Someone has snatched all the  data from a file. Police suspect open() and handle.readlines()and handle.read() .  Less suspicion has fallen on  handle.readline() because the poor thing can read only one line at a time. The stolen data has allegedly been transfered to another file with the involvement of write() and close()

So what's the opposite of print is it get? no it's input() but using input() really isn't recommended it does kind of an 'eval' on the input. Better to use raw_input(). Both methods not only read keyboard input but display a prompt as well, which can be passed in as a parameter. Example;  raw_input('input some text buddy').

But just to ensure that your life is complicated they did away with the raw_input() method in python 3.0 and renamed it as input(). In python 3.0 the input() method gives the same result as the raw_input() method of 2.7

 

Blocks

Like in Fortran blocks are characterized by their indentation level.  It's the ':' that marks the start of a new block. Functions, if, else, while, for all need to have an ':' at the end like so:

if x < 0:
    x = 0
    print 'Negative changed to zero'
elif x == 0:
    print 'Zero'
elif x == 1:
    print 'Single'
else:
    print 'More'

Before you write your first line of code, make sure that your editor or IDE is configured to use spaces instead of tabs when indenting. Else there will be hello to pay. You will encounter  'IndentationError: unindent does not match any outer indentation level' which bring your you grief and eat your brain cells.

Conditionals

Python's for loop syntax is similar to what you find in Ruby; for i in something . There is a little something extra the colon at the end.

for x in a:
     print x, len(x)

That 'a' is a list. You can use a range instead like in Ruby. Predictably ranges can be created with the range() function. Only one parameter is compulsory for the function call which is the number of elements in the range. But you can also use a three parameter version if that's your cup of tea. This is actually implemented through default values for parameters (something that PHP guys are very familiar with)

Exceptions

Exception handling in Python is somewhat akin to exception handling in Ruby. By the way Has anyone noticed how many of the error messages produced by the Ruby look like those produced by python? what's that you say? old hat? ok never mind.

for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except IOError:
        print 'cannot open', arg
        raise Exception('oh forget it')
    else:
        print arg, 'has', len(f.readlines()), 'lines'
        f.close()

In the code above (adapted from the python tutorial), my own two cents have been thrown in (no pun intended); a raise statement. To raise is to throw. raise takes an argument which is a name of an Exception. And that Exception can even be your own custom one creating by subclassing Exception.

Finally, there is also a finally clause, which like the one in java is meant to be run after the code executes cleanly OR after the exception handling has completed.

Break and Continue

The break and continue from C are also present and do exactly the same thing. Also avilable is pass which means NOP or the empty statement in languages that use the ';' to terminate lines. But there is no switch case.  Another python oddity is that  for and while loops is that they can have an else. I kid you not! here is another example straight from the python docs:

 for n in range(2, 10):
        for x in range(2, n):
           if n % x == 0:
               print n, 'equals', x, '*', n/x
                break
        else:
           # loop fell through without finding a factor
            print n, 'is a prime number

Remember folks, indentation is king in python. The else is not in line with the 'if' but with the for, which means what we have here is a for-else . Yeah there's no accounting for taste. On the other hand for-else is a replacement for the following PHP code

for($i=0 ; $i < $k < $i++) {}
if($i == 0) {
    // didn't enter the loop even once
}

Functions

Methods in python like those in Ruby are defined with the def keyword. I said method instead of function because like in Ruby everything is an object but perhaps not in the strictest sense.  Despite the claims python code doesn't look at all like object oriented. The python docs call these things function, so you better start adapting that convention if you don't want to get flamed.

You can't directly access a global variable from inside a function unless it's declared as one by using the global keyword (PHP style). Functions can be treated like variables. Which means you can change the name of a function by asigning it to something else like you do in javascript.

There is  lot more to functions than this, guess it's going to need an aside.