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 - Buckles Python

on Sun Apr 01, 2018 9:59 am
Loops are a new concept for you. They will allow you to repeat a certain operation as many times as necessary. The concept may seem a little theoretical because the practical applications presented in this chapter will probably not seem very interesting. However, it is imperative that this notion be understood before you move on. The moment will come when you will have trouble writing a loopless application.

In addition, the loops can be used to browse certain sequences such as character strings to, for example, extract each character.

So, we start?
What is it?
The while loop
The for loop
As I said before, we find the instruction whilein most other languages. In C ++ or Java, we also find instructions forbut do not have the same meaning. It is quite particular and this is the point on which I may miss examples in the immediate future, all its usefulness being revealed in the chapter on the lists. Note that if you did a Perl or PHP, you can find loops forin a fairly close keyword: foreach.

The instruction forworks on sequences. It is actually specialized in the course of a sequence of several data. We have not seen (and we will not see immediately) these rather particular but very widespread sequences, even if they can be complex. However, there is one type we have encountered for some time now: strings.

Strings are sequences ... of characters! You can browse a string (which is also possible with whilebut we will see later how). For now, let's look at for.

The instruction foris constructed as follows:
for element in sequence:
elementis a variable created by the for, it's not up to you to instantiate it. It successively takes each of the values ​​appearing in the sequence traversed.

It's not very clear ? So, as usual, everything is illuminated with the code!

chaine = "Bonjour les ZER0S"
for lettre in chaine:
Which gives us the following result:

Is that clearer ? In fact, the variable lettresuccessively takes the value of each letter contained in the character string (first B, then o, then n ...). These values ​​are displayed with printand this function returns to the line after each message, so that all the letters are on a single column. Literally, line 2 means "for letter in chain" . Arrived at this line, the interpreter will create a variable lettrewhich will contain the first element of the chain (in other words, the first letter). After the block is executed, the variable lettrecontains the second letter, and so on as long as there is a letter in the string.

Note that, suddenly, it is useless to increment the variable lettre(which would be quite ridiculous as it is not a number). Python takes care of incrementing, that's one of the great benefits of instruction for.

Like the conditions we have seen so far, incan be used elsewhere than in a loop for.
chaine = "Bonjour les ZER0S"
for lettre in chaine:
    if lettre in "AEIOUYaeiouy": # lettre est une voyelle
    else: # lettre est une consonne... ou plus exactement, lettre n'est pas une voyelle
… Which give :

Here ! The interpreter displays the letters if they are vowels and, otherwise, it displays "*". Note that the 0 is not displayed at the end, Python does not doubt that it is a stylized "o".

Remember this use of inin a condition. One tries to know if any element is contained in a given collection (here, if the letter is contained in "AEIOUYaeiouy", that is to say if lettreis a vowel). We will find further this feature.

A small bonus: the keywords break and continue
I am going to show you two new keywords, breakand continue. You may not use them a lot, but you should know at least that they exist ... and what they are for.

The keywordbreak
The keyword breaksimply allows to interrupt a loop. It is often used in a form of loop that I do not approve too much:
while 1: # 1 est toujours vrai -> boucle infinie
    lettre = input("Tapez 'Q' pour quitter : ")
    if lettre == "Q":
        print("Fin de la boucle")
The whilecondition of the loop 1is a condition that will always be true. In other words, looking at the line of the while, one thinks of an infinite loop. In practice, the user is asked to type a letter (a 'Q' to quit). As long as the user does not enter this letter, the program asks him again to type a letter. When he types 'Q', the program displays Fin de la boucleand the loop stops with the keyword break.

This keyword allows to stop a loop whatever the condition of the loop. Python immediately exits the loop and executes the code that follows the loop, if any.

This is a simplistic example but you can see the whole idea. In this case and, in my opinion, in most cases where breakis used, we could get away by specifying a true condition to the line of while. For example, why not create a boolean that will be true throughout the loop and false when the loop has to stop? Or to test directly if lettre != « Q »in the while?

Sometimes, breakis really useful and saves time. But do not use it excessively, prefer a loop with a clear condition rather than a block of instructions with one break, which will be harder to grasp at a glance.

The keywordcontinue
The keyword continueallows to ... continue a loop, starting directly at the line of whileor for. A small example is needed, I think:
i = 1
while i < 20: # Tant que i est inférieure à 20
    if i % 3 == 0:
        i += 4 # On ajoute 4 à i
        print("On incrémente i de 4. i est maintenant égale à", i)
        continue # On retourne au while sans exécuter les autres lignes
    print("La variable i =", i)
    i += 1 # Dans le cas classique on ajoute juste 1 à i
Here is the result :
La variable i = 1
La variable i = 2
On incrémente i de 4. i est maintenant égale à 7
La variable i = 7
La variable i = 8
On incrémente i de 4. i est maintenant égale à 13
La variable i = 13
La variable i = 14
On incrémente i de 4. i est maintenant égale à 19
La variable i = 19
As you can see, every three rounds of loop, iincrements by 4. When you reach the keyword continue, Python does not execute the end of the block but returns to the beginning of the loop by testing the condition again while. In other words, when Python arrives at line 6, it jumps to line 2 without executing lines 7 and 8. At the new loop turn, Python resumes the normal execution of the loop ( continueignoring the end of the block only for the current loop tour).

My example does not vividly demonstrate the utility of continue. The few times I use this keyword is, for example, to remove items from a list, but we have not seen the lists yet. The bottom line is that you remember these two keywords and know what they do, if you meet them at the end of an instruction. Personally, I do not use these keywords very often but it is also a matter of taste.
Back to top
Permissions in this forum:
You cannot reply to topics in this forum