Variables are used to store data that can be referenced and manipulated in a program. In Python, variables are created by assigning a value to a name using the assignment operator =. Python is dynamically typed, meaning you don't need to declare the type of a variable before using it. The type is inferred from the value assigned.
To create a variable, simply assign a value to a name:.
Example-
name = "Alice"
age = 25
height = 5.7
is_student = True
In this example:
When naming variables in Python, you need to follow these rules:
Example-
user_name = "Alice"
_user_age = 25
userHeight = 5.7
isStudent = True
You can assign multiple variables in one line:
Example-
a, b, c = 1, 2, 3
You can also assign the same value to multiple variables in one line:
Example-
x = y = z = 0
Python automatically determines the type of the variable based on the value assigned. You can check the type of a variable using the type() function.
Example-
name = "Alice"
age = 25
height = 5.7
is_student = True
print(type(name))
print(type(age))
print(type(height))
print(type(is_student))
You can change the type of a variable by assigning a value of a different type:
Example-
number = 10
number = "Ten"
print(number)
By convention, constants are usually defined using uppercase letters. Although Python does not have built-in constant types, it's a common practice to define constants at the beginning of the script.
Example-
PI = 3.14159
MAX_USERS = 100
You can delete a variable using the del keyword:
Example-
x = 10
print(x) # Output: 10
del x
# print(x) # This will raise a NameError because x is deleted