A variable in Python is a storage location that can hold a value. Variables are created by assigning a value to them. For example, the following code creates a variable named name
and assigns it the value “John Doe”:
Code snippet
name = "John Doe"
Once a variable has been created, you can use it to refer to the value that it stores. For example, the following code prints the value of the name
variable:
Code snippet
print(name)
Output:
Code snippet
John Doe
Variables can be used to store any type of value, including strings, numbers, lists, and dictionaries.
Here are some rules for naming variables in Python:
- Variable names must start with a letter or the underscore character.
- Variable names can contain letters, numbers, and underscores.
- Variable names are case-sensitive.
- Variable names cannot be the same as a Python keyword.
Here are some examples of valid variable names in Python:
Code snippet
name
my_variable
this_is_a_long_variable_name
Here are some examples of invalid variable names in Python:
Code snippet
123name
name_with_space
this_is_a_keyword
Variables are a powerful tool that can be used to store and manipulate data in Python. By using variables, you can make your code more readable and reusable.
I hope this helps!