Salvatore Lopiparo

Software Engineer

Super Simple Python #1 – Doing Math and Assigning Variables

Wait, wait! Don’t groan yet! It’s really simple math! Like, pluses and minuses and stuff! No long division, and no integrating differential equations, I promise! That’s a later chapter!

If this is your first time here, I recommend looking at the first lesson. Starting there and going through the rest of the lessons will prepare you to go through this more advanced lesson!

Open up the PyCharm Python Console (see SSP#0). You’ll notice that the lines you type on start with “>>>”. That’s normal. You’ll also notice that I’ll start things I want you to type with “>>>”. That’s also normal. You should not, however, type extra “>>>”. That’s not normal. The line after the “>>>” is the output line. That’s also also normal. You’ll also notice that I say also too much. That’s also not normal.

Now some math! Type:

>>> 1 + 1
2

Yay! Math! See? Easy stuff. Now try:

>>> 1 - 1
0

And it works like that with all the numbers, including negatives!

>>> 3 + 5 - 10
-2
>>> 111 * 7777
863247

Now a variable! A variable is a name for a piece of data, like a number.

>>> bananas = 3

We call that “assigning 3 to bananas.” You may have noticed that it didn’t have any output. That’s because the number 3 went “into” the variable bananas. Now if we type:

>>> bananas
3

There’s our 3!

We can also do:

>>> apples = 10 - 6
>>> apples
4

There, we subtracted 6 from 10, then assigned that (4) to apples! It will always completely figure out the right side of the = before assigning the value (in this case 10 - 6).

You can also do math on variables that contain numbers:

>>> apples + 10
14
>>> apples  # Notice here how apples did not change!
4
>>> apples = apples + 10  # Now it will change, because we assigned it again!
>>> apples
14

In addition to adding numbers to variables, you can add variables to other variables:

>>> apples + apples
28
>>> apples
14
>>> fruits = bananas + apples
>>>fruits
17

Whew! Math is done. That wasn’t so bad, was it?

Questions or comments? Let me know below!

DROP A COMMENT

Your email address will not be published. Required fields are marked *