Numbers in Python
Introduction
Numbers are one of the most fundamental data types in Python. Whether you’re adding prices, calculating averages, or working with scientific data, understanding how numbers work is crucial.
Python makes working with numbers simple and intuitive, but there are a few key concepts to understand to avoid errors and write clean code.
Types of Numbers in Python
Python has three main types of numbers:
- Integers (
int) – Whole numbers, positive or negative. - Floats (
float) – Numbers with a decimal point. - Complex (
complex) – Numbers with a real and imaginary part.
x = 10 # Integery = 3.14 # Floatz = 2 + 3j # ComplexBasic Arithmetic
Python can handle basic arithmetic operations just like a calculator:
a = 10b = 3
# Additionprint(a + b) # 13
# Subtractionprint(a - b) # 7
# Multiplicationprint(a * b) # 30
# Divisionprint(a / b) # 3.3333 (float division)print(a // b) # 3 (integer division)
# Modulus (remainder)print(a % b) # 1
# Powerprint(a ** b) # 1000 (10 to the power of 3)Type Conversion
You can convert between different types of numbers easily:
x = 10 # inty = 3.5 # float
# Convert int to floatx_float = float(x) # 10.0
# Convert float to inty_int = int(y) # 3 (rounds down)
# String to numberz = "42"z_int = int(z) # 42Common Operations
Python provides many built-in functions to work with numbers:
# Absolute valueprint(abs(-7)) # 7
# Round a numberprint(round(3.14159, 2)) # 3.14
# Max and Minprint(max(5, 10, 15)) # 15print(min(5, 10, 15)) # 5
# Sum of a listprint(sum([1, 2, 3, 4])) # 10Working with Large Numbers
Python can handle very large numbers without overflow:
big_number = 10 ** 100 # 1 followed by 100 zerosprint(big_number)
# Scientific notationsci_number = 3e5 # 3 * 10^5print(sci_number) # 300000.0Best Practices
- Use floats carefully – Floats can sometimes lead to precision errors:
Useprint(0.1 + 0.2) # 0.30000000000000004
round()to handle precision issues. - Avoid dividing by zero – Python will raise an error if you divide by zero.
- Use meaningful variable names –
price,total, andquantityare better thanx,y,z.
Conclusion
Numbers in Python are powerful and easy to work with. By understanding the basics and following best practices, you can avoid common pitfalls and write more efficient code.
Happy coding!