Python While loop with Assignment [With 4 real examples]

In this Python tutorial, we will see what is Python while loop with assignment, with some illustrative examples. We will also see what Python assign variable in the while condition with syntax.

Before diving into the while loop, let’s look at a traditional assignment:

USA = 'United States of America'
print(USA)

This code will simply assign the value ‘United States of America‘ to the ‘USA‘ variable in Python.

In Python, one of the fundamental ways to control the repeated execution of a block of code is through the while loop. A while loop tests a condition and keeps executing its block of code as long as the condition remains true. In essence, it says, “While this condition is true, keep doing these tasks.

Let’s understand the structure of the while loop in Python

while condition:
    # code to execute while the condition is true

Here, “condition” is a test, such as x < 10 or y != 5, which returns either True or False.

In this Python tutorial, we will see what is Python while loop with assignment, with some illustrative examples. We will also see what Python assign variable in the while condition with syntax.

Before diving into the while loop, let’s look at a traditional assignment:

USA = 'United States of America'
print(USA)

This code will simply assign the value ‘United States of America‘ to the ‘USA‘ variable in Python.

In Python, one of the fundamental ways to control the repeated execution of a block of code is through the while loop. A while loop tests a condition and keeps executing its block of code as long as the condition remains true. In essence, it says, “While this condition is true, keep doing these tasks.

Let’s understand the structure of the while loop in Python

while condition:
    # code to execute while the condition is true

Here, “condition” is a test, such as x < 10 or y != 5, which returns either True or False.

Python While loop with Assignment Methods

In Python, we can assign a value to a variable and simultaneously evaluate it as part of the while loop condition. The syntax of Python while loop looks like this:

while (variable := value) condition:

The (:=) is the ‘walrus operator‘ introduced in Python 3.8, allowing assignment expressions inside conditions (for or while loop).

Let’s see some examples for deep dive into variable assignments within while loop conditions in Python.

Example-1: Simple Assignments with while loop condition in Python

Using a baseball analogy, think of the assignment as the pitcher throwing the ball, and the variable as the catcher’s mitt in Python.

Here, for each iteration of the Python’s while loop, we add 1 to balls_thrown. The loop stops when 9 balls have been thrown and the data will be saved in the balls_thrown variable

balls_thrown = 0
while balls_thrown < 9:
    balls_thrown += 1

print(f"Ball {balls_thrown} thrown!")

The Output is:

Ball 9 thrown! 
python while with assignment

This is the simplest way to perform the assignment within a while loop condition in Python.

Example-2: Logging States Until a Specific Capital using Python assignment with while loop Walrus operator

Imagine we’re going through a string list of U.S. state capitals in a randomized order in Python, and we want to log each state we encounter until we come across the capital of Texas (Austin). When we do find Austin, we decide to stop our logging.

Let’s see how this can be achieved using the walrus operator within a while loop assigned in Python:

capitals = ["Denver", "Tallahassee", "Boise", "Austin", "Olympia", "Madison"]
current_capital = ""

print("Logging state capitals:")

while (current_capital := capitals.pop(0)) != "Austin":
    print(current_capital)

print("Reached Austin! Time to stop.")

The output is: The pop(0) method takes the first item from the ‘capitals‘ Python list during each iteration, assigns it to it, and then checks if it’s “Austin“. The while loop continues processing and logging capitals until “Austin” is encountered in the current_capital Variable.

Logging state capitals:
Denver
Tallahassee
Boise
Reached Austin! Time to stop.
python assign variable in while condition

This way we can assign a variable in Python within a while loop.

Example-3: Multiple Assignments with while loop in Python

Imagine we’re managing finances for a small New York company. Every month, we earn some money, but we also have expenses. We can simulate a quarter year’s worth of transactions using a while loop in Python.

months = 0
balance = 0

while months < 3:
    earnings = float(input("Enter month's earnings: $"))
    expenses = float(input("Enter month's expenses: $"))
    balance = earnings - expenses + balance
    print(f"Month {months + 1}: Total Balance is ${balance}")
    months += 1

The output is: This code simulates a quarter year where the user enters monthly earnings and expenses. The net for the month (earnings – expenses) is then added to the balance.

Enter month's earnings: $15785
Enter month's expenses: $4587
Month 1: Total Balance is $11198.0
Enter month's earnings: $12454
Enter month's expenses: $4457
Month 2: Total Balance is $19195.0
Enter month's earnings: $18547
Enter month's expenses: $3457
Month 3: Total Balance is $34285.0
python while loop assignment with multiple variable

This way we can assign multiple variables at once with a while loop in Python.

Example-4: While loop Assignment Using Python Functions

Imagine we’re on a cross-country road trip across the USA. One of the most critical elements of our journey is ensuring our vehicle doesn’t run out of fuel. We decide to write a Python program using a while loop to help us monitor and predict when we’ll need to stop for gas next based on our car’s miles per gallon (MPG) and the distance to the next gas station.

def calculate_fuel_remaining(current_fuel, mpg, distance_traveled):
    return current_fuel - (distance_traveled / mpg)

def main():
    current_fuel = 15 # gallons, assuming the tank starts full with 15 gallons
    mpg = 25 # miles per gallon for the car

    while current_fuel > 0:
        distance_to_next_station = float(input("Distance to the next gas station (in miles): "))
        distance_traveled = min(distance_to_next_station, current_fuel * mpg)

        current_fuel = calculate_fuel_remaining(current_fuel, mpg, distance_traveled)

        if current_fuel * mpg < distance_to_next_station:
            print("WARNING: We'll run out of fuel before the next station!")
        else:
            print(f"We will have approximately {current_fuel:.2f} gallons left when we reach the next station.")
        break
main()

In this program:

  • We first define a function calculate_fuel_remaining to determine the amount of fuel remaining after traveling a given distance.
  • Within the main function, we use a while loop to repeatedly check and predict our fuel situation until we run out of fuel (current_fuel > 0).
  • We prompt the user to enter the distance to the next gas station.
  • We calculate the distance_traveled as the minimum distance to the next station and the maximum distance, we can travel with our current fuel.
  • We then use the calculate_fuel_remaining function to update our current_fuel.
  • A warning is given if the predicted ‘fuel is not enough to reach the next station‘.

The output is: With this tool, we can better plan our fuel stops during our trip and avoid getting stranded on long stretches of road without a gas station in sight.

Distance to the next gas station (in miles): 10
We will have approximately 14.60 gallons left when we reach the next station.
python assignment in while loop with function

This way we can use Python function to assign with while condition.

Conclusion

Assignment in a while loop condition offers a blend of efficiency and conciseness in Python programming. So, in this article, we have seen what Python While loop with Assignment is, its syntax, and four different ways to assign variables within while loop conditions with examples.

You may like reading the following articles: