3.1. None¶A special object serves as an empty placeholder (much like a NULL pointer in C). it is returned from functions that don’t explicitly return anything. Show
>>> None, type(None) (None, <type 'NoneType'>) >>> def foo(): pass ... >>> print foo() None 3.2. Numeric types¶A complete inventory of Python’s numeric toolbox includes:
Literals: 1234, -24, 0, 9999999999999999 1.23, 1., 3.14e-10, 4E210, 4.0e+210 0o177, 0x9ff, 0b10101011, 0177 3+4j, 3.0+4.0j, 3j set('spam'), {1, 2, 3, 4} Decimal('1.0'), Decimal('-Inf'), Fraction(1, 3) bool(x), True, False Example: >>> 3 ** 2 / (4 + 1) 1 >>> 3 ^ 9 10 >> 3 | 9 11 >>> 1 << 3 8 >>> 0xf - 0b1000 + 010 15 >>> (2 + 1j) * -1j (1-2j) >>> ({1, 2, 3} & { 3, 5, 7} | {3, 4}) - {Decimal('3')} set([4]) >>> Decimal('3') == 3 True >>> True = False # 2.x >>> True == False True Operator precedence +, -, *, /, //, >>, <<, **, &, |, ^, %, ~ <, >, !=, ==, <=, >=, in, not in, not, and, or Built-in functions
>>> bool(3) and True or False True >>> ' '.join([bin(13), hex(13), oct(13)]) '0b1101 0xd 015' >>> divmod(7, 3) (2, 1) >>> abs(-3) 3 >>> pow(2, 8) == 2 ** 8 True >>> round(3.14) 3.0 >>> int('3') + float('.5') 5.5 >>> int('10', base=16) - int('10') - int('10', base=8) - int('10', base=2) -4 Built-in modules
>>> type(3) # 2.x <type 'int'> >>> type(2**100) <type 'long'> >>> 2**100 1267650600228229401496703205376L >>> type(3L) <type 'long'> >>> from numbers import Number, Complex, Real, Rational, Integral >>> issubclass(Integral, Complex) True >>> isinstance(1, Complex) True >>> math.factorial(3) + math.log(math.e) + math.sqrt(9) + math.sin(math.pi/2) + math.ceil(0.1) # 6+1+3+1+1 12.0 >>> math.sqrt(-1) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: math domain error >>> cmath.sqrt(-1) 1j >>> from random import * >>> random() 0.06091254441752425 >>> sample(range(10), 3) [0, 1, 4] >>> choice(range(10)) 5 >>> l = list(range(10)) >>> shuffle(l) >>> l [5, 7, 0, 1, 2, 3, 9, 6, 4, 8] >>> gauss(0, 1) -0.8042047260239109 >>> from decimal import * >>> .1 * 3 - .3 5.551115123125783e-17 >>> Decimal('.1') * Decimal('3') - Decimal('.3') Decimal('0.0') >>> 1.20 * 1.30 1.56 >>> Decimal('1.20') * Decimal('1.30') Decimal('1.5600') >>> getcontext().prec = 6 >>> Decimal(1) / Decimal(7) Decimal('0.142857') >>> getcontext().prec = 28 >>> Decimal(1) / Decimal(7) Decimal('0.1428571428571428571428571429') >>> from fractions import Fraction >>> (6/5) * (7/3) - 2.8 4.440892098500626e-16 >>> Fraction(6, 5) * Fraction(7, 3) - Fraction('2.8') Fraction(0, 1) >>> gcd(15, 6) >>> 3 >>> from statistics import * >>> mean([1, 2, 3, 4, 4]) >>> 2.8 >>> median([1, 3, 5]) >>> 3 >>> mod([1, 1, 2, 3, 3, 3, 3, 4]) >>> 3 >>> stdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75]) 1.0810874155219827 >>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5] >>> variance(data) 1.3720238095238095 New in 2.6
New in 3.0
3.3. Strings¶Literals
Single- and double-quoted strings are the same Implicit concatenation: >>> title = "Meaning " 'of' " Life" >>> title 'Meaning of Life' Escape characters
Raw strings suppress escapes: >>> path = r'C:\new\text.dat' >>> path # Show as Python code 'C:\\new\\text.dat' >>> print(path) # User-friendly format C:\new\text.dat >>> len(path) # String length 15 Triple quotes code multiline block strings: >>> mantra = """Always look ... on the bright ... side of life.""" >>> >>> mantra 'Always look\n on the bright\nside of life.' >>> print(mantra) Always look on the bright side of life. Basic operations: >>> len('abc') 3 >>> 'abc' + 'def' 'abcdef' >>> 'Ni!' * 4 'Ni!Ni!Ni!Ni!' >>> myjob = "hacker" >>> for c in myjob: print(c, end=' ') ... h a c k e r >>> "k" in myjob True >>> "z" in myjob False >>> 'spam' in 'abcspamdef' True Indexing and slicing: >>> S = 'spam' >>> S[0], S[−2] ('s', 'a') >>> S[1:3], S[1:], S[:−1] ('pa', 'pam', 'spa') >>> S = 'abcdefghijklmnop' >>> S[1:10:2] 'bdfhj' >>> S[::2] 'acegikmo' >>> S = 'hello' >>> S[::−1] # Reversing items 'olleh' >>> S = 'abcedfg' >>> S[5:1:−1] 'fdec' >>> 'spam'[1:3] 'pa' >>> 'spam'[slice(1, 3)] 'pa' >>> 'spam'[::-1] 'maps' >>> 'spam'[slice(None, None, −1)] 'maps' String conversion: >>> int("42"), str(42) (42, '42') >>> repr(42) '42' >>> str('spam'), repr('spam') ('spam', "'spam'") >>> str(3.1415), float("1.5") ('3.1415', 1.5) >>> text = "1.234E-10" >>> float(text) 1.234e-10 >>> ord('s') 115 >>> chr(115) 's' Changing string: >>> S = 'spam' # Immutable objects >>> S[0] = 'x' # Raises an error! TypeError: 'str' object does not support item assignment >>> S = S + 'SPAM!' # To change a string, make a new one >>> S 'spamSPAM!' >>> S = S[:4] + 'Burger' + S[−1] >>> S 'spamBurger!' >>> S = 'splot' >>> id(S) 18598192 >>> S = S.replace('pl', 'pamal') >>> id(S) 18598096 >>> S 'spamalot' >>> id('spam') 18597136 >>> id('spamalot') 18597760 >>> 'That is %d %s bird!' % (1, 'dead') That is 1 dead bird! >>> 'That is {0} {1} bird!'.format(1, 'dead') 'That is 1 dead bird!' str, the bytes type is immutable. There is a separate mutable type to hold buffered binary data, bytearray. String methods in 3.4
>>> [name for name in os.listdir('/etc/') if name.endswith('.conf')][:5] ['asl.conf', 'autofs.conf', 'dnsextd.conf', 'ftpd.conf', 'ip6addrctl.conf']
>>> 'abcd'.find('a') 0 >>> 'abcd'.find('1') -1 >>> 'abcd'.find('d', 2) 3 >>> 'abcd'.find('d') 3
>>> 'abcd'.find('e') -1 >>> 'abcd'.index('e') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found
>>> 'abd'.isalpha() True >>> 'abd1'.isalpha() False >>> '1234'.isdigit() True >>> '123a'.isdigit() False >>> '12ab'.isalnum() True >>> '\n\t '.isspace() True
>>> ','.join(['ab', 'c', 'd']) 'ab,c,d' >>> ','.join('abcd') 'a,b,c,d'
>>> 'PyTHon'.lower() 'python' >>> 'PyTHon'.upper() 'PYTHON'
>>> 'PyTHon'.replace('TH', 'C') 'PyCon'
>>> 'a b \t\t c\nd'.split() ['a', 'b', 'c', 'd'] >>> 'a,b,c,d'.split(',') ['a', 'b', 'c', 'd'] >>> 'a b \t\t c\nd'.split(None, 2) ['a', 'b', 'c\nd']
>>> ' line\n'.strip() 'line' >>> ' line\n'.lstrip() 'line\n' >>> ' line\n'.rstrip() ' line'
printf-style String Formatting
Text vs. data instead of unicode vs. 8-bit In 2.x: >>> type('hello'), repr('hello') (<type 'str'>, "'hello'") >>> type(u'你好'), repr(u'你好') (<type 'unicode'>, "u'\\u4f60\\u597d'") >>> type('你好'), type(u'hello') (<type 'str'>, <type 'unicode'>) >>> issubclass(str, basestring) True >>> issubclass(unicode, basestring) True >>> u'hello' + ' world' u'hello world'
In 3.x: >>> type('hello'), type(u'hello'), type(b'hello') (<class 'str'>, <class 'str'>, <class 'bytes'>) >>> type('你好'), type(u'你好') (<class 'str'>, <class 'str'>) >>> type(b'你好') File "<stdin>", line 1 SyntaxError: bytes can only contain ASCII literal characters. >>> type('你好'.encode()), repr('你好'.encode()) (<class 'bytes'>, "b'\\xe4\\xbd\\xa0\\xe5\\xa5\\xbd'") >>> 'hello' + b' world' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Can't convert 'bytes' object to str implicitly >>> type(open('name.txt').read()) <class 'str'> >>> type(open('name.txt', 'br').read()) <class 'bytes'> >>> type(os.listdir()[0]) <class 'str'> >>> type(sys.argv[0]) <class 'str'>
See Unicode HOWTO 3.4. Lists¶
Built-in functions range() and xrange(): >>> range(5) # 2.x [0, 1, 2, 3, 4] >>> xrange(5) xrange(5) >>> type(range(5)), type(xrange(5)) (<type 'list'>, <type 'xrange'>) >>> range(5) # 3.x range(0, 5) >>> type(range(5)) <class 'range'>Change in 3.0: range() now behaves like xrange() used to behave, except it works withvalues of arbitrary size. The latter no longer exists. 3.5. Dictionaries¶
Built-in function zip(): >>> zip(range(5), 'abc') [(0, 'a'), (1, 'b'), (2, 'c')]Change in 3.0:zip() now returns an iterator. 3.6. Tuples¶
3.7. Sets¶
>>> x = set('abcde') >>> y = set('bdxyz') >>> x set(['a', 'c', 'b', 'e', 'd']) >>> x − y # Difference set(['a', 'c', 'e']) >>> x | y # Uninon set(['a', 'c', 'b', 'e', 'd', 'y', 'x', 'z']) >>> x & y # Intersection set(['b', 'd']) >>> x ^ y # Symmetric difference (XOR) set(['a', 'c', 'e', 'y', 'x', 'z']) >>> x > y, x < y # Superset, subset (False, False) >>> 'e' in x # Membership True >>> z = x.intersection(y) # Same as x & y >>> z set(['b', 'd']) >>> z.add('SPAM') # Insert one item >>> z set(['b', 'd', 'SPAM']) >>> z.update(set(['X', 'Y'])) # Merge: in-place union >>> z set(['Y', 'X', 'b', 'd', 'SPAM']) >>> z.remove('b') # Delete one item >>> z set(['Y', 'X', 'd', 'SPAM']) >>> for item in set('abc'): print(item * 3) # Iterable, unordered aaa ccc bbb >>> {i for i in 'abc'} # Set compression set(['a', 'c', 'b'])fronzensetThe frozenset type is immutable and hashable — its contents cannot be altered after it is created; it can therefore be used as a dictionary key or as an element of another set.
See Scala’s mutable and immutable collections 3.8. The meaning of True and False in Python¶True and false are intrinsic properties of every object in Python, each object is either ture of false, as follows:
d = {1: 2} if d: print "it goes here" else: print "not here" 3.9. Files¶
Storing Native Python Objects: pickle >>> D = {'a': 1, 'b': 2} >>> F = open('datafile.pkl', 'wb') >>> import pickle >>> pickle.dump(D, F) # Pickle any object to file >>> F.close() >>> F = open('datafile.pkl', 'rb') >>> E = pickle.load(F) # Load any object from file >>> E {'a': 1, 'b': 2} >>> open('datafile.pkl', 'rb').read() # Format is prone to change! b'\x80\x03}q\x00(X\x01\x00\x00\x00bq\x01K\x02X\x01\x00\x00\x00aq\x02K\x01u.' Storing Python Objects in JSON Format >>> name = dict(first='Bob', last='Smith') >>> rec = dict(name=name, job=['dev', 'mgr'], age=40.5) >>> rec {'job': ['dev', 'mgr'], 'name': {'last': 'Smith', 'first': 'Bob'}, 'age': 40.5} >>> import json >>> S = json.dumps(rec) >>> S '{"job": ["dev", "mgr"], "name": {"last": "Smith", "first": "Bob"}, "age": 40.5}' >>> O = json.loads(S) >>> O {'job': ['dev', 'mgr'], 'name': {'last': 'Smith', 'first': 'Bob'}, 'age': 40.5} >>> O == rec True >>> json.dump(rec, fp=open('testjson.txt', 'w'), indent=4) >>> print(open('testjson.txt').read()) { "job": [ "dev", "mgr" ], "name": { "last": "Smith", "first": "Bob" }, "age": 40.5 } >>> P = json.load(open('testjson.txt')) >>> P {'job': ['dev', 'mgr'], 'name': {'last': 'Smith', 'first': 'Bob'}, 'age': 40.5} Storing Packed Binary Data: struct >>> F = open('data.bin', 'wb') # Open binary output file >>> import struct >>> data = struct.pack('>i4sh', 7, b'spam', 8) # Make packed binary data >>> data b'\x00\x00\x00\x07spam\x00\x08' >>> F.write(data) # Write byte string >>> F.close() >>> F = open('data.bin', 'rb') # Get packed binary data >>> data = F.read() >>> data b'\x00\x00\x00\x07spam\x00\x08' >>> values = struct.unpack('>i4sh', data) # Convert to Python objects >>> values (7, b'spam', 8) File Context Managers with open(r'C:\code\data.txt') as myfile: for line in myfile: ...use line here... => myfile = open(r'C:\code\data.txt') try: for line in myfile: ...use line here... finally: myfile.close() 3.10. The standard type hierarchy¶NoneThis type has a single value.NotImplementedThis type has a single value. raise NotImplementedclass CarInterface: def drive(self): raise NotImplementedEllipsisThis type has a single value. literal … or the built-in name Ellipsis. >>> ... Ellipsis >>> bool(...) True >>> def foo(): ... ... ... >>> foo <function foo at 0x10606a840> >>> a = [1] >>> a.append(a) >>> a [1, [...]] >>> from numpy import array >>> a = array([[1,2,3], [4,5,6], [7,8,9]]) >>> a array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> a[...,1] array([2, 5, 8]) >>> a[1,...] array([4, 5, 6]) numbers.Number
Sequences
Set types
Mappings
Callable types
Modules I/O objects(Also known as file objects) Internal types
3.11. Type objects¶The largest point to notice here is that everything in a Python system is an object type. In fact, even types themselves are an object type in Python: the type of an object is an object of type type. >>> class Foo: pass ... >>> type(Foo()) <class '__main__.Foo'> >>> type(Foo) <class 'type'> >>> issubclass(Foo, object) True >>> isinstance(Foo, type) True >>> type(object) <class 'type'> >>> type(type) <class 'type'> >>> type(1) <class 'int'> >>> type(int) <class 'type'> >>> issubclass(int, object) True >>> def foo(): pass ... >>> import types >>> types.FunctionType <class 'function'> >>> type(foo) == types.FunctionType True >>> type(types.FunctionType) <class 'type'>
What are the core data types?Core Data Types. Data Type Ranges. This topic describes the range of valid values for the core built-in 4Test data types.. AGENTOPTION Data Type. ... . AGENTSWITCH Data Type. ... . ALIGNMENT Data Type. ... . ANYTYPE Data Type. ... . APPID Data Type. ... . ARRAY Data Type. ... . BOOLEAN Data Type.. Is class A core data type in Python?1. Which of these in not a core data type? Explanation: Class is a user defined data type.
What are the 4 types of data in Python?Following are the standard or built-in data type of Python:. Numeric.. Sequence Type.. Boolean.. Dictionary.. What are the 5 types of data in Python?Python has five standard Data Types:. Numbers.. String.. Tuple.. Dictionary.. |