变量是存放数据值的容器。与其他编程语言不同,python不需要在使用变量之前声明。当第一次给变量赋值时,变量就被创建了。
Python 中的变量示例
Python 中变量的一个示例是用作指向对象的指针的代表性名称。一旦将对象分配给变量,就可以通过该名称来引用它。通俗地说,Python中的变量就是存储值的容器。
这里我们将“ hellworld ” 存储在一个变量中,当我们调用它的名字时,存储的信息将被打印出来。
Var = "helloworld"
print(Var)
输出:
helloworld
注意:
- 存储在变量中的值可以在程序执行期间更改。
- Python 中的变量只是给定内存位置的名称,对变量所做的所有操作都会影响该内存位置。
Python 变量的规则
- Python 变量名必须以字母或下划线字符开头。
- Python 变量名不能以数字开头。
- Python 变量名称只能包含字母数字字符和下划线(Az、0-9 和 _)。
- Python 中的变量名称区分大小写(name、Name 和 NAME 是三个不同的变量)。
- Python中的保留字(关键字)不能用来命名Python中的变量。
例子
# valid variable name
geeks = 1
Geeks = 2
Ge_e_ks = 5
_geeks = 6
geeks_ = 7
_GEEKS_ = 8
print(geeks, Geeks, Ge_e_ks)
print(_geeks, geeks_, _GEEKS_)
输出:
1 2 5
6 7 8
Python 中的变量赋值
假设我们为年龄、薪水和姓名等变量分配了一个数字、一个浮点数和一个字符串。
# An integer assignment
age = 45
# A floating point
salary = 1456.8
# A string
name = "John"
print(age)
print(salary)
print(name)
输出:
45
1456.8
John
变量的声明和初始化
让我们看看如何声明变量并打印变量。
# declaring the var
Number = 100
# display
print( Number)
输出:
100
在 Python 中重新声明变量
一旦我们已经声明了Python变量,我们就可以重新声明该变量。
申报前:100
重新申报后:120.3
Python 为多个变量赋值
此外,Python 允许使用“=”运算符同时将单个值分配给多个变量。 例如:
a = b = c = 10
print(a)
print(b)
print(c)
输出:
10
10
10
为多个变量分配不同的值
Python 允许使用“,”运算符在一行中添加不同的值。
a, b, c = 1, 20.2, "helloworld"
print(a)
print(b)
print(c)
输出:
1
20.2
helloworld
我们可以对不同类型使用相同的名称吗?
如果我们使用相同的名称,变量将开始引用新的值和类型。
a = 10
a = "helloworld"
print(a)
输出:
helloworld
+ 运算符如何处理变量?
Python 加号运算符 + 提供了一种方便的方法来添加值(如果是数字)和连接(如果是字符串)。如果已创建变量,则会将新值分配回同一变量。
a = 10
b = 20
print(a+b)
a = "Geeksin"
b = "jkhxw"
print(a+b)
输出:
30
Geeksinjkhxw
我们也可以对不同的数据类型使用 + 吗?
对不同的类型使用+会产生错误。
a = 10
b = "Geeks"
print(a+b)
输出 :
TypeError: unsupported operand type(s) for +: 'int' and 'str'
全局变量和局部变量
Python 中的局部变量是在函数内部定义和声明的变量。我们不能在函数外部调用这个变量。
# This function uses global variable s
def f():
s = "Welcome geeks"
print(s)
f()
输出:
Welcome geeks
Python中的全局变量是在函数外部定义和声明的变量,我们需要在函数内部使用它们。
# This function has a variable with
# name same as s.
def f():
print(s)
# Global scope
s = "I love Geeksforgeeks"
f()
输出:
I love Geeksforgeeks
Python 中的全局关键字
Python global 是一个关键字,允许用户修改当前范围之外的变量。它用于从非全局范围(即函数内部)创建全局变量。仅当我们想要进行赋值或想要更改变量时,才在函数内部使用全局关键字。打印和访问不需要全局。
全局关键字规则
- 如果在函数体内的任何位置为变量赋值,则假定该变量是局部变量,除非显式声明为全局变量。
- 仅在函数内部引用的变量是隐式全局的。
- 我们在 Python 中使用 global 来在函数内使用全局变量。
- Python 中无需在函数外部使用全局关键字。
例子:
用于修改函数内全局值的 Python 程序。
x = 15
def change():
# using a global keyword
global x
# increment value of a by 5
x = x + 5
print("Value of x inside a function :", x)
change()
print("Value of x outside a function :", x)
输出:
Value of x inside a function : 20
Value of x outside a function : 20
Python 中的变量类型
数据类型是数据项的分类或分类。它代表一种值,告诉我们可以对特定数据执行哪些操作。由于Python编程中一切都是对象,因此数据类型实际上是类,变量是这些类的实例(对象)。
Python 内置数据类型有:
- 数值类型
- 文本类型
- 序列类型(Python 列表、Python 元组、Python 范围)
- 布尔值
- 集合类型
- 字典
例子:
在此示例中,我们展示了 Python 中内置数据类型的不同示例。
# numberic
var = 123
print("Numeric data : ", var)
# Sequence Type
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)
# Boolean
print(type(True))
print(type(False))
# Creating a Set with
# the use of a String
set1 = set("GeeksForGeeks")
print("\nSet with the use of String: ")
print(set1)
# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
输出:
Numeric data : 123
String with the use of Single Quotes:
Welcome to the Geeks World
<class 'bool'>
<class 'bool'>
Set with the use of String:
{'r', 'G', 'e', 'k', 'o', 's', 'F'}
Dictionary with the use of Integer Keys:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Python 中的对象引用
让我们给变量 x 赋值 5。
另一个变量y赋值x。
y = x
当Python查看第一条语句时,它所做的是,首先,它创建一个对象来表示值5。然后,它创建变量x(如果它不存在),并使其成为对这个新对象5的引用。第二行Python 创建变量 y,并且它没有被赋值给 x,而是用来引用 x 所指向的对象。最终效果是变量 x 和 y 最终引用同一个对象。这种多个名称引用同一个对象的情况在 Python 中称为共享引用。
示例:
a = "hello world"
b = a
print("Before adding")
print("{id} || a: {val}".format(id=id(a), val=a))
print("{id} || b: {val}".format(id=id(b), val=b))
print("a is b: {}".format(a is b))
a.replace('world', 'python')
print("After adding")
print("{id} || a: {val}".format(id=id(a), val=a))
print("{id} || b: {val}".format(id=id(b), val=b))
print("a is b: {}".format(a is b))
输出:
Before adding
2303166191152 || a: hello world
2303166191152 || b: hello world
a is b: True
After adding
2303166191152 || a: hello world
2303166191152 || b: hello world
a is b: True
- a = “hello world”:即 “hello world” –> a,首先创建不可变字符串对象“hello world”,再创建变量 a,并把 a 指向字符串对象“hello world”
- b = a:即 a –> b,创建变量 b,并把 b 指向 a 指向的字符串对象“hello world”,在这之后,a 和 b 指向同一个对象
- a.replace(‘world’, ‘python’):这一步不是赋值操作,由于字符串对象不可改变,这一操作会在新的地址新建一个字符串来保存字符串替代后的结果“hello python”,但是由于没有赋值操作,这一结果的地址并没有保存在某个变量里,此时 a 和 b 依然指向原不可变字符串“hello world”