How do you set variables in Python?
In Python, you can assign a value to a variable using the equal sign (=). For example:
x = 10
This will create a variable called x and assign it the value of 10.
Variable names can be any valid identifier, but must follow the following rules:
- Variable names can only consist of letters, numbers, and underscores.
- Variable names cannot start with a number.
- Variable names are case-sensitive.
In Python, you don’t need to declare the type of a variable beforehand. The type of a variable is inferred based on the value assigned to it. For example:
x = 10 # 整数
y = 3.14 # 浮点数
z = "Hello, world!" # 字符串
You can also assign values to multiple variables at the same time. For example:
x, y, z = 10, 3.14, "Hello, world!"
This will create three variables, x, y, and z, and assign them values of 10, 3.14, and “Hello, world!” respectively.
You can also change a variable’s value by referencing the same variable. For example:
x = 10
x = 20 # 将x的值更改为20
In this example, the value of variable x is first set to 10, and then changed to 20.
Please note that variables must be assigned a value before they are referenced. Otherwise, a NameError exception will be raised. For example:
x = 10
print(y) # 会抛出NameError异常,因为y未定义