tutorial net
*********WOOOOOOW *********
We're happy to see you're enjoying our races (already 5 pages viewed today)! You can keep checking out by becoming a member of the tutorial net community. It's free!
You will also be able to keep track of your race progress, practice on exercises, and chat with other members.

Go down
Posts : 207
Join date : 2017-11-11
Age : 28
Location : algeria
View user profilehttp://www.tutorial-net.com

tutorial Python - variables of Python

on Fri Mar 30, 2018 11:31 am
In the previous chapter, you entered your first instructions in Python, although you may not have noticed. It is also true that the instructions entered would have worked in most languages. Here, however, we will begin to delve a little deeper into the syntax of the language, while discovering an important concept of programming: the variables.

This concept is essential and you absolutely can not ignore it. But I assure you, there is nothing complicated, only useful and pleasant.

What is a variable? And what is it for?
Variables are one of the concepts found in the majority (and even, in this case, all) of programming languages. In other words, without a variable, you can not program, and that's not an exaggeration.

What is a variable?
A variable is a piece of data from your program, stored on your computer. It is an alpha-numeric code that you will link to a data of your program, so you can use it several times and make calculations a little more interesting with. It's nice to know how to do operations, but if you can not store the result somewhere, it quickly becomes boring.

See the memory of your computer as a big cabinet with lots of drawers. Each drawer may contain data; some of these data will be variables of your program.

How does it work?
The simplest in the world. You will say to Python: "I want that, in a variable that I name age, you store my age, so that I can retain it (if I have very short memory), increase it (on my birthday) and 'show if needed'.

As I told you, we can not miss the variables. You may not yet see the value of storing program information, yet if you do not store anything, you can do virtually nothing.

In Python, to give a value to a variable, just write nom_de_la_variable = valeur.

A variable must respect some unavoidable syntax rules:

The name of the variable can only be composed of uppercase or lowercase letters, digits and the underlined symbol "_" (called underscore ).

The name of the variable can not start with a number.

The Python language is case-sensitive, which means that upper and lower case letters are not the same variable (the variable AGEis different from aGe, itself different from age).

Beyond these unavoidable syntax rules, there are conventions defined by the programmers themselves. One of them, which I tend to use quite often, is to write the variable in lowercase and to replace any spaces with an underlined space "_". If I have to create a variable containing my age, it will be named mon_age. Another convention used is to capitalize the first character of each word, with the exception of the first word constituting the variable. The variable containing my age would be named then monAge.

You can use the convention you like, or even create a good one for yourself, but try to stay consistent and use only one writing convention. Indeed, it is essential to be able to find your variables as soon as you start working on large programs.

So, if I want to associate my age with a variable, the syntax will be:
mon_age = 21
The interpreter immediately displays three chevrons without any message. That means he understood and there was no mistake.

Be aware that this step is called assigning value to a variable (sometimes shortened to "variable assignment"). It is said that the value 21 has been assigned to the variable mon_age.

The value of this variable can be displayed simply by entering it in the shell.
>>> mon_age
The spaces separating "=" from the name and value of the variable are optional. I put them for readability reasons.

Well, that's fine, but what do we do with this variable?

Well, all you have done in the previous chapter, but this time using the variable as a full number. You can even assign to other variables values ​​obtained by performing calculations on the first and this is the power of this mechanism.

For example, try to increase the variable by 2 mon_age.
>>> mon_age = mon_age + 2
>>> mon_age
Again, when assigning the value, nothing is displayed, which is perfectly normal.

Now, let's try to assign a value to another variable based on the value of mon_age.
>>> mon_age_x2 = mon_age * 2
>>> mon_age_x2
Once again, I invite you to test this possibility in length, across and across. The concept is not complicated but extremely powerful. In addition, compared to some languages, assigning a value to a variable is extremely simple. If the variable is not created, Python will do it automatically. If the variable already exists, the old value is deleted and replaced by the new one. What could be simpler ?

Some Python keywords are reserved , that is, you can not create variables with this name.

Here is the list for Python 3:

































These keywords are used by Python, you can not build variables with these names. You will discover in the rest of this course the majority of these keywords and how they are used.

Python data types
Here lies a very important concept, found in many programming languages. Open your ears, or rather your eyes, because you will have to be perfectly comfortable with this concept to continue reading this book. Rest assured, however, as long as you are attentive, there is nothing complicated to understand.

What is "data type"?
So far you have only worked with numbers. And, if we must admit that we will very rarely do a program without any number, it is far from the only data that can be used in Python. Eventually, you will even be able to create your own data types, but do not anticipate.

Python needs to know what types of data are used to know what operations it can perform with. In this chapter, you will learn how to work with strings, and multiplying a string of characters is not at all like multiplying a number. For some types of data, multiplication does not make sense. Python associates with each datum a type, which will define the operations allowed on this datum in particular.

The different types of data
We are going to see here only the inevitable and the easiest to handle. Whole chapters will be devoted to more complex types.

Whole numbers
And yes, Python differentiates integers from floating point numbers!

Why that ?

Initially, it is mainly for a question of place in memory but, for a computer, the operations that one carries out on numbers with comma are not the same ones as those on the integers, and this distinction remains still of actuality Nowadays.

The integer type is named intin Python (which corresponds to the English "integer", that is to say integer). The form of an integer is a number without a comma.

We have seen in the previous chapter the operations that could be performed on this type of data and, even if you do not remember, the guessing is quite basic.

Floating numbers
Floats are the decimal numbers. They are called floatPython (which means "floating" in English). The floating-point syntax is that of a floating-point number (remember to replace the comma with a dot). If this number does not have a floating part but you want it to be considered by the system as a floating point, you can add a floating part of 0 (example 52.0 ).

