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.

Join the forum, it's quick and easy

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.
tutorial net
Would you like to react to this message? Create an account in a few clicks or log in to continue.

Go down
avatar
Admin
Admin
Posts : 207
Join date : 2017-11-11
Age : 33
Location : algeria
http://www.tutorial-net.com

tutorial Python - structures Python Empty tutorial Python - structures Python

Sat Mar 31, 2018 10:35 pm
So far, we have tested instructions in a linear way: the interpreter was executing the code you entered in the console. But our programs would be very poor if we could not, from time to time, ask to carry out certain instructions in one case, and other instructions in another case.

In this chapter, I will talk about conditional structures, which will allow you to test and go further in programming.

The conditions allow to execute one or more instructions in one case, other instructions in another case.

You will finish this chapter by creating your first "real" program: even if you do not think you can still do something very consistent, at the end of this chapter you will have enough material to code a small program for a very specific purpose.

Your first conditions and instruction blocks
Minimum form inif
Conditions are an essential concept in programming (yes yes, I repeat myself by force but I must admit that essential concepts, we have not finished seeing). They will allow you to do a specific action if, for example, one variable is positive, another action if that variable is negative, or a third action if the variable is null. As a good example is better than several lines of explanation, here is a clear example of a condition taken in its simplest form.

From now on in my examples, I will use comments. Comments are messages that are ignored by the interpreter and that allow to give indications on the code (because, you will realize, read again its programs after several weeks of abandonment, without comment, it can be sometimes more than 'arduous). In Python, a comment begins with a sharp ("#") and ends with a line break. Everything between this #and this line break is ignored. A comment can thus occupy the whole of a line (one places it at the #beginning of line) or a part only, after an instruction (one places it #after the line of code to comment it more specifically).

That being said, let's go back to our conditions:
>>> # Premier exemple de condition
Code:
>>> a = 5
>>> if a > 0: # Si a est supérieur à 0
...     print("a est supérieur à 0.")
...
a est supérieur à 0.
>>>
Let's detail this code, line by line:

The first line is a comment describing that this is the first condition test. It is ignored by the interpreter and just serves to inform you about the code that will follow.

This line, you should understand it without any help. We just assign the value 5 to the variable a.

Here is our conditional test. It is composed, in order:

the keyword if"if" in English;

the condition itself a > 0, which is easy to read (a list of authorized operators for comparison will be presented below);

of the colon, ":", which ends the condition and is indispensable: Python will display a syntax error if you omit it.

Here is the instruction to execute in the case where ais greater than 0. After you press Entréeat the end of the previous line, the interpreter presents you with the three-point series, which means that it waits for the instruction block to be entered before interpreting it. This instruction (and other instructions to execute if any) is indented, that is, shifted to the right. Further explanation will be given below on the indentations.

The interpreter displays the series of three points again and you can take advantage of it to enter a new statement in this block of instructions. This is not the case at the moment. You therefore press Entréewithout having written anything and the interpreter displays the message "a is greater than 0", which is quite logical since it ais actually greater than 0.

There are two important notions that I must now return to, they are complementary do not worry.

The first is the block of instructions. By instruction block is meant a series of instructions that execute in a specific case (by condition, as we have just seen, by repetition, as will be seen later ...). Here, our block consists of only one instruction (line 4 that uses print). But nothing prevents you from putting multiple instructions in this block.
Code:
a = 5
b = 8
if a > 0:
    # On incrémente la valeur de b
    b += 1
    # On affiche les valeurs des variables
    print("a =",a,"et b =",b)
The second important notion is that of indentation. Indentation means a certain shift to the right, obtained by one (or more) spaces or tabs.

Indentations are essential for Python. It is not, as in other languages ​​such as C ++ or Java, a reading comfort but a means for the interpreter to know where are the beginning and the end of a block.

Complete form ( if, elifand else)
The limits of the simple conditionif
The first form of condition that we have just seen is practical but rather incomplete.

Consider, for example, an ainteger variable . We want to do an action if this variable is positive and a different action if it is negative. It is possible to obtain this result with the simple form of a condition:
Code:
>>> a = 5
>>> if a > 0: # Si a est positif
...    print("a est positif.")
... if a < 0: # a est négatif
...    print("a est négatif.")
Have fun changing the value of aand run the conditions each time; you will get different messages unless it ais 0. Indeed, no action has been scheduled if a is 0.

This method is not optimal, first of all because it forces us to write two separate conditions to test the same variable. Moreover, and even if it is hard to conceive by this example, in the case where the variable would fulfill the two conditions (here it is impossible of course), the two portions of code would execute.

The condition ifis therefore very practical but insufficient.

The instruction else:
The keyword else, which means "otherwise" in English, allows to define a first form of complement to our instruction if.
Code:
>>> age = 21
>>> if age >= 18: # Si age est supérieur ou égal à 18
...    print("Vous êtes majeur.")
... else: # Sinon (age inférieur à 18)
...    print("Vous êtes mineur.")
I think this example is more than enough to expose the use of else. The only subtlety is to realize that Python executes either one or the other, and never both. Note that this statement elsemust be at the same level of indentation as the statement ifit completes. Moreover, it also ends with two points since it is a condition, even if it is implied.

The example of earlier could be as follows, with the use of else:
Code:
>>> a = 5
>>> if a > 0:
...    print("a est supérieur à 0.")
... else:
...    print("a est inférieur ou égal à 0.")
But ... the result is not quite the same, though?

No, indeed. You will realize that this time, the case where is aworth 0is well taken into account. Indeed, the initial condition is to execute the first block of instructions if ais strictly greater than 0. Otherwise, the second instruction block is executed.

If we want to differentiate between positive, negative and null numbers, we will have to use an intermediate condition.

The instruction elif:
The key word elifis a contraction of "else if", which can be very literally translated as "if not". In the example we have just seen, the ideal would be to write:

if it ais strictly superior to 0, we say that it is positive;

if it ais strictly less than 0, we say that it is negative;

if not, ( acan only be equal to 0), then we say that ais null.

Translated into Python language, this gives:
Code:
>>> if a > 0: # Positif
...     print("a est positif.")
... elif a < 0: # Négatif
...     print("a est négatif.")
... else: # Nul
        print("a est nul.")
Have fun changing the value of aand run the conditions each time; you will get different messages unless it ais 0. Indeed, no action has been scheduled if a is 0.

This method is not optimal, first of all because it forces us to write two separate conditions to test the same variable. Moreover, and even if it is hard to conceive by this example, in the case where the variable would fulfill the two conditions (here it is impossible of course), the two portions of code would execute.

The condition ifis therefore very practical but insufficient.

The instruction else:
The keyword else, which means "otherwise" in English, allows to define a first form of complement to our instruction if.
Code:
>>> age = 21
>>> if age >= 18: # Si age est supérieur ou égal à 18
...    print("Vous êtes majeur.")
... else: # Sinon (age inférieur à 18)
...    print("Vous êtes mineur.")
I think this example is more than enough to expose the use of else. The only subtlety is to realize that Python executes either one or the other, and never both. Note that this statement elsemust be at the same level of indentation as the statement ifit completes. Moreover, it also ends with two points since it is a condition, even if it is implied.

The example of earlier could be as follows, with the use of else:

Code:
>>> a = 5
>>> if a > 0:
...    print("a est supérieur à 0.")
... else:
...    print("a est inférieur ou égal à 0.")
But ... the result is not quite the same, though?
No, indeed. You will realize that this time, the case where is aworth 0is well taken into account. Indeed, the initial condition is to execute the first block of instructions if ais strictly greater than 0. Otherwise, the second instruction block is executed.

If we want to differentiate between positive, negative and null numbers, we will have to use an intermediate condition.

The instruction elif:
The key word elifis a contraction of "else if", which can be very literally translated as "if not". In the example we have just seen, the ideal would be to write:

if it ais strictly superior to 0, we say that it is positive;

if it ais strictly less than 0, we say that it is negative;

if not, ( acan only be equal to 0), then we say that ais null.

Translated into Python language, this gives:

Code:
>>> if a > 0: # Positif
...     print("a est positif.")
... elif a < 0: # Négatif
...     print("a est négatif.")
... else: # Nul
        print("a est nul.")
Like the else, the elifis on the same level of indentation as the ifinitial. It also ends with two points. However, between the elifand the two points is a new condition. Linearly, the execution scheme translates as follows:

We look if ais strictly superior to 0. If so, we print "a is positive" and we stop there.

Otherwise, we look if ais strictly less than 0. If this is the case, we print "a is negative" and we stop.

Otherwise, we print "a is null".

Warning: when I say "we stop", it goes without saying that it is only for this condition. If there is code after the three blocks of instructions, it will be executed in all cases.

You can put as many elifas you want after a condition in if. Like else, this instruction is optional and, even though you would build an instruction if, elifyou are not obliged to provide an elseafter. However, the statement elsecan only appear once, closing the block of the condition. Two instructions elsein the same condition are not conceivable and would in any case have no meaning.

Be aware that it is fortunate to nest conditions and, in this case, the indentation makes it possible to clearly understand the execution scheme of the program. I let you try this possibility, I will not do everything for you either. :-)

