English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Python

Contrôle de flux Python

Fonctions en Python

Types de données en Python

Opérations de fichier Python

Python objects and classes

Python date and time

Advanced knowledge of Python

Python reference manual

Python program calculates square root

Complete Python examples

In this program, you will learn to use the exponent operator and the cmath module to find the square root of a number.

To understand this example, you should understand the followingPython programmingTopic:

Example: for positive numbers

# Program to calculate square root
# Note: You can change this value to a different number, which will yield different results
num = 8 
# Accept user input
#num = float(input('Enter a number: '))
num_sqrt = num ** 0.5
print('%0.3The square root of %s is %0.3f'%s's square root is %s' % (num, num_sqrt)

Output result

8The square root of .000 is 2.828

In this program, we store the number in num and use**The exponent operator is used to find the square root. This program is suitable for all positive real numbers. However, for negative numbers or complex numbers, you can proceed as follows.

Source code: real or complex number

# Calculate the square root of a real or complex number
# Import complex math module
import cmath
num = 1+2j
# Accept user input
#num = eval(input('Enter a number: '))
num_sqrt = cmath.sqrt(num)
print('{0}'s square root is {1}',1:0.3f}+{2:0.3f'{0}'s square root is {0}j'.format(num, num_sqrt.real, num_sqrt.imag)

Output result

(1+2The square root of j) is 1.272+0.786j

In this program, we use the sqrt() function from the cmath (complex math) module.

Note that we have used the eval() function instead of the float() to convert complex numbers. Also, please note the way of formatting the output.

Search here for more information aboutString formatting in PythonMore information.

Complete Python examples