» » » Python Exponent Square

# Square Numbers and Exponents in Python, With Examples

This tutorial will show you how to use exponents (e.g., calculating the square root of a number) in Python, with some code examples.

This tutorial covers several ways to calculate exponents in Python 3.

## Using ** (Power Operator)

The ** mathematical operator (known as the power operator) will calculate an exponent, raising the number on the left to the power of the number on the right of the operator:

`4**5 # Will evaluate 4*4*4*4*4 and return the integer value 1024`

Note that:

• You will receive a ZeroDivisionError if you try to raise 0 (zero) to a negative power
• Raising a negative number to a fractional power will result in a complex number
• If floating-point (non-integer) numbers are supplied, the result will be a floating-point number

## Using pow(x, y)

The built-in pow() function will do the same – the result will be identical – it just uses a function to calculate the result rather than a mathematical operator:

`pow(4, 5) # Will also return 1024, the same as above`

Note that:

• Everything that applies to the ** operator applies to the pow() function

## Using math.pow()

The math library also includes a pow() function which does the same thing – but with slightly different behavior and results:

```import math
math.pow(4, 5) # Returns 1024 - but as a floating point number, not an integer```

Note that:

• While the number returned is the same as the ** operator and the built-in pow() function, the number type is different. math.pow() converts the numbers passed to it to floating-point numbers – and always returns its answer as a floating-point number
• Both math.pow(1.0, num) and math.pow(num, 0.0) always return 1.0 when using math.pow()
• This occurs even when num is zero or NaN (Not a Number)
• math.pow() throws a ValueError exception when:
• The first argument is negative
• The second argument is not an integer

## Square Numbers

‘Squaring’ a number is simply raising it to a power (exponent) of 2.

So, 5 squared would be calculated as follows using the above methods:

```5**2
pow(5, 2)
math.pow(5, 2)```

All of the above will return the number 25.

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.