Latest web development tutorials

Python3 basic data types

Python variables need not be declared. Each variable must be assigned before use, variable assignment after the variable will be created.

In Python, variables are variables, it is not the type we call "type" is the type of a variable within the meaning of objects in memory.

Equal sign (=) is used to assign values ​​to variables.

Equal sign (=) operator on the left is a variable name, an equal sign (=) operator on the right is the value stored in the variable. E.g:


counter = 100          # 整型变量
miles   = 1000.0       # 浮点型变量
name    = "w3big"     # 字符串

print (counter)
print (miles)
print (name)

The above program will output the following results:


A plurality of variable assignment

Python allows you to assign multiple variables simultaneously. E.g:

a = b = c = 1

The above examples, create an Integer object, and a value of 1, three variables are assigned to the same memory space.

You can also specify multiple variables into multiple objects. E.g:

a, b, c = 1, 2, "w3big"

The above examples, two integer object allocation 1 and 2 to the variable a and b, string object "w3big" assigned to the variable c.

Standard data types

Python3 There are six standard data types:

  • Number (digital)
  • String (String)
  • List (list)
  • Tuple (tuple)
  • Sets (collections)
  • Dictionary (dictionary)

Number (digital)

Python3 supportint, float, bool, complex (plural).

In Python 3, there is only one integer type int, expressed as a long integer, no python2 of Long.

Like most languages, types of assignments and calculated values ​​are very intuitive.

Built-in type () function can be used to query the type of object variable referred to.

>>> a, b, c, d = 20, 5.5, True, 4+3j
>>> print(type(a), type(b), type(c), type(d))
<class 'int'> <class 'float'> <class 'bool'> <class 'complex'>

Note: Python2 is no Boolean type, which uses the digits 0 indicates False, represented by 1 True.To Python3 in the True and False is defined as the keyword, but their values ​​and 0 or 1, and they can add numbers.

When you specify a value, Number object is created:

var1 = 1
var2 = 10

You can also use the del statement to delete some object references.

del statement syntax is:

del var1[,var2[,var3[....,varN]]]]

You can delete single or multiple objects by using the del statement. E.g:

del var
del var_a, var_b

Numerical operations

>>> 5 + 4  # 加法
>>> 4.3 - 2 # 减法
>>> 3 * 7  # 乘法
>>> 2 / 4  # 除法,得到一个浮点数
>>> 2 // 4 # 除法,得到一个整数
>>> 17 % 3 # 取余 
>>> 2 ** 5 # 乘方


  • 1, Python can assign multiple variables, such as a, b = 1, 2.
  • 2, a variable can be assigned to objects of different types.
  • 3, the value of the division (/) always returns a floating-point, integer For use // operator.
  • 4, in the hybrid computing, Python integer will be converted into floating-point number.

Examples of numeric types

int float complex
10 0.0 3.14j
100 15.20 45.j
-786 -21.9 9.322e-36j
080 32.3 + e18 .876j
-0490 -90. -.6545 + 0J
-0x260 -32.54e100 3e + 26J
0x69 70.2-E12 4.53e-7j

Python also supports complex numbers, complex numbers by the real and imaginary parts, you can use a + bj, or complex (a, b) that the real part and an imaginary part b is a floating-point

String (String)