New operators
Comparison operators
The conditions must necessarily introduce new operators, called comparison operators . I will present them very briefly, leaving you the initiative to do tests because they are really not difficult to understand.
Predicates and Booleans
Before going further, know that the conditions that are, for example, between ifand between the two points are called predicates . You can test these predicates directly in the interpreter to understand the explanations that follow.

>>> a = 0
>>> a == 5
False
>>> a > -8
True
>>> a != 33.19
True
>>>
The interpreter sometimes returns True(that is, "true"), sometimes False(that is, "false").

Trueand Falseare the two possible values ​​of a type that we have not seen so far: the boolean type (bool).

Remember that Trueand Falseare values ​​with their first letter capitalized. If you start writing Truewithout a capital 'T', Python will not understand.

Variables of this type can only take the value of true or false, and can be useful precisely for storing predicates, in the way we have seen or in a more indirect way.

>>> age = 21
>>> majeur = False
>>> if age >= 18:
>>>     majeur = True
>>>
At the end of this example, major is true True, that is , true, if the age is greater than or equal to 18. Otherwise, it continues to be valid False. Booleans may not seem to you very useful at the moment but you will see that they render great services!

Keywords and, orandnot
It often happens that our conditions must test several predicates, for example when we try to check if any variable, of integer type, is in a precise interval (that is to say between two numbers). With our current methods, the simplest way would be to write:

