» » » Python Square Cube Root

# Python: Calculating a Number’s Root (Square/sqrt, Cube), With Examples

This article will show you how to calculate the square root, or any root, of numbers in the Python programming language.

We previously covered squaring and raising numbers to a power in this article.

## What is a Root in Mathematics?

The root of a number x is the number that must be multiplied by itself a given number of times to equal the number x.

For example, the second root of 16 is 4 as 4*4 = 16. It is the second root because 4 must be multiplied by itself twice to reach the required result of 16.

The third root of 64 is 4 as 4*4*4 = 64. It is the third root because 4 must be multiplied by itself three times to reach the required result of 64.

The second root is usually called the square root. The third root is usually called the cube root. After that, there are fourth, fifth roots, and onwards – you can calculate any root, though it is less common.

## Calculating Square Root In Python

Calculating the square root of a number is a common task, so Python has a built-in function for the job as part of the math library.

### math.sqrt() Syntax

Here’s the syntax for the math.sqrt() function:

`math.sqrt(n)`

Note that:

### math.sqrt() Examples

Here’s the math.sqrt() function in action:

```# Import the required math library
import math

# Calculate and print the square root of 9
print(math.sqrt(9))```

Which will print the result:

`3`

## Calculating Any Root In Python

If you want to calculate any other root number in Python, use the following syntax:

`x**(1/float(n))`

Where n is the root you wish to calculate, and x is the number you wish to calculate the root of.

In Python 3, it’s not necessary to coerce n to a float, so you can just use:

`x**(1/n)`

For example:

`64**(1/3)`

…to calculate the cubed root of 64.

SHARE:
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.