Python While Loop Tutorial – While True Syntax Examples and Infinite Loops (2023)

Python While Loop Tutorial – While True Syntax Examples and Infinite Loops (1)

Welcome! If you want to learn how to work with while loops in Python, then this article is for you.

While loops are very powerful programming structures that you can use in your programs to repeat a sequence of statements.

In this article, you will learn:

  • What while loops are.
  • What they are used for.
  • When they should be used.
  • How they work behind the scenes.
  • How to write a while loop in Python.
  • What infinite loops are and how to interrupt them.
  • What while True is used for and its general syntax.
  • How to use a break statement to stop a while loop.

You will learn how while loops work behind the scenes with examples, tables, and diagrams.

Are you ready? Let's begin. 🔅

🔹 Purpose and Use Cases for While Loops

Let's start with the purpose of while loops. What are they used for?

They are used to repeat a sequence of statements an unknown number of times. This type of loop runs while a given condition is True and it only stops when the condition becomes False.

When we write a while loop, we don't explicitly define how many iterations will be completed, we only write the condition that has to be True to continue the process and False to stop it.

💡 Tip: if the while loop condition never evaluates to False, then we will have an infinite loop, which is a loop that never stops (in theory) without external intervention.

These are some examples of real use cases of while loops:

  • User Input: When we ask for user input, we need to check if the value entered is valid. We can't possibly know in advance how many times the user will enter an invalid input before the program can continue. Therefore, a while loop would be perfect for this scenario.
  • Search: searching for an element in a data structure is another perfect use case for a while loop because we can't know in advance how many iterations will be needed to find the target value. For example, the Binary Search algorithm can be implemented using a while loop.
  • Games: In a game, a while loop could be used to keep the main logic of the game running until the player loses or the game ends. We can't know in advance when this will happen, so this is another perfect scenario for a while loop.

🔸 How While Loops Work

Now that you know what while loops are used for, let's see their main logic and how they work behind the scenes. Here we have a diagram:

Python While Loop Tutorial – While True Syntax Examples and Infinite Loops (2)

Let's break this down in more detail:

  • The process starts when a while loop is found during the execution of the program.
  • The condition is evaluated to check if it's True or False.
  • If the condition is True, the statements that belong to the loop are executed.
  • The while loop condition is checked again.
  • If the condition evaluates to True again, the sequence of statements runs again and the process is repeated.
  • When the condition evaluates to False, the loop stops and the program continues beyond the loop.

One of the most important characteristics of while loops is that the variables used in the loop condition are not updated automatically. We have to update their values explicitly with our code to make sure that the loop will eventually stop when the condition evaluates to False.

🔹 General Syntax of While Loops

Great. Now you know how while loops work, so let's dive into the code and see how you can write a while loop in Python. This is the basic syntax:

Python While Loop Tutorial – While True Syntax Examples and Infinite Loops (3)

These are the main elements (in order):

  • The while keyword (followed by a space).
  • A condition to determine if the loop will continue running or not based on its truth value (True or False ).
  • A colon (:) at the end of the first line.
  • The sequence of statements that will be repeated. This block of code is called the "body" of the loop and it has to be indented. If a statement is not indented, it will not be considered part of the loop (please see the diagram below).
Python While Loop Tutorial – While True Syntax Examples and Infinite Loops (4)

💡 Tip: The Python style guide (PEP 8) recommends using 4 spaces per indentation level. Tabs should only be used to remain consistent with code that is already indented with tabs.

(Video) WHILE Loop in Python (Syntax, Break, Continue, Else, Infinite Loops) - Python Tutorial for Beginners

🔸 Examples of While Loops

Now that you know how while loops work and how to write them in Python, let's see how they work behind the scenes with some examples.

How a Basic While Loop Works

Here we have a basic while loop that prints the value of i while i is less than 8 (i < 8):

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

If we run the code, we see this output:

4567

Let's see what happens behind the scenes when the code runs:

