Simple Assignment Operator
Making variables and putting data into them.¶
What does data look like?¶
Here's what the number 7 looks like in the computer as a base 2 number:
That's 32 bits in a row, which is maybe a little overwhelming to look at. So, we break up the bits into groups of 8 that we call bytes. (You've probably heard that term, like in a 500GB hard drive. That's 500 billion bytes!)
00000000 00000000 00000000 00000111
For the sake of discussion, we'll not worry about the first 3 bytes since they are all zeros. We'll just look at the last byte.
Now we'll blow it up and look at what it means if we are working with number data. The computer only understands base 2 arithmetic. The rightmost bit is the one's position, the next one to the left is the two's position, next is the four's, etc.
Here's what 10 looks like:¶
And here's 682 but we had to add back the next byte:¶
What about letters? Here's what the letter A is in the computer:
Huh? That looks like a number! Yep, that's what everything is in the computer. That's also the number 65.
How does the computer know that it's an A and not 65?
Because we tell it that it's an A. That's what Assignment means.
Using the Simple Assignment Operator¶
Assignment is setting a variable to a value and telling the computer the value's type.¶
- Numbers: 45, 123.99
- Strings: "this is a string", "Here's another", "12.99"
- A number is declared by not using quotes.
- A string is declared with the quotes, even if the value within the quotes is a set of digits 0-9 so that it superficially looks like a number.
The simplest is the Simple Assignment Operator.
Simple Assignment while declaring the variable¶
1 2 3 4 5 6 7 8
Simple Assignment after the variable has been declared.¶
This can happen anywhere in your code after the declaration. This is correct form that conforms to our coding standards.
1 2 3 4 5 6
Simple Assignment with Math.¶
1 2 3 4 5 6 7 8 9 10 11
Simple Assignment by replacing the value of a variable.¶
1 2 3 4 5 6 7 8 9 10 11 12
Simple Assignment to a new type.¶
Many other languages, like Java and C#, are "strongly typed" languages, and will not permit this kind of loosey-goosey work. Their variables have to be declared as being a certain type when you set them up, and you can't change the type of data placed into them later to some other type of data.
1 2 3 4 5 6 7 8 9 10 11 12
Simple Assignment with a function.¶
You can also assign the value of a variable with the results of a function. This is very common and will look very normal quickly.
- Notice the value of
userNamebefore and after the
1 2 3 4 5 6 7 8 9
Simple Assignment can be done to a variable "in-place", from itself to itself.¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
- Lab03: Simple Assignment