Back to Python
2026-01-255 min read

Python Numbers, Type Conversion and Mathematics

Learn Python Numbers, Type Conversion and Mathematics step by step with clear examples and exercises.

Title: Mastering Python Numbers, Type Conversion and Mathematics

Why This Matters

In this comprehensive lesson, we delve into the essentials of Python numbers, type conversion, and mathematics. Understanding these foundational concepts is crucial for solving real-world problems, acing programming interviews, and debugging common errors in your code.

Prerequisites

Before diving into this lesson, you should have a basic understanding of:

  1. Python syntax and variables
  2. Basic data structures like lists and dictionaries
  3. Control flow constructs such as if, for loops, and conditional expressions (and, or)
  4. Exception handling using try-except blocks

Core Concept

Python Numbers

Python supports several numeric types, including integers (int), floating-point numbers (float), and complex numbers (complex). Additionally, Python has a special type for Booleans (bool).

x = 10 # Integer
y = 20.5 # Float
z = 3j # Complex number
bool_val = True # Boolean

Type Conversion

Python automatically handles type conversion in many situations, but there are times when you need to explicitly convert types. The built-in functions int(), float(), complex(), and bool() can be used for this purpose.

str_num = "42"
int_num = int(str_num) # Type conversion from string to integer
float_num = float(str_num) # Type conversion from string to float
complex_num = complex("3+4j") # Type conversion from string to complex number
bool_val = bool(int_num) # Converting an integer to a Boolean (non-zero values are True, zero and empty values are False)

Mathematical Operations

Python supports basic arithmetic operations like addition, subtraction, multiplication, division, and modulus. It also offers higher-level functions like pow(), which raises a number to an exponent, and abs(), which returns the absolute value of a number.

a = 5
b = 3
sum_ab = a + b # Addition
product_ab = a * b # Multiplication
division_ab = a / b # Division
remainder_ab = a % b # Modulus
square_a = pow(a, 2) # Square of a
absolute_a = abs(a) # Absolute value of a

Comparison Operators

Python provides comparison operators like ==, !=, <, <=, >, and >=. These can be used to compare numbers or other types, but be aware that some comparisons may lead to unexpected results with certain data types.

x = 5
y = "5"
z = [5]

Comparing x to y and z will result in False because x is an integer, while y and z are string and list respectively

print(x == y) # Output: False

print(x == z) # Output: False

However, comparing y and z to each other will return True since they have the same value

print(y == z) # Output: True


### Common Mathematical Functions

Python provides several built-in mathematical functions in the `math` module. Some examples include:

1. `sqrt()`: Calculates the square root of a number
2. `sin()`, `cos()`, and `tan()`: Returns the sine, cosine, and tangent of an angle (measured in radians)
3. `exp()`: Computes the exponential value of a number (e^x)
4. `log()`: Calculates the natural logarithm of a number (ln(x))
5. `factorial()`: Returns the factorial of a non-negative integer (n!)
6. `gcd()`: Computes the greatest common divisor of two numbers
7. `lcm()`: Calculates the least common multiple of two numbers

import math

square_root = math.sqrt(16) # Square root of 16

sine = math.sin(math.pi / 2) # Sine of 90 degrees (π/2)

exponential = math.exp(1) # Exponential value of 1 (e^1)

logarithm = math.log(1000) # Natural logarithm of 1000 (ln(1000))

factorial_5 = math.factorial(5) # Factorial of 5 (5!)

gcd_result = math.gcd(24, 18) # Greatest common divisor of 24 and 18

lcm_result = math.lcm(24, 18) # Least common multiple of 24 and 18

Worked Example

Let's create a simple Python script that calculates the factorial of a number, checks if it's prime, and prints the Fibonacci sequence up to a given limit. Additionally, we will implement functions for finding the greatest common divisor (GCD) and least common multiple (LCM).

import math

def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result

def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True

def gcd(a, b):
while b != 0:
a, b = b, a % b
return abs(a)

def lcm(a, b):
return abs((a * b) // math.gcd(a, b))

number = int(input("Enter a number to find its factorial, check if it's prime, calculate the GCD and LCM of two numbers (separated by space), and print the Fibonacci sequence up to that number: "))
factorial_result = factorial(number)
prime_result = is_prime(number)
gcd_input = input("Enter two numbers separated by a space to find their GCD: ")
gcd_numbers = list(map(int, gcd_input.split()))
gcd_result = gcd(*gcd_numbers)
lcm_result = lcm(*gcd_numbers)
fibonacci_result = fibonacci(number)

print(f"Factorial of {number}: {factorial_result}")
print(f"Is {number} prime? {prime_result}")
print("GCD of ", gcd_input, ":", gcd_result)
print("LCM of ", gcd_input, ":", lcm_result)
print("Fibonacci sequence up to {number}:", fibonacci_result)

Common Mistakes

  1. Not handling integer division: When performing division with integers, Python returns a floating-point result by default. To get an integer result, use the // operator for floor division or the divmod() function.
  1. Forgetting to import necessary modules: Make sure you have imported any required modules before using their functions.
  1. Using the wrong data type: Be mindful of the data types you're working with and convert them appropriately when needed.
  1. Misunderstanding the order of operations: Python follows standard mathematical order, but it can sometimes lead to unexpected results if not handled carefully.
  1. Comparing incompatible data types: When comparing numbers with different data types (e.g., integers and floating-point numbers), Python may return unexpected results due to rounding errors. To avoid this, ensure that you're working with compatible data types for comparisons.

Practice Questions

  1. Write a script that calculates the sum of all multiples of 3 under 100.
  2. Create a program that finds the largest prime number less than or equal to 100.
  3. Write a Python function that converts a decimal number into its binary representation.
  4. Implement a function that calculates the greatest common divisor (GCD) of two numbers using Euclid's algorithm.
  5. Create a script that generates and prints the first 20 Fibonacci numbers.
  6. Write a Python function to calculate the average of a list of numbers.
  7. Implement a function that finds all roots of a quadratic equation (ax² + bx + c = 0).
  8. Create a program that calculates the area and perimeter of various geometric shapes like circles, rectangles, and triangles using user-provided inputs.
  9. Write a Python script to calculate the harmonic mean of a list of numbers.
  10. Implement a function that checks if a given number is a perfect square.

FAQ

How do I find the smallest common multiple (SCM) of two numbers?

To find the smallest common multiple (SCM), you can use the formula: lcm(a, b) = |a * b| / gcd(a, b). Here's a Python function that implements this formula.

def lcm(a, b):
return abs((a * b) // math.gcd(a, b))

What is the difference between floor division and true division in Python?

Floor division (//) returns the largest whole number less than or equal to the result of the division, while true division (/) returns the exact quotient without rounding. For example:

a = 10
b = 3
print(a // b) # Output: 3 (Floor division)
print(a / b) # Output: 3.3333333333333335 (True division)
Python Numbers, Type Conversion and Mathematics | Python | XQA Learn