Recently, I was working on a project where I had to repeatedly check values from a database until a condition was met.
The challenge was that I needed to assign values inside the loop while still controlling the exit condition.
That’s when I realized that many Python beginners struggle with using while loops with assignment.
So in this tutorial, I’ll share four simple methods I use to handle assignments inside a while loop.
Method 1 – Use Assignment Before the While Loop
The most common way is to assign a variable before the loop starts and then update it inside the loop. This is simple and works in most cases.
Here’s an example where I simulate checking gas prices in the USA until they drop below $3.
# Method 1: Assignment before the while loop
gas_price = 4.25 # initial value in USD
target_price = 3.00
while gas_price > target_price:
print(f"Current gas price: ${gas_price}")
# simulate price drop
gas_price -= 0.25
print("Gas price is now affordable!")You can see the output in the screenshot below.

Explanation:
- I first assign gas_price = 4.25.
- The loop runs until the price becomes less than or equal to 3.00.
- Inside the loop, I decrease the value by 0.25.
Method 2 – Use Input Assignment Inside the While Loop
Sometimes, I don’t know the value in advance. In such cases, I assign values inside the loop using user input.
Here’s an example where a user enters their age until it’s valid (greater than 0 and less than 120).
# Method 2: Assignment inside the while loop
age = 0 # initialize with an invalid value
while age <= 0 or age >= 120:
age = int(input("Enter your age (1-119): "))
print(f"Thanks! Your age is recorded as {age}.")You can see the output in the screenshot below.

Explanation:
- I start with age = 0 to ensure the loop runs at least once.
- Inside the loop, the program asks for user input.
- The loop only exits when a valid age is entered.
Method 3 – Using the Walrus Operator (:=)
Python 3.8 introduced the walrus operator (:=), which allows assignment inside the while condition itself. This is a powerful feature that makes code shorter and cleaner.
Here’s an example where I keep reading lines from a file until it’s empty.
# Method 3: Using the walrus operator
with open("us_states.txt", "r") as file:
while (line := file.readline().strip()):
print(f"Read state: {line}")You can see the output in the screenshot below.

Explanation:
- (line := file.readline().strip()) assigns a value to line and checks if it’s not empty.
- The loop continues until the file has no more lines.
- This avoids writing extra assignment statements outside the loop.
Method 4 – Use While with Assignment in a Data Processing Task
In real-world projects, I often use while loops for data processing. Here’s a practical example where I simulate processing customer orders until the list is empty.
# Method 4: Data processing with assignment
orders = ["Order-101", "Order-102", "Order-103"]
while (current_order := orders.pop(0)) if orders else None:
print(f"Processing {current_order}")Explanation:
- I use (current_order := orders.pop(0)) to assign and check at the same time.
- The loop continues until the orders list is empty.
- Each order is processed one by one.
Things to Keep in Mind
- Always make sure your while loop has a clear exit condition, or you’ll end up with an infinite loop.
- Use the walrus operator where it makes code more readable, but don’t overuse it.
- For user input, always include validation to prevent errors.
- When processing data, ensure that the source (like a list or file) eventually runs out of items.
While loops with assignment are incredibly useful in Python programming.
From simple variable updates to advanced use cases with the walrus operator, you now have multiple ways to handle them.
I’ve personally used these techniques in real-world projects, from automating reports to processing data pipelines.
Try each method in your own projects, and you’ll quickly see which one fits your scenario best.
You may read:
- Read a CSV into a Dictionary using Pandas in Python
- Python Dictionary of Sets
- Copy a Dictionary in Python
- Check if Python Dictionary is Empty

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.