The numbers after the comma are not infinite, since nothing is infinite in computing. But precision is important enough to work on very fine data.

Fortunately, the types of data available in Python are not limited to numbers alone, far from it. The last "simple" type that we will see in this chapter is the string. This type of data can store a series of letters, why not a sentence.

We can write a string of characters in different ways:

in quotation marks ( "ceci est une chaîne de caractères");

between single quotes ( 'ceci est une chaîne de caractères');

between triple quotation marks ( """ceci est une chaîne de caractères""").

Like numbers (and all types of data), we can store a string in a variable ( ma_chaine = "Bonjour, la foule !")

If you use simple delimiters (the quotation mark or the apostrophe) to enclose a string, there is the problem of quotation marks or quotation marks that can contain this string. For example, if you type chaine = 'J'aime le Python!', you get the following message:
File "<stdin>", line 1
chain = 'I love Python!'
SyntaxError: invalid syntax
This is because the "I like" apostrophe is considered by Python as the end of the chain and does not know what to do with anything beyond it.
To overcome this problem, we must escape the apostrophes in the heart of the chain. This inserts an anti-slash character "\" before the apostrophes contained in the message.
chaine = 'J\'aime le Python!'
We must also escape the quotation marks if we use quotation marks as delimiters.
chaine2 = "\"Le seul individu formé, c'est celui qui a appris comment apprendre (...)\" (Karl Rogers, 1976)"
The escape character "\" is used to create other very useful signs. Thus, "\ n" symbolizes a line break ( "essai\nsur\nplusieurs\nlignes"). To write a true anti-slash in a chain, you have to escape it yourself (and thus write "\\").

The interpreter displays line breaks as you type them, that is, as "\ n". We will see in the next part how to actually display these strings and why the interpreter does not display them as it should.

Using triple quotation marks to enclose a string of characters avoids escaping quotation marks and quotes, and allows you to write multiple lines without symbolizing line breaks using "\ n".
>>> chaine3 = """Ceci est un nouvel
... essai sur plusieurs
... lignes"""
Note that the three chevrons are replaced by three points: this means that the interpreter considers that you have not finished writing this instruction. Indeed, this one ends only once the chain closed with three new quotation marks. Line breaks will be automatically replaced in the string by "\ n".

You can use three quotation marks instead of the three quotation marks that play exactly the same role. I do not personally use these delimiters, but be aware that they exist and do not be surprised if you see them one day in a source code.

Here we have completed the quick overview of simple types. Qualifying simple type strings is not strictly true, but in this chapter we will not go into the details of the operations that can be performed on these strings. It is useless for the moment and it would be off topic. However, nothing prevents you from testing yourself some operations such as addition and multiplication (in the worst case, Python will tell you that he can not do what you ask him and, as we have seen, he is not very spiteful).

A small bonus
In the previous chapter, we saw the "classical" operators for manipulating numbers but also, as we will see later, other types of data. Other operators have been created to simplify the manipulation of variables.

You will be brought thereafter, and quite regularly, to increment variables. Incrementation refers to increasing the value of a variable by a number. So far, I proceed as below to increase a variable of 1:
variable = variable + 1
This syntax is clear and intuitive but long enough, and programmers, everyone knows, are born slackers. So we found it shorter.
variable += 1
This syntax is clear and intuitive but long enough, and programmers, everyone knows, are born slackers. So we found it shorter.
The operator +=returns to add to the variable the value that follows the operator. The operators - =, * = and / = also exist, although they are less used.

Some tips and tricks to make your life easier
Python offers a simple way to swap two variables (exchange their value). In other languages, it is necessary to pass by a third variable which retains one of the two values ​​... here it is much simpler:
>>> a = 5
>>> b = 32
>>> a,b = b,a # permutation
>>> a
>>> b
As you see, after running line 3, the variables aand bexchanged their values. This distribution of assignment will be found much further.

We can also quite simply assign the same value to several variables:
>>> x = y = 3
>>> x
>>> y
Finally, it is not yet relevant for you but know that you can cut a Python instruction to write on two lines or more.
>>> 1 + 4 - 3 * 19 + 33 - 45 * 2 + (8 - 3) \
... -6 + 23.5
As you can see, the "\" symbol allows, before a line break, to tell Python that "this instruction continues on the next line". You can break up your instruction on several lines.

First use of functions
Well, all of this is progressing nicely. I therefore allow myself to introduce here, in this chapter on variables, the use of functions. Ultimately, this is more of a concrete application of what you have learned at the moment. An entire chapter will be devoted to functions, but using the ones I'm going to show you is not rocket science and can be useful.

Use a function
What are the functions for?

A function executes a number of already saved instructions. Basically, it's like recording a group of instructions to do a specific action and giving it a name. You then only have to call this function by name as many times as necessary (this avoids many repetitions). But we will see all this in more detail later.

Most functions need at least one parameter to work on a given data; these settings are information that you pass to the function so that it works on it. The functions I'm going to show you are no exception. This concept may seem a little difficult to grasp as a whole but rest assured, the examples should make everything crystal clear.

The functions are used in the following syntax: nom_de_la_fonction(parametre_1,parametre_2,…,parametre_n).

You start by writing the name of the function.

You enclose the parameters of the function in parentheses. If the function does not expect any parameters, you will still have to put the parentheses, without anything between them.

The "type" function
In the previous part, I introduced you to the simple data types, at least some of them. One of the great powers of Python is that it automatically understands what type is a variable and that when it is assigned. But it is convenient to know which type is a variable.
Back to top
Permissions in this forum:
You cannot reply to topics in this forum