Friday, October 12, 2012

Assignments

Assignments

Assigning Values

As I've said before you can assign values to variables in a very simple way:
x = 1
y = "hello"
print (x, y)
1         hello

You can also do multiple assignments:
x, y = 2, "there"
print (x,y)
2        there
REMEMBER- That if x is first then the first variable listed is the x-value.

You can also do three at a time (and also add lists):
x,y,z = 1, "two", { table= "this is a table" }
print (x,y,z)
1      "two"       table: 32jk34k23j
REMEMBER- Printing a table as a variable gives you that nasty identifier.

You can change a variable in place of a variable:
i = 7
i, x = i+1, i
This is assigning i the value of: i+1 so in this case 8. And is giving x the value of the previous i: 7.

Swapping Values

a,b = 1,2
print (a,b)
1           2
a,b = b,a
print (a,b)
2           1

Assignment Order

You have to be careful because if you assign the same value two different values you dont know which one is being assigned.
a, a = 1, 2
print (a)
1

Mismatched List Sizes

If there are too many variables on the left side of the equation then it will ignore the extra values and assign them the value nil.
a, b, c, d, e = 1,2,3
print (a,b,c,d,e)
1    2    3   nil   nil
If the amount of numbers is too long it simply ignores the numbers.

No comments:

Post a Comment