How to use Python While with Assignment[4 Examples]

In this Python tutorial, you will learn “ How to use Python While with Assignment “, with multiple examples and different approaches.

While working on a project, I was assigned to optimise the code. In the research, I found that we can assign variables within a while loop in Python. This helps to reduce some lines of code.

Generally, we use the ” = “ assignment operator to assign the variable in Python. But we will also try the walrus operator “:= “ to assign the variable within the while loop in Python.

Let’s understand every example one by one with some practical scenarios.

Table of Contents

Python while loop with the assignment using the “=” operator

First, we will use the “=” operator, an assignment operator in Python. This operator is used to assign a value to a variable, and we will assign a variable inside the loop in Python using the ” = “ operator.

Let’s see how Python, while with assignment, works.

Python while loop with the assignment

In the above code, we always initialize the while loop with the true condition. “ while True :” means it will iterate infinite times and then assign the variable ‘line = “Hello” inside the while loop with one default string value.

Then assigned i = 0 , and again initialize nested while loop “print(line[i],’-‘,ord(line[i])) ” to target every character one by one and print its ascii value using ord() method in Python

Python assign variables in the while condition using the walrus operator

We can also use the walrus operator ” := “, a new assignment expression operator introduced in the 3.8 version of Python. It can create a new variable inside the expression even if that variable does not exist previously.

Let’s see how we can use it in a while loop:

Python assign variable in while condition using walrus operator

In the above code, we have a list named capitals. Then we initialize a while loop and create current_capital , giving a value as capitals.pop(0) , which means removing the first element in every iteration using the walrus operator like this: ‘current_capital:= capitals.pop(0)) != “Austin” .

When it iterates at “Austin”, the condition will be False because “Austin” != “Austin” will return false, and the loop will stop iterating.

Python while with assignment by taking user input

Here, we will see how Python While with Assignment will work if we take user input with a while loop using the walrus operator in Python.

python while assignment with walrus operator in python

In the above code, we are initializing a variable with a while loop and taking user input for an integer. Then, it will check whether the number is even or odd using the % operator.

Look at how it asks the user to enter the number repeatedly because we are not giving a break statement anywhere so it will work infinite times.

Python While with Assignment by calling the function

Now, we will see how to assign a variable inside a while loop in Python by calling the function name. We will create a user-defined function so you will understand how it is working.

How Python While with Assignment can be created by calling the user-defined function.

Python While with Assignment by calling the function

In the above code, we create a function called get_ascii_value() . This function takes a string as a parameter and returns the ASCII value of each character.

Then, we initialize a while loop, taking user_input as a string. The result variable calls a function and returns a character and ASCII value in a dictionary datatype.

In this Python article, you learned how to use Python while with assignment with different approaches and examples. We tried to cover all types of scenarios, such as creating user-defined functions , assigning within a while loop, taking user input, etc.

You may like to read:

  • Python Find Last Number in String
  • How to compare two lists in Python and return non-matches elements
  • How to Convert a Dict to String in Python[5 ways]

Bijay - Python Expert

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile .

Datagy logo

  • Learn Python
  • Python Lists
  • Python Dictionaries
  • Python Strings
  • Python Functions
  • Learn Pandas & NumPy
  • Pandas Tutorials
  • Numpy Tutorials
  • Learn Data Visualization
  • Python Seaborn
  • Python Matplotlib

Python While Loop with Multiple Conditions

  • September 25, 2021 December 20, 2022

Python While Loop Multiple Conditions Cover Image

In this tutorial, you’ll learn how to write a Python while loop with multiple conditions, including and and or conditions. You’ll also learn how to use the NOT operator as well as how to group multiple conditions.

The Quick Answer: Embed Conditions with AND or OR Operators in Your While Loop

Table of Contents

What is a Python While Loop

A Python while loop is an example of iteration , meaning that some Python statement is executed a certain number of times or while a condition is true. A while loop is similar to a Python for loop, but it is executed different. A Python while loop is both an example of definite iteration , meaning that it iterates a definite number of times, and an example of indefinite iteration , meaning that it iterates an indefinite number of times.

Let’s take a quick look at how a while loop is written in Python:

In the example above, the while loop will complete the step do something indefinitely, until the condition is no longer met.

If, for example, we wrote:

The program would run indefinitely , until the condition is not longer True. Because of this, we need to be careful about executing a while loop.

To see how we can stop a while loop in Python, let’s take a look at the example below:

In the sections below, you'll learn more about how the Python while loop can be implemented with multiple conditions. Let's get started!

Want to learn about Python for-loops? Check out my in-depth tutorial here , to learn all you need to know to get started!

Python While Loop with Multiple Conditions Using AND

Now that you've had a quick recap of how to write a Python while loop, let's take a look at how we can write a while loop with multiple conditions using the AND keyword.

In this case, we want all of the conditions to be true, whether or not there are two, three, or more conditions to be met.

To accomplish meeting two conditions, we simply place the and keyword between each of the conditions. Let's take a look at what this looks like:

We can see here that the code iterates only while both of the conditions are true. As soon as, in this case, a = 4 , the condition of a < 4 is no longer true and the code stops execution.

Now let's take a look at how we can implement an or condition in a Python while loop.

Check out some other Python tutorials on datagy.io, including our complete guide to styling Pandas and our comprehensive overview of Pivot Tables in Pandas !

Python While Loop with Multiple Conditions Using OR

Similar to using the and keyword in a Python while loop, we can also check if any of the conditions are true. For this, we use the or keyword, which checks whether either of our conditions are true.

In order to implement this, we simply place the or keyword in between the two conditions. We can also use more than two conditions and this would work in the same way.

For easier learning, let's stick to two conditions:

We can see that by simply switching from and to or , that or code execute many more times. In fact, the code runs until neither condition is not longer true .

Using a NOT Operator in a Python While Loop with Multiple Conditions

Another important and helpful operator to apply in Python while loops is the not operator. What this operator does is simply reverse the truth of a statement. For example, if we wrote not True , then it would evaluate to False . This can be immensely helpful when trying to write your code in a more plan language style.

Let's see how we can apply this in one of our examples:

Here our code checks that a is less than 4 and that b is not less than 3. Because of this, our code only executes here until a is equal to 4.

Next, let's take a look at how to group multiple conditions in a Python.

How to Group Multiple Conditions in a Python While Loop

There may be many times that you want to group multiple conditions, including mixing and and or statements. When you do this, it's important to understand the order in which these conditions execute. Anything placed in parentheses will evaluated against one another.

To better understand this, let's take a look at this example:

In the code above, if either a or b evaluate to True and c is True then the code will run.

This is known as a Python truth table and it's an important concept to understand.

In essence, the parentheses reduce the expression to a single truth that is checked against, simplifying the truth statement significantly.

Now, let's take a look at a practical, hands-on example to better understand this:

We can see here that the code stops after the third iteration. The reason for this a is less than 4 and b is greater than 3 after the third iteration. Because neither of the conditions in the parentheses are met, the code stops executing.

In this post, you learned how to use a Python while loop with multiple conditions. You learned how to use a Python while loop with both AND and OR conditions, as well as how to use the NOT operator. Finally, you learned how to group multiple conditions in a Python while loop.

To learn more about Python while loops, check out the official documentation here .

To learn more about related topics, check out the tutorials below:

  • Python New Line and How to Print Without Newline
  • Pandas Isin to Filter a Dataframe like SQL IN and NOT IN

Nik Piepenbreier

Nik is the author of datagy.io and has over a decade of experience working with data analytics, data science, and Python. He specializes in teaching developers how to use Python for data science using hands-on tutorials. View Author posts

1 thought on “Python While Loop with Multiple Conditions”

Pingback:  Python For Loop Tutorial - All You Need to Know! • datagy

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

Learn Python practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn python interactively, python introduction.

  • Get Started With Python
  • Your First Python Program
  • Python Comments

Python Fundamentals

  • Python Variables and Literals
  • Python Type Conversion
  • Python Basic Input and Output
  • Python Operators

