Movatterモバイル変換


[0]ホーム

URL:


— FREE Email Series —

🐍 Python Tricks 💌

Python Tricks Dictionary Merge

🔒 No spam. Unsubscribe any time.

Browse TopicsGuided Learning Paths
Basics Intermediate Advanced
aialgorithmsapibest-practicescareercommunitydatabasesdata-sciencedata-structuresdata-vizdevopsdjangodockereditorsflaskfront-endgamedevguimachine-learningnewsnumpyprojectspythonstdlibtestingtoolsweb-devweb-scraping

Table of Contents

Recommended Video Course
The Square Root Function in Python

Python Pit Stop

The Python Square Root Function

byAlex RonquilloReading time estimate 8mbasics

Table of Contents

Remove ads

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding:The Square Root Function in Python

The Python square root function,sqrt(), is part of themath module and is used to calculate the square root of a given number. To use it, you import themath module and callmath.sqrt() with a non-negative number as an argument. For example,math.sqrt(9) returns3.0.

This function works with both integers and floats and is essential for mathematical operations like solving equations and calculating geometric properties. In this tutorial, you’ll learn how to effectively use the square root function in Python.

By the end of this tutorial, you’ll understand how:

  • Python’ssqrt() function calculates square roots using Python’smath.sqrt() for quick and accurate results in your programs.
  • math.sqrt() calculates the square root of positive numbers and zero but raises an error for negative inputs.
  • Python’s square root function can be used to solve real-world problems like calculating distances using the Pythagorean theorem.

Time to dive in!

Python Pit Stop: This tutorial is aquick andpractical way to find the info you need, so you’ll be back to your project in no time!

Free Bonus:Click here to get our free Python Cheat Sheet that shows you the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.

Square Roots in Mathematics

In algebra, asquare,x, is the result of anumber,n, multiplied by itself:x = n²

You can calculate squares using Python:

Python
>>>n=5>>>x=n**2>>>x25

The Python** operator is used for calculating the power of a number. In this case, 5 squared, or 5 to the power of 2, is 25.

The square root, then, is the numbern, which when multiplied by itself yields the square,x.

In this example,n, the square root of 25, is 5.

25 is an example of aperfect square. Perfect squares are the squares of integer values:

Python
>>>1**21>>>2**24>>>3**29

You might have memorized some of these perfect squares when you learned your multiplication tables in an elementary algebra class.

If you’re given a small perfect square, it may be straightforward enough to calculate or memorize its square root. But for most other squares, this calculation can get a bit more tedious. Often, an estimation is good enough when you don’t have a calculator.

Fortunately, as a Python developer, you do have a calculator, namely thePython interpreter!

The Python Square Root Function

Python’smath module in the standard library can help you work on math-related problems in code. It contains many useful functions, such asremainder() andfactorial(). It also includes thePython square root function,sqrt().

You’ll begin byimportingmath:

Python
>>>importmath

That’s all it takes! You can now usemath.sqrt() to calculate square roots.

sqrt() has a straightforward interface. It takes one parameter,x, which as you saw before, stands for the square you want to calculate the square root for. In the example from earlier, this would be25.

The return value ofsqrt() is the square root ofx, as afloating-point number. In the example, this would be5.0.

Next, you’ll take a look at some examples of how to usesqrt() and how not to usesqrt().

The Square Root of a Positive Number

One type of argument you can pass tosqrt() is a positive number. This includes bothint andfloat types.

For example, you can solve for the square root of49 usingsqrt():

Python
>>>math.sqrt(49)7.0

The return value is7.0, the square root of49, as a floating-point number.

Along with integers, you can also passfloat values:

Python
>>>math.sqrt(70.5)8.396427811873332

You can verify the accuracy of this square root by calculating its inverse:

Python
>>>8.396427811873332**270.5

The Square Root of Zero

Even0 is a valid square to pass to the Python square root function:

Python
>>>math.sqrt(0)0.0

While you probably won’t need to calculate the square root of zero often, you may be passing avariable tosqrt() whose value you don’t actually know. So, it’s good to know that it can handle zero in those cases.

The Square Root of Negative Numbers

The square of anyreal number can’t be negative. This is because a negative product is only possible if one factor is positive and the other is negative. A square, by definition, is the product of a number and itself, so it’s impossible to have a negative real square:

