The walrus operator in Python

The translation was prepared as part of the " Python Developer. Basic " course .



We also invite everyone to the two-day online intensive "Development of a desktop application using the Tkinter library" . On the intensive course, we will get the initial skills of backend development in Python, and also start developing a desktop application using the Tkinter library.






The walrus operator, introduced in Python 3.8, allows you to solve two problems at once: assign a value to a variable and return that value, so sometimes you can write shorter code and make it more readable, and it can be even more computationally efficient.





Let's take a look at the walrus operator and give examples of where it can be useful.





Simple assignment operator

We all know how to assign a value to a variable. This is done using a simple assignment operator:





num = 15
      
      



And if we want to display the value of this variable using a function print



, then num



we can pass the variable as follows:





print(num)
# 15
      
      



Walrus operator

Python 3.8 (:=), . , , . , (=) num 15 .





. - .





, , . , (:=) , .





        





Expr



, . . .





, – . , 15 num



, num



. , :





print(num := 15)
# 15
      
      



15 num



. , print



. , 15.





, , num = 15



.





print(num = 15)
# TypeError
      
      



, - . , . while



:





- . while



, , . «Nice!», -. , .





:





. . True



( ), while



«Nice!». False



, .





, , , .





, num_list



, , 20. :





, cube



.





cube



, :





cube(x)



y



, 20. y



, 20. , cube()



, . , .





, Python . !






"Python Developer. Basic".





- « - Tkinter»: 1, 2.








All Articles