• 6 heures
  • Facile

Ce cours est visible gratuitement en ligne.

course.header.alt.is_video

course.header.alt.is_certifying

J'ai tout compris !

Mis à jour le 21/01/2021

Unravel the variable

Connectez-vous ou inscrivez-vous gratuitement pour bénéficier de toutes les fonctionnalités de ce cours !

What is a variable?

At the end of the day, a program's goal is to do something with data, or in other words, the stuff you put into your program. You use variables to manipulate the data. More specifically, a variable is a container used to store a piece of data that your program may need for processing.

Like the video mentioned, think of a variable as a box that contains a value. This box is stored on a shelf within a gigantic warehouse. The location of every box is carefully recorded, just like your computer records the location of your variable in memory.

Boxes stored in a warehouse
Boxes stored in a warehouse

A value is a piece of data you put in a variable. To go back to warehouse analogy, different boxes can store different values. For example, you can use one to store money for ongoing expenditures, and another one to save up for a specific occasion, like going on a trip. You can also empty the boxes or change their content, like adding money to boxes or taking some out.

To know what each box is for, you need to label them.  With programming, it's the same: you assign a name to your variable:

Labeled savings in jars
Labeled savings in jars

The name of a variable should always reflect the meaning of its contents, like when you label boxes. Here are some general recommendations for creating names:

  • Use descriptive names throughout your code
    It may get a bit lengthy! However, descriptive names will benefit you and your team in the long run because they provide better readability and make code maintenance easier. For example, if you want to store gluten free cookies, using a descriptive name such as glutenFreeCookies is much more comprehensive than just cookies or healthyCookies.

  • Spell it out
    Avoid abbreviation or shortening words when possible, even if a shorter version seems obvious. For example, annualRevenue is better than annualRev.

  • Follow a common naming convention
    One of the popular naming conventions is called camel case (also known as camel caps) - a compound phrase that consists of multiple words without spaces or punctuation. The first word is written in lowercase, and all other words are capitalized. For example myBudget.

Create a variable

You must create a variable in code if you are going to use one. Python is completely object-oriented, meaning that every variable is an object. Rather than declaring variables to reserve memory space, they are declared automatically when you assign a value to a variable.

There are several types of variables in Python. Variables containing numbers can be declared by writing the name of a variable and its initial value. For example:

ongoingAllowance = 500
savings = 1000

Here are two declared variables: ongoingAllowance and savings. They store values of 500 and 1000 respectively.

Try it out for yourself!

Console de code
Houston... ?
Il semblerait que votre ordinateur ne soit pas connecté à Internet.
Vous n'êtes pas connecté

Connectez-vous pour accéder aux exercices de codes et testez vos nouvelles compétences.

Pensez à vous entraîner avant de terminer ce chapitre.

Change your variable's value with operators

As its name suggests, a variable may vary, that is, change its value. You can do this by performing a number of operations.  Considering the variables ongoingAllowance and savings from the previous example, you could: 

  • Add more money to your savings.

  • Subtract some from your ongoing allowance.

  • Find out how long it will take to reach $5K if you save $500 every month.

  • Find out how much your spending allowance will be if you contribute $30 to it every day for a week.

  • Find out how much your spending allowance will be if you spend $10 daily.

Real world problems with programming solutions! 💻 Each operation works by applying arithmetic operators, which are:

  • + Addition

  • - Subtraction

  • * Multiplication

  • / Division

Regular arithmetic rules apply! This includes the order of execution! But just like in math, you can use parentheses to decide what happens when. Let's see how you can accomplish this in Python:

# add 100 to our current savings (Yeah!)
savings = savings + 100
# remove 50 from out ongoing allowance (Snif)
ongoingAllowance = ongoingAllowance - 50
# update the number of days we need to saveint
numberOfDaysToSave = (5000 - ongoingAllowance) / 500
# update our ongoing allowance (again)
ongoingAllowance = ongoingAllowance + (30 - 10) * 7

