Tuesday, 9 January 2018

difference between is and == in python

"is" vs "=="
-------------------------
  • "is" expressions evaluate to True if two variables point to the same object.
  • "==" evaluates to True if the objects referred to by the variables are equal.
>>> a = [1, 2, 3]
>>> b = a >>> a is b
True
>>> a == b
True >>> c = list(a) >>> a == c
True
>>> a is c
False

Switch case implementation in python

Example:

def calculator(operator, x, y):
    if operator == 'add':
        return x + y
    elif operator == 'sub':
        return x - y
    elif operator == 'mul':
        return x * y
    elif operator == 'div':
        return x / y
    else:
        return None

print(calculator('add',2,3))
print(calculator('div',6,2))
print(calculator('mod',4,2))

Output:

5
3.0

None


Example: by using dict

def calculator(operator, x, y):
    return {
        'add': lambda: x + y,
        'sub': lambda: x - y,
        'mul': lambda: x * y,
        'div': lambda: x / y,
    }.get(operator, lambda: None)()

print(calculator('add',2,3))
print(calculator('div',6,2))

print(calculator('mod',4,2))


Output:

5
3.0
None

Thursday, 4 January 2018

About Python





  • Python is powerful and faster execution
  • Python plays well with others
  • Python runs everywhere 
  • Python is friendly & easy to learn
  • Python is a Open source.