This section reads as follows:
- What is a variable
- Data types in Python
- Definition and assignment of variables
What is a variable
A variable is a unit of memory that a program uses to hold data, and can be manipulated by variable names to manipulate the data and memory allocations. Since variables take up memory space, consider how to allocate memory, when to allocate, how much to allocate, and when to recycle. These are very simple in Python, however, and Python implements these functions through automatic memory management.
Data types in Python
Above we say that the variable is used to save the memory of the data space, then, how to allocate the space, how much? These are the variable data types that are determined. Each data type has a relatively fixed size. The data type determines that the amount of space to allocate is determined. Let's look at what the data types in Python are:
1. Digital
An integer or a decimal.
2. String
A string of single or double quotation marks, for example: ' Hello ', ' Python '.
3. List
A set of data enclosed in square brackets, for example: [1,2,3,4]
4. Tuples
A set of data enclosed in parentheses, for example: (404, ' Page not found ')
5. Dictionaries
The key-value pair that the curly brace expands, for example: {name: ' Tom ', age:20}
6. Objects
Examples of classes, functions, and so on.
These data types will be covered in detail later, so here's a quick look.
Definition and assignment of variables
Defining variables in Python is not the same as other languages:
1. You do not need to specify a data type of 2. You must assign a value of 3 when defining a variable. Determining variable types based on data type
For example:
a
print
(a)
#错误 变量没有定义
‘‘‘
1.数字
一个整数或者一个小数。
‘‘‘
age
= 20
price
= 2.5
print
(
type
(age))
print
(
type
(price))
age
= ‘20‘
print
(
type
(age)) ‘‘‘
2.字符串
单引号或者双引号扩起来的字符串,例如:‘Hello‘ "Python"
‘‘‘
name
= ‘享学课堂‘
site_name
= "享学课堂"
html
= """
"""
print
(
type
(name))
‘‘‘
3.列表
方括号括起来的一组数据,例如:[1,2,3,4]
‘‘‘
l
= [
‘享学课堂‘
,
‘Python学院‘
,
‘老郭‘
]
print
(
type
(l))
for x
in l:
print
(x)
‘‘‘
4.元组
圆括号括起来的一组数据,例如:(404,‘Page not found‘)
‘‘‘
t
= (
404
,
‘页面未找到‘
)
print
(
type
(t))
‘‘‘
5.字典
方括号扩起来的键值对,例如: [name:‘tom‘,age:20]
‘‘‘
d
= {
‘name‘
:
‘老郭‘
,
‘site‘
:
‘2xkt.com‘
,
‘age‘
:
‘20‘
}
print
(
type
(d))
for k
in d.keys():
print
(k)
print
(d[k])
‘‘‘
6.对象
‘‘‘
class Person(
object
):
pass
p
= Person()
print
(
type
(p))
|
Python variables and data types