If you are using a Python 3.8+ version, you can use the Walrus Operator (:=) also known as the assignment operator, to assign a value to a variable inside an expression, like an if or while condition.
Syntax
if (var := expression):
pass
Visual representation
Assigning a value inside an if condition
Let’s say we define a custom function and, inside the if condition, fetch its value and assign it to a new variable. If it has a value, we print that variable.
def fetch_data():
# Simulate fetching data
return {"key": "value"}
if (data := fetch_data()):
print("Received:", data)
else:
print("No data found")
# Output:
# Received: {'key': 'value'}
The fetch_data() function returns a dictionary with key/value pairs. So, that dictionary is the returned value, and we assign it to a variable data using the assignment operator (:=).
The data was received successfully, and we printed it to the console using the print() function.
Assigning in while conditions
Let’s say you are reading a file and assigning its contents to a variable; you can use the walrus operator (:=) in the while condition. This is the most fruitful way to use the walrus operator.
Here is the app.txt file that we will read:
Let’s use the with open() context manager to open a file and use the readline() method to read a file line by line, and store its content in a variable.
with open("app.txt") as f:
while (line := f.readline().strip()):
print("Line:", line)
# Output:
# Line: Hello, World!
In this code, the variable line contains the first line of the app.txt file, “Hello, World!”.
Assigning inside Ternary (Conditional Expression)
In a conditional assignment, it chooses a value based on a condition and assigns it to a variable; all things will be done in one line. It does not create an if block; it produces a value.
input = int(s) if (s := input("Enter a number: ")) else 0
print("Value:", input)
# Output:
# Enter a number: 21
# Value: 21
In this code, the s := input() function assigns the value entered from the console to the variable “s”.
Here, the condition checks if s is non-empty (truthy).
If s is non-empty, the int(s) function is assigned to the input. If s is empty, 0 is assigned to the input.
Finally, we are printing the input’s value.
That’s all!


