Detailed explanation of Python data types

  • Python(English pronunciation: /ˈpaɪθən/), is an object-oriented, interpreted computer programming language. Guido van RossumSince its invention in 1989, the first public release was released in 1991.
  • PythonIs pure free software, the source code and interpreter CPythonfollow the GPL(GNU General Public License)agreement .
  • Python syntax is concise and clear, one of the features is the mandatory use of white space as statement indentation
    • PythonIs an interpreted language: This means that there is no compilation part of the development process. Similar to PHP and Perl languages
    • Pythonis an interactive language: this means that you can Pythonwrite your program at a prompt and execute it directly interactively
    • Pythonis an object-oriented language: this means Pythona programming technique that supports an object-oriented style or code encapsulated in objects
    • PythonBeginner's language: PythonA great language for beginning programmers, it supports a wide range of application development, from simple word processing to WWW browsers to games

1. Setting up the Pythonenvironment under the Mac system

  • First go to the Python official website to download and install the latest version Python, the installation is relatively mindless, press all the way and it will be OK
  • Install Pythonthe development software, recommend two development software Pycharmand Sublime Text, here only introduce Pycharmthe installation and cracking methods
    • First downloadPycharm the software here
    • Then go here to find the relevant cracking method of the software
  • PythonAfter the development environment and development software are all done, let's take a look at Pythonthe basic syntax.
  • See the GitHub address for the test code

2. Basic grammar

1. Output format

PythonThe output syntax Swiftis the same as the output of

# 输出
print("Hello Python")