Python Flow Control

Python if...else Statement

Python for Loop

Python while Loop

Python break and continue

  • Python pass Statement

Python Data types

  • Python Numbers and Mathematics
  • Python List
  • Python Tuple
  • Python String
  • Python Dictionary
  • Python Functions
  • Python Function Arguments
  • Python Variable Scope
  • Python Global Keyword
  • Python Recursion
  • Python Modules
  • Python Package
  • Python Main function

Python Files

  • Python Directory and Files Management
  • Python CSV: Read and Write CSV files
  • Reading CSV files in Python
  • Writing CSV files in Python
  • Python Exception Handling
  • Python Exceptions
  • Python Custom Exceptions

Python Object & Class

  • Python Objects and Classes
  • Python Inheritance
  • Python Multiple Inheritance
  • Polymorphism in Python
  • Python Operator Overloading

Python Advanced Topics

  • List comprehension
  • Python Lambda/Anonymous Function
  • Python Iterators
  • Python Generators
  • Python Namespace and Scope
  • Python Closures
  • Python Decorators
  • Python @property decorator
  • Python RegEx

Python Date and Time

  • Python datetime
  • Python strftime()
  • Python strptime()
  • How to get current date and time in Python?
  • Python Get Current Time
  • Python timestamp to datetime and vice-versa
  • Python time Module
  • Python sleep()

Additional Topic

  • Precedence and Associativity of Operators in Python
  • Python Keywords and Identifiers
  • Python Asserts
  • Python Json
  • Python *args and **kwargs

Python Tutorials

Python Looping Techniques

  • Python range() Function

In Python, we use a while loop to repeat a block of code until a certain condition is met. For example,

In the above example, we have used a while loop to print the numbers from 1 to 3 . The loop runs as long as the condition number <= 3 is True .

  • while Loop Syntax
  • The while loop evaluates condition , which is a boolean expression.
  • If the condition is True , body of while loop is executed. The condition is evaluated again.
  • This process continues until the condition is False .
  • Once the condition evaluates to False , the loop terminates.

Tip: We should update the variables used in condition inside the loop so that it eventually evaluates to False . Otherwise, the loop keeps running, creating an infinite loop.

  • Flowchart of Python while Loop

Flowchart of Python while Loop

  • Example: Python while Loop

Here is how the above program works:

  • It asks the user to enter a number.
  • If the user enters a number other than 0 , it is printed.
  • If the user enters 0 , the loop terminates.
  • Infinite while Loop

If the condition of a while loop always evaluates to True , the loop runs continuously, forming an infinite while loop . For example,

The above program is equivalent to:

More on Python while Loop

We can use a break statement inside a while loop to terminate the loop immediately without checking the test condition. For example,

Here, the condition of the while loop is always True . However, if the user enters end , the loop termiantes because of the break statement.

Here, on the third iteration, the counter becomes 2 which terminates the loop. It then executes the else block and prints This is inside else block .

Note : The else block will not execute if the while loop is terminated by a break statement.

The for loop is usually used in the sequence when the number of iterations is known. For example,

The while loop is usually used when the number of iterations is unknown. For example,

Table of Contents

  • Introduction

Before we wrap up, let’s put your knowledge of Python while loop to the test! Can you solve the following challenge?

Write a function to get the Fibonacci sequence less than a given number.

  • The Fibonacci sequence starts with 0 and 1 . Each subsequent number is the sum of the previous two.
  • For input 22 , the return value should be [0, 1, 1, 2, 3, 5, 8, 13, 21]

Video: Python while Loop

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

Python Tutorial

Logo for Rebus Press

Want to create or adapt books like this? Learn more about how Pressbooks supports open publishing practices.

Kenneth Leroy Busbee

A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. [1]

Introduction to Test Before Loops

There are two commonly used test before loops in the iteration (or repetition) category of control structures. They are: while and for. This module covers the: while.

Understanding Iteration in General – while

The concept of iteration is connected to possibly wanting to repeat an action. Like all control structures we ask a question to control the execution of the loop. The term loop comes from the circular looping motion that occurs when using flowcharting. The basic form of the while loop is as follows:

In most programming languages the question (called a test expression) is a Boolean expression. The Boolean data type has two values – true and false. Let’s rewrite the structure to consider this:

Within the while control structure there are four attributes to a properly working loop. They are:

  • Initializing the flag
  • Test expression
  • Action or actions
  • Update of the flag

The initialization of the flag is not technically part of the control structure, but a necessary item to occur before the loop is started. The English phrasing is, “While the expression is true, do the following actions”. This is looping on the true. When the test expression is false, you stop the loop and go on with the next item in the program. Notice, because this is a test before loop the action  might not happen . It is called a test before loop because the test comes before the action. It is also sometimes called a pre-test loop, meaning the test is pre (or Latin for before) the action and update.

Human Example of the while Loop

Consider the following one-way conversation from a mother to her child.

Child: The child says nothing, but mother knows the child had Cheerios for breakfast and history tells us that the child most likely spilled some Cheerios on the floor.

Mother says: “While it is true that you see (As long as you can see) a Cheerio on the floor, pick it up and put it in the garbage.”

Note: All of the elements are present to determine the action (or flow) that the child will be doing (in this case repeating). Because the question (can you see a Cheerios) has only two possible answers (true or false) the action will continue while there are Cheerios on the floor. Either the child 1) never picks up a Cheerio because they never spilled any or 2) picks up a Cheerio and keeps picking up Cheerios one at a time while he can see a Cheerio on the floor (that is until they are all picked up).

Infinite Loops

At this point, it is worth mentioning that good programming always provides for a method to ensure that the loop question will eventually be false so that the loop will stop executing and the program continues with the next line of code.  However, if this does not happen, then the program is in an infinite loop.  Infinite loops are a bad thing. Consider the following code:

Pseudocode infinite loop

The programmer assigned a value to the flag before the loop which is correct. However, they forgot to update the flag. Every time the test expression is asked it will always be true. Thus, an infinite loop because the programmer did not provide a way to exit the loop (he forgot to update the flag). Consider the following code:

No matter what the user replies during the flag update, the test expression does not do a relational comparison but does an assignment. It assigns ‘y’ to the variable and asks if ‘y’ is true? Since all non-zero values are treated as representing true, the answer to the test expression is true. Viola, you have an infinite loop.

Counting Loops

The examples above are for an event controlled loop. The flag updating is an event where someone decides if they want the loop to execute again. Often the initialization sets the flag so that the loop will execute at least once.

Another common usage of the while loop is as a counting loop. Consider:

The variable counter is said to be controlling the loop.  It is set to zero (called initialization) before entering the while loop structure and as long as it is less than 5 (five); the loop action will be executed.  But part of the loop action uses the increment operator to increase counter’s value by one.  After executing the loop five times (once for counter’s values of: 0, 1, 2, 3 and 4) the expression will be false and the next line of code in the program will execute. A counting loop is designed to execute the action (which could be more than one statement) a set of given number of times. In our example, the message is displayed five times on the monitor. It is accomplished by making sure all four attributes of the while control structure are present and working properly. The attributes are:

Missing an attribute might cause an infinite loop or give undesired results (does not work properly).

Missing the flag update usually causes an infinite loop.

Variations on Counting

In the following example, the integer variable age is said to be controlling the loop (that is the flag). We can assume that age has a value provided earlier in the program. Because the while structure is a test before loop; it is possible that the person’s age is 0 (zero) and the first time we test the expression it will be false and the action part of the loop would never be executed.

Consider the following variation assuming that age and counter are both integer data type and that age has a value:

This loop is a counting loop similar to our first counting loop example. The only difference is instead of using a literal constant (in other words 5) in our expression, we used the variable age (and thus the value stored in age) to determine how many times to execute the loop. However, unlike our first counting loop example which will always execute exactly 5 times; it is possible that the person’s age is 0 (zero) and the first time we test the expression it will be false and the action part of the loop would never be executed.

  • cnx.org: Programming Fundamentals – A Modular Structured Approach using C++
  • Wikipedia: While loop ↵
  • Wikipedia: Infinite loop ↵

