Tuesday, 17 January 2012

Taste of Python Power

Python is a programming language that lets you work more quickly and integrate your systems more effectively. You can learn to use Python and see almost immediate gains in productivity and lower maintenance costs. Python runs on Windows, Linux/Unix, Mac OS X, and has been ported to the Java and .NET virtual machines. Python is free to use, even for commercial products, because of its OSI-approved open source license. The below is a quick taste of the power of Python language:


List Comprehensions
print [x+1 for x in xrange(10) if x%3 == 0]

[1, 4, 7, 10]
Dictionary Defaults
my_dict = {}
world = my_dict.get('hello', 'world')
print world

world
Filter
from math import sqrt

def prime(n):
    if n < 1 : return False
    for d in range(2, int(sqrt(n))+1):
        if n % d == 0: return False
    return True

print [n for n in range(20) if prime(n)]

print filter(prime, range(20))

[1,2,3,5,7,11,13,17,19]
[1,2,3,5,7,11,13,17,19]
Unzip
tups = [(1,4,7),(2,5,8),(3,6,9)]
t0s, t1s, t2s = zip(*tups)
print t0s
print t1s
print t2s

(1,2,3)
(4,5,6)
(7,8,9)
dict() and zip() make for a powerful combination
voters = ['friends','neighbors','countrymen']
counts = [10,5,800]
print dict(zip(voters,counts))

votes = ['yes',66,'no',77,'abstain',9]
print dict(zip(votes[:-1:2],votes[1::2]))

{‘neighbours’:5, ‘countrymen’:800, ‘friends’:10}

{‘yes’:66, ’abstain’:9, ’no’:77}
Triple quotes
print """Dear John,
How are you?
Best of luck, George."""

Dear John,
How are you?
Best of luck, George.
Map
print map(int, "10 20 30".split())

[10,20,30]
Multiple Return Values
def get_center():
    return (10, 10)

x, y = get_center()
print "The center is at X: %d, Y: %d" % (x, y)

The center is at X: 10, Y: 10
Expanding Arrays to Function Arguments
def add(n1, n2):
    return n1 + n2

numbers = [3, 4]
print add(*numbers)

7
Collections
import collections
d=collections.defaultdict(int)
d["never seen before"] += 1
print d["never seen before"]

1
Generator Functions
def lottery_numbers():
    my_numbers = [1,3,2,5,4,6]

    for n in my_numbers:
        if n > 3:
            yield n+10
        else:
            yield n

for n in lottery_numbers():
    print n

1
3
2
15
14
16
Zip
names = ['john', 'peter', 'robert']
ages = [24, 26, 35]
cars = ['BMW', 'Audi', 'Ford']

print zip(names, ages, cars)

[('john', 24, 'BMW'), ('peter', 26, 'Audi'), ('robert', 35, 'Ford')]
Ordered and Named Function Arguments
def f(*args, **kwargs):
    print(args)
    print(kwargs)

f(1,2,3,named1="keyword arg1", another="another kwarg")

(1, 2, 3)
{'named1': 'keyword arg1', 'another': 'another kwarg'}
Locals and Strings
world = "earth"
print "hello %(world)s" % locals()

hello earth
Glass Half Empty?
from __future__ import division
import sys

print 1/2 + 1/2
print sys.version

1.0
2.7.2 (default, Jun 24 2011, 12:21:10) [MSC v.1500 32 bit (Intel)]
Set Comprehensions
print {1, 2, 2, 3, 1}

names = ["Foo", "bar", "foo", "Baz", "CATS", "dogs"]
print {name.upper() for name in names if name[0] in 'fFbB'}

set([1, 2, 3])
set(['BAZ', 'FOO', 'BAR'])
Functions as Objects
def talk(text):
    print text

def think(idea):
    print "thinking about %s" % idea

def do_something(what, with_what):
    what(with_what)

do_something(talk, 'hello!')
do_something(think, 'food...')

hello!
thinking about food...
Funception
def outside(a, b):
    def inside(x):
        return x + 5
    return inside(a) * inside(b)

print outside(1, 2)

42
Addition made easy
print eval('+'.join(map(str, [1, 1])))

2

9 comments:

  1. Your new valuable key points imply much a person like me and extremely more to my office workers. With thanks from every one of us.

    Best AWS Training in Chennai | Amazon Web Services Training in Chennai

    ReplyDelete
  2. Some us know all relating to the compelling medium you present powerful steps on this blog and therefore strongly encourage contribution from other ones on this subject while our own child is truly discovering a great deal. Have fun with the remaining portion of the year.
    python training in pune | python training institute in chennai | python training in Bangalore

    ReplyDelete
  3. After seeing your article I want to say that the presentation is very good and also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts like this.
    Java training in Annanagar | Java training in Chennai

    Java training in Chennai | Java training in Electronic city

    ReplyDelete
  4. Ini adalah latihan mental yang bagus untuk mereka yang ingin mengaktifkan sel-sel otak mereka. Ada banyak orang di seluruh dunia yang memiliki kebiasaan memainkannya 98toto

    ReplyDelete
  5. Hi, I read your whole blog. This is very nice. Good to know about the career in Python Training & Certification. We are also providing various Python Training , anyone interested can Python Courses for making their career in this field .

    ReplyDelete

  6. Searching for advanced scripting language courses to upgrade your aptitudes? On the off chance that indeed, at that point Python language is the ideal counterpart for you. python classes in pune can be extremely simple and advantageous with ITView Software Training Institute. In spite of the fact that we as a whole realize that there are incalculable python course in pune however there is something interesting and exceptional about ITView Software Training Institute.

    ReplyDelete
  7. I have thoroughly enjoyed reading your entire blog. It's great to learn about the opportunities in Python Training & Certification for a career. Additionally, we offer a range of Python training in Nagpur for individuals interested in pursuing a career in this field.

    ReplyDelete
  8. Thanks for sharing this here. Great Post, really it was very helpful for us. I found this blog to be very useful! python classes in satara

    ReplyDelete