In Python, a variable is a named reference to a value that can be changed during the execution of a program. Variables are used to store data of different types, such as numbers, strings, lists, dictionaries, and more.
To create a variable in Python, you need to follow these steps:
- Choose a name for your variable: A variable name can consist of letters, numbers, and underscores. It should start with a letter or underscore, and it should not be a Python keyword.
- Assign a value to your variable: You can assign a value to your variable using the equal sign
=
.
Here’s an example:
message = "Hello, World!"
In this example, we are creating a variable called message
and assigning it the value of the string “Hello, World!”.
You can also create a variable without assigning a value to it, like this:
count = None
In this example, we are creating a variable called count
without assigning it any value. We can later assign a value to it using the equal sign =
.
Here are the rules for creating a variable in Python:
- The name of a variable must start with a letter or underscore (
_
). It cannot start with a number. - The name of a variable can only contain letters, numbers, and underscores (
_
). It cannot contain spaces or special characters. - Variable names are case-sensitive, so
myVar
andmyvar
are two different variables. - Avoid using reserved keywords as variable names, such as
if
,else
,while
,for
,True
,False
,None
, and so on. - Choose descriptive variable names that are easy to understand and meaningful. For example,
age
is a better variable name thana
, andtotal_sales
is a better variable name thant
.
Here are some examples of valid variable names in Python:
x = 10 name = "John" _myVar = 5.5 total_sales = 1000
And here are some examples of invalid variable names in Python:
2nd_grade = 3 # Cannot start with a number my-var = 10 # Cannot contain a hyphen for = 5 # Cannot use reserved keyword as a variable name