Programming Fundamentals Copyright © 2018 by Kenneth Leroy Busbee is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License , except where otherwise noted.

Share This Book

Python While Loop Tutorial – While True Syntax Examples and Infinite Loops

Estefania Cassingena Navone

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:

Image

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:

Image

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

Image

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

🔸 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 ):

If we run the code, we see this output:

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

Image

  • 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:

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 .
  • Then, we define a while loop that will run while len(nums) < 4 .
  • We ask for user input with the input() function and store it in the user_input variable.

💡 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 it's even, we append it to the nums list.
  • 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:

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

Image

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

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.

Image

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 :

We see this output when the code runs:

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:

Image

  • 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?

We see this output:

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:

Image

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 ?

Image

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:

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.

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:

Image

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:

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:

Image

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:

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.

Image

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:

Image

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:

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:

Image

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

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

The third line checks if the input is odd.

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

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

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:

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

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 .

I'm a software developer, technical writer and online instructor. I love writing detailed articles with diagrams and step by step explanations.

If you read this far, thank the author to show them you care. Say Thanks

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

Python Enhancement Proposals

  • Python »
  • PEP Index »

PEP 572 – Assignment Expressions

The importance of real code, exceptional cases, scope of the target, relative precedence of :=, change to evaluation order, differences between assignment expressions and assignment statements, specification changes during implementation, _pydecimal.py, datetime.py, sysconfig.py, simplifying list comprehensions, capturing condition values, changing the scope rules for comprehensions, alternative spellings, special-casing conditional statements, special-casing comprehensions, lowering operator precedence, allowing commas to the right, always requiring parentheses, why not just turn existing assignment into an expression, with assignment expressions, why bother with assignment statements, why not use a sublocal scope and prevent namespace pollution, style guide recommendations, acknowledgements, a numeric example, appendix b: rough code translations for comprehensions, appendix c: no changes to scope semantics.

This is a proposal for creating a way to assign to variables within an expression using the notation NAME := expr .

As part of this change, there is also an update to dictionary comprehension evaluation order to ensure key expressions are executed before value expressions (allowing the key to be bound to a name and then re-used as part of calculating the corresponding value).

During discussion of this PEP, the operator became informally known as “the walrus operator”. The construct’s formal name is “Assignment Expressions” (as per the PEP title), but they may also be referred to as “Named Expressions” (e.g. the CPython reference implementation uses that name internally).

Naming the result of an expression is an important part of programming, allowing a descriptive name to be used in place of a longer expression, and permitting reuse. Currently, this feature is available only in statement form, making it unavailable in list comprehensions and other expression contexts.

Additionally, naming sub-parts of a large expression can assist an interactive debugger, providing useful display hooks and partial results. Without a way to capture sub-expressions inline, this would require refactoring of the original code; with assignment expressions, this merely requires the insertion of a few name := markers. Removing the need to refactor reduces the likelihood that the code be inadvertently changed as part of debugging (a common cause of Heisenbugs), and is easier to dictate to another programmer.

During the development of this PEP many people (supporters and critics both) have had a tendency to focus on toy examples on the one hand, and on overly complex examples on the other.

The danger of toy examples is twofold: they are often too abstract to make anyone go “ooh, that’s compelling”, and they are easily refuted with “I would never write it that way anyway”.

The danger of overly complex examples is that they provide a convenient strawman for critics of the proposal to shoot down (“that’s obfuscated”).

Yet there is some use for both extremely simple and extremely complex examples: they are helpful to clarify the intended semantics. Therefore, there will be some of each below.

However, in order to be compelling , examples should be rooted in real code, i.e. code that was written without any thought of this PEP, as part of a useful application, however large or small. Tim Peters has been extremely helpful by going over his own personal code repository and picking examples of code he had written that (in his view) would have been clearer if rewritten with (sparing) use of assignment expressions. His conclusion: the current proposal would have allowed a modest but clear improvement in quite a few bits of code.

Another use of real code is to observe indirectly how much value programmers place on compactness. Guido van Rossum searched through a Dropbox code base and discovered some evidence that programmers value writing fewer lines over shorter lines.

Case in point: Guido found several examples where a programmer repeated a subexpression, slowing down the program, in order to save one line of code, e.g. instead of writing:

they would write:

Another example illustrates that programmers sometimes do more work to save an extra level of indentation:

This code tries to match pattern2 even if pattern1 has a match (in which case the match on pattern2 is never used). The more efficient rewrite would have been:

Syntax and semantics

In most contexts where arbitrary Python expressions can be used, a named expression can appear. This is of the form NAME := expr where expr is any valid Python expression other than an unparenthesized tuple, and NAME is an identifier.

The value of such a named expression is the same as the incorporated expression, with the additional side-effect that the target is assigned that value:

There are a few places where assignment expressions are not allowed, in order to avoid ambiguities or user confusion:

This rule is included to simplify the choice for the user between an assignment statement and an assignment expression – there is no syntactic position where both are valid.

Again, this rule is included to avoid two visually similar ways of saying the same thing.

This rule is included to disallow excessively confusing code, and because parsing keyword arguments is complex enough already.

This rule is included to discourage side effects in a position whose exact semantics are already confusing to many users (cf. the common style recommendation against mutable default values), and also to echo the similar prohibition in calls (the previous bullet).

The reasoning here is similar to the two previous cases; this ungrouped assortment of symbols and operators composed of : and = is hard to read correctly.

This allows lambda to always bind less tightly than := ; having a name binding at the top level inside a lambda function is unlikely to be of value, as there is no way to make use of it. In cases where the name will be used more than once, the expression is likely to need parenthesizing anyway, so this prohibition will rarely affect code.

This shows that what looks like an assignment operator in an f-string is not always an assignment operator. The f-string parser uses : to indicate formatting options. To preserve backwards compatibility, assignment operator usage inside of f-strings must be parenthesized. As noted above, this usage of the assignment operator is not recommended.

An assignment expression does not introduce a new scope. In most cases the scope in which the target will be bound is self-explanatory: it is the current scope. If this scope contains a nonlocal or global declaration for the target, the assignment expression honors that. A lambda (being an explicit, if anonymous, function definition) counts as a scope for this purpose.

There is one special case: an assignment expression occurring in a list, set or dict comprehension or in a generator expression (below collectively referred to as “comprehensions”) binds the target in the containing scope, honoring a nonlocal or global declaration for the target in that scope, if one exists. For the purpose of this rule the containing scope of a nested comprehension is the scope that contains the outermost comprehension. A lambda counts as a containing scope.

The motivation for this special case is twofold. First, it allows us to conveniently capture a “witness” for an any() expression, or a counterexample for all() , for example:

Second, it allows a compact way of updating mutable state from a comprehension, for example:

However, an assignment expression target name cannot be the same as a for -target name appearing in any comprehension containing the assignment expression. The latter names are local to the comprehension in which they appear, so it would be contradictory for a contained use of the same name to refer to the scope containing the outermost comprehension instead.

For example, [i := i+1 for i in range(5)] is invalid: the for i part establishes that i is local to the comprehension, but the i := part insists that i is not local to the comprehension. The same reason makes these examples invalid too:

While it’s technically possible to assign consistent semantics to these cases, it’s difficult to determine whether those semantics actually make sense in the absence of real use cases. Accordingly, the reference implementation [1] will ensure that such cases raise SyntaxError , rather than executing with implementation defined behaviour.

This restriction applies even if the assignment expression is never executed:

For the comprehension body (the part before the first “for” keyword) and the filter expression (the part after “if” and before any nested “for”), this restriction applies solely to target names that are also used as iteration variables in the comprehension. Lambda expressions appearing in these positions introduce a new explicit function scope, and hence may use assignment expressions with no additional restrictions.