2. Notes

  • pythonSingle-line comments start with #.
  • pythonUse three single quotes '''or"""

# 这里是单行注释


'''
这是多行注释,使用单引号。
这是多行注释,使用单引号。
这是多行注释,使用单引号。
'''

"""
这是多行注释,使用双引号。
这是多行注释,使用双引号。
这是多行注释,使用双引号。
"""

3. Variables

PythonThe variables in the variable do not need to be declared, and the assignment operation of the variable is both the process of variable declaration and definition. Each variable must be assigned a value before it is used, and the variable will not be created until the variable is assigned

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

Python allows you to assign values ​​to multiple variables at the same time, as well as assign multiple variables to multiple objects. E.g:

a = b = c = 1 

# 多变量赋值
a, b, c = 1, 2, "jun" 

3. Standard data types

  • PythonThere are five standard data types:
    • Numbers(number)
    • String(string)
    • List(list)
    • Tuple(tuple)
    • Dictionary(dictionary)

1. Numbers(Number)

  • Numberis an immutable data type, when you specify a value, the Numberobject is created
  • PythonFour different numeric types are supported:
    • int(signed int)
    • long(Long Integer [can also represent Octal and Hexadecimal])
    • float(float)
    • complex(plural)
  • Complex number: The same as the meaning of complex number in mathematics, complex number consists of real part and imaginary part, which can be used a + bj, or complex(a, b)represented, the real part a and imaginary part b of complex numbers are both floating-point types
int long float complex
10 51924361L 0.0 3.14j
100 -0x19323L 15.20 45.j
-786 0122L -21.9 9.322e-36j
080 0xDEFABCECBDAECBFBAEl 32.3 + e18 .876j
-0490 535633629843L -90. -.6545+0J
-0x260 -052318172735L -32.54e100 3e+26J
0x69 -4721885298529L 70.2-E12 4.53e-7j

2. PythonString

  • A string or string (String) is a string of characters consisting of numbers, letters, and underscores
  • Like Swiftthe strings in , each character has an index corresponding to it
  • pythonThe list of strings has 2 value orders:
    • From left to right, the default index starts from 0, and the maximum range is 1 less than the length of the string
    • Right-to-left indexing starts from -1 by default, the maximum range is the beginning of the string
    • Get the format of a part of the string: [head subscript: tail subscript]
# 字符串
str = 'Hello Python'

# 1. 输出完整字符串
print("完整字符串--" + str)
# 结果输出:

# 2. 输出第一个字符
print("第一个字符--" + str[0])

# 3. 输出第三到七个字符
print("第3-7个字符--" + str[2:6])

# 4. 输出低2个字符开始的所有字符
print("第2个开始的所有字符--" + str[1:])

# 5. 拼接字符串
# 像上面一样, 字符串用 `+`拼接
print("拼接--" + str)

# 6. 输出3次
# `*` 表示重复操作, 需要重复操作几次, 后面跟上次数即可
print(str * 3)

# 7. 输出最后一个字符
print("最后一个字符--" + str[-1])

# 8. 输出倒数第二个字符
print("倒数第二个字符--" + str[-2])

Below is the output of the above syntax

/*
完整字符串--Hello Python
第一个字符--H
第3-7个字符--llo 
第2个开始的所有字符--ello Python
拼接--Hello Python
Hello PythonHello PythonHello Python
最后一个字符--n
倒数第二个字符--o
*/

3. List

  • List(list) is Pythonthe most frequently used data type in , and Clike arrays in the language, the syntax operations are similar to the above strings
  • Lists can complete the data structure implementation of most collection classes. It supports characters, numbers, strings and even lists (so-called nesting).
  • List [ ]identifiers. is pythonthe most general composite data type
  • The value segmentation in the list can also use the variable [head subscript: tail subscript] to intercept the corresponding list
    • Left-to-right index starts at 0 by default
    • Right-to-left indexing starts at -1 by default
    • The subscript can be empty to indicate the head or tail.
  • The plus sign (+) is the list concatenation operator, and the asterisk (*) is the repeat operation
# List 列表
list1 = [12, 34, 3.14, 5.3, 'titan']
list2 = [10, 'jun']

# 1.完整列表
print(list1)

# 2.列表第一个元素
print(list1[0])

# 3.获取第2-3个元素
print(list1[1:2])

# 4.获取第三个到最后的所有元素
print(list1[2:])

# 5.获取最后一个元素
print(list1[-1])

# 6.获取倒数第二个元素
print(list1[-2])

# 7.获取最后三个元素
print(list1[-3:-1])

# 8.合并列表
print(list1 + list2)

# 9.重复操作两次
print(list2 * 2)

The output of the above statement is as follows

[12, 34, 3.14, 5.3, 'titan']
12
[34]
[3.14, 5.3, 'titan']
titan
5.3
[3.14, 5.3]
[12, 34, 3.14, 5.3, 'titan', 10, 'jun']
[10, 'jun', 10, 'jun']

4. Tuples

  • A tuple is another data type ( Pythona tuple Swiftin is similar to a tuple in )
  • Tuples are identified with "()". Inner elements are separated by commas
  • Elements cannot be assigned twice, which is equivalent to a read-only list
# 元组
tuple1 = (12, 34, 3.14, 5.3, 'titan')
tuple2 = (10, 'jun')

# 1.完整元组
print(tuple1)

# 2.元组一个元素
print(tuple1[0])

# 3.获取第2-3个元素
print(tuple1[2:3])

# 4.获取第三个到最后的所有元素
print(tuple1[2:])

# 5.获取最后一个元素
print(tuple1[-1])

# 6.获取倒数第二个元素
print(tuple1[-2])

# 7.获取最后三个元素
print(tuple1[-3:-1])

# 8.合并元组
print(tuple1 + tuple2)

# 9.重复操作两次
print(tuple2 * 2)

output result

(12, 34, 3.14, 5.3, 'titan')
12
(3.14,)
(3.14, 5.3, 'titan')
titan
5.3
(3.14, 5.3)
(12, 34, 3.14, 5.3, 'titan', 10, 'jun')
(10, 'jun', 10, 'jun')

Note here that when intercepting a certain range of data, similar to [2:3], [-3:-1], the actual value range is inclusive of left and right, which is equivalent to the half-open and half-closed interval in mathematics (left closed right open)–[2, 3)

# 因元组的元素是只读的, 不能二次赋值, 所以请注意, 以下写法是错误的
# 运行会报错: TypeError: 'tuple' object does not support item assignment
tuple2[0] = 20
tuple2[1] = "titan"

5. Dictionary

  • Dictionaries ( ) are the most flexible built-in data structure type dictionarybesides lists .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 index.
  • Dictionaries are identified with "{ }". A dictionary consists of an index (key) and its corresponding value value
  • The key value of the dictionary here can not only use strings, but also Numbertypes
# 字典
dict1 = {'name': 'jun', 'age': 18, 'score': 90.98}
dict2 = {'name': 'titan'}

# 完整字典
print(dict2)

# 1.修改或添加字典元素
dict2['name'] = 'brother'
dict2['age'] = 20
dict2[3] = '完美'
dict2[0.9] = 0.9
print(dict2)

# 2.根据键值获取value
print(dict1['score'])

# 3.获取所有的键值
print(dict1.keys())

# 4.获取所有的value值
print(dict1.values())

# 5.删除字典元素
del dict1['name']
print(dict1)

# 6.清空字典所有条目
dict1.clear()
print(dict1)

# 7.删除字典
dict3 = {2: 3}
del dict3
# 当该数组呗删除之后, 在调用会报错
# print(dict3)

The output of the above statement is as follows

{'name': 'titan'}
{'name': 'brother', 'age': 20, 3: '完美', 0.9: 0.9}
90.98
dict_keys(['name', 'age', 'score'])
dict_values(['jun', 18, 90.98])
{'age': 18, 'score': 90.98}
{}

6. Collection

  • A collection object is a sequence consisting of a set of unordered values, and members of the collection can be keys in a dictionary
  • setsThere are two different types of collections: mutable collections and setimmutable collectionsfrozenset
# 集合
s = {1, 2, 3, 4}

# 1. 输出
print(s)

# 2. 用set转化已存在的类型, 可以去重
# 集合不会存在相同的元素
myList = [1, 2, 3, 3, 4, 4, 4]
mySet = set(myList)
print(mySet)

# 3. 添加元素(已经存在的元素, 无法添加)
mySet.add(2)
print(mySet)
mySet.add(6)
print(mySet)

# 4.删除元素
mySet.remove(2)
print(mySet)

# 5.方法difference
set1 = {1, 2, 4}
set2 = {1, 2, 5, 6}
# 用set1和set2做difference
diff = set1.difference(set2)
print(diff)
# 输出: {4}

# 用set2和set1做difference
diff2 = set2.difference(set1)
print(diff2)
# 输出: {5, 6}

# 6. 返回相同的元素
inter = set1.intersection(set2)
print(inter)
# 输出: {1, 2}

# 7.合并集合
union1 = set1.union(set2)
print(union1)
# 输出: {1, 2, 4, 5, 6}

7. Data type conversion

  • Sometimes, we need to convert the built-in type of data. For data type conversion, you only need to use the data type as the function name.
  • The following built-in functions can perform conversions between data types. These functions return a new object representing the converted value
function describe
int(x) convert x to an integer
long(x) convert x to a long integer
float(x) convert x to a float
complex(real [,imag]) create a plural
str(x) convert object x to string
repr(x) convert object x to expression string
eval(str) Evaluates a valid Python expression in a string and returns an object
tuple(s) convert the sequence s to a tuple
list(s) convert the sequence s to 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 Unicode character
word (x) converts a character to its integer value
hex(x) Convert an integer to a hex string
oct(x) Convert an integer to an octal string

The usage example is as follows

# 数据类型转换
dic = {'name': 'jun', 'age': 18}
# 1.将x转换为一个整数
print(int(9.89))
print(int('9'))
# print(int('8.89')) # 这样的写法会报错

# 2.创建一个复数
print(complex(1, 2))
print(complex('3'))
print(complex(-2, -4))

# 3.转换为一个浮点型
print(float(9))
print(float('12.45'))

# 4.转换为字符串
print(str(9))
print(str(9.09))
print(str('89'))
print(str(dic))

# 5.转换为表达式字符串
print(repr(9.09))
print(repr(9 + 10))
print(repr(dic))

# 6.用来计算在字符串中的有效Python表达式,并返回一个对象
print(eval('3*9'))
print(eval("dic['age']*2"))

# 7.将序列转换为一个元组
list7 = [1, 2, 3]
print(tuple(list7))

# 8.将序列转换为一个列表
tuple8 = ('a', 's', 'd')
print(list(tuple8))

# 9.转换为可变集合
print(set(list7))

# 10.创建一个字典
dic10 = dict([('name', 'titan'), ('age', 17)])
print(dic10)

# 11.转换为不可变集合
print(frozenset({1, 2}))

# 12.将一个整数转换为一个字符
# 48对应字符'0'(参照ASCII码表)
print(chr(122))

# 13.将一个字符转换为它的整数值
print(ord('0'))

# 14.将一个整数转换为一个十六进制字符串
print(hex(10))

# 15.将一个整数转换为一个八进制字符串
print(oct(10))
  • As for Pythonlanguage, I am also a novice, and I am studying hard. If there is any inadequacy in the text, I would like to give more advice.
  • See the GitHub address for the test code
  • Related articles will be updated in the future

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325906379&siteId=291194637