Look at that lovely block of code! You'll notice that the code doesn't all look the same. That's because it's composed of comments and statements:

  • Lines that start with # are comments. They are used to help another person understand the code.

  • Lines of code that do things are called statements. As the name implies, each statement tells the computer to do something.

Here, each of the statements assigns a value to a variable. The assignment operator is =.

  1. On the right of the assignment operator, you write an expression which is a statement that produces a value.

  2. On the left of the assignment operator, you write the name of the variable you want the result to correspond to.

To reiterate, to assign a value to a variable, you write a statement. This statement consists of the name of the variable, followed by the assignment operator, and finally, the expression that produces a value that matches the type of the variable. 

There are also more complex and useful operators such as:

  • %  Modulus: divides and returns the value of the remainder.

  • ** Exponentiation: raises the first number to the power of the second.

  • // Floor division: divides and returns the integer value of the quotient. It dumps the digits after the decimal.

print(savings % 500) # -> 100
# 1100 = 500 * 2 + 100, so 1100 % 500 = the remainder = 100
print(9 ** 3) # -> 729, 9*9*9 = 729
print(savings // 500) # -> 2
# 1100 = 500 * 2 + 100, so 1100 // 500 = integer value of the quotient = 2

Write shorter code with shortcut assignment operators

When you need to change the value of a variable with basic operators and assign it back to that variable, you can use a shorter version! For example, instead of using savings + 100 and the assignment operator =, you can use an assignment operator joined with the arithmetic operator  += :

# spelled out version
savings = savings + 100
# short version
savings += 100

The rest of the short variations are:

  • += Addition

  • -= Subtraction

  • *= Multiplication

  • /= Division

Try it out for yourself!

Console de code
Houston... ?
Il semblerait que votre ordinateur ne soit pas connecté à Internet.
Vous n'êtes pas connecté

Connectez-vous pour accéder aux exercices de codes et testez vos nouvelles compétences.

Pensez à vous entraîner avant de terminer ce chapitre.

Go beyond number arithmetics

In the current example, all the variables store amounts of money, which are numbers.

What other kind of values we can assign to variables?

The good news is that you can store any kind of data in variables! 😀

So far, you've seen that a variable is a value and type with a compound name; however, you don't need to define the variable's type as it depends on the value stored within. Storing money requires a different container from the one needed for a book. In Python, the storage space of a container automatically adapts itself to content: kind of magical, right?

Say you are working on a writing application and need to analyze some text and calculate the following:

  • The number of vowels present in the text. 

  • The percentage of vowels. 

You could break down the process into the following:

  1. Ask user for some text. 🆒

  2. Browse the text supplied by the user; character by character. 🔍

  3. Increase your total every time you find a vowel. ➕

  4. Divide the final number of vowels by the total number of characters in the string to get the percentage.➗

  5. Multiply the result by 100 for the final percentage. ✖️

A screen with lots of small text
Imagine having to do that by hand with this document!

How many variables do you need to implement this? Think about how many individual pieces of information you need to store:

  1. The initial sequence of characters you ask the user for (a string).

  2. The total of the number of vowels in the string.

  3. The percentage of vowels.

It looks like you need three variables! To define each of them, you need the following components:

  1. A name, so you can find the information later.

  2. An initial value, which will give you a starting point, and the type!

In Python, declare your three variables like this:

text = "A wonderful string that consists of multiple characters"
numberOfVowels = 0
percentageOfVowels = 0.0

Notice that you have to use quote delimiters to define a string. Otherwise, it will return an error. However, you can use single or double quote delimiters, like in the following example:

text = "A wonderful string that consists of multiple characters"
# same thing than
text = 'A wonderful string that consists of multiple characters'

Summary

In this chapter, we've covered the basics of variables:

  • A variable is composed of two elements: name and value.

  • Values of variables can be modified.

  • The type of a variable depends of its value.

  • The naming of variables should follow common naming conventions.

In the next chapter, we'll talk about Data types! 💫

Exemple de certificat de réussite
Exemple de certificat de réussite