Course contentsShow
← Python
Lesson 131 of 1,0602. Control Flow and LogicFree lesson

Assignment Expressions Using the Walrus Operator for Loop Readability

Utilize the walrus operator to assign values within expressions, simplifying code structure in input and processing loops.

In this lesson, you will learn how to streamline your input loops by using the "walrus operator" (:=) to assign and evaluate variables in a single step.

The Walrus Operator

In Python, the walrus operator (:=) allows you to assign a value to a variable as part of a larger expression. Its name comes from its resemblance to a walrus’s eyes and tusks. This is particularly useful when you need to capture user input or process data and immediately check its value to decide if a loop should continue.

Simplifying Input Loops

Without the walrus operator, you often have to repeat code. For example, if you want a user to type a command until they enter "quit," you typically write the input line twice: once before the while loop to prime the variable, and once inside the loop to get the next update.

Using the walrus operator, you can collapse these steps into one clean line:

# Instead of repeating 'input()' twice, we use the walrus
while (command := input("Enter command: ")) != "quit":
    print(f"You entered: {command}")

print("Loop exited.")

Why Use It?

In the code above, the expression (command := input(...)) does two things simultaneously:

  1. It executes the input() function and assigns the result to the variable command.
  2. It returns the value of command so the while loop can immediately compare it against the string "quit".

This makes your code much more readable and prevents the "duplicate code" trap, where you are forced to define the same variable in two different places. It keeps the loop condition concise and ensures that the variable is always updated exactly when the check occurs.

As you build more complex loops that process data streams or user interactions, the walrus operator acts as a shortcut that keeps your logic organized and reduces the total number of lines needed to manage state inside your loop.

Key Takeaway: The walrus operator (:=) lets you assign a value and use it in a condition simultaneously, eliminating the need for redundant code outside and inside your loops.