Python Tutorial for Beginners 9: Import Modules and Exploring The Standard Library
- March 28, 2024
- Posted by: MainInstructor
- Category: C Data Science Go Python Web Development
Video Title: Python Tutorial for Beginners 9: Import Modules and Exploring The Standard Library
Hey there how’s it going everybody in this video we’ll be learning how to import modules we’ll start by importing modules that we’ve written and then we’ll explore a bit of the standard library and how we can import those modules to solve a lot of common problems so I have a module here called
My module pi now within this module we have a print statement and we’ll talk about that in just a minute we also have this test variable set to test string and then we have this function called find index and this find index function takes in two arguments it takes in a
List to search and a target that we’re looking for and we can see that we have some documentation here that just says that this finds the index of a value in a sequence and then it returns that index but if it doesn’t find that value then it just returns negative one so
Let’s say that we wrote this function and that we want to use this and other modules or scripts so what we’re going to want to do is import this so I have another module over here which is just our intro PI file that we’ve been working with now within this file we
Have this courses variable that is just a list of course names so let’s say that we want to use that find index function from my module now I actually created this my module in the same directory as my intro PI so that means that we’re going to be able to directly import that
Now when we import a file it actually runs all of the code from the module that we import so that’s how it creates all the functions and variables but if we have any other code like print statements or anything like that then that will be run as well so that’s why I
Have the print statement here in my module so that we can see when that happens so to import this module we can just come to the top of the file here and say import my module and again we can import that directly because it’s in the same directory as our intro dot PI
File and now if we run this with this import then we can see that it imported successfully because it printed out that print statement within that module okay so let’s say that we want to use that find index function now when importing modules like this we just can’t call our
Find index function we instead have to type the module name first and then what we want to grab from that module so if we wanted to use that then we could say let’s say index is equal to my module dot find index and now we’ll pass in the list that we want
To search which is courses and now the target that we’re looking for so we’ll go ahead and say that we’re looking for mass and now let’s print out that index and run that so now we can see that that works it returned one and one is the
Index of the math value okay so if we’re using this find index function multiple times throughout our script then it might get a little old and take up a lot of room to keep typing my module dot find index everywhere we can actually specify a name that we want to use for
Our imported module and usually this is used to make the module name shorter so for example when we’re importing my module here at the top we could instead say import my module as mm or any other name that we come up with and now when using this import throughout the script
Instead of typing out my module everywhere we can instead just use mmm so if I save that and run it then we’ll see that that still works now you’ll see this a lot with modules like numpy or pandas so you might see someone who does an import and they’ll do import numpy as
NP or something like that now you might be wondering if there’s a way that we can import the function itself and there is a way to do this so instead we could say from my module import and then what we want to import from that module so we
Want to import find index so now when we use this throughout the code now we can just use that find index function anywhere and that really cuts down on the typing so now we can save that and run it and see that it still works now
One thing to note about that approach is that it only gives us access to that find index function and not everything else and the module so for example you’ll remember that we had this test variable equal to this test string so when we do the import this way now we
Don’t have access to that test variable since we’re only now importing the find index function now if we wanted to import that variable then we would have to include it by putting in a comma and specifying what we want so we want to say from my module import find index
Comma and test so now down below here we can print out that test variable and if we run that and we can see that we do have access to that test variable now now when doing the import this way we still have access to that as keyword so
If we wanted to make this even shorter hand that we can say import find index as F I and now throughout our code we can replace that with F I and run that you can see that it still works now at this point that’s not really readable anymore so don’t rename something like
That unless it’s still readable and make sense to others who are reading your code so now let’s go ahead and just undo that change now using this method of importing we’d have to add commas and specify each value that we want to import now there is a way to just import
Everything and I’ll show you how to do this but I have to be honest I never use this and it’s pretty frowned upon and we’ll see why that is but if we wanted to just import everything that we could say from my module import star so if we
Run this and we can see that everything still works we still have access to this find index function and this test variable but the reason that this is frowned upon is because now we can’t tell what came from that imported module and what didn’t so if we’re having
Problems with this find index function and we might try to track down where that function came from or where it was defined and with that asterisks it’s just not obvious that it came from that module that was imported so instead we’ll go back to importing both of those directly so basically importing
Everything with that asterisk just makes it harder to track down a problem so it’s better to do it this way okay so when we import a module how does it know where to find this module so we didn’t pass in a file path or tell Python where
To find this module I just found it so the way that this works is that when we import a module it checks multiple locations and the locations that it’s checks is within a list called sista and we can actually see this list if we import the Syst module so I’ll import
Sis and now down here will comment out these two prints they and now let’s print out that sis not path and run that so this is the list of directories on my machine where Python looks for modules when we run an import and it looks in this order now this
First value here is just the directory where I’m currently running the script from and the my module python file that we were importing is within that directory also so that’s how it found it okay so what directories are added to this cyst so directories get added in this order first the directory
Containing the script that we’re running so that is why this directory where we’re running the script is the first value insist that path so you can always import modules from the same directory and next it adds directories listed in the Python path environment variable and we’ll talk more about the Python path
Environment variable in just a minute and then after the Python path it then adds the standard library directories and that’s how we can import those modules from the standard library and lastly it adds the site packages director directory for third-party packages and we’ll look at all of these
So first let’s see what it looks like when the module that we want to import isn’t in the same directory as the script that we’re trying to import it from so I’m going to move the module that we’ve been importing from the same directory into a directory on our
Desktop so I’ve got finder pulled up here and I’m just going to drag this my module over here into this my modules directory that is on my desktop so now that module that we’re trying to import is in a completely different location on our machine so if we go back to here to
Our script and now try to run this and we can see that we get this air module not found no module named my module now there are a couple of approaches that we can take here first is that we can actually manually add that directory to our sistas list
So this sistah is a list just like any other that we’ve been looking at and we can treat it like one so before we try to import my module we could add that directory to sis not path so I’m going to import this here at the top before we try to import that
And then I’ll say sis dot path dot append and the location on my machine this is probably going to be different on yours but the location on mine is you users – Cory s desktop – my modules and I believe I need a – here at the
Beginning as well so if I save that and run it we can see that when we appended that directory to our sis not that we were now able to import that module and run our code but this isn’t the best looking approach because we’re appending this directory before our other imports
And also if we were to import our module and we had this manually hard-coded in multiple locations and we have to change all of those so instead we can make this change and the next place sistah path looks and if we remember that is the Python path environment variable now
Changing the environment variables is different on Mac and Windows so we’ll show how to do this on both really quick so first we’ll see how to do this on a Mac and to do this I’m going to pull up my terminal and we can set environment
Variables by adding them to the dot – underscore profile file in our home directory and you can edit this file with any text editor but I’m going to use the one built into the terminal here called Nano since Nano is easy for anyone to use so we’re going to say Nano
And then a tilde – just makes sure that we’re working within our home directory and we’ll say dot – underscore profile now I might have more stuff in this file than you do these are just personal preferences and customizations but I’m going to scroll
Down here to the end of the file and set my Python path but you can set this anywhere in this file that you’d like so we’re going to set this by saying export Python path all uppercase and then equals and now we want to set that
Location so I’m just going to come over here and grab that location and paste that in those quotes and we want it to look just like that no space in between the equals and the path so to save that we can just hit ctrl X and then Y to
Save and then enter to keep the same file name and now we can either restart our terminal or run a source command on that file but I’ll just restart the terminal here and pull this up and now if we run Python then let’s see if we can import that module so import my
Module and we can see that that worked and the reason that that worked is because if we import sis and look at our sis then we can see that after our current directory that we have the directory that was added there and the reason that
It’s added is because we added it to our Python path environment variable so now let’s take a look at how to set this environment variable on Windows now to set this environment variable on Windows we can click on our start button here and then right click on computer and go
To properties and from properties we want to go to advanced system settings and from here at the very bottom we can click on environment variables and now we can create a new environment variable so we’ll click new and we’ll name this python path all uppercase there and then
For the location that’s going to be C we’re going to go to the desktop again so again this is specific to my desktop but it may be a little bit different on yours so quarry MS slash desktop and then the name of that directory is my dash modules and again this Python path
Is going to be unique to your own machine so let’s hit OK there and ok to save those and exit out of that and now if we open up our command prompt by going to start run CMD and then typing in python now we should be able to
Import that module just by saying import my module and if we run that and we can see that it imported that module successfully now the reason that worked is because if we import sis and look at our sis pad then after our current directory you can see that our directory
That we added to our Python path is the second one that it looks at here so that is how we add that environment variable on Windows so now I’ll switch back to my native OS now I do want to point out that if you’re using an editor like
Sublime text or eclipse or pycharm then these may need to have their environment variables set in a different way and that’s different for every program so instead of going through each individual one and showing how you can likely find out how to do that just by searching for your editor plus Python
Path and there should be plenty of resources showing you how to do that okay so going back to this sista now after the directories in the Python path environment variable that we just looked at after that sista path looks at the standard library directories now this is what allows us to import modules
Directly from the standard library so when something is part of the standard library it means that we’re able to use it without installing anything separately so the standard library is incredibly useful because if you’re performing a common task then most likely someone has already written the
Functionality and if we use it from the standard library that we can be sure that it’s been written by some of the best programmers in the world and has been optimized to be as performant as possible now that’s not to say that you shouldn’t try to write your own versions
Of some of these things just to get some practice but as far as using any of that functionality in production it’s probably a good idea to use the tried-and-true standard library so for example let’s say that we wanted to grab a random value from a list of values so
You could probably write something to do this on your own but that functionality is already available to us when we use the random module from the standard library so let’s go ahead and take a look at this so I’ll get rid of everything here just to clean up except
For our courses list now this random module is just part of the standard library and we can just say import random and if we wanted to grab a random value from our courses list then we could just say random course is equal to random dot choice and then pass in our
Courses list so now if we print out that random course and run that and we can see it gave us a random value and if we run this multiple times then we can see that it gives us a random value just about every time we run through now I’m
Not going to go through all of the functionality in the standard library but I will create a future video to go over some of these modules in depth but right now I just want to give you an idea of what’s available to us so here are a few more useful standard library
Modules so if we need to perform some common mathematical operations then we can import the math module and now we can do some mathematic calculations so if we needed to convert 90 degrees into radians then we could say rads is equal to mass dot radians and pass in 90 and
Then if we print rads and run that and we can see that we get that conversion and if we wanted to get the sine of that value and we could pass those radians into the sine method so I can say math not sign a sin those radians and if I
Run that then we can see that one is the sine of 90 degrees okay and another useful module from the standard library is the eight-time module now this allows us to work with dates and times and while we’re at it let’s also go ahead and import the calendar module now these
Have some similarities but they’re also very different so for example if I wanted today’s date and we could just say today is equal to eight times eight dot today and if we print this out and run that then we can see that that gives us today’s date now with the calendar
Module we can ask for example is 2017 a leap year so I could print out and say calendar dot is leap and pass in 2017 if I run that we can see that that’s false but if I instead change that to 2020 and run that then you can see that that is
True in the last standard library module that we’ll look at for now is the OS module so I will import OS now this is going to give us access to the underlying operating system so for example if I wanted to see what directory we’re currently in with this
Script then I could print out OS dot get CWD which is current working directory so if we run that and we can see that it prints out the current working directory where this script is located now this OS module has a ton of other functionality it gives us the ability to scan the
Filesystem and create files delete files and all of that so you can see how these standard library modules provide a ton of functionality that might be riki or take forever for us to write ourselves so Python comes with a ton of stuff available to us and makes it super
Easy to get them imported and running so another great thing about Python is that these modules are just Python files themselves and we can view the location of a module just by printing out its dunder file method where it’s done your file attribute I’m sorry so if we print
Out OS dot Thunder file and thunder just means two underscores and don’t worry why those are double underscores that’ll be a topic for a future video so if we run this then we can see that it prints out the location of this file on our filesystem and if we open up that Python
Directory where that file lives and we could see the entire standard library so I actually have this open right here so let me open this up real quick so I actually have opened that Python three six directory where the entire standard library lives now I know that this may
Be a little small over here for you to see on my screen but let’s go ahead and look through a couple of these files so these are all in alphabetical order so one of the first piles in the standard library is actually this anti-gravity
Module now this is kind of a joke in the Python community so this is a module that you can import called antigravity that will open up a web comic on your machine and even though this is part of the standard library we can just open up this module here and see exactly how
This is done so we can see that basically it just imports this web browser module and opens up the web browser to this page here and I know that people are probably going to be curious what this comic is now so let’s go ahead and import that so back in
Intro PI I’ll just delete everything and do import anti-gravity and run this file then we can see it just opens up our web browser to this comic and I’ll leave this open while we close out here so if you get a chance then don’t be afraid to
Go into the standard library and look around at how different things are done it’s a great way to learn now I’m not going to lie there’s definitely some complicated code in there but you’ll be surprised how much you can understand if you just poke around a bit okay so I
Think that’s going to do it with this video so where do we go from here so so far in this series we’ve covered a lot of the fundamentals and working with Python so we’ve learned about different data types conditionals loops functions and importing modules and a bit of the standard library now I
Think that just about anyone would agree that no matter what specialty you plan on going into for Python whether it’s back in web development data science building desktop applications no matter what route you decide to take you’re going to need the fundamentals that we’ve covered up until this point but
Now that you understand these fundamentals the next topics that you learn are up to you so you can jump into learning object-oriented programming and Python you can learn how to work with files and file data start learning about a web framework basically anything that you want so I’m going to keep adding
Additional videos on to this playlist that I believe will be a good progression as you continue to learn Python but these videos won’t be numbered any more after this video and the reason for that is that I don’t want to give the impression that you have to watch one before understanding the
Others so I don’t want them to be numbered to make you feel like you have to understand virtual environments before learning how to work with file objects or something like that so you can just skip around depending on what it is that you’re wanting to learn so I
Hope that that makes sense now if anyone has any questions about what we covered in this video then feel free to ask in the comment section below and I’ll do my best to answer those if you enjoy these tutorials and would like to support them and there are several ways you can do
That the easiest way is to simply like the video and give it a thumbs up and also it’s a huge help to share these videos with anyone who you think would find them useful and if you have the means you can contribute through patreon and there’s a link to that page and the
Description section below be sure to subscribe for future videos and thank you all for watching you you
-
Sale!
Wireless WIFI Repeater Extender Amplifier Booster 300Mbps
$29.99$14.99 Add to cartWireless WIFI Repeater Extender Amplifier Booster 300Mbps
Categories: Electronics, Wi-Fi Router, Wireless Wi-Fi Extender Tags: 300Mbps, 802.11N, Amplifier, Booster, Extender, mobile wi-fi booster, Remote, WIFI, Wireless, Wireless WIFI, Wireless WIFI Repeater, Wireless WIFI Repeater Extender, Wireless WIFI Repeater Extender Amplifier, Wireless WIFI Repeater Extender Amplifier Booster, Wireless WIFI Repeater Extender Amplifier Booster 300Mbps$29.99$14.99 -
Sale!
Full RGB Light Design Gaming Headset Headphones with Mic
$24.99$14.99 Add to cartFull RGB Light Design Gaming Headset Headphones with Mic
Categories: Electronics, Gaming, Gaming Headsets Tags: Design, Full, Full RGB Light Design Gaming Headset, Full RGB Light Design Gaming Headset Headphones, Full RGB Light Design Gaming Headset Headphones with Mic, Gamer, Gaming, Gaming Headset Headphones, gaming headset wireless, Headphone, Headphones, Headset, Light, Mic, Package, RGB$24.99$14.99 -
Sale!
Wireless BlueTooth Multi-Device Keyboard Mouse Combo
$39.99$19.99 Add to cartWireless BlueTooth Multi-Device Keyboard Mouse Combo
Categories: Electronics, Gaming, Gaming Keyboards, Keyboard Mouse Combos Tags: Combo, Keyboard, keyboard mouse combos, Mouse, MultiDevice, Set, WireKeyboard Mouse Combo, Wireless, Wireless BlueTooth Keyboard Mouse Combo, Wireless BlueTooth Keyboard Mouse Combos, Wireless BlueTooth Multi-Device Keyboard Mouse Combo, Wireless BlueTooth Multi-Device Keyboard Mouse Combos$39.99$19.99 -
Sale!
High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
$199.99$139.99 Add to cartHigh Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
Categories: Gaming, Gaming Chairs Tags: Adjustable, Chair, computer chairs, Desk, Executive, Gaming, Girl, Headrest, High, High Back Leather Executive Adjustable Swivel Gaming Chair, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar, High Back Leather Executive Adjustable Swivel Gaming Chairs, Leather, Lumbar, Office, Racing, Swivel$199.99$139.99 -
Sale!
Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
$29.99$19.99 Select optionsProfessional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
SKU: N/A Categories: Electronics, Gaming, Gaming Headsets Tags: Cancelling, Gaming, Gaming Headphones with Noise Cancelling Microphone, gaming headset, Headphones, Headset, LED, Light, Mic, Microphone, Noise, Professional, Professional LED Light Wired Gaming Headphones, Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone, Wired, Wired Gaming Headphones, Wired Gaming Headphones with Noise Cancelling Microphone$29.99$19.99 -
Sale!
Gaming Desk with LED Lights USB Power Outlets and Charging Ports
$349.99$249.99 Select optionsGaming Desk with LED Lights USB Power Outlets and Charging Ports
SKU: N/A Categories: Computer Desk, Gaming, Gaming Desk Tags: and Charging Ports, Charging, Desk, Desks, Gaming, gaming desk with led lights, Gaming Desks with LED Lights, Home, LED, Lights, Monitor, Office, Outlets, Port, Power, Room, Stand, USB, USB Power Outlets, White, Workstation$349.99$249.99 -
Sale!
Wired Mixed Backlit Anti-Ghosting Gaming Keyboard
$99.99$79.99 Add to cartWired Mixed Backlit Anti-Ghosting Gaming Keyboard
Categories: Electronics, Gaming, Gaming Keyboards Tags: Antighosting, Backlit, Blue, brown, Gaming, Gaming Keyboard, gaming keyboards, gaming keyboards and mouse, Keyboard, Laptop, Switch, Wired, Wired Mixed Backlit Anti-Ghosting Gaming Keyboard, Wired Mixed Backlit Anti-Ghosting Gaming Keyboards, Wired Mixed Backlit Gaming Keyboard$99.99$79.99 -
Sale!
Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
$119.99$59.99 Add to cartWireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
Categories: Electronics, Gaming, Gaming Headsets Tags: 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, ANC, Audio, Bluetooth, Cancellation, Ear, Earphone, gaming headset, Headphones, Headset, Hi-Res Over the Ear Headphones Headset, HiRes, Noise, Wireless, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Headphones, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headsets$119.99$59.99 -
Sale!
Wired Sports Gaming Headset Earbuds with Microphone
$19.99$9.99 Select optionsWired Sports Gaming Headset Earbuds with Microphone
SKU: N/A Categories: Gaming, Gaming Headsets Tags: Accessories, Earbud, Earphone, Earphones, Gaming, gaming headset with microphone, Headphones, Headset, IOS, Microphone, Sports, Wired, Wired Sports Gaming Headset Earbuds, Wired Sports Gaming Headset Earbuds with Microphone, Wired Sports Headset Earbuds$19.99$9.99 -
Sale!
150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
$49.99$29.99 Add to cart150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
Categories: Charging Stations, Electronics Tags: 150W, 150W Charging Station, 150W Universal Multi USB Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Stations, 150W Universal Multi USB MAX Charging Station, 16 Port MAX Charging Station, 3.5A, Charger, Charging, Fast, laptop charging stations, Max, Multi, Port, Stand, Station, Universal, USB$49.99$29.99
Whats its use??
thankyou Sir
6 years later and still super helpful. blesses and much love brother!
Thanks! Please, make more videos
Your pace was perfect… not too fast, not too slow. Well done.
Amazing!
Hi, great video could you remake on how to import using __init__.py without using sys
LOL, its hilarious, import antigravity
WOW! Thanks Corey!
Thank you very much, I've been procrastinating to learn python for years, but your well explained and concise videos motivated me a lot that I covered all basics you taught us.
Outstanding, thank you.
just a small comment.. It's not SISTA path. It's sys dot path..
Import the SITH
EXECUTE ORDER 66
how is importing different from opening a file and closing it in a context manager?
i think even the crowd is a lil disappointed 😂
Hey Cory, I have a folder for the two modules in use at the beginning of the video but python is still not recognizing that the file exists. Is that because my directory is on the desktop?
I am from India.I am really interested in knowing the modules present in the standard library .could you please give me the document.
I have watched all the fundamental of Python videos thrice already. Though I know that Im kinda outdated of your videos but your way of teaching Corey makes me want to learn more. There are times I have thought I cant make it but because of these tutorials I have my hopes up again. You're the inspiration. Thank you.
best explanation ever
Chatgpt indicated you. And the playlist is really good! Congrats!
Many youtuber teaches python but they are not really good at it. They probably good at other programming language and since there is so much similarity so they just teach. But this guy seems to be very good in python. Hence, can teach very clearly since he has a very in-depth understanding.
It's crazy that thank to YouTube, we get this kind of content for free.