Assignment operator | COMP70050: Introduction to Machine Learning | Department of Computing | Imperial College London home article Introduction to Machine Learning COMP70050 Autumn Term 2021/2022 Introduction to Python for Java programmers The Zen of Python Example Python program Python vs. Java - Main method Python vs. Java - Variable declaration Python vs. Java - Semicolons Python vs. Java - Braces Python vs. Java - Comments Running Python Running Python as a script Running Python interactively Basic built-in data types Everything is an object Reserved words Variables - Java vs. Python Python Variables Objects in Python Operators Assignment operator Lists Accessing Lists Modifying Lists Tuples Strings are sequences Formatting strings Sets Dictionaries Grouping data with dict and tuple Control flow Loops Useful objects for loops List comprehensions Functions Function arguments Built-in functions Object-Oriented Programming in Python Constructor Attributes Methods Magic/Dunder methods Inheritance Encapsulation Encapsulation the Pythonic way What about protected? Python modules Custom modules What's in a __name__? Handling text files Reading CSV files Writing to CSV files Handling JSON files Pickle That's a wrap! Assignment operator In Python, you can assign the same object to multiple variables at once. >>> x = y = 558
>>> print(x)
>>> print(y)
You can also perform multiple assignments simultaneously. >>> x, y, z = 5, 5, 8
>>> print(x)
>>> print(y)
>>> print(z)
This naturally allows you to easily swap the values of variables, without requiring an intermediate variable. It’s actually the recommended way to swap variables in Python! >>> x = 5
>>> y = 8
>>> x, y = y, x
>>> print(x)
>>> print(y)
‘Shortcut’ assignment operators You can also use these ‘shortcut’ assignment operators just like in Java: +=, -=, *=, /=, %=, //=, **=. x += y is equivalent to x = x + y. You CANNOT do x++ and --y in Python. Sorry! Remember one of the philosophies behind Python – there should preferably be only one (obvious) way to do something. << Previous Next >> Page designed by Josiah Wang Department of Computing | Imperial College London