Home Subscribe

1. Basic Maths

This course will introduce you to the basic mathematical operations that can be performed in Python. We will cover:

  • Addition and Subtraction

  • Multiplication and Division

  • Modulo

  • Power

  • Operator Precedence

  • Assignment Operators

  • The Python Math Library

1.1. Introduction

Before we begin, it’s important to understand some basics about data types in Python. In Python, there are three main types of numerical data: integers, floats, and complex numbers.

Integers are whole numbers, while floats are decimal numbers. Complex numbers are a combination of a real and an imaginary number. When performing mathematical operations in Python, it’s important to understand the data types involved and how they interact with each other.

In this course, we will focus on using Python to perform basic arithmetic operations, such as addition, subtraction, multiplication, and division. We will also cover more advanced topics such as the modulo operator, power operator, and the Python Math Library.

1.2. Addition and Subtraction

Addition and subtraction are basic arithmetic operations in Python that can be performed on integers and floats.

# Working with integers:

print(1 + 5) # 6
# Initialize variables to stand for integer values:

a = 87
b = 103

print(a + b) # 190
# Integers can be both positive and negative numbers:

c = -36
d = 27

print(c + d) # -9
# Addition will behave similarly with floats:

e = 5.7
f = 2.3

print(e + f) # 8.0
# The syntax for subtraction is the same as for addition:

g = 75.61
h = 37
print(g - h) # 38.61
Python returns floats when adding integers and floats together. It’s important to keep this in mind when working with numerical data in Python.

Exercise 1

Write a program that asks the user to input two numbers and prints the sum of the two numbers.

Solution
a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))

sum = a + b
print(f"The sum of {a} and {b} is {sum}.")

1.3. Multiplication and Division

Multiplication and division are also basic arithmetic operations in Python.

# Doing multiplication in Python with two float values:

k = 100.1
l = 10.7

print(k * l) # 1071.07
# When you divide in Python 3, your quotient will always be returned as a float, even if you use two integers:

m = 90
n = 5

