User Tools

Site Tools


cs_lang:python:things-to-know:native-datatypes

Table of Contents

  • Booleans
  • Numbers
  • Strings
  • Bytes
  • Lists
  • Tuples
  • Sets
  • Dictionaries

Booleans

>>> x = 42
>>> 19 <= x <= 51
True
>>> 19 <= x <= 41
False
>>> 
>>> 0 == False
True
>>> a = 1
>>> a < 0
False
>>> a > 0
True
>>> 
>>> True + True
2
>>> True + False
1
>>> True * True
1
>>> True / False
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: int division or modulo by zero
>>> import this
>>> love = this
>>> this is love
True
>>> love is True
False
>>> love is False
False
>>> love is not True or False
True
>>> love is not True or False; love is love
True
True

Numbers

>>> type(42)
<class 'int'>
>>> isinstance(42, int)
True
>>> 
>>> type(1 + 1.0)
<class 'float'>
>>> 
>>> float(2)
2.0
>>> int(2.5) 
2
>>> int(-2.5)
-2
>>> 
>>> 1.12345678901234567890
1.1234567890123457
>>> type(1000000000000000000000)
<class 'int'>
>>> 11 /2
5.5
>>> 1 // 2   
0
>>> -11 // 2
-6
>>> 11.0 // 2
5.0
>>> 
>>> 11 ** 2
121
>>> 11 % 2
1

Lists

>>> a_list = ["a", 1, True, "Python", 3.6465]
>>> a_list[0]
'a'
>>> a_list[-1]
3.6465
>>> 
>>> a_list[:2]
['a', 1]
>>> a_list[2:]
[True, 'Python', 3.6465]
>>> a_list[1:4]
[1, True, 'Python']
>>> 
>>> 
>>> c = a_list[:2] + a_list[2:]
>>> c
['a', 1, True, 'Python', 3.6465]
>>> 
>>> d = a_list[:]
>>> d
['a', 1, True, 'Python', 3.6465]
>>> a_list = ["a", 1, True, "Python", 3.6465]
>>> a_list.append("Toto")
>>> a_list
['a', 1, True, 'Python', 3.6465, 'Toto']
>>> 
>>> a_list.extend([42, False])
>>> a_list
['a', 1, True, 'Python', 3.6465, 'Toto', 42, False]
>>> 
>>> a_list.insert(0, 'Ω')      
>>> a_list
['Ω', 'a', 1, True, 'Python', 3.6465, 'Toto', 42, False]
>>> 
>>> a_list.append((42, False))
>>> a_list
['Ω', 'a', 1, True, 'Python', 3.6465, 'Toto', 42, False, (42, False)]
>>> 
>>> len(a_list)
10
>>> a_list[-1]
(42, False)

Dictionaries

>>> a_dict = {'server': 'cedricbonhomme.org', 'database':'mysql'}
>>>
>>> a_dict['blog']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'blog'
>>> 'blog' in a_dict
False
>>> a_dict['blog'] = 'wordpress' 
>>> a_dict
{'blog': 'dotclear', 'database': 'mysql', 'server': 'cedricbonhomme.org'}
>>>
>>>
>>> a_dict.keys()
dict_keys(['blog', 'database', 'server'])
>>> a_dict.values()
dict_values(['dotclear', 'mysql', 'cedricbonhomme.org'])
cs_lang/python/things-to-know/native-datatypes.txt · Last modified: 2011/01/11 14:26 by cedric