Python is a popular, easy-to-learn programming language used for a wide range of applications from web development and scientific computing to machine learning and data analysis. One of the key aspects of Python is its support for performing mathematical computations and operations. In this comprehensive guide, we will explain how to carry out basic math with variables in Python using clear examples and sample code snippets.
Table of Contents
Open Table of Contents
Overview of Variables in Python
Before we can perform math with variables, it is important to understand what variables are in Python.
Variables are containers that store values in a program. We can give a variable a descriptive name that represents or refers to the value it contains. Variables don’t have fixed types - we can store integers, floats, strings etc in a variable and we can change the value of a variable later in the program.
To define a variable in Python, we use the assignment operator =
.
# Assign integer value to variable
num = 10
# Assign float value
price = 9.99
# Assign string
name = "John"
Variable names should follow PEP 8 naming conventions - they can contain letters, numbers and underscores but cannot start with a number.
Now that we have an overview of variables, let’s see how to use them for mathematical computations in Python.
Basic Mathematical Operators in Python
Python provides the following basic arithmetic operators that can be used to perform mathematical operations:
+
: Addition-
: Subtraction*
: Multiplication/
: Division%
: Modulus or remainder**
: Exponentiation//
: Floor division
These operators work as you would expect and follow standard mathematical rules for precedence and associativity.
We can use variables representing numeric values in combination with these operators to execute math operations in Python.
# Addition
num1 = 10
num2 = 20
sum = num1 + num2
print(sum) # Prints 30
# Subtraction
diff = num2 - num1
print(diff) # Prints 10
# Multiplication
product = num1 * num2
print(product) # Prints 200
# Division
quotient = num2 / num1
print(quotient) # Prints 2.0
# Modulus
remainder = num2 % num1
print(remainder) # Prints 0
# Exponentiation
result = num1 ** 2
print(result) # Prints 100
# Floor division
floor_val = num2 // num1
print(floor_val) # Prints 2
Note that dividing two integers in Python 3 returns a float value. Older Python 2 automatically returned an integer result for division of two ints.
We can also chain multiple math operators together:
# Operator chaining
x = 2 + 3 * 4 - 8 / 2
print(x) # Prints 10.0
The order of operations is followed based on precedence.
Math Functions in Python
Beyond the basic math operators, Python includes a set of built-in math functions that enable more complex mathematical calculations. These functions are included in the math
module.
To use the math
module, we need to import it first:
import math
Some common math functions provided by the math
module include:
math.ceil(x)
- Return the ceiling of x, i.e. the smallest integer greater than or equal to x.math.floor(x)
- Return the floor of x, i.e. the largest integer less than or equal to x.math.sqrt(x)
- Return the square root of x.math.pow(x, y)
- Return x raised to the power y.math.fabs(x)
- Return the absolute value of x.math.factorial(x)
- Return the factorial of an integer x.math.cos(x)
- Return the cosine of x radians.math.sin(x)
- Return the sine of x radians.math.tan(x)
- Return the tangent of x radians.
Let’s see some examples:
import math
print(math.ceil(4.2)) # 5
print(math.floor(4.2)) # 4
print(math.sqrt(16)) # 4.0
print(math.pow(2, 3)) # 8.0
print(math.fabs(-4.2)) # 4.2
print(math.factorial(5)) # 120
print(math.cos(math.pi)) # -1.0
print(math.sin(math.pi/2)) # 1.0
print(math.tan(math.pi/4)) # 0.9999999999999999
We pass the arguments to these math functions which perform the required mathematical operation and return the result.
This allows us to compute more complex math in Python very easily.
Accepting User Input for Math Operations
In real programs, we often want to get input from the user for our variables rather than hardcoding values. The input()
function allows us to accept user input in Python.
Here is an example that gets two numbers from the user and prints their sum:
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
num1 = float(num1)
num2 = float(num2)
# Convert input to floats
sum = num1 + num2
print("Sum:", sum)
Note that we have to explicitly convert the input to floats using float()
. Input values are always read as strings, so we need to convert them to numbers before math operations.
We can make this cleaner by putting it in a function:
def add():
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
sum = num1 + num2
print("Sum:", sum)
add()
Now we can call this add()
function whenever we need to get two numbers from user and print their sum.
This is a simple example, we can extend this to accept input for any mathematical operation and perform it.
Formatting Print Output
When printing math results, we may want to format the output in a particular way. For example, limiting to 2 decimal places or comma separation.
Python provides string formatting options that can be used to format numbers printed to console.
Some common ways to format numbers are:
import math
num = 4.55523
print(f"{num:.2f}") # 4.56
num2 = 1234
print(f"{num2:,}") # 1,234
num3 = math.pi
print(f"{num3:.4f}") # 3.1416
Where:
:.2f
limits to 2 decimal places:,
adds thousands comma separator:.4f
limits to 4 decimal places
String formatting provides many flexible options for formatting math results printed to console.
Examples of Common Math Operations
Let’s go through some examples of common math tasks and operations in Python.
Calculate Area of Circle
radius = 5
area = math.pi * radius ** 2
print("Area of circle:", area)
Generate Random Number
We can use the random
module to generate random numbers in Python.
import random
random_num = random.randint(1,10)
print(random_num)
This will print a random integer between 1 and 10.
Calculate Mean and Standard Deviation
The statistics
module provides functions for common statistical calculations.
import statistics
values = [1, 4, 7, 3, 2]
mean = statistics.mean(values)
std_dev = statistics.stdev(values)
print("Mean:", mean)
print("Standard deviation:", std_dev)
Solve Quadratic Equation
Given a
, b
, c
coefficients we can find roots of quadratic equation using:
import cmath
a = 1
b = 2
c = -3
root1 = (-b + cmath.sqrt(b**2 - 4*a*c)) / (2*a)
root2 = (-b - cmath.sqrt(b**2 - 4*a*c)) / (2*a)
print(root1, root2)
This prints the complex roots.
Generate Fibonacci Sequence
The Fibonacci sequence is a series of numbers where each number is the sum of the previous two.
We can generate n numbers of the sequence using:
def fibonacci(n):
a, b = 0, 1
for i in range(n):
print(a, end=' ')
a, b = b, a+b
fibonacci(10)
This recursively calculates and prints the first n Fibonacci numbers.
Calculate Factorial
To calculate the factorial of a number mathematically:
import math
num = 5
fact = math.factorial(num)
print(fact)
Or recursively implement the factorial function:
def factorial(x):
if x == 1:
return 1
else:
return x * factorial(x-1)
print(factorial(5))
Conclusion
In this comprehensive guide, we explored how to perform basic mathematical operations in Python using variables, operators, built-in math functions and by accepting user input. Key points covered include:
- Using variables and math operators for arithmetic operations
- Leveraging math module functions for complex computations
- Accepting user input and converting to numeric types
- Formatting output of math results
- Examples of common math tasks including statistics, generating sequences, solving equations etc.
Python provides extensive support for mathematical and scientific computing. With its simple syntax and built-in math capabilities, Python is easy to use for basic and advanced math operations alike. The concepts covered here should give you a solid base for using Python for most mathematical programming needs.