Python Basics
Python Numbers
Deep dive into Python numeric types: integers, floats, complex numbers, and mathematical operations.
Python Numbers
There are three numeric types in Python:
int— integer (whole numbers, no decimals):1,42,-100float— floating point numbers:1.0,3.14,-0.5complex— complex numbers:1+2j
Variables of numeric types are created when you assign a value to them.
Integer (int)
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
Float
Float, or "floating point number" is a number, positive or negative, containing one or more decimals. Float can also be scientific numbers with an "e" to indicate the power of 10.
The math Module
Python has a built-in module called math that provides mathematical functions.
Random Numbers
Python has a built-in module called random that can be used to make random numbers.
Example
python
# Integer operations
x = 100
y = 30
print(x + y) # 130
print(x - y) # 70
print(x * y) # 3000
print(x / y) # 3.333...
print(x // y) # 3 (floor division)
print(x % y) # 10 (modulo)
print(x ** 2) # 10000 (power)
# Float precision
import math
pi = math.pi
print(round(pi, 4)) # 3.1416
print(math.sqrt(16)) # 4.0
print(math.ceil(4.2)) # 5
print(math.floor(4.8))# 4
# Random numbers
import random
print(random.random()) # 0.0 - 1.0
print(random.randint(1, 10)) # 1 to 10
print(random.choice(["a", "b", "c"]))
# Type conversions
print(int(3.9)) # 3 (truncates)
print(float(5)) # 5.0
print(abs(-42)) # 42Try it yourself — PYTHON