YouTip LogoYouTip

Python3 Square Root

# Python3.x Python Square Root [![Image 3: Document Object Reference](#) Python3 Examples](#) The square root, also known as the second root, is represented as [√ ̄]. For example, in mathematical language: √ ̄16=4. In verbal description: the square root of 16 is 4. The following example calculates the square root of a number entered by the user: ## Example (Python 3.0+) ```python # -*- coding: UTF-8 -*- # Filename : test.py # author by : www..com 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)) The output of the above code is: $ python test.py Please enter a number: 4 The square root of 4.000 is 2.000 In this example, we take a number as input from the user and use the exponent operator `**` to calculate its square root. This program only works for positive numbers. Negative numbers and complex numbers can be handled as follows: ## Example (Python 3.0+) ```python # -*- coding: UTF-8 -*- # Filename : test.py # author by : www..com # Calculate square root of real and complex numbers # Import complex math module import cmath num = int(input("Please enter a number: ")) num_sqrt = cmath.sqrt(num) print('{0} square root is {1:0.3f}+{2:0.3f}j'.format(num, num_sqrt.real, num_sqrt.imag)) The output of the above code is: $ python test.py Please enter a number: -8 -8 square root is 0.000+2.828j In this example, we use the `sqrt()` method from the `cmath` (complex math) module. [![Image 4: Document Object Reference](#) Python3 Examples](#)
← Python3 99 TablePython3 Prime Number β†’