90_walrus.py 808 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. # Test walrus operator (:=)
  2. # Basic usage in if statement
  3. x = [1, 2, 3, 4, 5]
  4. if (n := len(x)) > 3:
  5. assert n == 5
  6. # Usage in while loop
  7. data = [1, 2, 3, 0, 4, 5]
  8. results = []
  9. i = 0
  10. while (val := data[i]) != 0:
  11. results.append(val)
  12. i += 1
  13. assert results == [1, 2, 3]
  14. # Usage in list comprehension filter
  15. values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  16. even_squares = [y for x in values if (y := x * x) % 2 == 0]
  17. assert even_squares == [4, 16, 36, 64, 100]
  18. # Walrus in expression context
  19. a = 10
  20. b = (a := a + 5) * 2
  21. assert a == 15
  22. assert b == 30
  23. # Nested parenthesized walrus
  24. result = (x := (y := 3) + 1)
  25. assert x == 4
  26. assert y == 3
  27. # Test function
  28. def test_walrus_in_function():
  29. result = (x := (y := 3) + 1)
  30. assert x == 4
  31. assert y == 3
  32. assert result == 4
  33. test_walrus_in_function()