Python
>>>math.sqrt(-25)Traceback (most recent call last):  File"<stdin>", line1, in<module>ValueError:math domain error

If you attempt to pass a negative number tosqrt(), then you’ll get aValueError because negative numbers aren’t in the domain of possible real squares. Instead, the square root of a negative number would need to becomplex, which is outside the scope of the Python square root function.

Square Roots in the Real World

To see a real-world application of the Python square root function, you’ll turn to the sport of tennis.

Imagine thatAlex de Minaur, one of the fastest players in the world, has just hit a forehand from the back corner, where the baseline meets the sideline of thetennis court:

Python Pit Stop: Tennis Ball Hit From Baseline

Now, assume his opponent has countered with a drop shot—one that would place the ball short with little forward momentum—to the opposite corner, where the other sideline meets the net:

Python Pit Stop: Tennis Ball Returned At The Net

How far must Nadal run to reach the ball?

You can determine fromregulation tennis court dimensions that the baseline is 27 feet long, and the sideline on one side of the net is 39 feet long. So, essentially, this boils down to solving for the hypotenuse of a right triangle:

Python Pit Stop: Solving For The Hypotenuse Using The Square Root

Using a valuable equation from geometry, thePythagorean theorem, you know thata² + b² = c², wherea andb are the legs of the right triangle andc is the hypotenuse.

Therefore, you can calculate the distance Nadal must run by rearranging the equation to solve forc:

Pythagorean Theorem: Solve For C

You can solve this equation using the Python square root function:

Python
>>>a=27>>>b=39>>>math.sqrt(a**2+b**2)47.43416490252569

So, Nadal must run about 47.4 feet (14.5 meters) in order to reach the ball and save the point.

Conclusion

Congratulations! You now know all about the Python square root function.

In this tutorial, you’ve covered:

  • A brief introduction to square roots
  • The ins and outs of the Python square root function,sqrt()
  • A practical application ofsqrt() using a real-world example

Knowing how to usesqrt() is only part of the equation. Understanding when to use it is equally important. Now that you know both, go ahead and apply your newfound mastery of the Python square root function!

FAQs

You now have some experience with square roots in Python. Below, you’ll find a few questions and answers that sum up the most important concepts that you’ve covered in this tutorial.

You can use these questions to check your understanding or to recap and solidify what you’ve just learned. After each question, you’ll find a brief explanation hidden in a collapsible section. Click theShow/Hide toggle to reveal the answer.

To find the square root in Python, you use themath.sqrt() function. First, import themath module, then callmath.sqrt() with the number you want to find the square root of. For example,math.sqrt(16) returns4.0.

Yes, you can calculate the square root of negative numbers in Python, but not with themath.sqrt() function. Instead, you should usecmath.sqrt(). Attempting to calculate the square root of a negative number withmath.sqrt() will result in aValueError because this function can’t handle negative numbers.

You can use bothmath.sqrt() andpow() to find a square root in Python. While both will return the same result for non-negative numbers,math.sqrt() is more readable and specifically designed for this purpose.

To use the square root function in Python, you need to import it from themath module. Use the statementimport math and then callmath.sqrt() to find the square root of a number.

Yes, you can calculate the square root without importing themath module by using the exponent operator** or the built-inpow() function. For example,4**0.5 will return2.0, giving you the same result asmath.sqrt().

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding:The Square Root Function in Python

🐍 Python Tricks 💌

Get a short & sweetPython Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

AboutAlex Ronquillo

Alex Ronquillo is a Software Engineer at thelab. He’s an avid Pythonista who is also passionate about writing and game development.

» More about Alex

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

MasterReal-World Python Skills With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

MasterReal-World Python Skills
With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

What Do You Think?

Rate this article:

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students.Get tips for asking good questions andget answers to common questions in our support portal.


Looking for a real-time conversation? Visit theReal Python Community Chat or join the next“Office Hours” Live Q&A Session. Happy Pythoning!

Keep Learning

Related Topics:basics

Recommended Video Course:The Square Root Function in Python

Keep reading Real Python by creating a free account or signing in:

Already have an account?Sign-In

Almost there! Complete this form and click the button below to gain instant access:

Python Logo

Get the Python Cheat Sheet (Free PDF)

🔒 No spam. We take your privacy seriously.


[8]ページ先頭

©2009-2025 Movatter.jp