Python Tutorial

Saturday, July 13, 2013

Python chain comparison


x = 10

print '5<x<9',5<x<9
print '5<x<11',5<x<11
print '5<x<11<10*x<101',5<x<11<10*x<101
print '10==x<90==9*x',10==x<90==9*x

Output:
5<x<9 False
5<x<11 True
5<x<11<10*x<101 True
10==x<90==9*x True

Python unpacking list, tuples or dictionary as function argument.


def my_func(a, b, c):
    print "a,b,c:",a,b,c

my_func(1,2,3)
my_func( *[1,2,3] ) # unpacking from list
my_func( *(1,2,3) ) # unpacking from tuples
my_func( **{'a':1, 'b':2, 'c':3} ) # unpacking from dictionary

Output:
a,b,c: 1 2 3
a,b,c: 1 2 3
a,b,c: 1 2 3
a,b,c: 1 2 3

hmac - Keyed hashing

Python hmac is a Keyed-Hashing for Message Authentication. Here we also can set digest mode, default mode is md5.

import hmac
import hashlib

print hmac.new("python","msg1", hashlib.sha256).hexdigest()
print hmac.new("python","msg2", hashlib.sha256).hexdigest()
print hmac.new("python","msg3", hashlib.sha256).hexdigest()

Output:
eb96a956ee4df54f5e2cd94bf326925c9405f989a69c64948f3b05f75c38f880
bcd3d2a7bb7d3ff12085a494c19de671a96a1892e75bb6a0e8bbee87473d873f
68a3d9807b17d303324dc24853f5c949076161a271ff41209da863e9e91f96e6