When the lines of code increase, it is cumbersome to search for the required block of code. It is a good practice to differentiate the lines of code according to their working. It can be done by having separate files for different working codes. As we know, various libraries in Python provide various methods and variables that we access using simple import <library_name>. For example, math library. If we want to use the pi variable we use import math and then math.pi.
To import variables from another file, we have to import that file from the current program. This will provide access to all the methods and variables available in that file.
Python’s from statement lets you import specific attributes from a module.
Note: For more information, refer Python Modules
Different approaches to import variables from other file
Example:
Suppose we have a file named “swaps.py”. We have to import the x and y variable from this file in another file named “calval.py”.
# swaps.py file from which variables to be imported x = 23 y = 30 def swapVal(x, y): x,y = y,x return x, y
Now create a second python file to call the variable from the above code:
# calval.py file where to import variables # import swaps.py file from which variables # to be imported # swaps.py and calval.py files should be in # same directory. import swaps # Import x and y variables using # file_name.variable_name notation new_x = swaps.x new_y = swaps.y print("x value: ", new_x, "y value:", new_y) # Similarly, import swapVal method from swaps file x , y = swaps.swapVal(new_x,new_y) print("x value: ", x, "y value:", y)
Output:
x value: 23 y value: 30 x value: 30 y value: 23
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.