CommonLounge Archive

Python3: Variables

July 26, 2018

So far, you’ve learnt a number of important concepts in Python. We’ve looked at numbers, expressions, strings, functions, objects and methods, type conversion and even escaping characters within a string!

In this tutorial, you’ll learn about variables in Python. Let’s get started!

Variables

Variables are used to store values. A good analogy for the variable is a box. You can imagine the name of the variable as the label on the box, and the value of the variable as what’s stored inside it. Let’s create a variable called name and put the value CommonLounge inside it.

name = "CommonLounge"
print(name)

Output:

CommonLounge

The above is equivalent to saying: Store the value "CommonLounge" in variable name

As you may have noticed, we did print(name) instead of print("name"). The first one (without the quotes) says, print the value of the variable name. The second one (with the quotes) says, print the string "name".

Yippee! You now have your first variable! :)

Of course, variables can be anything – numbers too! Try this:

name = "CommonLounge"
n = 4
print(name * n)

Output:

CommonLoungeCommonLoungeCommonLoungeCommonLounge

Remember we said all expressions in Python evaluate to a single value? The result of evaluating a variable is simply the value stored inside it. So, the step-by-step breakdown of evaluating the above expression would be:

name * n 
=> 'CommonLounge' * n  <—- Python looks up the value stored in variable "name"
=> 'CommonLounge' * 4  <—- Python looks up the value stored in variable "n"
=> 'CommonLoungeCommonLoungeCommonLoungeCommonLounge'

You can always change the value stored inside the variable:

name = "CommonLounge"
name = "David" # change the value stored in name
print(name)

Output:

David

Note: # denotes a comment in Python. You can write whatever you want after the # and Python will ignore it. Comments can make your code easier for other people to understand. We will look into comments in more detail as last part of this tutorial.

When you store a new value in a variable, the old value gets tossed out. This means we can’t get back to "CommonLounge" again, unless we stored it in some other variable. For example:

x = "CommonLounge"
y = x
print(y)    # CommonLounge
x = "David"
print(x)    # David
print(y)    # CommonLounge

Output:

CommonLounge
David
CommonLounge

Let’s see what’s going in the above code.

  • On line 1, we assign the value "CommonLounge" to variable x.
  • On line 2, when we do y = x, y now has the value "CommonLounge" inside it.
  • On line 3, we print out the value of y to confirm that that is indeed the case.
  • Then in line 4, we updated the value of x to "David", but the value of y remains unchanged.
  • Thus, on lines 5 and 6, our print statements confirm that the values of x and y are as expected.

You can also use a variable to assign value to itself.

name = "CommonLounge"
name = "Hello " + name + "!"
print(name)

Output:

Hello CommonLounge!

On line 2, when you assign a value to the variable name, Python first evaluates the expression on the right. Then sets the variable to point to that value. So, when you do name = "Hello " + name + "!", you are telling Python to evaluate the expression "Hello " + name + "!", and store the result in name.

Here’s another example:

a = 5
a = a * 3
print(a)     # Output: 15
a = a * a
print(a)     # Output: 225

Awesome, right? Let’s dive deeper to understand what’s going on here.

  • On line 2, we multiply a by 3, which assigns it a value of 15.
  • On line 4, we multiply a by itself, which assigns it a value of 15*15, which is 225.

You can use variables in functions too:

name = "David"
print(len(name))
# Output: 5

Here’s the step-by-step breakdown of evaluating the above expression:

len(name)
=> len("David")    <—- Python looks up the value stored in variable "name"
=> 5

But what if we used the wrong name? Can you guess what would happen? Let’s try!

city = "Tokyo"
print(ctiy)

Output:

Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'ctiy' is not defined

An error! As you can see, Python has different types of errors and this one is called a NameError. Python will give you this error if you try to use a variable that hasn’t been defined yet. If you encounter this error later, check your code to see if you’ve mistyped any names.

Play with this for a while and see what you can do!

Variable names

We can name a variable anything we want, such as age, grade, marks etc. However, there are some restrictions:

  • Can only contain alphanumeric characters and underscores (A-Z, 0-9, and ). For example, name, name2, `mynameandmyName` are all allowed.
  • Must start with a letter or the underscore character. (it cannot start with a number). For example, var and var3 are allowed, but 2var is not.
  • Is case-sensitive. For example, age and AGE are two different variables.

Apart from these strict restrictions, here are some other guidelines that are helpful when choosing variable names:

  • In general, people usually use snake case (examples - var, my_age, favorite_number) or camel case (examples - var, myAge, favoriteNumber) when naming variables.
  • Descriptive variable names will make it easier to avoid mistakes, and easier to fix mistakes when you do make them. For example, my_age is a much better variable name than n.

Comments

We briefly looked at comments above. As you already know, comments are lines beginning with a #. You can write whatever you want after the # and Python will ignore it. Comments can make your code easier for other people to understand.

Let’s see how that looks:

# Set the volume to 100
volume = 100
print(volume)

You don’t need to write a comment for every line of code, but they are useful for explaining why your code is doing something, or providing a summary when it’s doing something complex.

Summary

In this last tutorial you learned about:

  • variables – names for objects that allow you to code more easily and to make your code more readable
  • comments — lines that Python won’t run which let you document your code

Excited for the next part? :)

Based on content from https://tutorial.djangogirls.org/en/python_introduction/


© 2016-2022. All rights reserved.