Python string with a single quote ( ') or double quotes ( ") quotes, using backslash (\) to escape special characters.

Interception string syntax is as follows:


Index values ​​as the start value to 0, -1 for the starting position at the end.

Plus sign (+) is the connector string, an asterisk (*) indicates a copy of the current string, followed by the number is the number of replication. Examples are as follows:


str = 'w3big'

print (str)          # 输出字符串
print (str[0:-1])    # 输出第一个个到倒数第二个的所有字符
print (str[0])       # 输出字符串第一个字符
print (str[2:5])     # 输出从第三个开始到第五个的字符
print (str[2:])      # 输出从第三个开始的后的所有字符
print (str * 2)      # 输出字符串两次
print (str + "TEST") # 连接字符串

The above program will output the following results:


Python uses the backslash (\) escape special characters, if you do not want to happen backslash escapes, you can add a r in front of the string representation of the original string:

>>> print('Ru\noob')
>>> print(r'Ru\noob')

In addition, the backslash (\) as a line continuation character, indicating that the next line is a continuation of the previous line. You can also use"" "..." "" or '' '...' ''span multiple lines.

Note, Python is no separate character type is a character string of length 1.

>>> word = 'Python'
>>> print(word[0], word[5])
P n
>>> print(word[-1], word[-6])
n P

The difference is that with a C string, Python strings can not be changed. Index to a location assignment, such as word [0] = 'm' will cause an error.


  • 1, can be used to escape the backslash, backslash escapes allow the use of r does not occur.
  • 2, the string + operator can be used together with the * operator repeats.
  • 3, Python string two indexing methods, from left to right starting with 0, from right to left starting with -1.
  • 4, Python string can not be changed.

List (list)

List (list) is the most frequently used Python data types.

You can complete the list data structure to achieve most of the collection class. Type elements in the list may not be the same, it supports digital, string can even contain a list (called nesting).

The list is written between ([]) in square brackets, comma-separated list of elements.

And strings, lists can also be indexed and interception, interception return after the list is a new list containing the elements needed.

List intercepted syntax is as follows:


Index values ​​as the start value to 0, -1 for the starting position at the end.

Plus sign (+) is a list of the concatenation operator, the asterisk (*) is repeated operations. The following examples:


list = [ 'abcd', 786 , 2.23, 'w3big', 70.2 ]
tinylist = [123, 'w3big']

print (list)            # 输出完整列表
print (list[0])         # 输出列表第一个元素
print (list[1:3])       # 从第二个开始输出到第三个元素
print (list[2:])        # 输出从第三个元素开始的所有元素
print (tinylist * 2)    # 输出两次列表
print (list + tinylist) # 连接列表

Examples of the above output:

['abcd', 786, 2.23, 'w3big', 70.2]
[786, 2.23]
[2.23, 'w3big', 70.2]
[123, 'w3big', 123, 'w3big']
['abcd', 786, 2.23, 'w3big', 70.2, 123, 'w3big']

And Python strings are not the same, elements of a list can be changed:

>>> a = [1, 2, 3, 4, 5, 6]
>>> a[0] = 9
>>> a[2:5] = [13, 14, 15]
>>> a
[9, 2, 13, 14, 15, 6]
>>> a[2:5] = []   # 删除
>>> a
[9, 2, 6]

List built there are many ways, such as append (), pop (), etc., which will be mentioned later.


  • 1, List written between brackets, separated by commas elements.
  • 2, and the same string, list can be indexed and sliced.
  • 3, List You can use the + operator splicing.
  • 4, List of elements can be changed.

Tuple (tuple)

Tuple (tuple) is similar to the list, except that the tuple can not be modified. Tuples written in parentheses(()), the elements separated by commas.

Tuple element type may not be the same:


tuple = ( 'abcd', 786 , 2.23, 'w3big', 70.2  )
tinytuple = (123, 'w3big')

print (tuple)             # 输出完整元组
print (tuple[0])          # 输出元组的第一个元素
print (tuple[1:3])        # 输出从第二个元素开始到第三个元素
print (tuple[2:])         # 输出从第三个元素开始的所有元素
print (tinytuple * 2)     # 输出两次元组
print (tuple + tinytuple) # 连接元组

Examples of the above output:

('abcd', 786, 2.23, 'w3big', 70.2)
(786, 2.23)
(2.23, 'w3big', 70.2)
(123, 'w3big', 123, 'w3big')
('abcd', 786, 2.23, 'w3big', 70.2, 123, 'w3big')

Tuple is similar to a string, can be indexed and the subscript index starts at 0, -1 for the location from the end of the beginning. It can also be intercepted (see above, no further explanation).

In fact, you can put a string as a special tuple.

>>> tup = (1, 2, 3, 4, 5, 6)
>>> print(tup[0])
>>> print(tup[1:5]])
(2, 3, 4, 5)
>>> tup[0] = 11  # 修改元组元素的操作是非法的
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

Although tuple elements can not be changed, but it can contain a variable object, such as a list of list.

Structure contains 0 or 1 element tuple special, so there is some additional syntax rules:

tup1 = ()    # 空元组
tup2 = (20,) # 一个元素,需要在元素后添加逗号