Due to design constraints in the reference implementation (the symbol table analyser cannot easily detect when names are re-used between the leftmost comprehension iterable expression and the rest of the comprehension), named expressions are disallowed entirely as part of comprehension iterable expressions (the part after each “in”, and before any subsequent “if” or “for” keyword):

A further exception applies when an assignment expression occurs in a comprehension whose containing scope is a class scope. If the rules above were to result in the target being assigned in that class’s scope, the assignment expression is expressly invalid. This case also raises SyntaxError :

(The reason for the latter exception is the implicit function scope created for comprehensions – there is currently no runtime mechanism for a function to refer to a variable in the containing class scope, and we do not want to add such a mechanism. If this issue ever gets resolved this special case may be removed from the specification of assignment expressions. Note that the problem already exists for using a variable defined in the class scope from a comprehension.)

See Appendix B for some examples of how the rules for targets in comprehensions translate to equivalent code.

The := operator groups more tightly than a comma in all syntactic positions where it is legal, but less tightly than all other operators, including or , and , not , and conditional expressions ( A if C else B ). As follows from section “Exceptional cases” above, it is never allowed at the same level as = . In case a different grouping is desired, parentheses should be used.

The := operator may be used directly in a positional function call argument; however it is invalid directly in a keyword argument.

Some examples to clarify what’s technically valid or invalid:

Most of the “valid” examples above are not recommended, since human readers of Python source code who are quickly glancing at some code may miss the distinction. But simple cases are not objectionable:

This PEP recommends always putting spaces around := , similar to PEP 8 ’s recommendation for = when used for assignment, whereas the latter disallows spaces around = used for keyword arguments.)

In order to have precisely defined semantics, the proposal requires evaluation order to be well-defined. This is technically not a new requirement, as function calls may already have side effects. Python already has a rule that subexpressions are generally evaluated from left to right. However, assignment expressions make these side effects more visible, and we propose a single change to the current evaluation order:

  • In a dict comprehension {X: Y for ...} , Y is currently evaluated before X . We propose to change this so that X is evaluated before Y . (In a dict display like {X: Y} this is already the case, and also in dict((X, Y) for ...) which should clearly be equivalent to the dict comprehension.)

Most importantly, since := is an expression, it can be used in contexts where statements are illegal, including lambda functions and comprehensions.

Conversely, assignment expressions don’t support the advanced features found in assignment statements:

  • Multiple targets are not directly supported: x = y = z = 0 # Equivalent: (z := (y := (x := 0)))
  • Single assignment targets other than a single NAME are not supported: # No equivalent a [ i ] = x self . rest = []
  • Priority around commas is different: x = 1 , 2 # Sets x to (1, 2) ( x := 1 , 2 ) # Sets x to 1
  • Iterable packing and unpacking (both regular or extended forms) are not supported: # Equivalent needs extra parentheses loc = x , y # Use (loc := (x, y)) info = name , phone , * rest # Use (info := (name, phone, *rest)) # No equivalent px , py , pz = position name , phone , email , * other_info = contact
  • Inline type annotations are not supported: # Closest equivalent is "p: Optional[int]" as a separate declaration p : Optional [ int ] = None
  • Augmented assignment is not supported: total += tax # Equivalent: (total := total + tax)

The following changes have been made based on implementation experience and additional review after the PEP was first accepted and before Python 3.8 was released:

  • for consistency with other similar exceptions, and to avoid locking in an exception name that is not necessarily going to improve clarity for end users, the originally proposed TargetScopeError subclass of SyntaxError was dropped in favour of just raising SyntaxError directly. [3]
  • due to a limitation in CPython’s symbol table analysis process, the reference implementation raises SyntaxError for all uses of named expressions inside comprehension iterable expressions, rather than only raising them when the named expression target conflicts with one of the iteration variables in the comprehension. This could be revisited given sufficiently compelling examples, but the extra complexity needed to implement the more selective restriction doesn’t seem worthwhile for purely hypothetical use cases.

Examples from the Python standard library

env_base is only used on these lines, putting its assignment on the if moves it as the “header” of the block.

  • Current: env_base = os . environ . get ( "PYTHONUSERBASE" , None ) if env_base : return env_base
  • Improved: if env_base := os . environ . get ( "PYTHONUSERBASE" , None ): return env_base

Avoid nested if and remove one indentation level.

  • Current: if self . _is_special : ans = self . _check_nans ( context = context ) if ans : return ans
  • Improved: if self . _is_special and ( ans := self . _check_nans ( context = context )): return ans

Code looks more regular and avoid multiple nested if. (See Appendix A for the origin of this example.)

  • Current: reductor = dispatch_table . get ( cls ) if reductor : rv = reductor ( x ) else : reductor = getattr ( x , "__reduce_ex__" , None ) if reductor : rv = reductor ( 4 ) else : reductor = getattr ( x , "__reduce__" , None ) if reductor : rv = reductor () else : raise Error ( "un(deep)copyable object of type %s " % cls )
  • Improved: if reductor := dispatch_table . get ( cls ): rv = reductor ( x ) elif reductor := getattr ( x , "__reduce_ex__" , None ): rv = reductor ( 4 ) elif reductor := getattr ( x , "__reduce__" , None ): rv = reductor () else : raise Error ( "un(deep)copyable object of type %s " % cls )

tz is only used for s += tz , moving its assignment inside the if helps to show its scope.

  • Current: s = _format_time ( self . _hour , self . _minute , self . _second , self . _microsecond , timespec ) tz = self . _tzstr () if tz : s += tz return s
  • Improved: s = _format_time ( self . _hour , self . _minute , self . _second , self . _microsecond , timespec ) if tz := self . _tzstr (): s += tz return s

Calling fp.readline() in the while condition and calling .match() on the if lines make the code more compact without making it harder to understand.

  • Current: while True : line = fp . readline () if not line : break m = define_rx . match ( line ) if m : n , v = m . group ( 1 , 2 ) try : v = int ( v ) except ValueError : pass vars [ n ] = v else : m = undef_rx . match ( line ) if m : vars [ m . group ( 1 )] = 0
  • Improved: while line := fp . readline (): if m := define_rx . match ( line ): n , v = m . group ( 1 , 2 ) try : v = int ( v ) except ValueError : pass vars [ n ] = v elif m := undef_rx . match ( line ): vars [ m . group ( 1 )] = 0

A list comprehension can map and filter efficiently by capturing the condition:

Similarly, a subexpression can be reused within the main expression, by giving it a name on first use:

Note that in both cases the variable y is bound in the containing scope (i.e. at the same level as results or stuff ).

Assignment expressions can be used to good effect in the header of an if or while statement:

Particularly with the while loop, this can remove the need to have an infinite loop, an assignment, and a condition. It also creates a smooth parallel between a loop which simply uses a function call as its condition, and one which uses that as its condition but also uses the actual value.

An example from the low-level UNIX world:

Rejected alternative proposals

Proposals broadly similar to this one have come up frequently on python-ideas. Below are a number of alternative syntaxes, some of them specific to comprehensions, which have been rejected in favour of the one given above.

A previous version of this PEP proposed subtle changes to the scope rules for comprehensions, to make them more usable in class scope and to unify the scope of the “outermost iterable” and the rest of the comprehension. However, this part of the proposal would have caused backwards incompatibilities, and has been withdrawn so the PEP can focus on assignment expressions.

Broadly the same semantics as the current proposal, but spelled differently.

Since EXPR as NAME already has meaning in import , except and with statements (with different semantics), this would create unnecessary confusion or require special-casing (e.g. to forbid assignment within the headers of these statements).

(Note that with EXPR as VAR does not simply assign the value of EXPR to VAR – it calls EXPR.__enter__() and assigns the result of that to VAR .)

Additional reasons to prefer := over this spelling include:

  • In if f(x) as y the assignment target doesn’t jump out at you – it just reads like if f x blah blah and it is too similar visually to if f(x) and y .
  • import foo as bar
  • except Exc as var
  • with ctxmgr() as var

