Variables in Python

In the previous tutorial, we talked about data types, where we emphasize the study of numbers, strings and booleans.

Now let's see where and how we store this data by studying the variables in Python.



Storing data in memory

When you turn on your computer and open your email or Facebook, it probably already logs in directly. But how do they know what your account is? Your email and password?

Simple: this information was stored somewhere.

Do you have a music application on your phone or radio in the car?
If you turn off a day and have a Rush song at 21mins and 12s, when you turn it back on, it will open in that song, at that time of the song.

Magic? Witchcraft? Luck?
Obviously not, that information was stored somewhere.

What about the shopping cart of the sites?
You go in, choose some Python books to buy ... give up buying.
When I get back on the site, there will still be options I wanted.

How does this happen?
Surely this was stored somewhere, this information. Do you agree?

This is where the variables come in.


Variable in Python

The way in which we will store information, data, through Python programming, is using variables.

Variable is nothing more than a name that we will give to a particular block of memory. When the computer wants to save, for example, the IP number of a user in the 0xH2112 memory block, it is too bad for a human (programmer), having to be using those numbers, are difficult to decorate and manipulate.

Instead, we create a variable, for example, named 'user', and ready, whenever we want to use this data, we use the variable 'ip_user', instead of having to directly use the memory block where that data is stored .

A little theoretical, is not it? Let's stop chatting and go to practice.

How to use variables in Python

To create a variable in Python, we simply have to make an assignment statement.

Let's create, for example, a variable that will store a number, its age, for example. Her name is going to be 'age' (wow, that's original).

Let's declare this variable (say to Python: 'hey, call it a variable, okay?') And let's assign it a value, in this case a positive integer.

If you are 18 and want to assign this value to a variable called 'age', just do:

  • age = 18


Yes, that's all. Python will understand that 'age' is a variable, it's something that you programmer has created. It will allocate (reserve) a space in the memory (a space located in the address 0xFFF4h, for example), and there will save the value 18 there.

Whenever you want to print that age, use it in a program to know if you can drive, if you can vote etc etc, do not need to decorate memory address 0xFFF4h, just use the variable 'age', it will automatically be a reference to that address memory.



Printing variables on screen

Let's create a variable that, this time, store a string.
This variable will be called 'text', and we will put there the string 'Progressive Python Course'.

Just do this in our Python code:

text='Progressive Python Course' 

If you write that line and run it, it seems like nothing happens. But it happens: Python will store a memory space and there will save the message Python Progressive Course, then it will end the program, because that's all your code does.

It's not because nothing appeared on the screen that nothing happened. It happened, but behind the scenes, okay?

But as we said before, the print function serves to print (display) something (text, number, boolean etc) on the screen. But the 'text' variable stores a string ...

... then, to print it, just program the following code:

text='Progressive Python Coourse'
print(texto)

Here's how the code is (top window) and the result in the Python interpreter (bottom window):

Variables tutorial in Python

Printing more than one variables

The Python print function is much more powerful and versatile than we have ever studied.
We can, for example, print more than one data in the same command, just separate by comma.

The following program stores your age in one variable and your name in another. Then it prints everything in the same violent print:

name='Maria Joaquina de Amaral Pereira Goes'
age=18
print(name,age)

Do and see the result.

Note that the variable age stores a number, not a string, but the print function shows it the same way.
However, everything went in the same line, a name and a number.

It got a little ugly, let's beautify a little.
Type and run the following code:

age=18
name='Maria Joaquina de Amaral Pereira Goes'
print('Name:', name)
print('Age:', age)

Aaaaah! Now yes! Seriously, it was very cute and very tidy the result, see:

Python tutorial for download

Exercises using variables in Python

Exercise 01:

Create a program that displays your full name, city, state, and date of birth.

For each such data, create an appropriate variable. Use names that make sense ('city', 'state' etc, nothing to be creating variables with names 'a', 'b', 'x' or 'y' - this is a bad habit among programmers).

Show everything on the screen, cute and organized.

Exercise 02:

Create a program that displays on the screen the text 'The best band in the world is [name of the band] and the best song is [name of the song]'.

The band name and song name must be declared in two different variables.
The output should look like this:

Python course free

PS: If there is any problem with running the code, it may be a problem to display some characters like 'is' and 'รบ' for music.

To resolve this problem, add the following code at the beginning of your script:

#encoding: utf-8

Changing variables values

Do you know why it's called a variable?
Because it varies.

How to learn to program in Python

In fact, it is extremely normal for variables to change in value over the course of a program.
Let's give an example now using decimal number.

Initially, let's give the value '0.0' for a variable, then change to 5000.00 for example:

salary=0.0
print('Before I was a programmer, I earned $',salary,'in a month')

salary=5000.0
print('Now I am a Python programmer and earn $',salary)

The script will always print the value that is in the memory address pointed to by the 'wage' variable.
Initially, in the memory, the value 0.0 is stored, so the first print prints 0.0

Then we changed the value there from memory to 5000.0

The value 0.0 was already, changed, lost, now has recorded five thousand there in the memory block, and how the variable 'salary' points to that address, will print what is there, and now prints 5000.0

Perfectly logical and simple, is not it?
This is called reassigning value to a variable.

Rules for declaring a variable

You do not chooses any name for a variable.
Some words are said 'reserved', because they are of use of the language, which are:

['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']

Other rules for declaring a variable:

  • Must start with letter or underscore _ (underline)
  • After the first character, you can use digits
  • Upper case is different from lowercase: variable 'python_progressive' is different from 'Python_Progressive' variable, changed any character between uppercase and lowercase, change everything. 'test' is one thing and 'Test' is another, beware of this!


Another important tip, which is not rule, but shows that you are a good Python programmer, is to use variables that make sense.

If you are contracted to make the DMV system, use variables of name 'car', 'speed', 'register', 'validity' instead of 'a', 'b', 'c' ... because only to look at the first name, you understand what kind of information it is storing.

At first, this may seem pointless. But as you create larger and more complex programs, hundreds of lines of code or more, this is essential, it's a so-called good programming practice.

It is common for variable names to have more than one word:
pythonprogressive

But sometimes it's bad to read. Some things facilitate such as:
python_progressive

Or the camelCase, which is to use the first letter of the first lowercase word, and the first letter of the next uppercase words:
coursePythonProgressive

Easy to read, is not it?

Exercise: The following code prints all Python keywords, run it and write in the comments the result:


import keyword
print(keyword.kwlist)

No comments:

Post a Comment