Python3 basic data types


Variables in Python do not need to be declared. Each variable must be assigned a value before use. The variable will not be created until the variable is assigned a value.

In Python, a variable is a variable, it has no type. What we call "type" is the type of the object in memory pointed by the variable.

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

The left side of the equal sign (=) operator is a variable name, and the right side of the equal sign (=) operator is the value stored in the variable. For example:

#!/usr/bin/python3

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

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


Executing the above program will output the following results:

100
1000.0
php

Multiple variable assignments

Python allows you to assign values ​​to multiple variables at the same time Variable assignment. For example:

a = b = c = 1

The above example creates an integer object with a value of 1, and three variables are allocated to the same memory space.

You can also specify multiple variables for multiple objects. For example:

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

In the above example, the two integer objects 1 and 2 are assigned to variables a and b, and the string object "php" is assigned to variable c.


Standard data types

There are six standard data types in Python3:

  • Number (number)

  • String(String)

  • List(List)

  • ##Tuple(Tuple)

  • Sets (set)

  • Dictionary (dictionary)


Number (number)

Python3 supports

int, float, bool, complex (plural).

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

Like most languages, assignment and calculation of numeric types are very intuitive.

The built-in type() function can be used to query the type of object pointed to by the variable.

>>> 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: There is no Boolean type in Python2. It uses the number 0 to represent False and 1 to represent True. In Python 3, True and False are defined as keywords, but their values ​​are still 1 and 0, and they can be added to numbers.

When you specify a value, a Number object is created:

var1 = 1
var2 = 10

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

The syntax of the del statement is:

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

You can delete single or multiple objects by using the del statement. For example:

del var
del var_a, var_b

Numerical operations

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

Note:

  • 1. Python can assign values ​​to multiple variables at the same time, such as a, b = 1, 2.

  • 2. A variable can point to objects of different types through assignment.

  • 3. Numerical division (/) always returns a floating point number. To obtain an integer, use the // operator.

  • 4. During mixed calculations, Python will convert integers into floating point numbers.

Numeric type instance

##10015.2045.j-786-21.99.322e-36j##080-0490-0x260##0x6970.2-E124.53e-7j

Python also supports complex numbers. A complex number is composed of a real part and an imaginary part. It can be represented by a + bj, or complex(a,b). The real part a and the imaginary part b of the complex number are both floating point types


String (string)

