Python Tutorial 3 – Multiple Assignments

 

So let’s say you have to create a variable for each person in a class room. Each will have different names and stuff, so creating, say, 10 variables would become a tedious task.

So for example, you would be writing them out…

person1 = “Abby”

person2 = “James”

And so on until you’ve reached person 10. And at this point you would be groaning about how much you hate Python as you collapse to the floor.

And this is why we’ll be talking about Multiple Declaration. All that does is allow you to assign multiple values to multiple variables into one line.

This is the way it works, try something like this…

person1,person2,person3 = “Abby”,”James”,”Lebron”

So if you do this and you type person1 into Python, you’ll be returned “Abby”. Type person2 and you’ll get “James”. And so on.

This quickens the tediousness of having to write out each individual variable and their value on separate lines.

tut3-1

So let’s see this from another case. Say you have a string called “Apples” and you have ten variables. You want all of those variables to have the value of “Apples” assigned to it. So something like this…

var1 = “Apples”

var2 = “Apples”

var3 = “Apples”

So how can we set all three variables to “Apples” without having to do them all like the above example?

Well there’s the concept of “Multiple Assignments.”

With this we can say…

var1 = var2 = var3 = “Apples”

This will set all three of those variables to have “Apples” as their value without having to do them all separately. Type var1 and you get “Apples”, type var3 and you get “Apples”!

tut3-2

So now we’ve learned how to quickly give many variables different assignments with “Multiple Declaration” and how to quickly set multiple variables to the same value with “Multiple Assignments!”


Written for my own study of Python as I journey to learn it. I’m following the instructions from this YouTube video, and this section of the tutorial begins at 8:49

Python Tutorial for Beginners

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s