English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Los bucles se utilizan en la programación para repetir un bloque de código específico. En este artículo, aprenderá cómo crear un bucle while en Python.
Mientras que la expresión de prueba (condición) sea verdadera, el bucle while en Python puede iterar el bloque de código.
Cuando no se conoce el número de iteraciones anticipadas, se utiliza este bucle.
while test_expression: Cuerpo de while
En el bucle while, primero se verifica la expresión de prueba. Solamente cuando el resultado de test_expression es True, se ingresa al cuerpo del bucle. Después de una iteración, se verifica nuevamente la expresión de prueba. Este proceso continúa hasta que la evaluación de test_expression sea False.
En Python, el cuerpo del bucle while se determina mediante sangría.
El cuerpo comienza con sangría y se marca el final con una línea sin sangría.
Python interpreta cualquier valor no cero como True. None y 0 se interpretan como False.
# Program to add natural numbers # The maximum number of digits # sum = 1+2+3+...+n # Get input from the user # n = int(input("Enter n: ")) n = 10 # Initialize sum and counter sum = 0 i = 1 while i <= n: sum = sum + i i = i+1 # Update counter # Print sum print("The value of sum", sum)
When running this program, the output is:
Enter n: 10 the value of sum 55
In the above program, as long as our counter variableiless than or equal ton(In our program it is10),then the test expression is True.
We need to increase the value of the counter variable within the loop body. This is very important (Never forget)。Otherwise, it will cause an infinite loop (an endless loop).
Finally, display the result.
Withfor loopThe same, while loop can also have an optional else block.
If the condition of the while loop evaluates to False, then execute this part.
while loop can be usedbreak statementTermination. In this case, the else statement will be ignored. Therefore, if there is no break interrupt and the condition is False, the else statement of the while loop will run.
This is an example to illustrate this.
'''Example Using else statement with while loop''' counter = 0 while counter < 3: print("Internal loop") counter = counter + 1 else: print("else statement")
Output result
Internal loop Internal loop Internal loop else statement
Here, we use a counter variable to print the string Internal loop Three times.
In the fourth iteration, the condition in the while loop becomes False. Therefore, this else part will be executed.