10 Sept 2013

Python Code : Part 1

Python is amazing in terms of how once can code in just few lines. I'm starting a series which includes the code snippets from various resources on internet . The objective is to learn something new or something which is hidden in python.

Swap two variables
>> a=7
>> b=9
>> b, a=a, b       // tuple packing and unpacking is happening here.
on right side of = tuple packing is done (a, b) --> (7, 9)
on left side of = tuple unpacking is being done and values are swapped (b,a ) <--- (7 ,9)
>> a
9
>> b
7

Re-calculating a variable based on other variable.
>> a = 3
>> b = a + 3
now if i keep changing value of a then value of b should also be changed for example if a is 5 then b should be 8.
>> b = lambda : a + 3
 >> a =4
>> b() ............. it will pass current value of a to lambda expression.
7
>> a =2
>> b()
5

Apply operator on 2 and 2*3 to make it 6.
>> val = 2 and 2*3
>> val
6
for and operator , if both operand are true then it will return value of last operand , otherwise value of operand which is evaluating to be False.
>> val = 2 and 0   or( 0 and 2)
>> val
0
'and' and 'or' operator does not return True or False but value of expression !!

No comments:

Post a Comment