Python introductory tutorial | Python3 basic data types

assignment

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

In Python, a variable is a variable, it doesn't have a type, what we mean by "type" is the type of object in memory that the variable refers to.

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

single variable assignment

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:

count = 100          # 整型变量
length = 500.0       # 浮点型变量
name    = "tarzan"     # 字符串

print (count)
print (length)
print (name)

Executing the above program will output the following results:

100
1000.0
tarzan

multiple variable assignment

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

a = b = c = 1

In the above example, create an integer object with a value of 1, and assign values ​​from the back to the front, and the three variables are assigned the same value.

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

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

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

standard data type

Common data types in Python3 are:

  • Number
  • String (string)
  • List (list)
  • Tuple
  • Set (collection)
  • Dictionary

Among the six standard data types of Python3:

  • Immutable data (3): Number (number), String (string), Tuple (tuple);
  • Variable data (3): List (list), Dictionary (dictionary), Set (collection).

In addition, there are some advanced data types, such as: byte array type (bytes).

Number

Numeric data types are used to store numeric values. It is the basic data type of python, including four basic types of int, float, bool, and complex.

They are immutable data types, which means that changing the numeric data type will allocate a new object.

Number objects are created when you specify a value:

var1 = 1
var2 = 10

You can also delete references to some objects using the del statement.

The syntax of the del statement is:

del var1,var2,var3....,varN

Python supports four different numeric types:

  • int (integer)
  • float (floating point type)
  • bool (Boolean type)
  • complex (plural)

Examples
Examples of some numeric types:

int float bool complex
10 3.14 True 3.14y
-10 -3.14 False 9.322e-36j

int

  • In Python 3, there is only one integer type int, which is represented as a long integer, and there is no Long in python2. The long type is removed and replaced by int.

float

  • Decimal Types in Floating-Point Math

bool

bool Boolean type is True or False.

In Python, True and False are keywords that represent boolean values.

The Boolean type can be used to control the flow of a program, such as judging whether a certain condition is true, or executing a certain piece of code when a certain condition is met.

Boolean type features:

  • The Boolean type has only two values: True and False.
  • The boolean type can be compared with other data types, such as numbers, strings, etc. Python treats True as 1 and False as 0 when comparing.
  • Boolean types can be used with logical operators, including and, or, and not. These operators can be used to combine multiple Boolean expressions to produce a new Boolean value.
  • Boolean types can also be converted to other data types such as integers, floats, and strings. When converting, True will be converted to 1 and False will be converted to 0.
a = True
b = False

# 比较运算符
print(2 < 3)   # True
print(2 == 3)  # False

# 逻辑运算符
print(a and b)  # False
print(a or b)   # True
print(not a)    # False

# 类型转换
print(int(a))   # 1
print(float(b)) # 0.0
print(str(a))   # "True"

Note : In Python, all non-zero numbers and non-empty strings, lists, tuples and other data types are considered True, and only 0, empty strings, empty lists, empty tuples, etc. are considered False. Therefore, when performing Boolean type conversion, you need to pay attention to the authenticity of the data type.

complex

  • Python also supports complex numbers. A complex number consists 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 a complex number are both floating point types.
  • Complex complex numbers are used in the design of advanced mathematics applications, and are rarely used in ordinary development.

String (string)

Strings in Python are enclosed in single quotes ' or double quotes ", and special characters are escaped with a backslash \.

The grammatical format of string interception is as follows:

variable [head subscript: tail subscript]

Index values ​​start at 0 and start at -1 from the end.
insert image description here
The plus sign + is the connector of the string, the asterisk * means to copy the current string, and the number combined with it is the number of times of copying. Examples are as follows:

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

Executing the above program will output the following results:

Tarzan
Tarzan
Trza
rzan TarzanTarzan TarzanTEST
_

Python uses the 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('Tar\zan')
Tar
zan
>>> print(r'Tar\zan')
Tar\zan
>>>

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

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

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

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

  • 1. Backslashes can be used for escaping, and r can be used to prevent backslashes from escaping.
  • 2. Strings can be concatenated with the + operator and repeated with the * operator.
  • 3. Strings in Python have two indexing methods, starting with 0 from left to right, and starting with -1 from right to left.
  • 4. Strings in Python cannot be changed.

List (list)

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

Lists can complete the data structure implementation of most collection classes. The types of elements in the list can be different, it supports numbers, strings can even contain lists (so-called nesting).

A list is a comma-separated list of elements written between square brackets [].

Like strings, lists can also be indexed and truncated. After the list is truncated, a new list containing the required elements is returned.

The syntax format of list interception is as follows:

variable [head subscript: tail subscript]

Index values ​​start at 0 and start at -1 from the end.
insert image description here
The plus sign + is the list concatenation operator and the asterisk * is the repetition operation. Examples are as follows:

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

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

The output of the above example (ordered):

