Most of your programs will use numbers, and will need to perform and calculations on those numbers. Computers are ideal for doing numerical calculation — its what they were created for. If it takes you a minute to multiply two ten digit numbers together, then an average desktop computer today is more than a trillion times faster than you.
and the output was:
1+1
But, what if we didn't want the program to output the string, but instead wanted the program to calculate the ‘1+1' and output the result? This is accomplished by simply leaving off the quotation marks in our code, like this:
If you were to enter this code into your code window and run the program, your output would look like this, exactly what you'd be looking for:
2
The most common math calculations you'll do while programming will be addition, subtraction, multiplication and division. You've already seen that when doing addition in your code, you use the '+' (plus) sign, just like in the real world. And subtraction will use the '- (minus) sign as well. But, when writing code, we use different operator signs for multiply and divide.
Here is a quick reference of the basic operator signs you will need to know (there are lots of others, but these are the most common):
Addition |
|
Subtraction |
|
Multiplication |
|
Division |
|
Let's practice using these operators. In your code window, enter the following lines:
If you run this code, you should expect the following output:
2 3 4 5.0
Of course, computers can do more complicated calculations as well. For example, let's say we wanted to calculate the number of seconds in a day? How would we do this?
To calculate the number of seconds in a day, the easiest way would be to multiply:
(# seconds in a minute) x (# minutes in an hour) x (# hours in a day)
We know that there are:
60 seconds in a minute
60 minutes in an hour
24 hours in a day
If we multiple each of those numbers, we should get the number of seconds in a day. Here is what the code would look like:
Go ahead and enter that code into your Code Window and run the program. Here is what your output should look like:
86400
There are 86,400 seconds in a day.
Programmers are lazy — they often invent shorthands for code that is
very common, to make easier to write code quickly and efficiently.
Assignment statements are something that occur very frequently in the code,
an extremely common operation is just to increment a variable by one. The
way you'd do this, for a variable named x
is:
x = x + 1
So, programmers came up with a nifty shorthand for this:
x += 1
But they didn't stop there — they added new assignment operators for
addition, subtraction, multiplication, and division. The table below shows
how a variable x
could be modified by 5 using these assignment
operators.
Operation |
Operator |
How to Use It |
Equivalent To |
---|---|---|---|
Addition |
|
|
|
Subtraction |
|
|
|
Multiplication |
|
|
|
Division |
|
|
|