Strings in Python are enclosed in single quotes (') or double quotes ("), and special characters are escaped using backslash (\).

The syntax format of string interception is as follows:

变量[头下标:尾下标]

The index value starts with 0, and -1 is the starting position from the end.

The plus sign (+) is. The string concatenation character, asterisk (*) means copying the current string, and the following number is the number of copies. The example is as follows:

#!/usr/bin/python3

str = 'php'

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

Executing the above program will output the following result:

php
Runoo
R
noo
noob
phpphp
phpTEST

Python uses backslash (\) to escape special characters. If you don’t want the backslash to be escaped, you can add an r in front of the string to represent the original string:

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

In addition, backslash The bar (\) can be used as a line continuation character to indicate that the next line is a continuation of the previous line. You can also use """..."" or '''...'''. Spanning multiple lines.

Note that Python does not have a separate character type, a character is a string of length 1


# and C. Unlike strings, Python strings cannot be changed. Assigning a value to an index position, such as word[0] = 'm', will cause an error.

Note:

    1. Backslashes can be used to escape. Use r to prevent backslashes from being escaped.
  • 2. Strings can use +. Operators are connected together and repeated using the * operator.
  • 3. There are two indexing methods for strings in Python, starting with 0 from left to right and starting with 0 from right to left. -1 starts.
  • ##4. Strings in Python cannot be changed.
  • ##List (list)
List (list) is the most frequently used data type in Python.

The list can complete the data structure implementation of most collection classes. The types of elements in the list can be different. It supports numbers, strings and even numbers. Contains a list (so-called nesting).

A list is a list of elements written between square brackets ([]) and separated by commas.

Like strings, lists can also be used. Being indexed and intercepted, the list is intercepted and a new list containing the required elements is returned.

The syntax format of list interception is as follows:

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

The index value starts with 0 and -1. Starting position from the end.

The plus sign (+) is the list concatenation operator, and the asterisk (*) is the repeat operation. The following example:

变量[头下标:尾下标]

The output result of the above example:

#!/usr/bin/python3

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

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

Unlike Python strings, the elements in the list can be changed:

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

List has built-in There are many methods, such as append(), pop(), etc., which will be discussed later.

Note:

1. List is written between square brackets, and the elements are separated by commas.

  • 2. Like strings, lists can be indexed and sliced.

  • 3. List can be spliced ​​using the + operator.

  • 4. The elements in the List can be changed.


Tuple (tuple)

A tuple is similar to a list, except that the elements of a tuple cannot be modified. Tuples are written in parentheses (()), and the elements are separated by commas.

The element types in the tuple can also be different:

>>> 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]

The above example output result:

#!/usr/bin/python3

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

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

Tuples are similar to strings and can be indexed and indexed by subscripts Starting from 0, -1 is the position starting from the end. Interception can also be performed (see above, I won’t go into details here).

In fact, strings can be regarded as a special tuple.

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

Although the elements of a tuple cannot be changed, it can contain mutable objects, such as lists.

Constructing a tuple containing 0 or 1 elements is special, so there are some additional syntax rules:

>>> tup = (1, 2, 3, 4, 5, 6)
>>> print(tup[0])
1
>>> 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
>>>

String, list and tuple all belong to sequence.

Note:

  • 1. Like strings, the elements of tuples cannot be modified.

  • 2. Tuples can also be indexed and sliced ​​in the same way.

  • 3. Pay attention to the special syntax rules for constructing tuples containing 0 or 1 elements.

  • 4. Tuples can also be spliced ​​using the + operator.


Set (set)

A set (set) is an unordered sequence of non-repeating elements.

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

You can use curly brackets ({}) or the set() function to create a set. Note: To create an empty set, you must use set() instead of { }, because { } is used to create an empty dictionary.

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

The above example output result:

#!/usr/bin/python3

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)

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

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

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

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

Dictionary (Dictionary) (Dictionary)

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

Lists are ordered combinations of objects, and dictionaries are unordered collections of objects. The difference between the two is that the elements in the dictionary are accessed by key, not by offset.

Dictionary is a mapping type. The dictionary is identified with "{ }". It is an unordered key (key): value (value) pair set.

Key must use immutable type.

In the same dictionary, the key must be unique.

{'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'}

The above example output results:

#!/usr/bin/python3

dict = {}
dict['one'] = "1 - php中文网"
dict[2]     = "2 - php工具"

tinydict = {'name': 'php','code':1, 'site': 'www.php.cn'}


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

The constructor dict() can directly build a dictionary from the sequence of key-value pairs as follows:

1 - php中文网
2 - php工具
{'name': 'php', 'site': 'www.php.cn', 'code': 1}
dict_keys(['name', 'site', 'code'])
dict_values(['php', 'www.php.cn', 1])

In addition, the dictionary type also has some built-in Functions, such as clear(), keys(), values(), etc.

Note:

  • 1. A dictionary is a mapping type, and its elements are key-value pairs.

  • 2. The keywords of the dictionary must be of immutable type and cannot be repeated.

  • 3. Create an empty dictionary using { }.


Python data type conversion

Sometimes, we need to convert the built-in type of data. To convert the data type, you only need to convert the data type as Just the function name.

The following built-in functions can perform conversion between data types. These functions return a new object representing the converted value.

intfloatcomplex
100.03.14j
32.3+ e18.876j
-90.-.6545+0J
-32.54e1003e+26J
Function describe

int(x [,base])

Convert x to an integer

float(x)

Convert x to a floating point number

# complex(real [,imag])

Create a plural

str(x)

Convert object x to string

# repr(x)

Convert object x to expression string

eval(str)

Used to evaluate a valid Python expression in a string and return an object

tuple(s)

Convert sequence s into a tuple

list(s)

Convert sequence s into a list

set(s)

Convert to mutable collection

dict(d)

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

frozenset(s)

Convert to immutable collection

# chr(x)

Convert an integer to a character

# unichr(x)

Convert an integer to the Unicode character

ord(x)

Convert a character to its integer value

hex(x)

Convert an integer to a hexadecimal string

oct(x)

Convert an integer to an octal string