Python变量

时间:2020-02-23 14:43:39  来源:igfitidea点击:

在本教程中,我们将了解有关Python变量的一些基础知识。
在之前的教程中,我们讨论了有关Python打印功能的信息。

Python变量

在您的数学书中,您可能听说过变量。
Python变量用于存储值。

当您在python中声明变量时,有关该变量的某些空间将保留在内存中。
然后,您可以访问它们。
如果您阅读了有关Python数据类型的教程,则可能应该了解pythons数据类型。

Python声明变量

在最常见的编程语言(如c,C++,java等)中,声明变量时必须设置变量的数据类型。

Python python对此很灵活。
您可以声明一个变量,然后变量的数据类型取决于要存储其中的数据。
请参见以下示例。

# declare a variable
var = 'new variable'

print('The type of var is :',type(var))  # the type is str

var = 23.0
print('Now, the type of var is :', type(var))  # the type is float

这样您将看到这样的输出。

多变量分配

在所有这些教程中,您从未见过这些。
好了,您看到了有关单个变量值分配的信息。

但是,您也可以将值分配给多个值。
您必须将值保留在最右边。

之所以不使用此想法,是因为我们不需要使用这种分配。
但是也许您的项目可能需要这个想法,并且学习新事物没有错。
但是,请参见以下代码以了解多变量分配。

# assign multiple variable with the same value
var1 = var2 = var3 = 'init'

# print the value of each variable separately
print('Value of var1 :', var1)
print('Now, value of var1 :', var2)
print('Again, value of var1 :', var3)

因此,以下代码的输出将是

Value of var1 : init
Now, value of var1 : init
Again, value of var1 : init

有关python变量的一些说明

下面提供了有关创建Python变量名称的一些注意事项。

  • Python变量名称不能以数字开头

  • 不能以特殊字符开头

  • Python变量名称不能与任何python的预定义关键字相同。

  • 变量名称应使用camelCase编写

Python打印变量

如上面的程序所示,我们可以使用print()函数将变量打印到控制台。

Python变量范围

Python变量的范围取决于程序中声明的位置。
我们已经在python名称空间发布中更详细地解释了python变量范围。