The Python from keyword is used to import a specific section from a modules, classes or functions. It is a case-sensitive keyword. Without import keyword we cannot use the from because both are interdependent and raise a SyntaxError.
UsageFollowing is the usage of the Python from keyword −
from <module> import <function>
Where,
Following is a basic example of the Python from keyword −
# Importing specific functions from math import sqrt, pow # Using the imported functions print("Square root of 81 is:", sqrt(81)) print("5 to the power of 3 is:", pow(5, 3))Output
Following is the output of the above code −
Square root of 81 is: 9.0 5 to the power of 3 is: 125.0Using the from Keyword Without 'import'
When we use from keyword without the import keyword it will raise an SyntaxError.
ExampleIn the following example we have not used import keyword along with from −
# Importing the datetime class from the datetime module from datetime datetime print(datetime.now())
Output
Following is the output of the above code −
File "/home/cg/root/47560/main.py", line 2 from datetime datetime ^^^^^^^^ SyntaxError: invalid syntaxUsing the from Keyword to import an Entire Module
We can also import all the functions from a module using from keyword and import followed by asterisk[*].
ExampleHere, is an example to import all the functions from a module using from keyword −
from math import * print("The remainder of 16 when divided by 7 :",remainder(16,7)) print("The sine value of 90:",sin(90))
Output
Following is the output of the above code −
The remainder of 16 when divided by 7 : 2.0 The sine value of 90: 0.8939966636005579Using from Keyword with 'as'
We can also use as keyword along with from to make a selected name for a particular function.
ExampleFollowing is an example of, usage of from keyword along with as keyword −
# Importing a class and renaming it from datetime import datetime as dt # Using the renamed class print("Current date and time:", dt.now())
Output
Following is the output of the above code −
Current date and time: 2024-08-07 11:54:06.534770
python_keywords.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4