a = {1, 2, 3}
a.add(1)
{1,2,3}
dataList = []
tempList = []
for elem in dataList:
tempList.append(func(elem))
print dataList
tempList = [func(elem) for elem in dataList]
open (<filename>, <access mode>)
w a w+
# open file data.out in write mode
out = open("data.out", "w")
# write "content" to out
print >>out, "content"
# close the file when done
out.close()
when you have a situation when code must always run no matter what erros occur.
if you try to change an immutable value, Python raises a TypeError exception
data = open('file.txt')
# using locals() to check whether data object (file.txt represent) exists or not
if 'data' in locals():
data.close()
with open('file.txt', 'w') as data:
print >>data, "content here"
is equivalent to
data = open('file.txt', 'w')
print >>data, "content here"
data.close()
without additional close()
And also, two with
statements````` can be combined with comma ","
class Decimal(object):
""" define base class """
def __init__(self, number, place):
self.number = number
self.place = place
def __repr__(self):
""" method to automatically return the value when call class itself"""
return "%.{}f".format(self.place) % self.number
class Currency(Decimal):
def __init__(self, number, place, symbol):
""" inherit from Decimal class, initilize the attribute which base class support """
super(Currency, self).__init__(number, place)
self.symbol = symbol
def __repr__(self):
""" use the __repr__ method from base class to get the value """
return "{}{}".format(self.symbol, super(Currency, self).__repr__())
print Decimal(2,5)
print Currency(3,5,'$')
Install python with sqlite3 support on mac os