logo

Controlestructuren in Python

De meeste programma's werken niet door een eenvoudige reeks instructies uit te voeren. Er is een code geschreven om het maken van keuzes mogelijk te maken en er kunnen verschillende trajecten door het programma worden gevolgd, afhankelijk van verschuivingen in variabele waarden.

Alle programmeertalen bevatten een vooraf opgenomen set besturingsstructuren die het mogelijk maken deze besturingsstromen uit te voeren, wat het denkbaar maakt.

In deze tutorial wordt onderzocht hoe je lussen en vertakkingen, d.w.z. voorwaarden, aan onze Python-programma's kunt toevoegen.

Soorten controlestructuren

Controlestroom verwijst naar de volgorde die een programma zal volgen tijdens de uitvoering ervan.

Voorwaarden, lussen en aanroepfuncties hebben een aanzienlijke invloed op de manier waarop een Python-programma wordt bestuurd.

Er zijn drie soorten besturingsstructuren in Python:

  • Sequentieel - De standaardwerking van een programma
  • Selectie - Deze structuur wordt gebruikt voor het nemen van beslissingen door het controleren van voorwaarden en vertakkingen
  • Herhaling - Deze structuur wordt gebruikt voor looping, dat wil zeggen het herhaaldelijk uitvoeren van een bepaald stuk van een codeblok.

Sequentieel

Opeenvolgende instructies zijn een reeks instructies waarvan het uitvoeringsproces in een bepaalde volgorde plaatsvindt. Het probleem met opeenvolgende instructies is dat als de logica in een van de regels kapot gaat, de volledige uitvoering van de broncode mislukt.

Code

scanner in java
 # Python program to show how a sequential control structure works # We will initialize some variables # Then operations will be done # And, at last, results will be printed # Execution flow will be the same as the code is written, and there is no hidden flow a = 20 b = 10 c = a - b d = a + b e = a * b print('The result of the subtraction is: ', c) print('The result of the addition is: ', d) print('The result of the multiplication is: ', e) 

Uitgang:

 The result of the subtraction is: 10 The result of the addition is : 30 The result of the multiplication is: 200 

Selectie-/beslissingscontroleverklaringen

De uitspraken die in selectiecontrolestructuren worden gebruikt, worden ook wel vertakkingsverklaringen genoemd of, omdat hun fundamentele rol het nemen van beslissingen is, beslissingscontroleverklaringen.

Een programma kan veel voorwaarden testen met behulp van deze selectie-instructies, en afhankelijk van of de gegeven voorwaarde waar is of niet, kan het verschillende codeblokken uitvoeren.

Er kunnen vele vormen van beslissingscontrolestructuren bestaan. Hier zijn enkele meest gebruikte controlestructuren:

  • Alleen als
  • als-anders
  • De geneste if
  • Het complete als-elif-anders

Simpel als

Als instructies in Python control flow-instructies worden genoemd. De selectie-instructies helpen ons bij het uitvoeren van een bepaald stuk code, maar alleen in bepaalde omstandigheden. Er is slechts één voorwaarde om te testen in een eenvoudige if-instructie.

De fundamentele structuur van de if-instructie is als volgt:

Syntaxis

 if : The code block to be executed if the condition is True 

Deze instructies worden altijd uitgevoerd. Ze maken deel uit van de hoofdcode.

Alle instructies die na de if-instructie zijn ingesprongen, worden uitgevoerd als de voorwaardegever na de if het trefwoord True is. Alleen de code-instructie die altijd zal worden uitgevoerd, ongeacht of de voorwaarde de geschreven instructie is die is uitgelijnd met de hoofdcode. Python gebruikt dit soort inkepingen om een ​​codeblok van een bepaalde control flow-instructie te identificeren. De gespecificeerde controlestructuur zal de stroom van alleen die ingesprongen instructies veranderen.

Hier zijn een paar voorbeelden:

Code

