Python While Loop-vejledning - Mens ægte syntakseksempler og uendelige sløjfer

Velkommen! Hvis du vil lære at arbejde med mens sløjfer i Python, så er denne artikel noget for dig.

Mens sløjfer er meget kraftige programmeringsstrukturer, som du kan bruge i dine programmer til at gentage en række udsagn.

I denne artikel lærer du:

  • Hvad mens sløjfer er.
  • Hvad de bruges til.
  • Hvornår de skal bruges.
  • Hvordan de fungerer bag kulisserne.
  • Hvordan man skriver en while-loop i Python.
  • Hvad uendelige sløjfer er, og hvordan man afbryder dem.
  • Hvad while Truebruges til og dens generelle syntaks.
  • Sådan bruges en breakerklæring til at stoppe et stykke løb.

Du lærer hvordan sløjfer arbejder bag kulisserne med eksempler, tabeller og diagrammer.

Er du klar? Lad os begynde. ?

? Formål og brug sager til mens sløjfer

Lad os starte med formålet med mens sløjfer. Hvad bruges de til?

De bruges til at gentage en række udsagn et ukendt antal gange. Denne type sløjfe kører, mens en given tilstand er, Trueog den stopper kun, når tilstanden bliver False.

Når vi skriver en while-loop, definerer vi ikke eksplicit, hvor mange iterationer, der skal gennemføres, vi skriver kun den betingelse, der skal være for Trueat fortsætte processen og Falsestoppe den.

Tip: Hvis tilstanden mens løkke aldrig evalueres til False, vil vi have en uendelig løkke, som er en løkke, der aldrig stopper (i teorien) uden ekstern indgriben.

Dette er nogle eksempler på reelle brugstilfælde af mens sløjfer:

  • Brugerinput: Når vi beder om brugerinput, skal vi kontrollere, om den indtastede værdi er gyldig. Vi kan umuligt vide på forhånd, hvor mange gange brugeren vil indtaste et ugyldigt input, før programmet kan fortsætte. Derfor vil en stund-løkke være perfekt til dette scenario.
  • Søgning: at søge efter et element i en datastruktur er en anden perfekt brugssag i et stykke tid, fordi vi ikke på forhånd kan vide, hvor mange iterationer der er behov for for at finde målværdien. For eksempel kan binær søgealgoritmen implementeres ved hjælp af en while-loop.
  • Spil: I et spil kan en while-loop bruges til at holde hovedlogikken i spillet kørende, indtil spilleren taber eller spillet slutter. Vi kan ikke vide på forhånd, hvornår dette vil ske, så dette er et andet perfekt scenarie i et stykke tid.

? Hvordan mens sløjfer fungerer

Nu hvor du ved hvad mens sløjfer bruges til, lad os se deres vigtigste logik og hvordan de fungerer bag kulisserne. Her har vi et diagram:

Lad os nedbryde dette mere detaljeret:

  • Processen starter, når der findes en stund-løkke under udførelsen af ​​programmet.
  • Tilstanden evalueres for at kontrollere, om den er Trueeller False.
  • Hvis betingelsen er True, udføres udsagnene, der hører til sløjfen.
  • While-loop-tilstanden kontrolleres igen.
  • Hvis tilstanden evalueres til Trueigen, kører rækkefølgen af ​​udsagn igen, og processen gentages.
  • Når tilstanden evalueres til False, stopper sløjfen, og programmet fortsætter ud over sløjfen.

En af de vigtigste egenskaber ved while-sløjfer er, at de variabler, der bruges i loop-tilstanden ikke opdateres automatisk. Vi er nødt til at opdatere deres værdier eksplicit med vores kode for at sikre, at sløjfen til sidst stopper, når tilstanden evalueres til False.

? Generel syntaks for mens sløjfer

Store. Nu ved du, hvordan mens sløjfer fungerer, så lad os dykke ned i koden og se, hvordan du kan skrive et stykke loop i Python. Dette er den grundlæggende syntaks:

