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

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operation

Python objects and classes

Python date and time

Advanced knowledge of Python

Python reference manual

Python program to calculate square root

Python instance大全

In this program, you will learn to use the exponentiation 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 the square root
# Note: You can change this value to a different number, and you will get different results
num = 8 
# Accept user input
#num = float(input('Enter a number: '))
num_sqrt = num ** 0.5
print('%0.3The square root of %0 is3f'%(num, num_sqrt))

Output result

8The square root of .000 is 2.828

In this program, we store the number in num and use**Exponentiation operator to find the square root. This program is suitable for all positive real numbers. However, for negative numbers or complex numbers, you can follow the following steps.

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} is the square root of {1:0.3f}+{2:0.3f'{num}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 for more information hereString formatting in PythonMore information.

Python instance大全