Python语言没有用于声明变量的关键字。当我们首先为变量赋值时,会立即在适当位置创建一个变量。
创建变量:i = 20
blogName = "leftso"
print(i) # prints 20
print(blogName) # prints leftso
可以使用单引号和双引号来创建字符串类型的变量。
$title(String类型)
author = 'Lokesh'
blogName = "leftso"
print(author) # prints Lokesh
print(blogName) # prints leftso
i = j = k = 20
print(i) # prints 20
print(j) # prints 20
print(k) # prints 20
x, y, z = "A", "B", 100
print(x) # prints A
print(y) # prints B
print(z) # prints 100
$title(变量重申明)
index = 10
index = 20
index = "NA"
print(index) # prints NA
在Python中创建变量的规则是:
(A-z, 0-9, and _ )
。注意: Python 3具有完整的Unicode支持,它也允许在变量名中使用Unicode字符。
x = 10 # 全局变量
def myfunc():
y = 10 # 局部变量
print("Sum of x and y = " + str(x + y)) # prints Sum of x and y = 20
myfunc()
print("Sum of x and y = " + str(x + y)) # NameError: name 'y' is not defined
x = 10 # 全局变量
def myfunc():
x = 20 # 局部变量
print("x is " + str(x)) # prints x is 20
myfunc()
print("x is " + str(x)) # prints x is 10
global
关键字。
x = 10 # 全局变量
def myfunc():
global y
y = 10 # 在函数内部创建的全局变量
print("Sum of x and y = " + str(x + y)) # prints Sum of x and y = 20
myfunc()
print("Sum of x and y = " + str(x + y)) # prints Sum of x and y = 20
https://www.leftso.com/article/724.html