Variables in Python
Summary : Variables are quite simply a placeholder for something. That something could be numbers, strings, booleans or any other object type.We will explore what a variable can be, how it should be named, how variables should be assigned and how each of the variables types are used
- What is a Variable
- Types of Variables
- Variable naming convention
- Multiple assignments
- Python Variables Cheat sheet
What is a variable
A variable is quite simply a placeholder for something. Basically, variables can contain Numbers or Strings or Objects. Technically, even numbers and strings are objects, but we will discuss that later.
name = "Ajay Tech" age = 2
How do we know if a variable contains a string or a number ? Use the type ( ) function. We will discuss more about functions later – but for now think of them as a blackbox that just gets a task done – In this case, we want to find out if the variable name is an stringor not. For us, it does not matter where the function type ( ) gets this from – we just use it.
int means integer. That brings us to the next point. How many types of numbers are there ?
Types of Numbers
There are 3 types of numbers supported in Python.
For example, the age variable above was an integer. What if you wanted to hold a negative value ? Say a discount of 30$ represented with a negative sign
discount = -30 type(discount)
So, integers can hold negative numbers as well. How big can these numbers get ? Can we store the age of the universe ? Thats 13 billion years. Let’s try it.
age_universe = 13000000000
That held ok – Let’s count the age of the universe in seconds. Basically multiply it by 365 days x 24 hours x 60 minutes x 60 seconds.
age_u_seconds = age_universe * 365 * 24 * 60 * 60 print ( age_u_seconds)
So, basically an integer in Python can hold virtually insanely large numbers. And you can very well do all mathematical operations on them that you would typically do on numbers.
Let’s do a division operation and see what happens. Say, we want to calculate the age of the universe in months,
age_u_months = age_universe / 12 age_u_months
Now, we have decimals. Can an integer variable in Python hold decimal values ? No it can’t. For that you need a float. Let’s see.
See, when we asked python to store the result in the variable _age_umonths, Python has automatically chosen to store the value in a float instead of an int. When people say that Python is a dynamically typed language, this is what they mean – We don’t have to explicitly let Python know what kind of data a variable needs to hold ( Like in C or C++ ). It is automatically decided for us.
Complex numbers are another type of number, that is used typically in scientific computation. For example, to store a complex number 1 + 2j , use
v = 1 + 2j type(v)
If you don’t understand complex numbers, that’s fine. Most of you might never need them.
A variable can also hold strings, like we have seen previously.
name = "Ajay Tech"
You can use single quotes or double quotes. Both mean the same thing.
name_s = 'Ajay Tech' name_d = "Ajay Tech"
We will see in a later section that strings in python have many in-built functions for slicing, stripping etc.
Another variable type is Boolean . It just takes 2 values – True or False. It is typically used to hold a function’s return value or the return value of an expression. For example, if a computer has a color monitor or not, use the variable has_color as follows.
has_color = True type(has_color)
This is not the same as a string “True”
We will explore more on boolean variables when we explore expressions.
Variable naming convention
When creating variables, make sure
- it starts with a letter ( capital or small ) only
- it does not contain any special characters ( except an underscore )
- is NOT a reserved keyword
For example, the following are not valid variables.
_age = 10
print ( _age)
Well, it works OK, but there is a specific meaning that python gives to a variable that starts with an underscore ( private variable ) and to understand it, we need to go into object oriented Python. For now, just remember that having an underscore at the beginning of the variable makes it special – use it only when you understand it. For all other casese, just don’t use underscore as the first letter.
1_age = 2
File "<ipython-input-27-957b2d800c96>", line 1 1_age = 2 ^ SyntaxError: invalid token
Having a number as the first letter is not a valid variable name. Python throws a Syntax error as shown above. How about these variables ?
name# = "Ajay Tech"
Well, this works because, we have already declared a name variable and everything after the has( # ) is a comment. More on this later.
name@first = "Ajay Tech"
File "<ipython-input-30-97a3570cc45d>", line 1 name@first = "Ajay Tech" ^ SyntaxError: can't assign to operator
So, no special characters in the variable name.
Also, you cannot use reserved words for variable names, like name a variable as for
for = 1
File "<ipython-input-33-b26be1b49601>", line 1 for = 1 ^ SyntaxError: invalid syntax
How would you know all the reserved words ? Well, over time you would know them anyway. However, if you want the list, you can get them as below. You don’t have to memorize them though.
import keyword print ( keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
Sometimes it is convenient to assign multiple variables at the same time. A simple example would be
age, weight = 21, 101.5
print ( age ) print ( weight )
They will respective be assigned variables of type int and float.
type( age )
type( weight )
Challenge – Swap the two variables age_1 and age_2’s values.
age_1 = 21 age_2 = 22
temp = age_1 age_1 = age_2 age_2 = temp print ( age_1 , age_2)