To the contrary, the assignment expression does not belong to the if or while that starts the line, and we intentionally allow assignment expressions in other contexts as well.

  • NAME = EXPR
  • if NAME := EXPR

reinforces the visual recognition of assignment expressions.

This syntax is inspired by languages such as R and Haskell, and some programmable calculators. (Note that a left-facing arrow y <- f(x) is not possible in Python, as it would be interpreted as less-than and unary minus.) This syntax has a slight advantage over ‘as’ in that it does not conflict with with , except and import , but otherwise is equivalent. But it is entirely unrelated to Python’s other use of -> (function return type annotations), and compared to := (which dates back to Algol-58) it has a much weaker tradition.

This has the advantage that leaked usage can be readily detected, removing some forms of syntactic ambiguity. However, this would be the only place in Python where a variable’s scope is encoded into its name, making refactoring harder.

Execution order is inverted (the indented body is performed first, followed by the “header”). This requires a new keyword, unless an existing keyword is repurposed (most likely with: ). See PEP 3150 for prior discussion on this subject (with the proposed keyword being given: ).

This syntax has fewer conflicts than as does (conflicting only with the raise Exc from Exc notation), but is otherwise comparable to it. Instead of paralleling with expr as target: (which can be useful but can also be confusing), this has no parallels, but is evocative.

One of the most popular use-cases is if and while statements. Instead of a more general solution, this proposal enhances the syntax of these two statements to add a means of capturing the compared value:

This works beautifully if and ONLY if the desired condition is based on the truthiness of the captured value. It is thus effective for specific use-cases (regex matches, socket reads that return '' when done), and completely useless in more complicated cases (e.g. where the condition is f(x) < 0 and you want to capture the value of f(x) ). It also has no benefit to list comprehensions.

Advantages: No syntactic ambiguities. Disadvantages: Answers only a fraction of possible use-cases, even in if / while statements.

Another common use-case is comprehensions (list/set/dict, and genexps). As above, proposals have been made for comprehension-specific solutions.

This brings the subexpression to a location in between the ‘for’ loop and the expression. It introduces an additional language keyword, which creates conflicts. Of the three, where reads the most cleanly, but also has the greatest potential for conflict (e.g. SQLAlchemy and numpy have where methods, as does tkinter.dnd.Icon in the standard library).

As above, but reusing the with keyword. Doesn’t read too badly, and needs no additional language keyword. Is restricted to comprehensions, though, and cannot as easily be transformed into “longhand” for-loop syntax. Has the C problem that an equals sign in an expression can now create a name binding, rather than performing a comparison. Would raise the question of why “with NAME = EXPR:” cannot be used as a statement on its own.

As per option 2, but using as rather than an equals sign. Aligns syntactically with other uses of as for name binding, but a simple transformation to for-loop longhand would create drastically different semantics; the meaning of with inside a comprehension would be completely different from the meaning as a stand-alone statement, while retaining identical syntax.

Regardless of the spelling chosen, this introduces a stark difference between comprehensions and the equivalent unrolled long-hand form of the loop. It is no longer possible to unwrap the loop into statement form without reworking any name bindings. The only keyword that can be repurposed to this task is with , thus giving it sneakily different semantics in a comprehension than in a statement; alternatively, a new keyword is needed, with all the costs therein.

There are two logical precedences for the := operator. Either it should bind as loosely as possible, as does statement-assignment; or it should bind more tightly than comparison operators. Placing its precedence between the comparison and arithmetic operators (to be precise: just lower than bitwise OR) allows most uses inside while and if conditions to be spelled without parentheses, as it is most likely that you wish to capture the value of something, then perform a comparison on it:

Once find() returns -1, the loop terminates. If := binds as loosely as = does, this would capture the result of the comparison (generally either True or False ), which is less useful.

While this behaviour would be convenient in many situations, it is also harder to explain than “the := operator behaves just like the assignment statement”, and as such, the precedence for := has been made as close as possible to that of = (with the exception that it binds tighter than comma).

Some critics have claimed that the assignment expressions should allow unparenthesized tuples on the right, so that these two would be equivalent:

(With the current version of the proposal, the latter would be equivalent to ((point := x), y) .)

However, adopting this stance would logically lead to the conclusion that when used in a function call, assignment expressions also bind less tight than comma, so we’d have the following confusing equivalence:

The less confusing option is to make := bind more tightly than comma.

It’s been proposed to just always require parentheses around an assignment expression. This would resolve many ambiguities, and indeed parentheses will frequently be needed to extract the desired subexpression. But in the following cases the extra parentheses feel redundant:

Frequently Raised Objections

C and its derivatives define the = operator as an expression, rather than a statement as is Python’s way. This allows assignments in more contexts, including contexts where comparisons are more common. The syntactic similarity between if (x == y) and if (x = y) belies their drastically different semantics. Thus this proposal uses := to clarify the distinction.

The two forms have different flexibilities. The := operator can be used inside a larger expression; the = statement can be augmented to += and its friends, can be chained, and can assign to attributes and subscripts.

Previous revisions of this proposal involved sublocal scope (restricted to a single statement), preventing name leakage and namespace pollution. While a definite advantage in a number of situations, this increases complexity in many others, and the costs are not justified by the benefits. In the interests of language simplicity, the name bindings created here are exactly equivalent to any other name bindings, including that usage at class or module scope will create externally-visible names. This is no different from for loops or other constructs, and can be solved the same way: del the name once it is no longer needed, or prefix it with an underscore.

(The author wishes to thank Guido van Rossum and Christoph Groth for their suggestions to move the proposal in this direction. [2] )

As expression assignments can sometimes be used equivalently to statement assignments, the question of which should be preferred will arise. For the benefit of style guides such as PEP 8 , two recommendations are suggested.

  • If either assignment statements or assignment expressions can be used, prefer statements; they are a clear declaration of intent.
  • If using assignment expressions would lead to ambiguity about execution order, restructure it to use statements instead.

The authors wish to thank Alyssa Coghlan and Steven D’Aprano for their considerable contributions to this proposal, and members of the core-mentorship mailing list for assistance with implementation.

Appendix A: Tim Peters’s findings

Here’s a brief essay Tim Peters wrote on the topic.

I dislike “busy” lines of code, and also dislike putting conceptually unrelated logic on a single line. So, for example, instead of:

instead. So I suspected I’d find few places I’d want to use assignment expressions. I didn’t even consider them for lines already stretching halfway across the screen. In other cases, “unrelated” ruled:

is a vast improvement over the briefer:

The original two statements are doing entirely different conceptual things, and slamming them together is conceptually insane.

In other cases, combining related logic made it harder to understand, such as rewriting:

as the briefer:

The while test there is too subtle, crucially relying on strict left-to-right evaluation in a non-short-circuiting or method-chaining context. My brain isn’t wired that way.

But cases like that were rare. Name binding is very frequent, and “sparse is better than dense” does not mean “almost empty is better than sparse”. For example, I have many functions that return None or 0 to communicate “I have nothing useful to return in this case, but since that’s expected often I’m not going to annoy you with an exception”. This is essentially the same as regular expression search functions returning None when there is no match. So there was lots of code of the form:

I find that clearer, and certainly a bit less typing and pattern-matching reading, as:

It’s also nice to trade away a small amount of horizontal whitespace to get another _line_ of surrounding code on screen. I didn’t give much weight to this at first, but it was so very frequent it added up, and I soon enough became annoyed that I couldn’t actually run the briefer code. That surprised me!

There are other cases where assignment expressions really shine. Rather than pick another from my code, Kirill Balunov gave a lovely example from the standard library’s copy() function in copy.py :

The ever-increasing indentation is semantically misleading: the logic is conceptually flat, “the first test that succeeds wins”:

Using easy assignment expressions allows the visual structure of the code to emphasize the conceptual flatness of the logic; ever-increasing indentation obscured it.

A smaller example from my code delighted me, both allowing to put inherently related logic in a single line, and allowing to remove an annoying “artificial” indentation level:

That if is about as long as I want my lines to get, but remains easy to follow.