Python While Loop Tutorial – While True Syntax Examples and Infinite Loops (5)
  • Iteration 1: initially, the value of i is 4, so the condition i < 8 evaluates to True and the loop starts to run. The value of i is printed (4) and this value is incremented by 1. The loop starts again.
  • Iteration 2: now the value of i is 5, so the condition i < 8 evaluates to True. The body of the loop runs, the value of i is printed (5) and this value i is incremented by 1. The loop starts again.
  • Iterations 3 and 4: The same process is repeated for the third and fourth iterations, so the integers 6 and 7 are printed.
  • 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 listnums = []# The loop will run while the length of the# list nums is less than 4while 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: 3Enter an integer: 4 Enter an integer: 2 Enter an integer: 1Enter an integer: 7Enter an integer: 6 Enter an integer: 3Enter an integer: 4 

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

Python While Loop Tutorial – While True Syntax Examples and Infinite Loops (6)

💡 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.

(Video) Python 101 Tutorial - while Loop Statements - Writing simple loops and avoiding infinite loops.

🔹 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.

Python While Loop Tutorial – While True Syntax Examples and Infinite Loops (7)

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 = 6while i < 9: print(i) i += 1

We see this output when the code runs:

678

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:

Python While Loop Tutorial – While True Syntax Examples and Infinite Loops (8)
  • 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 = 6while i <= 9: print(i) i += 1

We see this output:

6789

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:

Python While Loop Tutorial – While True Syntax Examples and Infinite Loops (9)

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?

Python While Loop Tutorial – While True Syntax Examples and Infinite Loops (10)

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.

(Video) #7 Learn to use Python while loop | While loop syntax and infinite loop

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 variablei = 5# Run this loop while i is less than 15while 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:

Python While Loop Tutorial – While True Syntax Examples and Infinite Loops (11)

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 = 5while 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:

Python While Loop Tutorial – While True Syntax Examples and Infinite Loops (12)

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:

(Video) Python While Loops And Infinite Loops

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

The loop runs until CTRL + C is pressed, but Python also has a break statement that we can use directly in our code to stop this type of loop.

The break statement

This statement is used to stop a loop immediately. You should think of it as a red "stop sign" that you can use in your code to have more control over the behavior of the loop.

Python While Loop Tutorial – While True Syntax Examples and Infinite Loops (13)

According to the Python Documentation:

The break statement, like in C, breaks out of the innermost enclosing for or while loop.

This diagram illustrates the basic logic of the break statement:

Python While Loop Tutorial – While True Syntax Examples and Infinite Loops (14)

This is the basic logic of the break statement:

  • The while loop starts only if the condition evaluates to 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 <condition>: 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:

Python While Loop Tutorial – While True Syntax Examples and Infinite Loops (15)

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: 4This number is evenEnter an integer: 6This number is evenEnter an integer: 8This number is evenEnter an integer: 3This 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.

(Video) #20 Python Tutorial for Beginners | While Loop in Python

Follow me on Twitter @EstefaniaCassN and if you want to learn more about this topic, check out my online course Python Loops and Looping Techniques: Beginner to Advanced.

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

FAQs

What is the syntax of while loop in Python? ›

Syntax of while Loop in Python

In the while loop, test expression is checked first. The body of the loop is entered only if the test_expression evaluates to True . After one iteration, the test expression is checked again. This process continues until the test_expression evaluates to False .

Is while true an infinite loop? ›

🔹 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).

What is infinite loop in Python with example? ›

