What is a variable?
Variables can be considered as a box. In Python, you can put anything inside that box, without specifying the size or type, which will be needed in languages such as C, C++ or Java. Note that Python is case-sensitive. Be careful about using letters in different cases.
1 2 3 4 |
age = 25 # integer email = "suresh@somedomainname.com" # string address = "112 main street" # string gpa = 3.9 # float |
Declaring and assigning variables
In programming terms, we say that we just declared a variable, email, and assigned it to the string, user@aol.com
. To do so, we’ll follow the procedure below:
1 |
email_address = "user@aol.com" |
Note that if you introduce a new variable, (declare it), but do not also assign it in the same line, Python will raise an error.
1 2 3 4 5 |
>>> name Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'name' is not defined >>> |
So that error tells us that name is not defined. We just fix this by declaring name and assigning the variable in the same line.
1 |
name = "John" |
Declaring variables without assignment
We have seen that we can have data without assigning it to variables. Sometimes we wish to declare a variable without assigning it to data. In Python, that’s a little tricky to do. As we just saw with name, declaring variables without assignment throws an error. Thankfully, Python has a special type for us that represents nothing at all.
1 |
age = None |
None is a data type in Python that represents nothing. So, if we do not know the type of a variable and want to have the data to the variable be assigned later, we can assign that variable to None.
Notice that age is now assigned, but it is assigned to date type None.