Learning python…
June 17, 2008 at 9:17 pm (Uncategorized)
After quite some time not blogging anything, I though I would blog about my recent “success.” Ok, you see it’s in quotes and that means it’s not generally a big deal. Simply I started to learn python. And I was able to write an addressbook ( I really needed one ) in just 4 hours, and with only 62 lines of code ( no OOP, only structured ). so, for a quick reference, I’ll just post it here. it’s also good to say that it was written in less than 30 mins ( including debugging and including the fact that it was my first python script/program ).
=====================================================
#!/usr/bin/python
D = { }
name = ”
number = 0
print “For searching a particular phone# press 1″
print “For adding an entry press 2″
opt = raw_input()
if opt == ‘1′:
file = open( ‘adb.txt’, ‘r’ )
string = file.readline()
string = string.rstrip()
while string != ”:
rl = string.split()
fname = rl[ 0 ]
fnum = rl[ 1 ]
D[ fname ] = fnum
string = file.readline()
string = string.rstrip()
print “enter the desired name: “
name = raw_input()
for key in sorted( D ):
if key == name:
number = D[ key ]
print number
exit()
print “no entry found”
exit()
elif opt == ‘2′:
print “enter a name and a number: “
file = open( ‘adb.txt’, ‘a’ )
s = raw_input()
while s != ‘0′:
l = s.split()
name = l[ 0 ]
number = l[ 1 ]
D[ name ] = number
file.write( name )
file.write( ‘ ‘ )
file.write( number )
s = raw_input()
exit()
else:
print “inappropriate option”
exit()
======================================================
so, that’s it, 62 lines. It still feels strange to not put if, while, for statements in blocks {} but I will get used to it. The indentation syntax is also good, I thought I wouldn’t like it, but turned out that it makes the code easy to read. Not much difference though, I still did the same thing with C++.
Anyhow, that’s enough for today, I’ll keep you posted.