Skip to main content

Python Numbers

Numbers are one of the fundamental data types in Python. Understanding how Python handles numeric values is essential for any beginner programmer. In this tutorial, you'll learn about different types of numbers in Python, how to work with them, and common operations you can perform.

Introduction to Python Numbers

Python supports several numeric data types that allow you to work with numbers in different ways:

  • Integers (int): Whole numbers without decimal points
  • Floating-point numbers (float): Numbers with decimal points
  • Complex numbers (complex): Numbers with real and imaginary parts

Let's explore each of these types in detail.

Integer Numbers

Integers are whole numbers without a decimal point. They can be positive, negative, or zero.

Creating Integers

python
# Simple integer assignment
x = 10
y = -5
z = 0

# Large integers
big_number = 1000000
# Python can handle arbitrarily large integers
very_big = 9999999999999999999999999

print(x)
print(big_number)
print(type(x))

Output:

10
1000000
<class 'int'>

Integer Representations

Python supports different ways to represent integers:

python
# Decimal (base 10) - default
decimal_num = 123

# Binary (base 2) - prefix: 0b
binary_num = 0b1010 # 10 in decimal

# Octal (base 8) - prefix: 0o
octal_num = 0o17 # 15 in decimal

# Hexadecimal (base 16) - prefix: 0x
hex_num = 0xFF # 255 in decimal

print(f"Decimal: {decimal_num}")
print(f"Binary: {binary_num} (0b1010)")
print(f"Octal: {octal_num} (0o17)")
print(f"Hexadecimal: {hex_num} (0xFF)")

Output:

Decimal: 123
Binary: 10 (0b1010)
Octal: 15 (0o17)
Hexadecimal: 255 (0xFF)

Floating-Point Numbers

Floating-point numbers, or floats, are numbers with decimal points.

Creating Floats

python
# Simple float assignment
a = 10.5
b = -3.14
c = 0.0

# Scientific notation
scientific = 1.5e3 # 1.5 × 10^3 = 1500
tiny = 1.5e-3 # 1.5 × 10^-3 = 0.0015

print(a)
print(scientific)
print(type(a))

Output:

10.5
1500.0
<class 'float'>

Float Precision

It's important to know that floating-point numbers may have precision issues:

python
# Precision issues
result = 0.1 + 0.2
print(f"0.1 + 0.2 = {result}") # Not exactly 0.3
print(f"Is 0.1 + 0.2 equal to 0.3? {result == 0.3}")

Output:

0.1 + 0.2 = 0.30000000000000004
Is 0.1 + 0.2 equal to 0.3? False

To handle this issue, you can use the round() function or the decimal module for precise decimal arithmetic:

python
# Using round function
rounded_result = round(0.1 + 0.2, 1)
print(f"Rounded result: {rounded_result}")
print(f"Is rounded result equal to 0.3? {rounded_result == 0.3}")

# Using decimal module for precision
from decimal import Decimal
precise_result = Decimal('0.1') + Decimal('0.2')
print(f"Precise result: {precise_result}")

Output:

Rounded result: 0.3
Is rounded result equal to 0.3? True
Precise result: 0.3

Complex Numbers

Complex numbers consist of a real part and an imaginary part. In Python, the imaginary part is represented by j or J.

Creating Complex Numbers

python
# Creating complex numbers
complex1 = 2 + 3j
complex2 = complex(4, 5) # 4 + 5j

print(complex1)
print(complex2)
print(type(complex1))

# Accessing real and imaginary parts
print(f"Real part of {complex1}: {complex1.real}")
print(f"Imaginary part of {complex1}: {complex1.imag}")

Output:

(2+3j)
(4+5j)
<class 'complex'>
Real part of (2+3j): 2.0
Imaginary part of (2+3j): 3.0

Numeric Operations

Python supports all standard arithmetic operations on numbers.

Basic Arithmetic

python
a = 10
b = 3

# Addition
print(f"{a} + {b} = {a + b}")

# Subtraction
print(f"{a} - {b} = {a - b}")

# Multiplication
print(f"{a} * {b} = {a * b}")

# Division (results in float)
print(f"{a} / {b} = {a / b}")

# Floor division (results in integer)
print(f"{a} // {b} = {a // b}")

# Modulus (remainder)
print(f"{a} % {b} = {a % b}")

# Exponentiation
print(f"{a} ** {b} = {a ** b}")

Output:

10 + 3 = 13
10 - 3 = 7
10 * 3 = 30
10 / 3 = 3.3333333333333335
10 // 3 = 3
10 % 3 = 1
10 ** 3 = 1000

Type Conversion

You can convert between different number types:

python
# Integer to float
a = 10
float_a = float(a)
print(f"{a} converted to float: {float_a}")

# Float to integer (truncates decimal part)
b = 7.8
int_b = int(b)
print(f"{b} converted to int: {int_b}")

# String to number
str_num = "25"
num_from_str = int(str_num)
print(f"String '{str_num}' to number: {num_from_str}")

# To complex
c = complex(a, b)
print(f"Complex from {a} and {b}: {c}")

Output:

10 converted to float: 10.0
7.8 converted to int: 7
String '25' to number: 25
Complex from 10 and 7.8: (10+7.8j)

Built-in Numeric Functions

Python provides several built-in functions for working with numbers:

python
# Absolute value
print(f"abs(-10): {abs(-10)}")

# Rounding
print(f"round(3.75): {round(3.75)}")
print(f"round(3.75, 1): {round(3.75, 1)}") # Round to 1 decimal place

# Maximum and minimum
numbers = [5, 2, 8, 1, 9]
print(f"max({numbers}): {max(numbers)}")
print(f"min({numbers}): {min(numbers)}")

# Sum
print(f"sum({numbers}): {sum(numbers)}")