Dette er hovedelementerne (i rækkefølge):

  • Den whilesøgeord (efterfulgt af et mellemrum).
  • En betingelse for at bestemme, om sløjfen fortsætter med at køre eller ikke baseret på dens sandhedsværdi ( Trueeller False).
  • Et kolon ( :) i slutningen af ​​første linje.
  • Sekvensen af ​​udsagn, der gentages. Denne kodeblok kaldes loopens "krop", og den skal indrykkes. Hvis en erklæring ikke er indrykket, betragtes den ikke som en del af sløjfen (se diagrammet nedenfor).

? Tip: Python- stilvejledningen (PEP 8) anbefaler, at du bruger 4 mellemrum pr. Indrykningsniveau. Faner bør kun bruges til at forblive i overensstemmelse med kode, der allerede er indrykket med faner.

? Eksempler på While Loops

Nu hvor du ved, hvordan mens sløjfer fungerer, og hvordan du skriver dem i Python, lad os se, hvordan de fungerer bag kulisserne med nogle eksempler.

Sådan fungerer en Basic While Loop

Her har vi en grundlæggende mens løkke, der udskriver værdien af imensi er mindre end 8 ( i < 8):

i = 4 while i < 8: print(i) i += 1

Hvis vi kører koden, ser vi denne output:

4 5 6 7

Lad os se, hvad der sker bag kulisserne, når koden kører:

  • Iteration 1: oprindeligt er værdien i4, så tilstanden i < 8evalueres til, Trueog sløjfen begynder at køre. Værdien af iudskrives (4), og denne værdi forøges med 1. Sløjfen starter igen.
  • Iteration 2: nu er værdien i5, så tilstanden i < 8evalueres til True. Sløjfens krop kører, værdien af iudskrives (5), og denne værdi iøges med 1. Sløjfen starter igen.
  • Iterationer 3 og 4: Den samme proces gentages for tredje og fjerde iteration, så heltalene 6 og 7 udskrives.
  • Before starting the fifth iteration, the value of i is 8. Now the while loop condition i < 8 evaluates to False and the loop stops immediately.

? Tip: If the while loop condition is False before starting the first iteration, the while loop will not even start running.

User Input Using a While Loop

Now let's see an example of a while loop in a program that takes user input. We will the input() function to ask the user to enter an integer and that integer will only be appended to list if it's even.

This is the code:

# Define the list nums = [] # The loop will run while the length of the # list nums is less than 4 while len(nums) < 4: # Ask for user input and store it in a variable as an integer. user_input = int(input("Enter an integer: ")) # If the input is an even number, add it to the list if user_input % 2 == 0: nums.append(user_input)

The loop condition is len(nums) < 4, so the loop will run while the length of the list nums is strictly less than 4.

Let's analyze this program line by line:

  • We start by defining an empty list and assigning it to a variable called nums.
nums = []
  • Then, we define a while loop that will run while len(nums) < 4.
while len(nums) < 4:
  • We ask for user input with the input() function and store it in the user_input variable.
user_input = int(input("Enter an integer: "))

? Tip: We need to convert (cast) the value entered by the user to an integer using the int() function before assigning it to the variable because the input() function returns a string (source).

  • We check if this value is even or odd.
if user_input % 2 == 0:
  • If it's even, we append it to the nums list.
nums.append(user_input)
  • Else, if it's odd, the loop starts again and the condition is checked to determine if the loop should continue or not.

If we run this code with custom user input, we get the following output:

Enter an integer: 3 Enter an integer: 4 Enter an integer: 2 Enter an integer: 1 Enter an integer: 7 Enter an integer: 6 Enter an integer: 3 Enter an integer: 4 

This table summarizes what happens behind the scenes when the code runs:

