#15 Python Tutorial for Beginners | Import Math Functions in Python
Python Math Functions
In this video, the presenter discusses Python's mathematical functions and how to use them. The video covers finding square roots, using the float function, using the power function, and accessing constants like pi.
Finding Square Roots
- To find a square root of a number in Python, use the built-in
sqrtfunction from themathmodule.
- Importing the
mathmodule is necessary before using its functions.
- Use
math.sqrt(number)to find the square root of a number.
- Example:
X = math.sqrt(25)will give you 5.0 as X.
Using Float Function
- The
floatfunction can be used to round down any decimal value to an integer.
- Example:
float(2.9)will return 2.
Using Power Function
- The power function can be used to raise a number to a certain power.
- Two ways of doing this are by using double stars or by calling the built-in
pow()function from the math module.
- Example:
math.pow(3, 2)or3 ** 2both return 9.
Accessing Constants
- The math module also provides access to some useful constants such as pi.
- To access pi in Python, use
math.pi.
- Example: printing out
math.piwill give you approximately 3.141592653589793.
Using Aliases in Python
In this section, the speaker explains how to use aliases in Python to avoid typing long module names repeatedly.
Importing Modules with Long Names
- When importing modules with long names, it can be tedious to type out the full name every time.
- Aliases can be used to shorten the name of a module when importing it.
- For example, instead of typing
import mathevery time, you can use an alias likeimport math as m.
Using Aliases for Specific Functions
- If you only need specific functions from a module, you can import them using aliases as well.
- For example, if you only need the square root and power functions from the math module, you can import them like this:
from math import sqrt, pow.
- This allows you to use these specific functions without having to type out the full module name or import all of its functions.
Importing Specific Functions from Modules
In this section, the speaker explains how to import specific functions from modules in Python.
Importing Specific Functions
- To import specific functions from a module in Python, use the syntax
from <module> import <function1>, <function2>, ....
- This allows you to only import the necessary functions and not clutter your code with unused ones.
- Once imported, these functions can be used directly without having to reference their parent module.