+ 6
How we can create modules and import it easily??
For example : look at the code https://code.sololearn.com/cW1fo04L0Ul6/?ref=app
5 Respuestas
+ 11
Modules are just python scripts that you can import to use the functions or variables inside it.
For example, in your computer create a python script called: mymath.py
Inside mymath.py write some sample function like:
def sum(a, b):
return a + b
Save it.
On the same folder as the mymath.py, create another script, (or open the interpreter through your terminal)
and do:
import mymath
Then you can use the sum function like: print(mymath.sum(1, 2)) # 3
Notes:
1) You can do: from mymath import sum
2) On Windows, if you click the address bar, you can type commands like cmd and it will open command prompt directed at that folder. You can even type python or py to open up the interpreter.
I wish you success!
+ 2
I didn't understand the 11th line after the Save it.
+ 2
Rishabh inside the same folder, where you created the mymath.py script, create another script called test.py
Inside, write this:
import mymath
print(mymath.sum(1,2))
Save it and run it
+ 1
I wanted to edit my original post, but you may not get a notification for it. You can also "install" your module by putting your .py file inside the Lib directory of your Python installation. Although I don't know if there are any "bad practices" involved, but if it's for some function you use in a lot of codes, it's better than just copy/pasting the file everywhere you need it. Cheers!
+ 1
python imports scripts in same folder as module...
for example if i have two script in folder:
1.Sample. py
2.Sample2.py
then i can import them as module in my third script by giving syntac
import Sample
import Sample2