? Tip: The initial value of len(nums) is 0 because the list is initially empty. The last column of the table shows the length of the list at the end of the current iteration. This value is used to check the condition before the next iteration starts.

As you can see in the table, the user enters even integers in the second, third, sixth, and eight iterations and these values are appended to the nums list.

Before a "ninth" iteration starts, the condition is checked again but now it evaluates to False because the nums list has four elements (length 4), so the loop stops.

If we check the value of the nums list when the process has been completed, we see this:

>>> nums [4, 2, 6, 4]

Exactly what we expected, the while loop stopped when the condition len(nums) < 4 evaluated to False.

Now you know how while loops work behind the scenes and you've seen some practical examples, so let's dive into a key element of while loops: the condition.

? Tips for the Condition in While Loops

Before you start working with while loops, you should know that the loop condition plays a central role in the functionality and output of a while loop.

You must be very careful with the comparison operator that you choose because this is a very common source of bugs.

For example, common errors include:

  • Using < (less than) instead of <= (less than or equal to) (or vice versa).
  • Using > (greater than) instead of >= (greater than or equal to) (or vice versa).  

This can affect the number of iterations of the loop and even its output.

Let's see an example:

If we write this while loop with the condition i < 9:

i = 6 while i < 9: print(i) i += 1 

We see this output when the code runs:

6 7 8

The loop completes three iterations and it stops when i is equal to 9.

This table illustrates what happens behind the scenes when the code runs:

  • Before the first iteration of the loop, the value of i is 6, so the condition i < 9 is True and the loop starts running. The value of i is printed and then it is incremented by 1.
  • In the second iteration of the loop, the value of i is 7, so the condition i < 9 is True. The body of the loop runs, the value of i is printed, and then it is incremented by 1.
  • In the third iteration of the loop, the value of i is 8, so the condition i < 9 is True. The body of the loop runs, the value of i is printed, and then it is incremented by 1.
  • The condition is checked again before a fourth iteration starts, but now the value of i is 9, so i < 9 is False and the loop stops.

In this case, we used < as the comparison operator in the condition, but what do you think will happen if we use <= instead?

i = 6 while i <= 9: print(i) i += 1

We see this output:

6 7 8 9

The loop completes one more iteration because now we are using the "less than or equal to" operator <= , so the condition is still True when i is equal to 9.

This table illustrates what happens behind the scenes:

Four iterations are completed. The condition is checked again before starting a "fifth" iteration. At this point, the value of i is 10, so the condition i <= 9 is False and the loop stops.

? Infinite While Loops

Now you know how while loops work, but what do you think will happen if the while loop condition never evaluates to False?

What are Infinite While Loops?

Remember that while loops don't update variables automatically (we are in charge of doing that explicitly with our code). So there is no guarantee that the loop will stop unless we write the necessary code to make the condition False at some point during the execution of the loop.

If we don't do this and the condition always evaluates to True, then we will have an infinite loop, which is a while loop that runs indefinitely (in theory).

Infinite loops are typically the result of a bug, but they can also be caused intentionally when we want to repeat a sequence of statements indefinitely until a break statement is found.

Let's see these two types of infinite loops in the examples below.

? Tip: A bug is an error in the program that causes incorrect or unexpected results.

Example of Infinite Loop

This is an example of an unintentional infinite loop caused by a bug in the program:

# Define a variable i = 5 # Run this loop while i is less than 15 while i < 15: # Print a message print("Hello, World!") 

Analyze this code for a moment.

Don't you notice something missing in the body of the loop?

That's right!

