Python natively supports two types of numbers:
int
s
float
s
Python does support other kinds of numbers (e.g. imaginary, complex), but it requires a module.
Python will automatically convert between the two types of numbers. However, if you want to force a particular type, you can:
int(value)
float(value)
Makes sense, right? We'll talk more about this in a future lecture.
Python supports the basic math operations:
Operator | Description | Example |
---|---|---|
+ | Addition: Adds values on either side of the operator. | 5 + 3 (equals 8) |
- | Subtraction: Subtracts right hand operand from left hand operand. | 3 - 5 (equals -2) |
* | Multiplication: Multiplies values on either side of the operator | 5 * 3 (equals 15) |
/ | Division: Divides left hand operand by right hand operand | 5 / 3 (equals 1.6666666666666667) |
// | Floor Division: The division of operands where the result is the quotient in which the digits after the decimal point are removed. | 5 // 3 (equals 1) |
% | Modulus: Divides left hand operand by right hand operand and returns remainder | 5 % 3 (equals 2) |
** | Exponent: Performs exponential (power) calculation on operators. Do not use ^, that is the bitwise XOR operation. | 5 ** 3 (equals 125) |
Python supports a lot of other math operations in the math module.
The order of operations in Python is the same as in math:
For each item above, if more than one is in the expression, work from left to right evaluating them.
Math is boring without variables. Python supports variables (as almost every programming language does). To create a variable, you just decide on a name and give it a value.
Variable names must follow these rules:
a
-z
or A
-Z
0
-9
_
Items_Ordered
is not the same as items_ordered
Some suggestions when deciding on variable names:
num_bright_spots
is better than nbs
We use the assignment operator (=
) to assign values to variables. The variable goes on the left and the value goes on the right.
The value can be (almost) anything:
If you've programmed in other languages, you might be wondering about how you specify a variable's type. In Python, you don't! Python will figure out the type for you.
In fact, it's possible for a variable's type to change. At one point, the variable could hold a float, then later an int, and later text.
If you want to know a variable's type you can use the type
function:
The <class 'int'>
is telling you that number_nine
is an int.
Comments are a great way to leave notes for other programmers (or yourself). Python will ignore comments, so you can type anything you want into a comment. They're great for explaining how a piece of code works or how to use it.
In Python, a comment starts with #
and ends at the end of the line.
If you want multi-line comments (also called block comments), it's possible to get that with multi-line strings.
Next Notes >> |