Easy Tutorial
❮ Python Att List Index Ref Math Floor ❯

Python Square Root

Python3 Examples

A square root, also known as a second root, is represented as 〔√ ̄〕, for example: in mathematical terms, √ ̄16=4. In descriptive language: the square root of 16 equals 4.

The following example demonstrates how to take a user-input number and calculate its square root:

Example (Python 3.0+)

# -*- coding: UTF-8 -*-

# Filename : test.py
# author by : www.tutorialpro.org

num = float(input('Please enter a number: '))
num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f'%(num, num_sqrt))

Execution of the above code produces the following result:

$ python test.py 
Please enter a number: 4
The square root of 4.000 is 2.000

In this example, we take a number from the user and calculate its square root using the exponentiation operator **.

This program works only for positive numbers. For negative numbers and complex numbers, you can use the following method:

Example (Python 3.0+)

# -*- coding: UTF-8 -*-

# Filename : test.py
# author by : www.tutorialpro.org

# Calculate the square root for real and complex numbers
# Import the complex math module

import cmath

num = int(input("Please enter a number: "))
num_sqrt = cmath.sqrt(num)
print('The square root of {0} is {1:0.3f}+{2:0.3f}j'.format(num, num_sqrt.real, num_sqrt.imag))

Execution of the above code produces the following result:

$ python test.py 
Please enter a number: -8
The square root of -8 is 0.000+2.828j

In this example, we used the sqrt() method from the cmath (complex math) module.

Python3 Examples

❮ Python Att List Index Ref Math Floor ❯