Python in one post

Default featured post

Two years ago when I started learning Python I had made a small note for myself as a quick reference which turned out to be so handy. The time I made the note I did not consider about sharing it. Now, after two years when I was working with Python for my Ubuntu Indicator Weather project, I was thinking maybe sharing the note could be useful for someone, though many better tutorials are available all over the Internet.

Apart from this post, as a Java developer I believe Python is one of the most beautiful languages, . Indeed I love it. It is easy to learn, code, and a great choice for RAD small projects.
Python scripts starts with the following line,


Defining a variable,

x = 10
print x

Python loosely typed language, means you do not need to specify the type of variables.
Working with strings:

str = "ABCDE"
print string[0]     # A
print String[0:1] # AB
print String[1:]  # BCDE


lst = ['a',1,'qq']
len(lst) >>> 3


v = {'key1':'value', 1:2}

Saving Python interaction into a file after writing your program,

import readline

Getting ascii code of char:


Getting hexadecimal of a decimal number:


Getting octal of a decimal number:


Start variable or method with underscore means private, with two __ means too private.
Power :

2**3 # 8

If structure,

if x <> 10:
    print "x is not 10"
elif x == 2:
    print "x is 2"
    print "x is not 10 or 2"

Bubble sort (for loop):

arr = [10,79,4,12,80,100,400]
for cnt in range(len(arr)):
...     for cnt1 in range(cnt+1,len(arr)):
...             if(arr[cnt]>arr[cnt1]):
...                     swap = arr[cnt]
...                     arr[cnt] = arr[cnt1]
...                     arr[cnt1] = swap
print arr  # [4, 10, 12, 79, 80, 100, 400]

Pass is like ; (null instruction) in the C style language:

if (x == y);
if x == y: pass

Getting maximum and minimum value of a list:


More amazing stuff with lists:

choice(list)       # Get a random number from the list
randrange(10)  # Generate a random number

Randomizing the items of a list in place.

import random
print list

Keyword arguments:

def printinfo( name, age )
   print "Name: ", name
   print "Age ", age

printinfo( age=50, name="miki" ) # Name: miki, Age: 50

Default argument:

def printinfo( name, age = 35 ):
   print "Name: ", name
   print "Age ", age

printinfo( age=50, name="miki" )  # Name:  miki, Age  50
printinfo( name="miki" ) # Name:  miki, Age  35

Variable-length arguments:

def printinfo( arg1, *vartuple ):
   print "Output is: "
   print arg1
   for var in vartuple:
      print var

printinfo( 10 )
printinfo( 70, 60, 50 )

Lambda expression or anonymous function,

lambda [arg1 [,arg2,.....argn]]:expression
sum = lambda x,y,z,q: x*y*z*y

The dir() built-in function returns a sorted list of strings containing the names defined by a module.