3.1 Number Types: int
, float
, complex
Python has several number types, each suited for different tasks and data processing. We've already mentioned data types like int
, float
, complex
, and also the boolean type bool
, which is a subclass of integers. Now, let's dive deeper into each of these types.
int
(Integers):
This is probably the most frequently used number type in Python. Integers can be positive or negative and don't have decimal points. Python supports arbitrary precision, which means there are virtually no limits on the size of numbers you can handle, except for your machine's memory limitations.
float
(Floating Point Numbers):
These numbers are used to represent real numbers and can contain decimal points. Python implements floating point numbers according to the IEEE 754 double-precision standard, which provides about 15 decimal digits of precision.
complex
(Complex Numbers):
Complex numbers have a real part and an imaginary part. Both are represented as floating point numbers. In Python, the imaginary part is designated with the suffix j
or J
. For example, a complex number can be created like this:
complex_number = 3 + 5j
bool
(Boolean Values):
In Python, True
and False
are specialized versions of integers and function as 1 and 0 respectively. This allows them to be used in arithmetic operations and other mathematical expressions.
Arithmetic Operations:
Python supports all major arithmetic operations, including addition, subtraction, multiplication, division, floor division, modulus, and exponentiation. For example:
- Addition: 3 + 2
- Subtraction: 5 - 2
- Multiplication: 2 * 3
- Division: 7 / 2
- Floor division: 7 // 2
- Modulus: 7 % 2
- Exponentiation: 2 ** 3
Type Conversion:
We've already talked about type conversion (or casting). You can convert numbers using casting functions like int()
, float()
, and complex()
.
Some of the numerical type conversion issues we've already discussed, others we'll go into more detail in upcoming lectures.
3.2 Pseudorandom Numbers
Sometimes a programmer faces seemingly simple tasks: "pick a random movie for the evening from a specific list", "select a lottery winner", "shuffle a playlist when shaking a smartphone", "pick a random number for encrypting a message". And every time, they have a very reasonable question: how do I get this random number?
Getting a "true" random number is pretty tough. To the point that computers have special mathematical coprocessors built-in, that can generate such numbers, meeting the criteria of "true randomness".
So programmers invented their own solution – pseudorandom numbers. Pseudorandom numbers are a sequence that appears random at first glance, but a specialist can find certain patterns upon closer analysis. For encrypting secret documents, such numbers are unsuitable, but for simulating a dice roll in a game – they're just fine.
There are many algorithms for generating a sequence of pseudorandom numbers and almost all of them generate the next random number based on the previous one and some additional numbers.
For example, this program will display 1000 unique numbers on the screen:
a = 41
c = 11119
m = 11113
seed = 1
def get_next_random():
global seed
seed = (a * seed + c) % m
return seed
for t in range(1000):
x = get_next_random()
print(x)
By the way, we are not talking about pseudorandom numbers, but about a sequence of such numbers. Because looking at a single number, it's impossible to tell if it's random or not.
A random number can be obtained in different ways:
def get_random_number():
return 4 # this is definitely a random number (z threw it with dice), see "Dice Joke"
3.3 Library random
Python has a built-in random library that you'll find interesting to work with. As you might have guessed from its name, this library can generate [pseudo]random numbers.
The random
library, although built-in, is still a separate library, so before using it, you need to import it into your code. This is done using the import
keyword. Example:
import random
The random
library has many interesting methods, but today we'll get acquainted with just two of them: method random()
and method randint()
. They perform similar, but different tasks:
Method random.random()
:
This method returns a random floating point number between 0.0 and 1.0. The numbers are generated uniformly in this range. This means that each number within the interval has the same probability of being chosen.
import random
probability = random.random()
print("Random probability:", probability)
Method random.randint(a, b):
This function returns a random integer within the range from a
to b
inclusive. Unlike random.random()
, which returns a random floating point number between 0 and 1, randint()
is used when you need to choose an integer. For example, random.randint(1, 10)
can return any integer from 1
to 10
, including both endpoints.
import random
dice_roll = random.randint(1, 6) # Simulating a die roll
print("Rolled number:", dice_roll)
These are very useful and interesting methods, so feel free to use them.
3.4 Library math
Well, since we're on this topic, let me introduce you to another interesting library. This is the math
library. It contains basic mathematical functions and constants, such as numbers π and e.
And just like the random
library, you need to import it before using:
import math
Here's a table with the main functions and constants of the math
library in Python:
Function/Constant | Description |
---|---|
math.pi | Constant π, approximately 3.14159 |
math.e | Base of the natural logarithm, approximately 2.71828 |
math.sqrt(x) | Returns the square root of x |
math.exp(x) | Returns e raised to the power of x |
math.log(x[, base]) | Returns the logarithm of x to the given base; if base is not specified, returns the natural logarithm. |
math.cos(x) | Returns the cosine of x, where x is in radians |
math.sin(x) | Returns the sine of x, where x is in radians |
math.tan(x) | Returns the tangent of x, where x is in radians |
math.ceil(x) | Rounds a number up to the nearest integer |
math.floor(x) | Rounds a number down to the nearest integer |
math.factorial(x) | Returns the factorial of x |
Even if you don't really love math and don't plan to use these functions in the next 10 years, there are at least three very useful ones:
sqrt()
— square root of a numberceil()
— rounding up to the nearest integerfloor()
— rounding down to the nearest integer
Examples:
import math
number = 9.7
rounded_up = math.ceil(number) # Rounds up, result is 10
rounded_down = math.floor(number) # Rounds down, result is 9
print("Rounded up number:", rounded_up)
print("Rounded down number:", rounded_down)
GO TO FULL VERSION