I. Overview
Variables in Python do not need to be declared. Each variable must be assigned a value before it is used, and the variable will only be created after it is assigned a value.
In Python, a variable is just a variable; it has no type. The "type" we refer to is the type of the object in memory that the variable points to.
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 = "example" # 字符串 a = b = c = 1 # 同时为多个变量赋值 a,b,c=1,2,'hello' # 为多个对象指定多个变量
II. Standard Data Types
Python3 has six standard data types:
Number(数字) String(字符串) List(列表) Tuple(元组) Sets(集合) Dictionary(字典)
2.1 Number
Python3 supports int, float, bool, and complex (complex numbers).
There is only one integer type, int, represented as a long integer. There is no Long like in Python2.
The built-in type() function can be used to query the type of the object referenced by a variable.
>>> a,b,c,d=5,6.7,true,2+3j Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'true' is not defined >>> a,b,c,d=5,6.7,True,2+3j >>> print(type(a),type(b),type(c),type(d)) <class 'int'> <class 'float'> <class 'bool'> <class 'complex'>
Note:
- 1. Python can assign values to multiple variables at the same time, e.g., a, b = 1, 2.
- 2. A variable can point to objects of different types through assignment.
- 3. Numeric division (/) always returns a floating-point number (print(2/4) outputs 0.5); to get an integer, use the // operator.
- 4. In mixed calculations, Python will convert integers to floating-point numbers. 5. Boolean: True and False, 1 and 0.
- 6. The del statement can delete defined objects, e.g., del a,b.
2.2 String
Strings in Python are enclosed in single quotes (') or double quotes ("), and backslashes are used to escape special characters.
The syntax for string slicing is as follows:
variable[start_index:end_index]
The index starts at 0, and -1 is the starting position from the end.
The plus sign (+) is the string concatenation operator, and the asterisk (*) means to repeat the current string; the number following it is the number of repetitions.
Example:
#!/usr/bin/python3
# -*- coding:UTF-8 -*-
str='hello,world!'
print(str) # 输出字符串
print(str[0:-1]) # 输出第一个到倒数第二个的所有字符
print(str[0]) # 输出字符串第一个字符
print(str[2:5]) # 输出从第三个开始到第五个的字符
print(str[2:]) # 输出从第三个开始的后的所有字符
print(str * 2) # 输出字符串两次
print(str + '你好') # 连接字符串
print('------------------------------')
print('hello\nworld') # 使用反斜杠(\)+n转义特殊字符
print(r'hello\nworld') # 在字符串前面添加一个 r,表示原始字符串,不会发生转义
Execution result:
hello,world! hello,world h llo llo,world! hello,world!hello,world! hello,world!你好 ------------------------------ hello world hello\nworld
Note:
- 1. Backslashes can be used for escaping. Using r can prevent backslashes from being escaped.
- 2. Strings can be concatenated with the + operator and repeated with the * operator.
- 3. Strings in Python have two indexing methods: starting from 0 from left to right, and starting from -1 from right to left.
- 4. Strings in Python cannot be changed.
- 5. Python has no separate character type; a character is a string of length 1.
2.3 List
List is the most frequently used data type in Python.
Lists can implement most collection-class data structures.
The types of elements in a list can be different. It supports numbers, strings, and can even contain lists (so-called nesting).
A list is written between square brackets [] with elements separated by commas.
Like strings, lists can be indexed and sliced. After a list is sliced, it returns a new list containing the required elements.
The syntax for list slicing is as follows:
variable[start_index:end_index]
The index starts at 0, and -1 is the starting position from the end.
The plus sign (+) is the list concatenation operator, and the asterisk (*) is the repetition operation.
Example:
#!/usr/bin/python3 # -*- coding:UTF-8 -*- list=['hello',357,6.6,'world'] ttlist=[123,'new'] print(list) # 输出完整列表 print(list[0]) # 输出列表第一个元素 print(list[1:3]) # 输出从第2个开始到第3个元素 print(list[2:]) # 输出从第三个开始的后的所有元素 print(ttlist * 2) # 输出两次列表 print(str + ttlist) # 连接列表
Execution result:
['hello', 357, 6.6, 'world'] hello [357, 6.6] [6.6, 'world'] [123, 'new', 123, 'new'] ['hello', 357, 6.6, 'world', 123, 'new']
Unlike Python strings, the elements in a list can be changed:
>>> new=[1,2,3,4,5,'hi'] >>> new [1, 2, 3, 4, 5, 'hi'] >>> new[1]='hehe' #改变列表new中的第2个元素为hehe >>> new [1, 'hehe', 3, 4, 5, 'hi'] >>> new[2:4]=[8,10] #改变列表new中的第3/4个元素为8,9 >>> new [1, 'hehe', 8, 10, 5, 'hi' >>> new[2:4]=[] #删除列表new中的第3、4个元素 >>> new [1, 'hehe', 5, 'hi'] >>> new[2:3]=[]
Note:
- 1. Lists are written between square brackets, with elements separated by commas.
- 2. Like strings, lists can be indexed and sliced.
- 3. Lists can be concatenated using the + operator.
- 4. Elements in a list can be changed.
2.4 Tuple
Tuples are similar to lists, except that the elements of a tuple cannot be modified.
Tuples are written in parentheses () with elements separated by commas.
The types of elements in a tuple can also be different.
Tuples are similar to strings in that they can be indexed, with index starting at 0 and -1 being the position from the end. They can also be sliced.
In fact, a string can be viewed as a special kind of tuple.
Constructing a tuple containing 0 or 1 elements is special, so there are some extra syntax rules:
tup1 = () # 空元组 tup2 = (20,) # 一个元素,需要在元素后添加逗号
string, list, and tuple all belong to sequence.
Note:
- 1. Like strings, the elements of a tuple 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 with 0 or 1 elements.
- 4. Tuples can also be concatenated using the + operator.
2.5 Sets
A set is an unordered sequence of unique elements.
Its basic functions are membership testing and deleting duplicate elements.
You can use curly braces { } 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.
Example:
#!/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(b)
print(a - b) # a和b的差集
print(b - a) # b和a的差集
print(a | b) # a和b的并集
print(a & b) # a和b的交集
print(a ^ b) # a和b中不同时存在的元素
Output result:
{'Jim', 'Mary', 'Rose', 'Tom', 'Jack'}
Rose 在集合中
{'d', 'c', 'r', 'a', 'b'}
{'l', 'c', 'm', 'a', 'z'}
{'d', 'b', 'r'}
{'l', 'm', 'z'}
{'l', 'd', 'c', 'r', 'm', 'a', 'b', 'z'}
{'c', 'a'}
{'l', 'd', 'r', 'm', 'b', 'z'}
2.6 Dictionary
Dictionary is another very useful built-in data type in Python.
Lists are ordered collections of objects, while dictionaries are unordered collections of objects.
The difference between the two is that elements in a dictionary are accessed by key, not by offset.
A dictionary is a mapping type. Dictionaries are identified by "{ }" and are an unordered collection of key: value pairs.
Keys must use immutable types.
In the same dictionary, keys must be unique.
Example:
#!/usr/bin/python3
dict = {}
dict['one'] = "1 - hello,world"
dict[2] = "2 - 嘿嘿"
tinydict = {'name': 'lucy', 'code': 100, 'class': '5年级6班'}
print(dict['one']) # 输出键为 'one' 的值
print(dict[2]) # 输出键为 2 的值
print(tinydict) # 输出完整的字典
print(tinydict.keys()) # 输出所有键
print(tinydict.values()) # 输出所有值
Output result:
1 - hello,world
2 - 嘿嘿
{'name': 'lucy', 'code': 100, 'class': '5年级6班'}
dict_keys(['name', 'code', 'class'])
dict_values(['lucy', 100, '5年级6班'])
Built-in functions:
get: returns the corresponding value according to the key; if no value is found, returns None without raising an error.
>>> dic = {'k1':'v1','k2':'v2'}
>>> v = dic.get('k1')
>>> print(v)
v1
clear: empty the dictionary.
>>> dic = {'k1':'v1','k2':'v2'}
>>> v = dic.clear()
>>> print(dic)
{}
>>> print(v)
None
copy: copy (shallow copy).
>>> dic = {'k1':'v1','k2':'v2'}
>>> v = dic.copy()
>>> print(v)
{'k1':'v1','k2':'v2'}
pop: delete and get the corresponding value.
>>> dic = {'k1':'v1','k2':'v2'}
>>> v = dic.pop('k1')
>>> print(dic)
{'k2':'v2'}
>>> print(v)
v1
popitem: randomly delete a key-value pair and get the deleted key and value.
>>> dic = {'k1':'v1','k2':'v2'}
>>> v = dic.popitem()
>>> print(dic)
{'k1':'v1'}
>>> print(v)
{'k2':'v2'}
setdefault: add; if the key exists, do nothing.
>>> dic = {'k1':'v1','k2':'v2'}
>>> dic.setdefault('k3','v3')
>>> print(dic)
{'k1':'v1','k2':'v2','k3':'v3'}
update: batch add or modify.
dic = {'k1':'v1','k2':'v2'}
dic.update({'k3':'v3','k4':'v4'})
print(dic)
{'k1':'v1','k2':'v2','k3':'v3','k4':'v4'}
Note:
- 1. A dictionary is a mapping type, and its elements are key-value pairs.
- 2. The keys of a dictionary must be immutable types and cannot be duplicated.
- 3. Use { } to create an empty dictionary.
III. Data Type Conversion
For data type conversion, you simply 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 | Description | |
|---|---|---|
| int(x [,base]) | Convert x to an integer. | |
| float(x) | Convert x to a floating-point number. | |
| complex(real [,imag]) | Create a complex number. | |
| str(x) | Convert object x to a string. | |
| repr(x) | Convert object x to an expression string. | |
| eval(str) | Used to evaluate a valid Python expression in a string and return an object. | |
| tuple(s) | Convert sequence s to a tuple. | |
| list(s) | Convert sequence s to a list. | |
| set(s) | Convert to a mutable set. | |
| dict(d) | Create a dictionary. d must be a sequence of (key, value) tuples. | |
| frozenset(s) | Convert to an immutable set. | |
| chr(x) | Convert an integer to a character. | |
| unichr(x) | Convert an integer to a 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. | |
Original article address: https://segmentfault.com/a/1190000009722187