in volgorde
 # Python program to show how a simple if keyword works # Initializing some variables v = 5 t = 4 print(&apos;The initial value of v is&apos;, v, &apos;and that of t is &apos;,t) # Creating a selection control structure if v &gt; t : print(v, &apos;is bigger than &apos;, t) v -= 2 print(&apos;The new value of v is&apos;, v, &apos;and the t is &apos;,t) # Creating the second control structure if v <t : print(v , 'is smaller than ', t) v +="1" print('the new value of is v) # creating the third control structure if t: v, ' and t,', t, are equal') < pre> <p> <strong>Output:</strong> </p> <pre> The initial value of v is 5 and that of t is 4 5 is bigger than 4 The new value of v is 3 and the t is 4 3 is smaller than 4 the new value of v is 4 The value of v, 4 and t, 4, are equal </pre> <h3>if-else</h3> <p>If the condition given in if is False, the if-else block will perform the code t=given in the else block.</p> <p> <strong>Code</strong> </p> <pre> # Python program to show how to use the if-else control structure # Initializing two variables v = 4 t = 5 print(&apos;The value of v is &apos;, v, &apos;and that of t is &apos;, t) # Checking the condition if v &gt; t : print(&apos;v is greater than t&apos;) # Giving the instructions to perform if the if condition is not true else : print(&apos;v is less than t&apos;) </pre> <p> <strong>Output:</strong> </p> <pre> The value of v is 4 and that of t is 5 v is less than t </pre> <h2>Repetition</h2> <p>To repeat a certain set of statements, we use the repetition structure.</p> <p>There are generally two loop statements to implement the repetition structure:</p> <ul> <li>The for loop</li> <li>The while loop</li> </ul> <h3>For Loop</h3> <p>We use a for loop to iterate over an iterable Python sequence. Examples of these data structures are lists, strings, tuples, dictionaries, etc. Under the for loop code block, we write the commands we want to execute repeatedly for each sequence item.</p> <p> <strong>Code</strong> </p> <pre> # Python program to show how to execute a for loop # Creating a sequence. In this case, a list l = [2, 4, 7, 1, 6, 4] # Executing the for loops for i in range(len(l)): print(l[i], end = &apos;, &apos;) print(&apos;
&apos;) for j in range(0,10): print(j, end = &apos;, &apos;) </pre> <p> <strong>Output:</strong> </p> <pre> 2, 4, 7, 1, 6, 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, </pre> <h3>While Loop</h3> <p>While loops are also used to execute a certain code block repeatedly, the difference is that loops continue to work until a given precondition is satisfied. The expression is checked before each execution. Once the condition results in Boolean False, the loop stops the iteration.</p> <p> <strong>Code</strong> </p> <pre> # Python program to show how to execute a while loop b = 9 a = 2 # Starting the while loop # The condition a <b 1 will be checked before each iteration while a < b: print(a, end=" " ) + print('while loop is completed') pre> <p> <strong>Output:</strong> </p> <pre> 2 3 4 5 6 7 8 While loop is completed </pre> <hr></b></pre></t>

als-anders

Als de voorwaarde gegeven in if False is, zal het if-else blok de code t=gegeven uitvoeren in het else blok.

Code

 # Python program to show how to use the if-else control structure # Initializing two variables v = 4 t = 5 print(&apos;The value of v is &apos;, v, &apos;and that of t is &apos;, t) # Checking the condition if v &gt; t : print(&apos;v is greater than t&apos;) # Giving the instructions to perform if the if condition is not true else : print(&apos;v is less than t&apos;) 

Uitgang:

 The value of v is 4 and that of t is 5 v is less than t 

Herhaling

Om een ​​bepaalde reeks uitspraken te herhalen, gebruiken we de herhalingsstructuur.

Er zijn over het algemeen twee lusinstructies om de herhalingsstructuur te implementeren:

  • De for-lus
  • De while-lus

For loop

We gebruiken een for-lus om een ​​iterabele Python-reeks te herhalen. Voorbeelden van deze datastructuren zijn lijsten, strings, tupels, woordenboeken, enz. Onder het for-luscodeblok schrijven we de commando's die we herhaaldelijk willen uitvoeren voor elk reeksitem.

Code

 # Python program to show how to execute a for loop # Creating a sequence. In this case, a list l = [2, 4, 7, 1, 6, 4] # Executing the for loops for i in range(len(l)): print(l[i], end = &apos;, &apos;) print(&apos;
&apos;) for j in range(0,10): print(j, end = &apos;, &apos;) 

Uitgang:

 2, 4, 7, 1, 6, 4, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 

Herhalingslus

Hoewel lussen ook worden gebruikt om een ​​bepaald codeblok herhaaldelijk uit te voeren, is het verschil dat lussen blijven werken totdat aan een bepaalde voorwaarde is voldaan. De expressie wordt vóór elke uitvoering gecontroleerd. Zodra de voorwaarde resulteert in Boolean False, stopt de lus de iteratie.

Code

 # Python program to show how to execute a while loop b = 9 a = 2 # Starting the while loop # The condition a <b 1 will be checked before each iteration while a < b: print(a, end=" " ) + print(\'while loop is completed\') pre> <p> <strong>Output:</strong> </p> <pre> 2 3 4 5 6 7 8 While loop is completed </pre> <hr></b>