When a condition never becomes false, the program enters the loop and keeps repeating that same block of code over and over again, and the loop never ends. The following example shows an infinite loop: a = 1 while a==1: b = input(“what's your name?”) print(“Hi”, b, “, Welcome to Intellipaat!”)

Which statements about the Python while loop are true? ›

The "while true" loop in python runs without any conditions until the break statement executes inside the loop. To run a statement if a python while loop fails, the programmer can implement a python "while" with else loop. Python does not support the "do while" loop.

What is while loop example? ›

A "While" Loop is used to repeat a specific block of code an unknown number of times, until a condition is met. For example, if we want to ask a user for a number between 1 and 10, we don't know how many times the user may enter a larger number, so we keep asking "while the number is not between 1 and 10".

How many loops are there in Python? ›

There are two types of loops in Python, for and while.

Which is an infinite loop? ›

An infinite loop (sometimes called an endless loop ) is a piece of coding that lacks a functional exit so that it repeats indefinitely. In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached.

Which loop will be an infinite loop? ›

while loop represents the infinite condition as we provide the '1' value inside the loop condition. As we already know that non-zero integer represents the true condition, so this loop will run infinite times. We can also use the goto statement to define the infinite loop.

What is true while loop? ›

While loop is used to execute a block of code repeatedly until given boolean condition evaluated to False. If we write while True then the loop will run forever.

How do you write an infinite loop? ›

We can create an infinite loop using while statement. If the condition of while loop is always True , we get an infinite loop.

Is while 1 an infinite loop? ›

What is while(1)? The while(1) acts as an infinite loop that runs continually until a break statement is explicitly issued.

Is infinite loop an error in Python? ›

An Infinite Loop in Python is a continuous repetitive conditional loop that gets executed until an external factor interferes in the execution flow, like insufficient CPU memory, a failed feature/ error code that stopped the execution, or a new feature in the other legacy systems that needs code integration.

How do you end a true loop in Python? ›

Python provides two keywords that terminate a loop iteration prematurely: The Python break statement immediately terminates a loop entirely. Program execution proceeds to the first statement following the loop body. The Python continue statement immediately terminates the current loop iteration.

Why is my while loop infinite? ›

Basically, the infinite loop happens when the condition in the while loop always evaluates to true. This can happen when the variables within the loop aren't updated correctly, or aren't updated at all. Let's say you have a variable that's set to 10 and you want to loop while the value is less than 100.

What does == true mean in Python? ›

It's used to represent the truth value of an expression. For example, the expression 1 <= 2 is True , while the expression 0 == 1 is False .

What is the syntax of loop? ›

Syntax of a For Loop

The initialization statement describes the starting point of the loop, where the loop variable is initialized with a starting value. A loop variable or counter is simply a variable that controls the flow of the loop. The test expression is the condition until when the loop is repeated.

Why is a while loop used? ›

The while loop is used when we don't know the number of times it will repeat. If that number is infinite, or the Boolean condition of the loop never gets set to False, then it will run forever.

What is loop in Python? ›

In python, while loop is used to execute a block of statements repeatedly until a given condition is satisfied. And when the condition becomes false, the line immediately after the loop in the program is executed.

What are the 3 types of loops? ›

The three types of loop control statements are: break statement. continue statement. pass statement.

What does loop mean? ›

1a : a curving or doubling of a line so as to form a closed or partly open curve within itself through which another line can be passed or into which a hook may be hooked. b : such a fold of cord or ribbon serving as an ornament. 2a : something shaped like or suggestive of a loop.

What are the two basic types of loops in Python? ›

Answer: Python generally supports two types of loops: for loop and while loop.

How do you stop an infinite loop? ›

Answer 53965aad7c82ca49c00001a1. Since to exit the loop, you will need to make the condition in the while loop evaluate to false , you will have to set $loopCond to false . But this variable reassignment should be done inside of the while loop.

What is an infinite loop and what causes it? ›

An infinite loop is a sequence of instructions in a computer program which loops endlessly, either due to the loop having no terminating condition, having one that can never be met, or one that causes the loop to start over.

Which statement is false about infinite loop? ›

Which statement is false about infinite loop? The body of a while loop eventually must make the condition false to avoid infinite loop.

Which statement is true for infinite loop? ›

Yes, by definition. A while loop repeats until the condition returns false. “True” will always return true for reasons I hope are obvious, so it will never return false and thus the loop will never end normally.

Is an empty for loop infinite? ›

Answer. An empty loop is a loop that doesn't contain any executable statement, whereas, an infinite loop is a loop that runs an infinite number of times. An empty loop contain only one empty statement. They are mostly used to produce time breaks.

What happens if you run an infinite loop? ›

What are infinite loops? An infinite loop is a piece of code that keeps running forever as the terminating condition is never reached. An infinite loop can crash your program or browser and freeze your computer.

What is the structure of while loop? ›

Overview. The while construct consists of a block of code and a condition/expression. The condition/expression is evaluated, and if the condition/expression is true, the code within all of their following in the block is executed. This repeats until the condition/expression becomes false.

How does a while loop start? ›

Syntax. The while loop starts by evaluating condition . If condition evaluates to true , the code in the code block gets executed. If condition evaluates to false , the code in the code block is not executed and the loop ends.

What is a Do While loop example in real life? ›

Real World Example, Go to the bath room: DO { Check_Door_Lock(); } WHILE (WAIT_WHILE_DOOR_IS_LOCKED()); after the loop is done then the WAIT_WHILE_DOOR_IS_LOCKED() has returned a false value, so it isn't locked anymore, thus, the whole loop ends.

What is infinite loop explain how it can be broken through an example? ›

An infinite loop occurs when a condition always evaluates to true and because of this the loop control doesn't go outside of that loop. Example: i = -1. while(i != 0): print(1)

What is an indefinite loop in Python? ›

Indefinite loop is a loop that will continue to run infinite number of times until and unless it is asked to stop. In order to execute an indefinite loop, we use the while statement. Syntax. while <condition>: <statements>

Which of the following is not infinite loop? ›

11. Which of the following is not infinite loop? Explanation: None.

How many times does the while 1 run? ›

Answer: Therefore, while(1), while(2) or while(-255), all will give infinite loop only. A simple usage of while(1) can be in the Client-Server program. In the program, the server runs in an infinite while loop to receive the packets sent from the clients.

What is a while 1 loop? ›

In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The boolean condition is either true or false. while(1) It is an infinite loop which will run till a break statement is issued explicitly.

What does while 1 mean in Python? ›

While 1 is a bit kinder to old versions of Python. While 1 will create an infinite loop in Python. while True: do_something() The most pythonic way will always be the most readable.

What are finite and infinite loops? ›

A finite loop ends itself. An infinite loop will not end without an outside cause.

How do you end a while loop? ›

Breaking Out of While Loops. To break out of a while loop, you can use the endloop, continue, resume, or return statement.

How do you print infinite values in Python? ›

But in python, as it is a dynamic language, float values can be used to represent an infinite integer. One can use float('inf') as an integer to represent it as infinity.

How do I get out of a true loop? ›

The break statement exits a for or while loop completely. To skip the rest of the instructions in the loop and begin the next iteration, use a continue statement. break is not defined outside a for or while loop. To exit a function, use return .

How do you input a while loop in Python? ›

The general case for accepting input looks something like this: # Get some input from the user. variable = input('Please enter a value: ') # Do something with the value that was entered. You need a variable that will hold whatever value the user enters, and you need a message that will be displayed to the user.

What is an infinite loop give one example? ›

What is an Infinite Loop? An infinite loop occurs when a condition always evaluates to true. Usually, this is an error. For example, you might have a loop that decrements until it reaches 0.

Is 0 True or False? ›

Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true. To make life easier, C Programmers typically define the terms "true" and "false" to have values 1 and 0 respectively.

Is 0 true or False in Python? ›

Python assigns boolean values to values of other types. For numerical types like integers and floating-points, zero values are false and non-zero values are true. For strings, empty strings are false and non-empty strings are true.

What is a Boolean Python? ›

Python boolean type is one of the built-in data types provided by Python, which represents one of the two values i.e. True or False. Generally, it is used to represent the truth values of the expressions. For example, 1==1 is True whereas 2<1 is False.

What is the syntax of while loop statement? ›

Syntax of Do-While Loop in C:

do { statements } while (expression); As we saw in a while loop, the body is executed if and only if the condition is true. In some cases, we have to execute a body of the loop at least once even if the condition is false.

How do you write a Do While loop? ›

The syntax for a do while statement is: do loop_body_statement while (cond_exp); where: loop_body_statement is any valid C statement or block.
...
Any of the following C statements used as part of the loop_body_statement can alter the flow of control in a do while statement:
  1. break.
  2. continue.
  3. goto.
  4. return.

How do you input a while loop in Python? ›

The general case for accepting input looks something like this: # Get some input from the user. variable = input('Please enter a value: ') # Do something with the value that was entered. You need a variable that will hold whatever value the user enters, and you need a message that will be displayed to the user.

What is the Do While loop syntax in C? ›

Syntax. do { statement(s); } while( condition ); Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop executes once before the condition is tested. If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop executes again.

What are the 3 types of loops? ›

The three types of loop control statements are: break statement. continue statement. pass statement.

What are the types of loops? ›

There are two types of loops, “while loops” and “for loops”. While loops will repeat while a condition is true, and for loops will repeat a certain number of times.

What is the structure of while loop? ›

Overview. The while construct consists of a block of code and a condition/expression. The condition/expression is evaluated, and if the condition/expression is true, the code within all of their following in the block is executed. This repeats until the condition/expression becomes false.

Why is a while loop used? ›

The while loop is used when we don't know the number of times it will repeat. If that number is infinite, or the Boolean condition of the loop never gets set to False, then it will run forever.

What does loop mean? ›

1a : a curving or doubling of a line so as to form a closed or partly open curve within itself through which another line can be passed or into which a hook may be hooked. b : such a fold of cord or ribbon serving as an ornament. 2a : something shaped like or suggestive of a loop.

Do-while loop is? ›

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

How do you take input from user while loop? ›

Python: While Loops (Reading User Input Indefinitely?!!) - YouTube

How do you end a while loop in Python? ›

Python provides two keywords that terminate a loop iteration prematurely: The Python break statement immediately terminates a loop entirely. Program execution proceeds to the first statement following the loop body. The Python continue statement immediately terminates the current loop iteration.

How do you repeat a while loop in Python? ›

While Loop in Python (Perform a Task 1000000 times With Ease) #8

Do-while loop is also known as? ›

Because do while loops check the condition after the block is executed, the control structure is often also known as a post-test loop.

What is difference between while loop and for loop? ›

The loops are used to repeatedly execute the instructions till the condition is true. The difference between for loop and while loop is that For is an entry controlled loop whereas while is an exit controlled loop.

What is a do-while loop example in real life? ›

Real World Example, Go to the bath room: DO { Check_Door_Lock(); } WHILE (WAIT_WHILE_DOOR_IS_LOCKED()); after the loop is done then the WAIT_WHILE_DOOR_IS_LOCKED() has returned a false value, so it isn't locked anymore, thus, the whole loop ends.

Videos

1. While True Loops in Python // Learning Python
(Tommy's Code)
2. While Loop In Python | Python While Loop Explained | Python Tutorial For Beginners | Edureka
(edureka!)
3. Python While Loop and infinite loop
(ZebraCode)
4. Does it matter how I write my infinite loops? (for vs. while?)
(Jacob Sorber)
5. Python While Loop & Try and Except Block
(Deep Hobbying)
6. Infinite WHILE Loops in Python - Python Tutorial for Beginners
(Digital Academy)
Top Articles
Latest Posts
Article information

Author: Edmund Hettinger DC

Last Updated: 12/02/2022

Views: 6326

Rating: 4.8 / 5 (78 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Edmund Hettinger DC

Birthday: 1994-08-17

Address: 2033 Gerhold Pine, Port Jocelyn, VA 12101-5654

Phone: +8524399971620

Job: Central Manufacturing Supervisor

Hobby: Jogging, Metalworking, Tai chi, Shopping, Puzzles, Rock climbing, Crocheting

Introduction: My name is Edmund Hettinger DC, I am a adventurous, colorful, gifted, determined, precious, open, colorful person who loves writing and wants to share my knowledge and understanding with you.