Python Guide Sidebar

Numbers in Python: A Comprehensive Guide

Numbers are one of the most fundamental data types in Python. They are used for mathematical operations, measurements, indexing, and more. Python supports a wide range of numeric types and operations.

Understand different numeric types in Python, including integers, floats, and complex numbers. Learn how to work with them for mathematical operations and number manipulation.

Table of Contents

  1. What Are Numbers in Python?
  2. Types of Numbers in Python
    • Integer
    • Float
    • Complex
  3. Numeric Operations
  4. Type Conversion Between Numbers
  5. Working with Built-in Numeric Functions
  6. Random Numbers in Python
  7. Mini-Project: Basic Financial Calculator
  8. Common Pitfalls and Best Practices
  9. Interview Questions and Answers (Google, Amazon, TCS, Infosys, Zoho)

1. What Are Numbers in Python?

Numbers in Python are used to store numeric values. Python automatically determines the type of a number based on the value you assign to it.

Example:

x = 10      # Integer
y = 3.14    # Float
z = 2 + 3j  # Complex

2. Types of Numbers in Python

Python supports three main types of numbers:

a) Integer (int)

  • Whole numbers, positive or negative, without decimal points.
  • Unlimited precision in Python 3.
x = 42
y = -7
print(type(x))  # Output: <class 'int'>

b) Float (float)

  • Numbers with decimal points.
  • Can represent real numbers and scientific notation.
x = 3.14159
y = 1.5e3  # Scientific notation (1.5 × 10³)
print(type(x))  # Output: <class 'float'>

c) Complex (complex)

  • Numbers with a real and imaginary part (e.g., a + bj).
z = 2 + 3j
print(z.real)  # Output: 2.0
print(z.imag)  # Output: 3.0

3. Numeric Operations

Python supports a wide range of arithmetic and bitwise operations:

Arithmetic Operations

OperatorDescriptionExampleResult
+Addition5 + 38
-Subtraction5 - 32
*Multiplication5 * 315
/Division5 / 22.5
//Floor Division5 // 22
%Modulus (Remainder)5 % 21
**Exponentiation5 ** 225

Example:

a = 10
b = 3
print(a + b)   # Output: 13
print(a / b)   # Output: 3.3333333333333335
print(a // b)  # Output: 3

Bitwise Operations

Python also supports bitwise operators like &, |, ^, ~, <<, and >>.

4. Type Conversion Between Numbers

Python allows you to convert between numeric types using the following functions:

  • int(): Converts to integer.
  • float(): Converts to float.
  • complex(): Converts to complex.

Example:

x = 5.7
y = int(x)   # y = 5
z = float(y) # z = 5.0
print(z)     # Output: 5.0

5. Working with Built-in Numeric Functions

a) abs()

Returns the absolute value.

print(abs(-5))  # Output: 5

b) round()

Rounds a number to the nearest integer or specified decimal places.

print(round(3.14159, 2))  # Output: 3.14

c) pow()

Returns a number raised to a power.

print(pow(2, 3))  # Output: 8

d) divmod()

Returns the quotient and remainder as a tuple.

print(divmod(7, 3))  # Output: (2, 1)

6. Random Numbers in Python

The random module provides functions to generate random numbers:

  • random.random(): Returns a random float between 0 and 1.
  • random.randint(a, b): Returns a random integer between a and b.
  • random.choice(sequence): Picks a random item from a sequence.

Example:

import random

print(random.random())          # Random float
print(random.randint(1, 10))    # Random integer between 1 and 10

7. Mini-Project: Basic Financial Calculator

Objective:

Create a calculator that computes compound interest based on user input.

# Financial Calculator

def calculate_compound_interest(principal, rate, time):
    amount = principal * (1 + rate / 100) ** time
    interest = amount - principal
    return interest, amount

# User input
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the annual interest rate (%): "))
time = float(input("Enter the time (years): "))

interest, total_amount = calculate_compound_interest(principal, rate, time)
print(f"Compound Interest: {interest:.2f}")
print(f"Total Amount: {total_amount:.2f}")

Sample Output:

Enter the principal amount: 1000
Enter the annual interest rate (%): 5
Enter the time (years): 2
Compound Interest: 102.50
Total Amount: 1102.50

8. Common Pitfalls and Best Practices

Pitfall 1: Division by Zero

  • Issue: Attempting to divide by zero causes a runtime error.
  • Solution: Always validate divisor values before performing division.

Pitfall 2: Precision Errors with Floating-Point Numbers

  • Issue: Floating-point arithmetic may result in slight precision errors.
  • Solution: Use the decimal module for high-precision calculations.

Interview Questions and Answers


Google

Q: What is the difference between // and / in Python?
A: / performs regular division and returns a float, while // performs floor division and returns an integer (or float if one operand is a float).

print(5 / 2)   # Output: 2.5
print(5 // 2)  # Output: 2

Amazon

Q: How can you generate random numbers in Python?
A: Use the random module. For example:

import random
print(random.randint(1, 10))  # Random integer between 1 and 10

TCS

Q: Write a Python program to find the sum of the digits of a number input by the user.
A:

num = int(input("Enter a number: "))
total = sum(int(digit) for digit in str(num))
print(f"Sum of digits: {total}")

Infosy

Q: How can you represent complex numbers in Python?
A: Use the complex type, with the syntax a + bj.

z = 3 + 4j
print(z.real)  # Output: 3.0
print(z.imag)  # Output: 4.0

Zoho

Q: What will the following code output? Why?

print(0.1 + 0.2 == 0.3)

A: Output: False
Reason: Due to floating-point precision errors, 0.1 + 0.2 evaluates to 0.30000000000000004.

Conclusion

Understanding Python’s numeric types and operations is vital for data analysis, scientific computing, and financial modeling. By mastering Python’s number system, you can handle calculations efficiently and effectively.

Numbers