# On fait un test pour savoir si a est comprise dans l'intervalle allant de 2 à 8 inclus
a = 5
if a >= 2:
   if a <= 8:
       print("a est dans l'intervalle.")
   else:
       print("a n'est pas dans l'intervalle.")
else:
   print("a n'est pas dans l'intervalle.")
It works but it is quite heavy, especially since, to be sure that a message is displayed each time, it is necessary to close each of the two conditions using a else(the second being nested in the first) . If you have trouble understanding this example, take the time to unravel it, line by line, there is nothing complicated.

There is however the key word and(which means "and" in English) which will make us here a proud service. Indeed, we try to test both if ais greater than or equal to 2 and less than or equal to 8. We can thus reduce the nested conditions:

if a>=2 and a<=8:
   print("a est dans l'intervalle.")
else:
   print("a n'est pas dans l'intervalle.")
Simple and much more understandable, admit it.

In the same mode, there is the key word orwhich means this time "or". We will take the same example, except that we will evaluate our condition differently.

We will try to find out if ais not in the meantime. The variable is not in the range if it is less than 2 or greater than 8. Here is the code:

if a<2 or a>8:
   print("a n'est pas dans l'intervalle.")
else:
   print("a est dans l'intervalle.")
Finally, there is the key word notthat "reverses" a predicate. The predicate not a==5is therefore equivalent to a!=5.