print(m / n) #18.0
# Floor division:
print(100 // 40) # 2
In Python 3, when you perform division, the quotient will always be returned as a float, even if you use two integers. If you want to perform integer division, you can use the // operator.

Exercise 2

Write a program that asks the user to input two numbers and prints the product of the two numbers.

1.4. Modulo

The modulo operator returns the remainder of a division operation. This can be useful for checking divisibility or finding the next multiple of a number.

# Modulo in action:

o = 95
p = 25

print(o % p) # 20
# Floats with the modulo:

q = 46.5
r = 6.5
print(q % r) # 3.0

Exercise 3

Write a program that asks the user to input two numbers and prints the remainder when the first number is divided by the second number.

1.5. Power

The power operator is used to raise a number to a certain power.

s = 52.25
t = 3
print(s ** t) # 142645.765625

Exercise 4

Write a program that asks the user to input two numbers and prints the first number raised to the power of the second number.

1.6. Operator Precedence

When performing arithmetic operations in Python, it’s important to understand operator precedence. This determines the order in which operations are performed.

u = 10 + 10 * 5
print(u) # 60
u = (10 + 10) * 5
print(u) # 100

In the example above, the multiplication operation is performed before the addition operation in the first line because it has a higher precedence. In the second line, the addition operation is performed first because it is contained within parentheses.

Exercise 5

Write a program that uses parentheses to change the order of operations in an arithmetic expression.

1.7. Assignment Operators (=)

Assignment operators are used to assign values to variables. There are several different types of assignment operators, including +=, -=, *=, and /=.

# I. e.g. a = 3
# II. Compound assignment operators:
w = 5
w += 1
print(w) # 6

In the example above, the += operator is used to add 1 to the value of the variable w and then assign the result back to w.

Exercise 6

Write a program that uses a compound assignment operator to increment a variable by a certain amount.

1.8. Python Math Library

The Python Math Library provides a set of mathematical functions that can be used to perform more advanced calculations in Python.

To use the Python Math Library, you first need to import it into your program:

To use a function from the Python Math Library, you simply call the function using the module name (math) and the function name separated by a dot (.), like this:

import math
print(math.sqrt(16)) # 4.0

Or you can import the math module with an alias (m in the example below) to make the code shorter:

import math as m
print(m.sqrt(16)) # 4.0

Here is a list of some of the functions available in the Python Math Library:

Function Description

ceil(x)

Returns the smallest integer greater than or equal to x.

copysign(x, y)

Returns x with the sign of y

fabs(x)

Returns the absolute value of x

factorial(x)

Returns the factorial of x

floor(x)

Returns the largest integer less than or equal to x

fmod(x, y)

Returns the remainder when x is divided by y

frexp(x)

Returns the mantissa and exponent of x as the pair (m, e)

fsum(iterable)

Returns an accurate floating point sum of values in the iterable

isfinite(x)

Returns True if x is neither an infinity nor a NaN (Not a Number)

isinf(x)

Returns True if x is a positive or negative infinity

isnan(x)

Returns True if x is a NaN

ldexp(x, i)

Returns \(x \times (2^i)\)

modf(x)

Returns the fractional and integer parts of x

trunc(x)

Returns the truncated integer value of x

exp(x)

Returns \(e^x\)

expm1(x)

Returns \(e^x - 1\)

log(x[, base])

Returns the logarithm of x to the base (defaults to e)

log1p(x)

Returns the natural logarithm of 1+x

log2(x)

Returns the base-2 logarithm of x

log10(x)

Returns the base-10 logarithm of x

pow(x, y)

Returns x raised to the power y

sqrt(x)

Returns the square root of x

acos(x)

Returns the arc cosine of x

asin(x)

Returns the arc sine of x

atan(x)

Returns the arc tangent of x

atan2(y, x)

Returns atan(y / x)

cos(x)

Returns the cosine of x

hypot(x, y)

Returns the Euclidean norm, sqrt(xx + yy)

sin(x)

Returns the sine of x

tan(x)

Returns the tangent of x

degrees(x)

Converts angle x from radians to degrees

radians(x)

Converts angle x from degrees to radians

acosh(x)

Returns the inverse hyperbolic cosine of x

asinh(x)

Returns the inverse hyperbolic sine of x

atanh(x)

Returns the inverse hyperbolic tangent of x

cosh(x)

Returns the hyperbolic cosine of x

sinh(x)

Returns the hyperbolic cosine of x

tanh(x)

Returns the hyperbolic tangent of x

erf(x)

Returns the error function at x

erfc(x)

Returns the complementary error function at x

gamma(x)

Returns the Gamma function at x

lgamma(x)

Returns the natural logarithm of the absolute value of the Gamma function at x

pi

Mathematical constant, the ratio of circumference of a circle to it’s diameter (3.14159…)

e

mathematical constant e (2.71828…)

Exercise 7

Write a program that uses a function from the Python Math Library to perform a mathematical calculation.

# Pie
m.pi # 3.141592653589793

# Euler's number
m.e # 2.718281828459045

m.radians(30) # 0.5235987755982988

m.degrees(m.pi/30) # 6.0

m.sin(45) # 0.8509035245341184

m.cos(0) # 1.0

m.sin(51)**2 + m.cos(51)**2 # 1.0

m.log(10) # 2.302585092994046

m.log10(10) # 1.0

#  2**4
m.pow(2,4) # 16.0

m.sqrt(16) # 4.0

m.ceil(6.5877) # 7

m.floor(6.5677) # 6

1.9. Exercises

1.9.1. Calculate the Area of a Circle

Write a program that asks the user for the radius of a circle and calculates its area using the formula \(A = \pi r^2\). Use the math library to access the value of \(\pi\).

Solution:
import math

radius = float(input("Enter the radius of the circle: "))
area = math.pi * radius**2
print(f"The area of the circle is: {area:.2f}")

1.9.2. Find the Hypotenuse of a Right Triangle

Write a program that asks the user for the lengths of the two legs of a right triangle and calculates the length of its hypotenuse using the Pythagorean theorem. Use the math library to access the square root function.

Solution:
import math

leg1 = float(input("Enter the length of the first leg: "))
leg2 = float(input("Enter the length of the second leg: "))
hypotenuse = math.sqrt(leg1**2 + leg2**2)
print(f"The length of the hypotenuse is: {hypotenuse:.2f}")

1.9.3. Convert Degrees to Radians

Write a program that asks the user for an angle in degrees and converts it to radians using the math library.

Solution:
import math

degrees = float(input("Enter an angle in degrees: "))
radians = math.radians(degrees)
print(f"The angle in radians is: {radians:.2f}")

1.9.4. Solve a Quadratic Equation

Write a program that asks the user for the coefficients of a quadratic equation (a, b, and c) and calculates its roots using the quadratic formula. Use the math library to access the square root function.

Solution:
import math

a = float(input("Enter the coefficient of x^2: "))
b = float(input("Enter the coefficient of x: "))
c = float(input("Enter the constant term: "))

discriminant = b**2 - 4*a*c

if discriminant < 0:
    print("The equation has no real roots.")
elif discriminant == 0:
    root = -b / (2*a)
    print(f"The equation has one real root: {root:.2f}")
else:
    root1 = (-b + math.sqrt(discriminant)) / (2*a)
    root2 = (-b - math.sqrt(discriminant)) / (2*a)
    print(f"The equation has two real roots: {root1:.2f} and {root2:.2f}")

1.9.5. Calculate the Fibonacci Sequence

Write a program that asks the user for a number n and prints the first n terms of the Fibonacci sequence. The Fibonacci sequence is defined as follows: the first two terms are 0 and 1, and each subsequent term is the sum of the previous two terms.

Solution:
n = int(input("Enter the number of terms: "))

a, b = 0, 1
for i in range(n):
    print(a, end=" ")
    a, b = b, a + b

1.9.6. Calculate the Factorial of a Number

Write a program that asks the user for a non-negative integer n and calculates its factorial using a loop.

Solution:
n = int(input("Enter a non-negative integer: "))

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

print(f"The factorial of {n} is: {factorial}")

1.9.7. Find the GCD of Two Numbers

Write a program that asks the user for two positive integers and finds their greatest common divisor (GCD) using the Euclidean algorithm.

Solution:
a = int(input("Enter the first positive integer: "))
b = int(input("Enter the second positive integer: "))

while b != 0:
    a, b = b, a % b

print(f"The GCD of {a} and {b} is: {a}")

1.9.8. Find the LCM of Two Numbers

Write a program that asks the user for two positive integers and finds their least common multiple (LCM).

Solution:
a = int(input("Enter the first positive integer: "))
b = int(input("Enter the second positive integer: "))

lcm = a*b
while a != b:
    if a < b:
        a += a
    else:
        b += b
    if a*b < lcm:
        lcm = a*b

print(f"The LCM of {a} and {b} is: {lcm}")

1.9.9. Generate Prime Numbers

Write a program that asks the user for a positive integer n and generates the first n prime numbers.

Solution:
n = int(input("Enter the number of prime numbers to generate: "))

primes = []
num = 2
while len(primes) < n:
    is_prime = True
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            is_prime = False
            break
    if is_prime:
        primes.append(num)
    num += 1

print(f"The first {n} prime numbers are: {primes}")

These additional exercises will help you further practice and apply the concepts covered in this short course.

1.9.10. Calculate the Area of a Trapezoid

Write a program that asks the user for the lengths of the bases and the height of a trapezoid and calculates its area using the formula \(A = (b1 + b2)h/2\).

Solution:
b1 = float(input("Enter the length of the first base: "))
b2 = float(input("Enter the length of the second base: "))
h = float(input("Enter the height: "))

area = (b1 + b2) * h / 2
print(f"The area of the trapezoid is: {area:.2f}")

1.9.11. Calculate the Volume of a Sphere

Write a program that asks the user for the radius of a sphere and calculates its volume using the formula \(V = 4/3 \pi r^3\).

Solution:
import math

radius = float(input("Enter the radius of the sphere: "))
volume = 4/3 * math.pi * radius**3
print(f"The volume of the sphere is: {volume:.2f}")

1.9.12. Calculate the Distance Between Two Points

Write a program that asks the user for the coordinates of two points in 3D space and calculates the distance between them using the distance formula.

Solution:
import math

x1 = float(input("Enter the x-coordinate of the first point: "))
y1 = float(input("Enter the y-coordinate of the first point: "))
z1 = float(input("Enter the z-coordinate of the first point: "))

x2 = float(input("Enter the x-coordinate of the second point: "))
y2 = float(input("Enter the y-coordinate of the second point: "))
z2 = float(input("Enter the z-coordinate of the second point: "))

distance = math.sqrt((x2-x1)**2 + (y2-y1)**2 + (z2-z1)**2)
print(f"The distance between the two points is: {distance:.2f}")

1.9.13. Solve a System of Linear Equations

Write a program that asks the user for the coefficients of a system of two linear equations \((ax + by = c and dx + ey = f)\) and solves it using Cramer’s rule.

Solution:
a = float(input("Enter the coefficient of x in the first equation: "))
b = float(input("Enter the coefficient of y in the first equation: "))
c = float(input("Enter the constant term in the first equation: "))

d = float(input("Enter the coefficient of x in the second equation: "))
e = float(input("Enter the coefficient of y in the second equation: "))
f = float(input("Enter the constant term in the second equation: "))

determinant = a*e - b*d

if determinant == 0:
    print("The system has no unique solution.")
else:
    x = (c*e - b*f) / determinant
    y = (a*f - c*d) / determinant
    print(f"The solution is: x={x:.2f}, y={y:.2f}")

1.9.14. Generate a Sequence of Fibonacci Numbers Using Recursion

Write a program that asks the user for a number n and generates the first n terms of the Fibonacci sequence using recursion. The Fibonacci sequence is defined as follows: the first two terms are 0 and 1, and each subsequent term is the sum of the previous two terms.

Solution:
# This program uses recursion to generate the first n terms of the Fibonacci sequence.

def fibonacci(n):
    if n <= 1:
        return n
    else:
        return fibonacci(n-1) + fibonacci(n-2)

n = int(input("Enter the number of terms: "))

for i in range(n):
    print(fibonacci(i), end=" ")

1.10. Conclusion

In this course, you have learned the basics of mathematical operations in Python, including addition, subtraction, multiplication, and division. You have also learned about more advanced topics such as the modulo operator, power operator, operator precedence, assignment operators, and the Python Math Library.



Add Comment

* Required information
1000
Drag & drop images (max 3)
Enter the word shark backwards.

Comments

No comments yet. Be the first!