[‘abcd’, 786, 2.23, ‘tarzan’, 70.2]
abcd
[786, 2.23]
[2.23, ‘tarzan’,70.2]
[123, ‘tarzan’, 123, ‘tarzan’]
[‘abcd’, 786, 2.23, ‘tarzan’, 70.2, 123, ‘tarzan’]

Unlike Python strings, elements in lists 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 has many built-in methods, such as append(), pop(), etc., which will be mentioned later.

Tuple

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

The element types in the tuple can also be different:

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

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

The output of the above example (ordered):

(‘abcd’, 786, 2.23, ‘tarzan’, 70.2)
abcd
(786, 2.23)
(2.23, ‘tarzan’, 70.2)
(123, ‘tarzan’, 123, ‘tarzan’)
(‘abcd’, 786, 2.23, ‘tarzan’, 70.2, 123, ‘tarzan’)

Similar to strings, tuples can be indexed and the subscript index starts from 0, and -1 is the position from the end. Interception can also be performed (see above, no more details here).
In fact, strings can be thought of as a special kind of tuple.

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

Although the elements of a tuple are immutable, it can contain mutable objects, such as lists.
Constructing tuples with 0 or 1 elements is special, so there are some additional syntax rules:

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

string, list and tuple all belong to sequence (sequence).

Note :

  • 1. Like strings, 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 concatenated using the + operator.

Set (collection)

A collection (Set) in Python is an unordered, mutable data type used to store unique elements.
The elements in the set will not be repeated, and common set operations such as intersection, union, and difference can be performed.
In Python, collections are represented by curly braces {}, and elements are separated by commas, .
Alternatively, sets can be created using the set() function.
Note : To create an empty collection, you must use set() instead of { }, because { } is used to create an empty dictionary.
Create format:

parame = {
    
    value01,value02,...}
或者
set(value)
sites = {
    
    'Google', 'Taobao', 'Tarzan', 'Facebook', 'Zhihu', 'Baidu'}
print(sites)   # 输出集合,重复的元素被自动去掉

a = set('abracadabra')
print(a)

The output of the above example (unordered):

{'Baidu', 'Zhihu', 'Google', 'Facebook', 'Tarzan', 'Taobao'} {'c', 'b'
, 'd', 'r', 'a'}

The order of output results is random

Dictionary

Dictionaries are another very useful built-in data type in Python.

  • A list is an ordered collection of objects, and a dictionary is an unordered collection of objects. The difference between the two is that the elements in the dictionary are accessed by key, not by offset.
  • A dictionary is a mapping type, and the dictionary is marked with { }, which is an unordered key (key): value (value) collection.
  • Keys must use immutable types.
  • Within the same dictionary, keys must be unique.
dict = {
    
    }
dict['one'] = "1"
dict[2]     = 2
tinydict = {
    
    'name': 'tarzan','code':1, 'site': 'https://tarzan.blog.csdn.net'}
print (dict['one'])       # 输出键为 'one' 的值
print (dict[2])           # 输出键为 2 的值
print (tinydict)          # 输出完整的字典
print (tinydict.keys())   # 输出所有键
print (tinydict.values()) # 输出所有值

The output of the above example:

1
2
{‘name’: ‘tarzan’, ‘code’: 1, ‘site’: ‘https://tarzan.blog.csdn.net’}
dict_keys([‘name’, ‘code’, ‘site’])
dict_values([‘tarzan’, 1, ‘https://tarzan.blog.csdn.net’])

bytes type

In Python3, the bytes type represents an immutable binary sequence (byte sequence).
Unlike the string type, the elements in the bytes type are integer values ​​(integer numbers between 0 and 255), rather than Unicode characters.
The bytes type is usually used to deal with binary data, such as image files, audio files, video files, and so on. In network programming, the bytes type is often used to transmit binary data.
There are several ways to create a bytes object, the most common way is to use the b prefix:
In addition, you can also use the bytes() function to convert other types of objects to the bytes type. The first parameter of the bytes() function is the object to be converted, and the second parameter is the encoding method. If the second parameter is omitted, UTF-8 encoding will be used by default:

x = bytes("hello", encoding="utf-8")

Similar to the string type, the bytes type also supports many operations and methods, such as slicing, concatenating, searching, replacing, and so on. At the same time, since the bytes type is immutable, a new bytes object needs to be created when modifying. For example:

x = b"hello"
y = x[1:3]  # 切片操作,得到 b"el"
z = x + b"world"  # 拼接操作,得到 b"helloworld"

It should be noted that the elements in the bytes type are integer values, so the corresponding integer values ​​need to be used when performing comparison operations. For example:

x = b"hello"
if x[0] == ord("h"):
    print("The first element is 'h'")

where the ord() function is used to convert a character to its corresponding integer value.
== is a comparison operator, which will be mentioned later.

Guess you like

Origin blog.csdn.net/weixin_40986713/article/details/132420460