notmakes the syntax clearer. For this example, I add to the list a new keyword, iswhich tests the equality not of the values ​​of two variables, but of their references. I will not go into detail about this mechanism before long. You only need to know that for integers, floats and booleans, it's strictly the same thing. But to test an equality between variables whose type is more complex, prefer the operator "==". Let's go back to this demonstration:

>>> majeur = False
>>> if majeur is not True:
...     print("Vous n'êtes pas encore majeur.")
...
Vous n'êtes pas encore majeur.
>>>
If you speak a minimum of English, this predicate is crystal clear and unparalleled in simplicity.

You can test more complex predicates in the same way as the previous ones, by typing them directly, without the ifcolon, into the shell. You can use opening and closing parentheses to frame predicates and compare them according to specific priorities (we'll see this later if you do not understand the usefulness).

Your first program!
What are we playing?

The time of the first TP has come. As this is the very first, and because there are some indications that I must give you so that you reach the end, I will accompany you step by step in its realization.

Before you start
You are going in this section to write your first program. You will surely test the syntax directly in the shell.

You might prefer to write your code directly to a file that you can then execute. If so, I refer you to the chapter dealing with this point in this course .

Subject
The purpose of our program is to determine if a year entered by the user is leap. This is a very popular subject of computer science teachers when it comes to explaining the conditions. A thousand pardons, therefore, to those who have already done this exercise in another language but I think this small program takes enough topics in this chapter to be really interesting.

I remind you of the rules that determine whether a year is leap or not (you may even learn things that ordinary people do not know).

A leap year is a multiple of 4, unless it is a multiple of 100. However, it is considered leap if it is a multiple of 400. I develop:

If a year is not multiple of 4, we stop there, it is not leap.

If it is multiple of 4, we look if it is multiple of 100.

If so, we look at whether it is multiple of 400.

If so, the year is leap year.

Otherwise, she is not leap.

Otherwise, it is leap.

Solution or resolution
Here. The problem is clearly stated (if not carefully reread the statement as many times as necessary), we must now think about its resolution in terms of programming. It is a rather delicate phase of transition at first glance and I advise you to schematize the problem, to take notes on the different stages, without for now thinking about the code. It is a purely algorithmic phase, in other words, we think about the program without thinking about the code itself.

You will need, to realize this small program, some indications which are really specific to Python. Do not read this until you have identified and clearly written the problem in a more algorithmic way. That being said, if you struggle to find a solution, do not dwell on it. This phase of reflection is quite difficult at the beginning and sometimes it takes a little practice and explanations to understand the basics.

Functioninput()
First, I mentioned a year entered by the user. Indeed, since just now, we test variables that we declare ourselves, with a precise value. The condition is therefore ridiculous.

input()is a function that will, for us, characterize our first interactions with the user: the program will react differently according to the number entered by the user.

input()accepts an optional parameter: the message to display to the user. This instruction interrupts the program and waits for the user to type in what he wants and press Entrée. At this point, the function returns what the user has entered. It is necessary to trap this value in a variable.

>>> # Test de la fonction input
>>> annee = input("Saisissez une année : ")
Saisissez une année : 2009
>>> print(annee)
'2009'
>>>
There is still a problem: the type of the variable anneeafter the call to input()is ... a string of characters. You can see this with quotes that enclose the value of the variable when you display it directly in the interpreter.

It's really boring: we who wanted to work on an integer, we will have to convert this variable. To convert a variable to another type, you have to use the name of the type as a function (that's exactly what it is).

>>> type(annee)
<type 'str'>
>>> # On veut convertir la variable en un entier, on utilise
>>> # donc la fonction int qui prend en paramètre la variable
>>> # d'origine
>>> annee = int(annee)
>>> type(annee)
<type 'int'>
>>> print(annee)
2009
>>>
Good, perfect! We now have the year in its whole form. Note that if you enter letters when calling input(), the conversion will return an error.

The call to function int()may have puzzled some. We pass in parameter of this function the variable containing the string of characters from input(), to try to convert it. The function int()returns the value converted to an integer and thus retrieves it in the same variable. This avoids working on several variables, knowing that the former is no longer useful now that it has been converted.

