What are variables in Python?

Variables are the fundamental building blocks of python. You can think of variables being akin to containers lying around your home. At a certain moment, you may use a container to hold some cookies. You could keep adding more cookies or consuming some with time. Once they’re exhausted, you may wish to use that container for something else entirely, like storing chocolates. Upon long usage, you may discard the container for recycling! This is what variables in python also allow you to do!

You can store a large variety of data such as text, phone numbers, addresses, mathematical formulae, and even a list of groceries into variables in python. You may freely wish to manipulate these variables (as allowed by Python of course) , to accomplish the tasks that you need. This could be retrieving a phone number for example, or finding the square root of a number, which you may want to store for later calculations.

Examples of Variables in Python

Are you ready with your python editor to get coding? If not, you can refer to our previous post where we explain how to set up your python tools for coding. Alright, let’s get started!

 # this 'cookies' variable below stores the number of cookies! 
cookies = 10

number_of_cookies_eaten = 6 

remaining_cookies = cookies - number_of_cookies_eaten 

print(remaining_cookies)

Explanation of the code above

In line 2 of the code, we define a variable called “cookies”. It is a way of letting python know that we’re going to be needing some space in our computer’s memory to store a variable. Upon reading cookies = 10 , Python infers that the variable (our cookie jar) will store a number (the type of data) and allocates memory accordingly (You can read about exactly how much memory here). The step where we use the equal to (“=”) operator is called variable assignment, as the value 10 gets assigned to this variable cookies.

Similar explanation goes for the variable in line 4, number_of_cookies_eaten. You may notice that here we used an underscore (_) between words to clearly explain what our variable will store. In this case, it stores the number of the number of cookies we need to remove from the cookie jar.

Line 6 of the code declares yet another variable. But we do not store a value directly. Instead, we perform a mathematical operation by subtracting the number of cookies eaten from the cookies variable using the minus (-) operator. The result of 10 – 6 , which is 4, gets stored in the remaining_cookies variable.

Finally, the print function is used to display the value stored by remaining_cookies variable to the console. Simply put, the print function uses an argument ( which is the variable between the parenthesis in this case) , and outputs it for the user to see. Here is how the output looks in visual studio code, if you’ve been implementing the code there:

Declaring and assigning variables in python

Rules for Naming Python Variables

Variable names are the addresses to a memory location. For e.g., the name “cookies” above is the address to a memory location where the number “10” is stored. You can create any variable names you want, as long as they adhere to following Python commandments:

  • Thou shall not start a variable name with anything else but an underscore (_) or a letter (A-Z,a-z)
# Valid variables
cookies_in_a_jar = 50

_hidden_cookie = 1

#invalid or illegal variables

3DoorsDown = "my favorite band"

$money = 200
  • Thou shall only use a letter, number or underscore within a variable name ( A-Z, a-z, 0-9, _)
# Invalid variable, using a special symbol in name

response@website = 200 

# Valid variable , with numbers in the name

james_bond_007 = "skyfall"
  • Thy variable names shall be case sensitive. For e.g. the variable name “Cookies” is different from “cookies”
Cookies = 10
cookies = 100

print (Cookies)

#code still outputs 10, because that's what Cookies has
  • Thou shall not use reserved keywords in Python. (This confuses Python if you try to overwrite existing Python keywords, and could cause your program to break. Following is the list of reserved keywords in python
False      class      finally    is         return
None       continue   for        lambda     try
True       def        from       nonlocal   while
and        del        global     not        with
as         elif       if         or         yield
pass       else       import     assert
break      except     in         raise

Assigning Multiple Variables

There are multiple ways to assign a value to a variable name. The one we’ve looked at above, using equal to symbol directly (=) is one of them. One can also assign multiple variables at the same time to the same value, or to different values. Here are some examples:

Assigning multiple variable to the same value in Python

This syntax must seem familiar to you if you’ve taken mathematics in high school. It is very common to write a=b=c=5 , as a short hand of saying the 3 parameters have the same value. This is also valid in Python. Try it out:

a = b = c = 4
print(a,b,c)

Output:

4 4 4

Assigning multiple values to multiple variables in Python

In Python, you could also assign multiple variables in a sequence like so:

a,b,c = 300,400,500

print(a,b,c)

Output:

300 400 500

Scope of Variables in Python

Imagine a person named “Leonardo DiCaprio” (not the celebrity) studying in Math class. They’re the only person in their class named as such, so their faculty and peers can call him by that name when he is in class. In this context, we can say, “Leonardo DiCaprio is unique in the local context of his class”, which is true. However, when we go outside that class, in a different scope, when people generally talk about Leonardo DiCaprio’s acting in Titanic, it is common sense that they’re talking about the “Global” personality and not the one “locally known”.

The same goes for variables in python. Two different variables with the same name can be defined, provided they’re in a different scope. The one known to the main program, is said to be in the “Global scope” or is a Global variable, just like the globally known Leonardo DiCaprio. The one defined locally within a code block such as a function is said to be in “Local Scope” or is a Local Variable, since it can only be accessed by the local elements.

Global and Local Variables

Consider the following code and then its step by step explanation. I’m jumping ahead a bit to functions, but we only need it to understand the concept of code blocks. So stay with me.

# I define a variable called cookies and give it a values of 100
cookies = 100
print("In global scope")
print(cookies)

# Now I create a function, which you can think of as an isolated code block
def localCookies ():
    cookies = 50
    print("In function scope")
    print(cookies)

#we're calling the function here to do its thing
localCookies()

# now we continue to do our work in the global scope
print("Back In Global scope")
print(cookies)

Output:

In global scope
100
In function scope
50
Back In Global scope
100

In line 2, we define a variable as we’ve done before. When we print it out in the global scope in line 4, it outputs 100. Then I go on to define a function called “localCookies”. We’ll talk about functions in more depth in a later blog, but essentially it is a re-usable block of code that can be named and used in a program, without having to type out that same code. Here “localCookies” is the name of the function which wraps the lines from line 8-10. The job of the function is basically to create a variable called cookies and print out its value. This is just the definition of the function. It does not execute until it is called.

In line 13, we call this function, which is akin to replacing lines 8-10 with the line 13. Only exception is that these lines 8-10 are their own local block of code.

Once the function executes, we again go back to printing the value of “cookies” outside the function call.

What we see in the output:

The variable cookies defined outside the function is in the global scope and hence is output by the program as 100 when we print it.

Then the program executes a function called “localCookies”. This function has its own local variable called cookies, which is much like our local Leonardo DiCaprio, the lanky kid studying math class. It thus outputs “50“, as it only knows about the variable in its local scope.

Once we’re out of the function, we’re back in global scope, and the program forgets about the local variable that had existed during the previous step. When asked to print out “cookies”, it does not hesitate to print 100 again.

If you’d want to read more about scopes and namespaces, you can refer to the Python tutorial to understand key concepts in detail. However, this would require pre-existing knowledge about classes, namespaces and bindings, which we will cover in future blogs. So stick with us and your understanding in these concepts will definitely improve as we do more exercises!

Conclusion

In this chapter, we looked at what variables are in python and got a sense of the right ways to name our own variables. We’ve also understood the variables in different scopes in a program, although we’ll still cover what functions are in a bit more detail in the upcoming blogs. As an added exercise, the readers are encouraged to trying out writing and printing their own variables in python, and seeing what works. Experiment away, and don’t be deterred by error messages! Happy coding!

0

Leave a Comment

Scroll to Top