Python in one 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,

#!/us/bin/python

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

Lists:

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

Maps:

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

Saving Python interaction into a file after writing your program

import readline
readline.write_history_file("path_of_the_file")

Getting ascii code of char:

ord('A')

Getting hexadecimal of a decimal number:

hex(123)

Getting octal of a decimal number:

oct(11)

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"
else:
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:

max(list)
min(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
random.shuffle(list);
print list;

Keyword arguments:

#!/usr/bin/python
# Function definition is here
def printinfo( name, age )
   print "Name: ", name
   print "Age ", age

# Now you can call printinfo function
printinfo( age=50, name="miki" ) # Name: miki, Age: 50

Default argument:

#!/usr/bin/python
# Function definition is here
def printinfo( name, age = 35 ):
   print "Name: ", name
   print "Age ", age
# Now you can call printinfo function
printinfo( age=50, name="miki" )  # Name:  miki, Age  50
printinfo( name="miki" ) # Name:  miki, Age  35

Variable-length arguments:

#!/usr/bin/python
# Function definition is here
def printinfo( arg1, *vartuple ):
   print "Output is: "
   print arg1
   for var in vartuple:
      print var
# Now you can call printinfo function
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.

dir(importModuleName);

Leave a Reply