Multiple test
Some might also ask how to test if a number a is multiple of a number b. It suffices, in fact, to test the remainder of the entire division of b by a. If this remainder is zero, then a is a multiple of b.

>>> 5 % 2 # 5 n'est pas un multiple de 2
1
>>> 8 % 2 # 8 est un multiple de 2
0
>>>
It's your turn
I think I gave you all the necessary elements to succeed. In my opinion, the most difficult part is the reflection phase that precedes the composition of the program. If you have trouble doing this, go to the correction and study it carefully. Otherwise, we are in the next section.

Good luck !

Correction
It's time to compare our methods and, before you disclose the code of my solution, I tell you that it is far from the only possible. You may have found something different but that works just as well.

Attention ... the message ...

# Programme testant si une année, saisie par l'utilisateur,
# est bissextile ou non

annee = input("Saisissez une année : ") # On attend que l'utilisateur saisisse l'année qu'il désire tester
annee = int(annee) # Risque d'erreur si l'utilisateur n'a pas saisi un nombre
bissextile = False # On crée un booléen qui vaut vrai ou faux
                  # selon que l'année est bissextile ou non

if annee % 400 == 0:
   bissextile = True
elif annee % 100 == 0:
   bissextile = False
elif annee % 4 == 0:
   bissextile = True
else:
   bissextile = False

if bissextile: # Si l'année est bissextile
   print("L'année saisie est bissextile.")
else:
   print("L'année saisie n'est pas bissextile.")
I remind you that you can save your codes in files in order to execute them. I refer you to the chapter on writing Python code in files for more information.

I think the code is pretty clear, remains to clarify the sequence of conditions. You will notice that we reversed the problem. We test first if the year is a multiple of 400, then if it is a multiple of 100, and finally if it is a multiple of 4. Indeed, the elifguarantee that, if anneeis a multiple of 100, it is not a multiple of 400 (because the case was treated above). In this way, we make sure that all cases are managed. You can experiment with several years and find out if the program is right or not.

Using it bissextileas a full-fledged predicate may be confusing to you. It's actually quite possible and logical, since it's bissextilea boolean. It is therefore true or false and therefore it can be tested simply. One can of course also write if bissextile==True:, it comes down to the same thing.

A bit of optimization
What we did was good but we can improve it. Besides, you will realize that it is almost always the case. Here, it is of course our condition, which I will sift to build a shorter and more logical, if possible. We can speak of optimization in this case, even if the optimization also integrates and especially the resources consumed by your application, in order to reduce these resources and improve the speed of application. But, for a small application like this one, I do not think we'll waste time on optimizing the execution time.

The first detail you might have noticed is that the elseend is useless. Indeed, the variable bissextileis by default Falseand thus preserves this value if the case is not treated (here, when the year is neither a multiple of 400, nor a multiple of 100, nor a multiple of 4).

Then, it appears that we can do a great cleaning in our condition because the only two cases corresponding to a leap year are "if the year is a multiple of 400" or "if the year is a multiple of 4 but not 100 ".

The corresponding predicate is a bit tricky, it makes use of parentheses priorities. I did not expect you to find it alone, but I hope you understand it now.

# Programme testant si une année, saisie par l'utilisateur, est bissextile ou non

annee = input("Saisissez une année : ") # On attend que l'utilisateur saisisse l'année qu'il désire tester
annee = int(annee) # Risque d'erreur si l'utilisateur n'a pas saisi un nombre

if annee % 400 == 0 or (annee % 4 == 0 and annee % 100 != 0):
   print("L'année saisie est bissextile.")
else:
   print("L'année saisie n'est pas bissextile.")
So, we do not need the variable bissextile, it's already won. We went from 16 lines of code to only 7 (not counting comments and line breaks) which is not nothing.

In summary
The conditions allow to execute certain instructions in some cases, other instructions in another case.

The conditions are marked by the keywords if("if"), elif("if not") and else("otherwise").

The keywords ifand elifmust be followed by a test (also called predicate).

Booleans are either true ( True) or false ( False) data.
Back to top
Permissions in this forum:
You cannot reply to topics in this forum