So, in all, in most lines binding a name, I wouldn’t use assignment expressions, but because that construct is so very frequent, that leaves many places I would. In most of the latter, I found a small win that adds up due to how often it occurs, and in the rest I found a moderate to major win. I’d certainly use it more often than ternary if , but significantly less often than augmented assignment.

I have another example that quite impressed me at the time.

Where all variables are positive integers, and a is at least as large as the n’th root of x, this algorithm returns the floor of the n’th root of x (and roughly doubling the number of accurate bits per iteration):

It’s not obvious why that works, but is no more obvious in the “loop and a half” form. It’s hard to prove correctness without building on the right insight (the “arithmetic mean - geometric mean inequality”), and knowing some non-trivial things about how nested floor functions behave. That is, the challenges are in the math, not really in the coding.

If you do know all that, then the assignment-expression form is easily read as “while the current guess is too large, get a smaller guess”, where the “too large?” test and the new guess share an expensive sub-expression.

To my eyes, the original form is harder to understand:

This appendix attempts to clarify (though not specify) the rules when a target occurs in a comprehension or in a generator expression. For a number of illustrative examples we show the original code, containing a comprehension, and the translation, where the comprehension has been replaced by an equivalent generator function plus some scaffolding.

Since [x for ...] is equivalent to list(x for ...) these examples all use list comprehensions without loss of generality. And since these examples are meant to clarify edge cases of the rules, they aren’t trying to look like real code.

Note: comprehensions are already implemented via synthesizing nested generator functions like those in this appendix. The new part is adding appropriate declarations to establish the intended scope of assignment expression targets (the same scope they resolve to as if the assignment were performed in the block containing the outermost comprehension). For type inference purposes, these illustrative expansions do not imply that assignment expression targets are always Optional (but they do indicate the target binding scope).

Let’s start with a reminder of what code is generated for a generator expression without assignment expression.

  • Original code (EXPR usually references VAR): def f (): a = [ EXPR for VAR in ITERABLE ]
  • Translation (let’s not worry about name conflicts): def f (): def genexpr ( iterator ): for VAR in iterator : yield EXPR a = list ( genexpr ( iter ( ITERABLE )))

Let’s add a simple assignment expression.

  • Original code: def f (): a = [ TARGET := EXPR for VAR in ITERABLE ]
  • Translation: def f (): if False : TARGET = None # Dead code to ensure TARGET is a local variable def genexpr ( iterator ): nonlocal TARGET for VAR in iterator : TARGET = EXPR yield TARGET a = list ( genexpr ( iter ( ITERABLE )))

Let’s add a global TARGET declaration in f() .

  • Original code: def f (): global TARGET a = [ TARGET := EXPR for VAR in ITERABLE ]
  • Translation: def f (): global TARGET def genexpr ( iterator ): global TARGET for VAR in iterator : TARGET = EXPR yield TARGET a = list ( genexpr ( iter ( ITERABLE )))

Or instead let’s add a nonlocal TARGET declaration in f() .

  • Original code: def g (): TARGET = ... def f (): nonlocal TARGET a = [ TARGET := EXPR for VAR in ITERABLE ]
  • Translation: def g (): TARGET = ... def f (): nonlocal TARGET def genexpr ( iterator ): nonlocal TARGET for VAR in iterator : TARGET = EXPR yield TARGET a = list ( genexpr ( iter ( ITERABLE )))

Finally, let’s nest two comprehensions.

  • Original code: def f (): a = [[ TARGET := i for i in range ( 3 )] for j in range ( 2 )] # I.e., a = [[0, 1, 2], [0, 1, 2]] print ( TARGET ) # prints 2
  • Translation: def f (): if False : TARGET = None def outer_genexpr ( outer_iterator ): nonlocal TARGET def inner_generator ( inner_iterator ): nonlocal TARGET for i in inner_iterator : TARGET = i yield i for j in outer_iterator : yield list ( inner_generator ( range ( 3 ))) a = list ( outer_genexpr ( range ( 2 ))) print ( TARGET )

Because it has been a point of confusion, note that nothing about Python’s scoping semantics is changed. Function-local scopes continue to be resolved at compile time, and to have indefinite temporal extent at run time (“full closures”). Example:

This document has been placed in the public domain.

Source: https://github.com/python/peps/blob/main/peps/pep-0572.rst

Last modified: 2023-10-11 12:05:51 GMT

18 Python while Loop Examples and Exercises

In Python programming, we use while loops to do a task a certain number of times repeatedly. The while loop checks a condition and executes the task as long as that condition is satisfied. The loop will stop its execution once the condition becomes not satisfied.

1. Example of using while loops in Python

2. example of using the break statement in while loops.

In Python, we can use the  break  statement to end a while loop prematurely.

3. Example of using the continue statement in while loops

4. using if-elif-else statements inside while loop, 5. adding elements to a list using while loop, 6. python while loop to print a number series, 7. printing the items in a tuple using while loop, 8. finding the sum of numbers in a list using while loop, 9. popping out elements from a list using while loop, 10. printing all letters except some using python while loop, 11. python while loop to take inputs from the user, 12. converting numbers from decimal to binary using while loop, 13. finding the average of 5 numbers using while loop, 14. printing the square of numbers using while loop, 15. finding the multiples of a number using while loop, 16. reversing a number using while loop in python, 17. finding the sum of even numbers using while loop, 18. finding the factorial of a given number using while loop.

I hope this article was helpful. Check out my post on 21 Python for Loop Examples .

16 thoughts on “ 18 Python while Loop Examples and Exercises ”

I am looking for a way to take user inputs in while loop & compare it & print the smallest/largest value. Can you help?

Write a program that reads a value V, and then starts to read further values and adds them to a List until the initial value V is added again. Don’t add the first V and last V to the list. Print the list to the console.

print(f”The given list of numerical entities is formed by {internal_list}”) if i >= x: print(f”The maximal value contained by user’ list is equal with… {max(internal_list)}”) else: pass

i=0 newlist=[] #create an empty list while i<5: #for 5 values x=int(input(' Enter numbers')) i+=1 newlist.append(x) print(newlist) #you may skip this line print("The smallest number is", min(newlist))

Printing the items in a tuple using while loop exercise shows wrong answer please review the answer.

# Now i want to see both methods while and for to striped out the strip’s values from the name’s letters.

Rony its true but what do you mean by write coments on your code

Leave a Reply Cancel reply

Recent posts.

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

The while statement creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.

An expression evaluated before each pass through the loop. If this condition evaluates to true , statement is executed. When condition evaluates to false , execution continues with the statement after the while loop.

A statement that is executed as long as the condition evaluates to true. You can use a block statement to execute multiple statements.

Description

Like other looping statements, you can use control flow statements inside statement :

  • break stops statement execution and goes to the first statement after the loop.
  • continue stops statement execution and re-evaluates condition .

Using while

The following while loop iterates as long as n is less than three.

Each iteration, the loop increments n and adds it to x . Therefore, x and n take on the following values:

  • After the first pass: n = 1 and x = 1
  • After the second pass: n = 2 and x = 3
  • After the third pass: n = 3 and x = 6

After completing the third pass, the condition n < 3 is no longer true, so the loop terminates.

Using an assignment as a condition

In some cases, it can make sense to use an assignment as a condition. This comes with readability tradeoffs, so there are certain stylistic recommendations that would make the pattern more obvious for everyone.

Consider the following example, which iterates over a document's comments, logging them to the console.

That's not completely a good-practice example, due to the following line specifically:

The effect of that line is fine — in that, each time a comment node is found:

  • iterator.nextNode() returns that comment node, which gets assigned to currentNode .
  • The value of currentNode = iterator.nextNode() is therefore truthy .
  • So the console.log() call executes and the loop continues.

…and then, when there are no more comment nodes in the document:

  • iterator.nextNode() returns null .
  • The value of currentNode = iterator.nextNode() is therefore also null , which is falsy .
  • So the loop ends.

