def contains(dict, key):
return key in dict
dict={}
dict['a']=1
dict['b']=2
dict['c']=3
print(contains(dict, 'a')) # True
print(contains(dict, 'd')) # False
def contains(dict, key):
return key in dict
dict={}
dict['a']=1
dict['b']=2
dict['c']=3
print(contains(dict, 'a')) # True
print(contains(dict, 'd')) # False
if e in list:
list.remove(e)
while e in list:
list.remove(e)
try:
list.remove(e)
except ValueError:
# not in the list
pass
while True:
try:
list.remove(e)
except ValueError:
break
Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.
>>> x=1 >>> print x 1 >>> del x >>> print x Traceback (most recent call last): File "", line 1, in NameError: name 'x' is not defined
>>> x=1 >>> print x 1 >>> x=None >>> print x None
class AClass {
private int count =0;
public synchronized inc(){
count++;
}
public synchronized dec(){
count--;
}
}
import threading
class AClass(object):
def __init__(self):
self.__count = 0;
self.__lock = threading.RLock()
def inc(self):
with self.__lock:
self.__count += 1
def dec(self):
with self.__lock:
self.__count -= 1
class AClass {
private static int _count = 0;
public static synchronized inc(){
_count ++;
}
public static synchronized dec(){
_count --;
}
}
import threading
class AClass(object):
__count = 0
__lock = threading.RLock()
@classmethod
def inc(cls):
with cls.__lock:
cls.__count += 1
@classmethod
def dec(cls):
with cls.__lock:
cls.__count -= 1