python变量和数据类型

107 阅读1分钟

python变量和数据类型

在Python中,变量是用来存储数据的容器,可以通过变量名来访问和操作数据。在使用变量之前,需要先进行变量的声明和赋值。

# 变量的声明和赋值
x = 10
y = "Hello"

Python中的数据类型包括

  • 整数(int)
  • 浮点数(float)
  • 字符串(str)
  • 布尔值(bool)
  • 列表(list)
  • 元组(tuple)
  • 字典(dict)等

整数类型(int):

x = 10
y = -5

浮点数类型(float):

x = 3.14
y = -2.5

字符串类型(str):

x = "Hello"
y = 'World'

布尔值类型(bool):

x = True
y = False

列表类型(list):

x = [1, 2, 3, 4, 5]
y = ["apple", "banana", "orange"]

元组类型(tuple):

x = (1, 2, 3)
y = ("apple", "banana", "orange")

字典类型(dict):

x = {"name": "John", "age": 25, "city": "New York"}
y = {"apple": 1.99, "banana": 0.99, "orange": 1.49}

Python还提供了一些内置函数来进行数据类型的转换,如int()、float()、str()等。

x = 10
y = str(x)  # 将整数转换为字符串
z = float(x)  # 将整数转换为浮点数