The problem with this line is: conditions typically use comparison operators such as === , but the = in that line isn't a comparison operator — instead, it's an assignment operator . So that = looks like it's a typo for === — even though it's not actually a typo.

Therefore, in cases like that one, some code-linting tools such as ESLint's no-cond-assign rule — in order to help you catch a possible typo so that you can fix it — will report a warning such as the following:

Expected a conditional expression and instead saw an assignment.

Many style guides recommend more explicitly indicating the intention for the condition to be an assignment. You can do that minimally by putting additional parentheses as a grouping operator around the assignment:

In fact, this is the style enforced by ESLint's no-cond-assign 's default configuration, as well as Prettier , so you'll likely see this pattern a lot in the wild.

Some people may further recommend adding a comparison operator to turn the condition into an explicit comparison:

There are other ways to write this pattern, such as:

Or, forgoing the idea of using a while loop altogether:

If the reader is sufficiently familiar with the assignment as condition pattern, all these variations should have equivalent readability. Otherwise, the last form is probably the most readable, albeit the most verbose.

Specifications

Specification

Browser compatibility

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Preprocessors
  • C File Handling
  • C Cheatsheet
  • C Interview Questions

while loop in C

The while Loop is an entry-controlled loop in C programming language. This loop can be used to iterate a part of code while the given condition remains true.

The while loop syntax is as follows:

The below example shows how to use a while loop in a C program

while Loop Structure

The while loop works by following a very structured top-down approach that can be divided into the following parts:

  • Initialization: In this step, we initialize the loop variable to some initial value. Initialization is not part of while loop syntax but it is essential when we are using some variable in the test expression  
  •  Conditional Statement: This is one of the most crucial steps as it decides whether the block in the while loop code will execute. The while loop body will be executed if and only the test condition defined in the conditional statement is true.  
  • Body: It is the actual set of statements that will be executed till the specified condition is true. It is generally enclosed inside { } braces.  
  • Updation: It is an expression that updates the value of the loop variable in each iteration. It is also not part of the syntax but we have to define it explicitly in the body of the loop.

Flowchart of while loop in C

C While Loop

Working of while Loop

We can understand the working of the while loop by looking at the above flowchart:

  • STEP 1: When the program first comes to the loop, the test condition will be evaluated.  
  • STEP 2A: If the test condition is false, the body of the loop will be skipped program will continue.  
  • STEP 2B: If the expression evaluates to true, the body of the loop will be executed.  
  • STEP 3:  After executing the body, the program control will go to STEP 1. This process will continue till the test expression is true.

Infinite w hile loop

An infinite while loop is created when the given condition is always true. It is encountered by programmers in when:

  • The test condition is incorrect.
  • Updation statement not present.

As seen in the above example, the loop will continue till infinite because the loop variable will always remain the same resulting in the condition that is always true.

Important Points

  • It is an entry-controlled loop.
  • It runs the block of statements till the conditions are satiated, once the conditions are not satisfied it will terminate.
  • Its workflow is firstly it checks the condition and then executes the body. Hence, a type of pre-tested loop.
  • This loop is generally preferred over for loop when the number of iterations is unknown.

author

Please Login to comment...

Similar reads.

  • Top Android Apps for 2024
  • Top Cell Phone Signal Boosters in 2024
  • Best Travel Apps (Paid & Free) in 2024
  • The Best Smart Home Devices for 2024
  • 15 Most Important Aptitude Topics For Placements [2024]

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Python Tutorial

File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python while loops, python loops.

Python has two primitive loop commands:

  • while loops

The while Loop

With the while loop we can execute a set of statements as long as a condition is true.

Print i as long as i is less than 6:

Note: remember to increment i, or else the loop will continue forever.

The while loop requires relevant variables to be ready, in this example we need to define an indexing variable, i , which we set to 1.

The break Statement

With the break statement we can stop the loop even if the while condition is true:

Exit the loop when i is 3:

Advertisement

The continue Statement

With the continue statement we can stop the current iteration, and continue with the next:

Continue to the next iteration if i is 3:

The else Statement

With the else statement we can run a block of code once when the condition no longer is true:

Print a message once the condition is false:

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Is it good practice to use array.pop() assignment in a while loop condition?

Just saw a code snippet that used an array pop assignment in the while condition; was wondering if this is acceptable/good practice?

  • programming-practices

flewk's user avatar

  • It's a destructive way to iterate (meaning the array is destroyed as you go). If you just want to iterate the array, modifying the array on each step of the iteration is wasted cycles. May as well use a traditional for look or the newer for/of or .forEach() to just iterate it. –  jfriend00 Commented Sep 8, 2016 at 23:41

2 Answers 2

It is not necessarily wrong if the code does what it is supposed to do, however, decisions such as this can be a matter of taste or opinion in personally written code. Conversely, avoiding this particular arrangement of logic may be a requirement of an employer.

Here are the things to consider.

  • Do you understand what the code is doing?
  • Is anyone else expected to read the code and understand what it is doing, and will it be relatively easy for them to read and understand what the code is doing?
  • Will the code be used as part of the development code on a project for a group or organization that implements Programming Style guidelines?

To be more specific, here are some pros and cons using the code in your example.

  • In specific use cases, such as an array which is guaranteed to contain objects or other "truthy" values, this way is concise, doubling as a conditional statement and an assignment statement.
  • If the array contains undefined , null , 0 , false , NaN , "" or has "holes" in it, this way will fail.

"Holes" means when the array has a length greater than 0 and some (or all) of the elements of the array have not been assigned a value.

"Truthy" means values that do not evaluate to false ( see the cons ). Do not forget NaN or "" , I almost just did.

The code in your example already contains a bug. The first element in the array will be missed. Why? The first element is zero, which when used in an assignment statement, returns the value zero, which is treated as false by the while loop, meaning the while loop stops before processing the last item on the "stack", or rather the first element in the array.

Community's user avatar

  • Could you expand this answer with the pros/cons of doing things this way? It might help the poster make these determinations. –  Alex Feinman Commented Sep 12, 2016 at 18:29
  • @AlexFeinman Will do. –  Nolo Commented Sep 12, 2016 at 20:14
  • 1 If you want to avoid issues with falsy values and keep it concise: while(arr.length) doStuffWithElement(arr.pop()) –  Felipe Müller Commented Feb 1, 2021 at 2:55

If the intention is to process the array like a queue or a stack, wherein items are removed as they're processed, yes. This is a pretty standard approach.

In fact, you'll sometimes see this sort of loop for tree traversals where stack overflows, or the need to pause and resume, are a potential problem in the recursive solution.

svidgen's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Software Engineering Stack Exchange. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged javascript programming-practices array loops conditions or ask your own question .

  • The Overflow Blog
  • The hidden cost of speed
  • The creator of Jenkins discusses CI/CD and balancing business with open source
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites

Hot Network Questions

  • How can I play MechWarrior 2?
  • How to connect 20 plus external hard drives to a computer?
  • When can the cat and mouse meet?
  • Cohomological range of a perverse sheaf
  • Dirichlet Series that fail to be L-functions
  • Using rule-based symbology for overlapping layers in QGIS
  • Numbering Equations in a Closed Bracket
  • If a Palestinian converts to Judaism, can they get Israeli citizenship?
  • When has the SR-71 been used for civilian purposes?
  • How Does This Antique Television Circuit Work?
  • An instructor is being added to co-teach a course for questionable reasons, against the course author's wishes—what can be done?
  • Blackboard math font that is compatible with mlmodern
  • Can a quadrilateral polygon have 3 obtuse angles?
  • Why doesn’t dust interfere with the adhesion of geckos’ feet?
  • Referencing an other tikzpicture without overlay
  • Escape from the magic prison
  • Why didn't Air Force Ones have camouflage?
  • Fusion September 2024: Where are we with respect to "engineering break even"?
  • Why would autopilot be prohibited below 1000 AGL?
  • Did Babylon 4 actually do anything in the first shadow war?
  • Has any astronomer ever observed that after a specific star going supernova it became a Black Hole?
  • Is it a good idea to perform I2C Communication in the ISR?
  • Is it safe to install programs other than with a distro's package manager?
  • Does it make sense for the governments of my world to genetically engineer soldiers?

