Wednesday, February 23, 2011

Programming: my first steps with Python

Maybe it's the beginning of a new hobby, but I'm going back to programming - but this time instead of using basic, pascal or C ... I'll have a try with Python.

I installed geany to have a better programming experience, than a bare text editor and the terminal - and the idea was to create a first program to get a touch with the syntax, and the overall logic of Python.

The program should receive a value through the command line, then display an histogram of that value. e.g : if I entered 20 - I should see 2 bars and 8 empty space

Pretty simple, let's begin.

First good surprise in Geany you can generate empty template for Python program
I named mine '' and save it.
The first challenge was to find a way to get '' to read the argument given to him - and using google search, I found that 'for arg in sys.argv' was the way to do it.
then second challenge was to convert 'arg' which is a string of characters into a numeric value - some search got me into using 'int()' but the program had to be sure it wasn't text - so I had to put a test 'arg.isdigit()' if that was true then a will receive the numeric value of arg.

At this point I was pretty happy with Python - no need to declare variables (like pascal or C would require) and since Geany was indenting the program for me - it was a pretty good experience so far.
Now that I had 'a' containing the numeric value - I had to make sure it was in the range of 0..100 - my first test condition - easy 'if a>=0 and a<=100:' no need to had then - the ':' was enough assuming I would indent properly afterward (see the gray zone) below.

Next step was to assign 'g' the integer result of division of 'a' by 10
In the meantime I had to assign str1 - my histogram string in preparation the '<' symbol
and initialize my index i to zero.

Then 2 loops have to be introduced (blue zone) the first one - will assign '[]' (which represents a full block) - then the 2nd loop would assign '__' (which represents empty space) to the histogram's string.

After that I finish the histogram with a '>' to signal his ending and print str1.

Here's the program '' when executed with 6 arguments and the output result.

My conclusion after this little experiment is that Python is really fun to work with and assuming the indentation is respected and there's no infinite loop (got one in my second loop, because I forgot to add "i=i+1" - and I had to kill the process) everything went better than expected.

No comments: