With Python, you can assign one single value to several variables at the same time. This lets you initialize several variables at once, which you can reassign later in the program yourself, or through user input.
Through multiple assignment, you can set the variables x, y, and z to the value of the integer 0:
x = y = z = 0 print(x) print(y) print(z)
In this example, all three of the variables (x, y, and z) are assigned to the same memory location. They are each equal to the value of 0.
Python also allows you to assign several values to several variables within the same line. Each of these values can be of a different data type:
j, k, l = "shark", 2.05, 15 print(j) print(k) print(l)
In the example above, the variable j was assigned to the string "shark", the variable k was assigned to the float 2.05, and the variable l was assigned to the integer 15.
This approach to assigning multiple variables to multiple values in one line can keep your lines of code down, but make sure you are not compromising readability for fewer lines of code.
Write a program that stores two variables. It should then print the variable values before changing them both in a single statement, it should then output the changes.
Write a program that stores one variable for each data type. It should then print the variable values before changing them all in a single statement. Once changed the variables should be outputted again.
Thanks [name] from [whichclass][location], Mr McG will get your message…"
[message]"…and will get back to you ASAP via [email]. Catch you soon.
Have a great day!!
K McGuinness - 2018
No personal data will be shared with any third party. The only data processed via this website is anonymous browsing data to best manage your user experience.