assignment in while loop condition

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Assignment Within the Check of a While Loop

I was trying out the following basic summation program using while loops:

I'm having some trouble understanding why the while loop executes even if the user enters 0.

Anedar's user avatar

  • Reading references of functions/operators is better way to learn c++ than just wild guessing. –  kotlomoy Commented May 23, 2013 at 18:34

2 Answers 2

(std::cin >> userIn) will be != 0 if the input succeeded, not if the input was 0 .

To check both, you can do while ( (std::cint >> userIn) && userIn ) . This will first make sure that the input succeeded and then that the number is actually non-zero.

Luchian Grigore's user avatar

It would be beneficial for you to get used to reference pages like http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/

It describes the return value of the operator>>() function, which is the istream (cin) objects itself. This means that

while((std::cin >> userIn) != 0)

will not do what you expect it to do, and the loop will actually never be broken.

What you're actually looking for is something along the lines of

Steven Maitlall's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged c++ while-loop io or ask your own question .

  • The Overflow Blog
  • The hidden cost of speed
  • The creator of Jenkins discusses CI/CD and balancing business with open source
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • Why is there so much salt in cheese?
  • Is it a good idea to perform I2C Communication in the ISR?
  • Why are poverty definitions not based off a person's access to necessities rather than a fixed number?
  • Is loss of availability automatically a security incident?
  • Which weather condition causes the most accidents?
  • Deleting all files but some on Mac in Terminal
  • How can I prevent solid mix-ins from sinking or floating in my sous vide egg bites
  • Is there an error in Lurie, HTT, Proposition 6.1.2.6.?
  • Is it helpful to use a thicker gage wire for part of a long circuit run that could have higher loads?
  • Would an LEO asking for a race constitute entrapment?
  • How to run only selected lines of a shell script?
  • How to Interpret Statistically Non-Significant Estimates and Rule Out Large Effects?
  • How to change upward facing track lights 26 feet above living room?
  • If a Palestinian converts to Judaism, can they get Israeli citizenship?
  • A seven letter *
  • You find yourself locked in a room
  • Is it safe to install programs other than with a distro's package manager?
  • Cohomological range of a perverse sheaf
  • Why doesn’t dust interfere with the adhesion of geckos’ feet?
  • Thriller from the early to mid 1960's involving blackmailing an official over underage liason
  • How do I apologize to a lecturer who told me not to ever call him again?
  • How do I safely download and run an older version of software for testing without interfering with the currently installed version?
  • 99 camaro overheating
  • Pull up resistor question

assignment in while loop condition

IMAGES

  1. [Solved] Assignment Condition in Python While Loop

    assignment in while loop condition

  2. Python While Loop With Assignment [With 4 Real Examples]

    assignment in while loop condition

  3. How to use For Loop

    assignment in while loop condition

  4. While Loop MATLAB Example Completed by an Expert

    assignment in while loop condition

  5. Assignment statement

    assignment in while loop condition

  6. Python While Loop With Assignment [With 4 Real Examples]

    assignment in while loop condition

VIDEO

  1. Python class

  2. While Loop without an exit condition in real life. #loop #reallife #condition #while #looping

  3. Assignment 08

  4. Repetition structures in python

  5. WHILE LOOP

  6. While Loops Lesson 11.19 Tutorial with Answers Code.org CS Principles

COMMENTS

  1. c

    For your specific example: while (c = getchar(), c != EOF && c != 'x') the following occurs: c = getchar() is executed fully (the comma operator is a sequence point). c != EOF && c != 'x' is executed. the comma operator throws away the first value (c) and "returns" the second. the while uses that return value to control the loop.

  2. Assign variable in while loop condition in Python?

    150. Starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), it's now possible to capture the condition value (data.readline()) of the while loop as a variable (line) in order to re-use it within the body of the loop: while line := data.readline(): do_smthg(line)

  3. How to use Python While with Assignment[4 Examples]

    Learn how to use the assignment operator and the walrus operator to assign variables within a while loop in Python. See how to take user input, call functions, and check conditions with while loop and assignment.

  4. Is doing an assignment inside a condition considered a code smell?

    Doing a call like GetCurrentStrings() once outside a while loop, and then calling it inside the loop, is a very common, well understood, accepted as best practice pattern. It's not code duplication; you have to call GetCurrentStrings() once outside the loop to establish the initial condition for the while. -

  5. How To Use Assignment Expressions in Python

    Learn how to use assignment expressions in Python 3.8 to assign variables inside of if statements, while loops, and list comprehensions. Assignment expressions can make your code more concise and readable by eliminating extra lines or calculations.

  6. Python While Loop with Multiple Conditions

    Learn how to write a Python while loop with multiple conditions, such as and, or, and not, and how to group them. See examples of how to use the NOT operator to reverse the truth of a statement and stop the loop.

  7. Python while Loop (With Examples)

    Learn how to use a while loop to repeat a block of code until a condition is met. See examples of while loop with break, else, and range statements, and compare with for loop.

  8. While Loop

    A while loop is a control flow statement that repeats code based on a Boolean condition. Learn the structure, attributes, examples and variations of while loops, and how to avoid infinite loops.

  9. While loop in Programming

    Learn how to use while loop, a fundamental control flow structure in programming, to execute a block of code repeatedly as long as a condition remains true. See syntax, examples, and applications of while loop in different languages.

  10. Python While Loop Tutorial

    Learn how to use while loops in Python to repeat a sequence of statements until a condition is False. See examples of while loops, while True, break statements, and infinite loops.

  11. PEP 572

    This is a proposal for creating a way to assign to variables within an expression using the notation NAME := expr in Python 3.8. It explains the rationale, syntax, semantics and examples of assignment expressions, and the reasons for not supporting them in Python 3.7.

  12. while loop

    Learn how to use the while loop in C++, a control flow statement that executes a statement or a block of statements repeatedly until a condition is false. See examples, syntax, keywords, and documentation links.

  13. 18 Python while Loop Examples and Exercises

    Learn how to use while loops in Python to repeat a task until a condition is satisfied. See 18 examples of while loops for various needs, such as finding sum, average, factorial, and more.

  14. while

    Learn how to use the while statement to create a loop that executes a statement as long as a condition is true. See the syntax, description, and examples of while loops, including using an assignment as a condition.

  15. coding style

    change the loop body to "first assign, then either check or save the assigned char, then increment indices". Checking the condition in the middle of the loop means breaking out of the loop (reducing clarity, frowned upon by most purists). Saving the assigned char would mean introducing a temporary variable (reducing clarity and efficiency).

  16. while loop in C

    Learn how to use the while loop, an entry-controlled loop that iterates a part of code while a condition is true, in C programming language. See syntax, examples, and important points about the while loop.

  17. Python While Loops

    Learn how to use while loops in Python to execute a set of statements as long as a condition is true. See examples of break, continue and else statements, and try exercises to test your skills.

  18. Combined assignment operator in a while loop condition in C

    The test is purposely obfuscated. Here are the steps: --x > -10 always decrements x and compares the resulting value to -10, breaking from the loop if x reaches -10 or below. if x >= -10 from the previous test, (x -= 2) further decreases the value of x by 2 and tests whether the resulting value is non zero.

  19. Is it good practice to use array.pop() assignment in a while loop

    The first element in the array will be missed. Why? The first element is zero, which when used in an assignment statement, returns the value zero, which is treated as false by the while loop, meaning the while loop stops before processing the last item on the "stack", or rather the first element in the array.

  20. Assignment Within the Check of a While Loop

    2. (std::cin >> userIn) will be != 0 if the input succeeded, not if the input was 0. To check both, you can do while ( (std::cint >> userIn) && userIn ). This will first make sure that the input succeeded and then that the number is actually non-zero. answered May 23, 2013 at 18:04.