Welcome to UNIT два!!!!
You did SO good on that last unit! You get a gold star.
Math Operators in programming are universal, so they are the same in all programming languages. They are as follows:
Addition: +
Subtraction: -
Multiplication: *
Division: /
When 2 integers are added/subtracted, the result is an integer.
When 2 float values are added/subtracted, the result is a float.
In python, dividing 2 integers will always result in a float, even with no remainder.
Say you have a variable X, and it is equal to 2. If you want to add 4 to it, you can do:
X = X + 4
An easier way of doing this would be:
x += 2
You can do this with any operator.
Modulus is another math operator, not taught in normal school.
The modulus operator divides the given numbers and provides only the remainder.
It is indicated by %.
To do modulus in AP Pseudocode, it is 'MOD'.
In pseudocode, it would look like this: '8 MOD 3', and in python 'X = 8 % 3'
In python, the order of operations are 1. Parenthesis, 2. Multiplication, division, modulus, 3. Addition, subtraction
Comparison operators compare 2 value or data types. In programming, after comparing, it gives you a True/False value. They are as follows:
Greater than: >
Less than: <
Greater than or equal to: >=
Less than or equal to: <=
To use comparison operators, you can do:
X = 3 < 7, then X will be true.
There are 2 more comparison operators, they are:
Equal to: ==
Not equal to: !=
To use these you can:
X = 7 == 7, then X will be true, because 7 equals 7.
X = 5 != 1, then X will be false, because 5 is not equal to 1.
Logical operators give the ability to use more than 1 comparison statement to get a boolean result.
There are 3 basic types of logical operators in python.
They are AND, OR, and NOT.
'and' will return true if both conditions are true, else it will return false.
If the first condition is false, it will not check the second
'or' will return true if one of the conditions is true, else it will return false.
If the first condition is true, it will not check the second, as the requirements have been met already.
'not' will simply return the opposite of what's given.
To get a random number in AP pseudocode, you will need to use the RANDOM() function. To use it, you do:
RANDOM(A, B), the function will be a random number between A and B.
In python, you need to import the "random" function. To do this, put this at the start of your code:
import random
Now, to get a random number, you use randint. To do this:
random.randint(a,b), which will randomly select and integer between a and b (including a and b).
Another useful function of random in python is the ability to get randoms at intervals.
For example, if you wanted to only get even numbers, you could do this:
random.randrange(10, 100, 2), where the first integer is the starting integer, second is ending, and the third is your interval.