# Power
print(f"pow(2, 3): {pow(2, 3)}") # Same as 2 ** 3

Output:

abs(-10): 10
round(3.75): 4
round(3.75, 1): 3.8
max([5, 2, 8, 1, 9]): 9
min([5, 2, 8, 1, 9]): 1
sum([5, 2, 8, 1, 9]): 25
pow(2, 3): 8

The Math Module

For more advanced mathematical operations, Python provides the math module:

python
import math

# Square root
print(f"Square root of 16: {math.sqrt(16)}")

# Constants
print(f"Value of pi: {math.pi}")
print(f"Value of e: {math.e}")

# Trigonometric functions (angles in radians)
print(f"sin(30°): {math.sin(math.radians(30))}")
print(f"cos(60°): {math.cos(math.radians(60))}")

# Logarithms
print(f"log(100) base 10: {math.log10(100)}")
print(f"Natural log of 10: {math.log(10)}")

# Ceiling and floor
print(f"ceil(4.3): {math.ceil(4.3)}") # Smallest integer >= 4.3
print(f"floor(4.7): {math.floor(4.7)}") # Largest integer <= 4.7

Output:

Square root of 16: 4.0
Value of pi: 3.141592653589793
Value of e: 2.718281828459045
sin(30°): 0.49999999999999994
cos(60°): 0.5000000000000001
log(100) base 10: 2.0
Natural log of 10: 2.302585092994046
ceil(4.3): 5
floor(4.7): 4

Real-World Applications

Let's look at some practical examples where numeric operations are used:

Example 1: Simple Interest Calculator

python
def calculate_simple_interest(principal, rate, time):
"""
Calculate simple interest

Parameters:
principal (float): The principal amount
rate (float): The interest rate (as a decimal)
time (float): The time in years

Returns:
float: The simple interest amount
"""
interest = principal * rate * time
return interest

# Calculate interest on a loan
loan_amount = 10000
annual_rate = 0.05 # 5%
loan_period = 3 # years

interest_amount = calculate_simple_interest(loan_amount, annual_rate, loan_period)
total_amount = loan_amount + interest_amount

print(f"Loan amount: ${loan_amount}")
print(f"Annual interest rate: {annual_rate * 100}%")
print(f"Loan period: {loan_period} years")
print(f"Interest amount: ${interest_amount}")
print(f"Total amount to be paid: ${total_amount}")

Output:

Loan amount: $10000
Annual interest rate: 5.0%
Loan period: 3 years
Interest amount: $1500.0
Total amount to be paid: $11500.0

Example 2: Temperature Converter

python
def celsius_to_fahrenheit(celsius):
"""Convert temperature from Celsius to Fahrenheit"""
return (celsius * 9/5) + 32

def fahrenheit_to_celsius(fahrenheit):
"""Convert temperature from Fahrenheit to Celsius"""
return (fahrenheit - 32) * 5/9

# Test conversions
celsius_temp = 25
fahrenheit_temp = celsius_to_fahrenheit(celsius_temp)
print(f"{celsius_temp}°C is equal to {round(fahrenheit_temp, 1)}°F")

fahrenheit_temp = 98.6
celsius_temp = fahrenheit_to_celsius(fahrenheit_temp)
print(f"{fahrenheit_temp}°F is equal to {round(celsius_temp, 1)}°C")

Output:

25°C is equal to 77.0°F
98.6°F is equal to 37.0°C

Example 3: Geometric Calculations

python
import math

# Calculate the area and circumference of a circle
def circle_properties(radius):
area = math.pi * radius**2
circumference = 2 * math.pi * radius
return area, circumference

# Calculate volume and surface area of a sphere
def sphere_properties(radius):
volume = (4/3) * math.pi * radius**3
surface_area = 4 * math.pi * radius**2
return volume, surface_area

radius = 5
circle_area, circle_circumference = circle_properties(radius)
sphere_volume, sphere_surface_area = sphere_properties(radius)

print(f"Circle with radius {radius}:")
print(f"Area: {circle_area:.2f} square units")
print(f"Circumference: {circle_circumference:.2f} units")
print(f"\nSphere with radius {radius}:")
print(f"Volume: {sphere_volume:.2f} cubic units")
print(f"Surface area: {sphere_surface_area:.2f} square units")

Output:

Circle with radius 5:
Area: 78.54 square units
Circumference: 31.42 units

Sphere with radius 5:
Volume: 523.60 cubic units
Surface area: 314.16 square units

Summary

In this tutorial, we've covered:

  • Different numeric types in Python: integers, floating-point numbers, and complex numbers
  • How to create and work with each numeric type
  • Basic arithmetic operations on numbers
  • Type conversion between numeric types
  • Built-in functions for working with numbers
  • The math module for advanced mathematical operations
  • Real-world examples demonstrating practical applications of Python numbers

Python's numeric data types and operations provide a solid foundation for performing calculations in your programs. Whether you're developing financial applications, scientific programs, or simple utilities, understanding how to work with numbers is essential.

Additional Resources and Exercises

Further Reading

Practice Exercises

  1. Number Type Exploration: Write a program that takes user input and determines whether it's an integer, float, or neither.

  2. Quadratic Equation Solver: Create a program that solves quadratic equations (ax² + bx + c = 0) using the quadratic formula.

  3. Currency Converter: Implement a simple currency converter that converts between USD, EUR, and GBP using current exchange rates.

  4. BMI Calculator: Create a Body Mass Index (BMI) calculator that takes weight (in kg) and height (in m) and calculates BMI.

  5. Compound Interest Calculator: Extend the simple interest example to calculate compound interest, where interest is added back to the principal.

Keep practicing with these concepts, and you'll become more comfortable working with numbers in Python!



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)