The value of the variable i is never updated (it's always 5). Therefore, the condition i < 15 is always True and the loop never stops.

If we run this code, the output will be an "infinite" sequence of Hello, World! messages because the body of the loop print("Hello, World!") will run indefinitely.

Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! Hello, World! . . . # Continues indefinitely

To stop the program, we will need to interrupt the loop manually by pressing CTRL + C.

When we do, we will see a KeyboardInterrupt error similar to this one:

To fix this loop, we will need to update the value of i in the body of the loop to make sure that the condition i < 15 will eventually evaluate to False.

This is one possible solution, incrementing the value of i by 2 on every iteration:

i = 5 while i < 15: print("Hello, World!") # Update the value of i i += 2

Great. Now you know how to fix infinite loops caused by a bug. You just need to write code to guarantee that the condition will eventually evaluate to False.

Let's start diving into intentional infinite loops and how they work.

? How to Make an Infinite Loop with While True

We can generate an infinite loop intentionally using while True. In this case, the loop will run indefinitely until the process is stopped by external intervention (CTRL + C) or when a break statement is found (you will learn more about break in just a moment).

This is the basic syntax:

Instead of writing a condition after the while keyword, we just write the truth value directly to indicate that the condition will always be True.

Here we have an example:

>>> while True: print(0) 0 0 0 0 0 0 0 0 0 0 0 0 0 Traceback (most recent call last): File "", line 2, in  print(0) KeyboardInterrupt

Sløjfen kører indtil CTRL + Cder trykkes på, men Python har også en breakerklæring om, at vi kan bruge direkte i vores kode til at stoppe denne type sløjfe.

den breakopgørelse

Denne erklæring bruges til at stoppe en løkke med det samme. Du skal tænke på det som et rødt "stopskilt", som du kan bruge i din kode til at have mere kontrol over sløjfens opførsel.

Ifølge Python-dokumentationen:

Den breakerklæring, som i C, bryder ud af den inderste omsluttende foreller whileløkke.

Dette diagram illustrerer breakudsagnets grundlæggende logik :

Dette er den grundlæggende logik i breakudsagnet:

  • While-sløjfen starter kun, hvis tilstanden evalueres til True.
  • If a break statement is found at any point during the execution of the loop, the loop stops immediately.
  • Else, if break is not found, the loop continues its normal execution and it stops when the condition evaluates to False.

We can use break to stop a while loop when a condition is met at a particular point of its execution, so you will typically find it within a conditional statement, like this:

while True: # Code if : break # Code

This stops the loop immediately if the condition is True.

? Tip: You can (in theory) write a break statement anywhere in the body of the loop. It doesn't necessarily have to be part of a conditional, but we commonly use it to stop the loop when a given condition is True.

Here we have an example of break in a while True loop:

Let's see it in more detail:

The first line defines a while True loop that will run indefinitely until a break statement is found (or until it is interrupted with CTRL + C).

while True:

The second line asks for user input. This input is converted to an integer and assigned to the variable user_input.

user_input = int(input("Enter an integer: "))

The third line checks if the input is odd.

if user_input % 2 != 0:

If it is, the message This number is odd is printed and the break statement stops the loop immediately.

print("This number of odd") break

Else, if the input is even , the message This number is even is printed and the loop starts again.

print("This number is even")

The loop will run indefinitely until an odd integer is entered because that is the only way in which the break statement will be found.

Here we have an example with custom user input:

Enter an integer: 4 This number is even Enter an integer: 6 This number is even Enter an integer: 8 This number is even Enter an integer: 3 This number is odd >>>

? In Summary

  • While loops are programming structures used to repeat a sequence of statements while a condition is True. They stop when the condition evaluates to False.
  • When you write a while loop, you need to make the necessary updates in your code to make sure that the loop will eventually stop.
  • An infinite loop is a loop that runs indefinitely and it only stops with external intervention or when a break statement is found.
  • You can stop an infinite loop with CTRL + C.
  • You can generate an infinite loop intentionally with while True.
  • The break statement can be used to stop a while loop immediately.

I really hope you liked my article and found it helpful. Now you know how to work with While Loops in Python.

Følg mig på Twitter @EstefaniaCassN, og hvis du vil lære mere om dette emne, så tjek mit online kursus Python Loops and Looping Techniques: Beginner to Advanced.