string, list and tuple belong sequence (sequence).


  • 1, with the same string, tuple can not be modified.
  • 2, tuples can also be indexed and sliced ​​same way.
  • 3, pay attention to the special structure of the grammar rules tuples containing 0 or 1 element.
  • 4, tuples can also use the + operator splicing.

Set (collection)

Set (set) is a disorder of unique element of the sequence.

The basic function is to carry membership testing and remove duplicate elements.

You can use curly braces ({}) or set () function to create a collection Note: Creating an empty set must be set () instead of {}, {because} is used to create an empty dictionary.


student = {'Tom', 'Jim', 'Mary', 'Tom', 'Jack', 'Rose'}

print(student)   # 输出集合,重复的元素被自动去掉

# 成员测试
if('Rose' in student) :
    print('Rose 在集合中')
else :
	print('Rose 不在集合中')

# set可以进行集合运算
a = set('abracadabra')
b = set('alacazam')


print(a - b)     # a和b的差集

print(a | b)     # a和b的并集

print(a & b)     # a和b的交集

print(a ^ b)     # a和b中不同时存在的元素

Examples of the above output:

{'Jack', 'Rose', 'Mary', 'Jim', 'Tom'}
Rose 在集合中
{'r', 'b', 'a', 'c', 'd'}
{'r', 'b', 'd'}
{'a', 'l', 'z', 'b', 'm', 'd', 'r', 'c'}
{'a', 'c'}
{'l', 'z', 'b', 'm', 'd', 'r'}

Dictionary (dictionary) (dictionary)

Dictionary (dictionary) Python is another very useful built-in data types.

The list is ordered binding objects, dictionaries are unordered collections of objects. The difference between the two is: among the elements of the dictionary is accessed by a key, rather than through an offset access.

It is a dictionary mapping type, the dictionary with the "{}" logo, which is an unorderedkey (key): value (value) pairs.

Key (key) must be immutable.

In the same dictionary, the key (key) must be unique.


dict = {}
dict['one'] = "1 - 本教程"
dict[2]     = "2 - 本工具"

tinydict = {'name': 'w3big','code':1, 'site': ''}

print (dict['one'])       # 输出键为 'one' 的值
print (dict[2])           # 输出键为 2 的值
print (tinydict)          # 输出完整的字典
print (tinydict.keys())   # 输出所有键
print (tinydict.values()) # 输出所有值

Examples of the above output:

1 - 本教程
2 - 本工具
{'name': 'w3big', 'site': '', 'code': 1}
dict_keys(['name', 'site', 'code'])
dict_values(['w3big', '', 1])

Constructor dict () can construct a sequence of keys directly from the dictionary as follows:

>>> dict([('w3big', 1), ('Google', 2), ('Taobao', 3)])
{'Taobao': 3, 'w3big': 1, 'Google': 2}

>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}

>>> dict(w3big=1, Google=2, Taobao=3)
{'Taobao': 3, 'w3big': 1, 'Google': 2}

In addition, there are some types of dictionaries built-in functions, such as clear (), keys (), values ​​() and so on.


  • 1, is a dictionary mapping type, whose elements are pairs.
  • 2, the dictionary of keywords must be immutable and can not be repeated.
  • 3. Create an empty dictionary using{}.

Python data type conversion

Sometimes, we need to built-in data type conversion, data type conversion, you only need to type the data as a function name.

Several built-in functions can perform conversions between data types. These functions return a new object that represents the converted value.

function description

int (x [, base])

Converts x to an integer

float (x)

The transition to a floating-point number x

complex (real [, imag])

Create a complex

str (x)

The object is converted to a string x

repr (x)

The object x is converted to a string expression

eval (str)

It used to calculate string valid Python expression and returns an object

tuple (s)

The sequence s into a tuple

list (s)

The sequence s is converted to a list

set (s)

Converted to variable set

dict (d)

Create a dictionary. d must be a sequence of (key, value) tuple.

frozenset (s)

Converted to immutable collection

chr (x)

Will convert an integer to a character

unichr (x)

An integer is converted to Unicode characters

ord (x)

Convert a character to its integer value

hex (x)

An integer is converted to a hexadecimal string

oct (x)

An integer is converted to an octal string