Python and programming crash course in 5 hours | Mashrur Hossain | Skillshare

Playback Speed


  • 0.5x
  • 1x (Normal)
  • 1.25x
  • 1.5x
  • 2x

Python and programming crash course in 5 hours

teacher avatar Mashrur Hossain, Development Trainer

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Watch this class and thousands more

Get unlimited access to every class
Taught by industry leaders & working professionals
Topics include illustration, design, photography, and more

Lessons in This Class

30 Lessons (6h 3m)
    • 1. Course intro

      3:33
    • 2. Course overview

      4:36
    • 3. Install Python

      5:59
    • 4. Set up Atom as code editor - used in course

      13:38
    • 5. Explore Jupyter notebooks (optional)

      16:58
    • 6. Command line

      6:27
    • 7. Strings, variables, top down execution flow

      10:31
    • 8. Strings: concatenation, indexing, slicing, python console

      14:13
    • 9. String methods, functions and import statements

      17:20
    • 10. Print formatting and special characters

      13:28
    • 11. Numbers, math, type casting and input

      16:47
    • 12. Introduction to branching (if, elif, else) and conditionals

      12:16
    • 13. Building if, elif, else blocks incrementally

      12:54
    • 14. Lists, dicts, sets and tuples - Intro to compound data types in Python

      11:02
    • 15. Lists - an in-depth look 1

      12:06
    • 16. Lists - an in-depth look 2

      11:18
    • 17. Dictionaries, sets and tuples

      18:23
    • 18. Iterators, for loops, generators, list comprehension

      18:07
    • 19. While loops, enumerate, zip

      12:43
    • 20. Functions - an introductory look

      13:01
    • 21. Functions - implementation step by step

      14:51
    • 22. Functions - execution context, frames, mutable vs. immutable arguments in-depth

      14:19
    • 23. Classes and objects - an introductory look

      9:29
    • 24. Building a custom Student class and intro to special methods

      11:58
    • 25. Add some methods to the class

      6:48
    • 26. Special methods and what they are

      12:33
    • 27. Reading from and writing to files

      12:22
    • 28. Add read functionality and utilize special and static methods

      19:46
    • 29. Inheritance, subclasses and complete example class

      14:46
    • 30. Thank you

      1:16
  • --
  • Beginner level
  • Intermediate level
  • Advanced level
  • All levels
  • Beg/Int level
  • Int/Adv level

Community Generated

The level is determined by a majority opinion of students who have reviewed this class. The teacher's recommendation is shown until at least 5 student responses are collected.

16

Students

--

Projects

About This Class

d8777f2b

Join the most comprehensive and beginner friendly course on learning to code with Python - one of the top programming languages in the world - in 5 hours!

What you'll learn:

- Text - Strings

- Numbers - Ints and Floats

- Execution flow control - Branching with if/elif/else

- Compound data types - Lists, Dictionaries, Tuples, Sets

- Iterables and Iteration with generators, for and while loops and more!

- Functions, execution context and frames, building custom functions

- List comprehension

- Lambda expressions

- Generators and creating your own generators with yield

- Objects and building classes, methods, special methods

- Reading from and writing to files using context managers

- Projects

- Visualization with each topic and more!

Let's go!

Meet Your Teacher

Teacher Profile Image

Mashrur Hossain

Development Trainer

Teacher

Hi, I'm Mashrur, I'm a content creator and development trainer with over 100,000 students worldwide. I specialize in Ruby and Ruby on Rails development and have published over 10 courses in various topics over the last 3 years. I have been a technology professional for over 12 years and have degrees in Computer Science and Economics

In my prior corporate life, I worked with Enterprise Software Systems throughout with roles played in analysis, development and management. I led projects using both agile and waterfall methodologies and am well versed in the inner workings of the software development and delivery world.

During my career, I realized how much I enjoyed training new hires and new team members and helping them succeed. I had dedicated a good amount of time over a ... See full profile

Class Ratings

Expectations Met?
  • Exceeded!
    0%
  • Yes
    0%
  • Somewhat
    0%
  • Not really
    0%
Reviews Archive

In October 2018, we updated our review system to improve the way we collect feedback. Below are the reviews written before that update.

Why Join Skillshare?

Take award-winning Skillshare Original Classes

Each class has short lessons, hands-on projects

Your membership supports Skillshare teachers

Learn From Anywhere

Take classes on the go with the Skillshare app. Stream or download to watch on the plane, the subway, or wherever you learn best.

Transcripts

1. Course intro: Hello and welcome to Python and programming crash course in five hours. My name is mature and I'll be your instructor for the course. I'm a full-time technology trainer with over 200 thousand students worldwide, multiple platforms. And I specialize in web app development and programming fundamentals. As you probably guessed already, since I'm teaching this course, I love programming with Python and working with its vast libraries when it comes to machine learning and more, this course aims to get you proficient in Python through five hours of video. You don't need any prior programming experience since it will start from scratch with installation, with a couple of options and also how to use the command line or terminal. And we'll go through a whole lot of code and explanations and work toward building a student course enrollment Project where we will apply what we have learned. Here's a brief look at what we're going to cover in this course. Will cover the basics with strings, numbers, lists, dictionaries, and other data structures. We'll learn how to use branching, which are if-else statements, iterations for loops, while loops and others. And we'll learn about and how to use built-in functions and then learn how to build our own custom functions as well. Ending with how to design and build our own custom classes and some of the other lingo like methods and under methods and so on that go along with them. And don't worry if none of this makes any sense to you, that's totally okay. We'll learn all of this in this course and more. Now, let's take a brief look at the completed final project we're going to build in this course. Here we go, here's the code for the completed project, and this is the completed student class. And what it will look like will build this entire class from scratch, starting with the very basic, which would be the class definition, and build it incrementally. Here you can see we're initializing the student class so we can create shoot an objects. And then we're creating custom methods like add course to add courses to his students curriculum, remove course to remove courses from the student's curriculum. Then work with a data file so we can track what courses students are taking. And then use this data file to verify whether a student is already enrolled in a course or not while we're adding courses to their schedule and modify the schedule as we need. And then if I scroll down, you'll see we're using static methods here as well. And then special methods called defender methods. What they are, how to use them, why they're different, and so on and so forth. So basically what this program accomplishes is that attract students and adds or removes courses from their curriculum. And while building this, while building the special method, you are also going to come across other programs that we build where we test out how to do individual parts of the program. For example, in this case, how to read from a file, how to write to a file, how to create student objects out of things that we read from the data file and so on. Ok, so that's a quick look at the curriculum and a brief look at the final project that we're going to build in the course. I hope you're excited to get started. In the next video, we'll look at the structure of the course and how the lectures are grouped. See you there. 2. Course overview: Hello and welcome to the course structure and overview video. In this video, we'll take a quick look at the order of the video. So you have a general idea of the course and how it's structured. And we'll also see how you can use online resources to share your project code with other students. Let's start with the videos. The next three videos, we'll deal with the installation of Python. I give a couple of options here on how to set it up and how to use it. You'll also learn how to install and set up a code editor like atom, which is the one that I'm going to use for the course videos. But additionally as an option, I provide this video on how to set up Jupiter Notebooks. This is a very popular option, especially now in the era of machine learning, which you can easily use an iterate through multiple versions of code very quickly. The video provides setup and general usage instructions. Again, this is optional and you don't have to use it for the course, but I would still encourage you to view the video. Next, I'll show you how to use the command line and after that jumper right into using the language with strings. Now, if at any point you'd like to share your code with other students to review. Then I'm going to show you how to do that now. And I would encourage you to do that prettied regularly, including specially when we approach the final project, you are definitely encouraged to share your code for the final project using this method. Alright, so first you're going to need an account with GitHub. I already have it, but I'll show you over here. The link you want to go to is just dot github.com. And if you hit enter or return for me, this page shows up. And if you have an account with GitHub, this is what it would look like. If you don't have an account with GitHub, then it would look like something else. I'll pull up an Incognito window. Here we go. And if I type in just a dot github.com, you see it goes to this link. And since I'm not logged in, I'm not able to create a just right away. So what I would encourage you to do is sign up for GitHub. They have free accounts and once you do go to just dot github.com, alright, and then once you are in this page, first, enter what this lecture is about. So here just description and you can enter the lecture name or something like that. I'm going to say sharing my code for the final student project, okay, and then include the filename. So I'll say student dot pi. Again, this is just for demo purposes. You don't have to know what any of this means. And then here you can type out your code. So I'll just put a comment here and say, this is comment. Alright, and once I've done that, I can click on this link in the bottom right, right here that says create public. Just. If I click on it. There you go. There's new just has been created and then copy this link command C and paste it anywhere you want people to be able to see your code. So in our case, back to, let's say this are any other lecture. Let's say I'll go to the strings lecture. I'll pause the video and I'll scroll down. I can go to discussions right here. And then over here I can say, let say, start a conversation. And over here I'll say something like this is my student project code example. And then I'll put in example two. So no one takes this seriously. And then command V to paste the link and then just click on post. Alright, and once you pose this, myself or other students are able to look at this link and review your work. For example, I can right-click and open this in an Incognito window, so I'm not logged in. And you see that it takes me to this page and there is the code. It says this is a comment, alright? And remember, even if you don't do this for all the lectures, you're definitely encouraged to post your final student project code through this method and share it with other students, are right. So that's it for this core structure video. Hope you're excited to get started. And in the next video, we'll jump right in to the installation of Python. See you there. 3. Install Python: Hello and welcome to the installation video for Python. First, let's check and see if you have the required version off bison already. So I have my terminal pulled up since I'm using a Mac. If you're using Windows, either pull up your command line our power shell window and type in python space. Dash dash version. You can see I have Python 36 just from the Anaconda distribution installed in my system. So if in your system, it says anything in the threes over here like 353637 or more than you're already good to go and won't have to install the latest version of Python if you don't want to, you can then simply get a quote editor off choice, like Adam or sublime or none at all. If you already have one of choice or would like to get Jupiter notebooks, okay, now if it says anything lower than the threes over here, like 2.7 or nothing at all, if it gives you an error, then you'll need to install Python three and there are several options. Of course. One of the easiest ways is to get it from the Anaconda distribution. It comes preinstalled with a lot of packages and tools that might be useful later on. You can navigate to www dot anaconda dot com and then scroll down. Here is the anaconda distribution. If you click on download now and scroll down, you can see there are different versions for whatever system you may be using. There's Mac. There's Windows, there's linen. The system you are in should automatically pop up over here. But you can click on the others if necessary, and the one you want is the Python 3.7 version, which is the latest version right now. As you can see, this requires quite a bit of space as it comes with a lot of machine learning, deep learning and data science packages preinstalled. But if you have the space and a bit of time, go ahead and download the installer right here and you will walk you through a few quick installation steps to get started. Once installed, you can go back to your terminal and do the same test as we did earlier, and then it should say something like this pie thin 37 Anaconda custom or something to that order. So the other option if you want to avoid using up too much space but still want Jupiter notebooks and pythons. Latest version Ready to go. You can look for many conduct. So in Google here I have the page pulled up, but I'll show you how to get it in Google if you type in many Kanda and there you go, the first option. Many Kanda Kanda documentation. If you click on it here, our options to download and install for your specific system. So if you're using Windows, Mac or Linux, click on the one that you're using. But make sure you get Python three and not python to and the same as before. Once the download completes, click on it and it walk you to the simple guided steps to get an insult. Now the next part. If you don't care much about Jupiter notebooks and simply want to get up and running with Python three, you can get it from the official hyphen website here. I haven't pulled up its python dot org's, and then there are all these helpful links, and we'll look at documentation later on. But for now, if you go to downloads. You see, the one for your system will pop up over here. I'm using a Mac. So is giving me the option to download python directly from here. So you can simply click on this and wants to download completes. Click on it, get it installed to the simple, helpful instructions. Step by step. But if you do install python in this way, one thing to keep in mind is that in your terminal over here, you may have to reference python three when you reference Python three. If you already have an installation of python to in your system, then when you reference python like this, it might call Python to So if you wanted to run Hello world, for example, you would have to do something like this. Python three. Hello, world dot pie. Okay, Now, if you wanted Python over here to reference Python three instead of python to that is obviously given that you already had python to and are running into this issue, then you can use an alias over here in my system, I'm using a Mac, and this is called a bash shell. So what I would do is create an alias So when I would type in python, it would automatically convert that to Python three and execute the command. And that would be different for your Windows command line or power shell set up. So I'm not gonna cover that for now. Just know that you may have to do that. Python three. Okay, all right. Now, the next step is to get text editors like Adam or sublime, I personally, I'm going to use Adam. When I used text editors in this course I love it and have been using it for a while. So I'll also have a development environment set up and Familiarization with Adam coming up so you can utilize that as well. If you like to download Adam, you can simply go to adam dot io and get it from here. It will download for your system, and again I will cover the download on Familiarization for Adam. You can also, alternatively, you sublime text now sublime text. While it's great and a lot off people use, this is slightly more difficult to get up and running, especially with packages. They're improving that process, but I'm not going to use sublime text in this course when I use quote editors, I'll use Adam, but it's up to you. If you're already using it. Feel free to continue using it. Okay, so that's all I wanted to cover in this download and installation video. Hope you enjoyed it, and I'll see you in the next one. 4. Set up Atom as code editor - used in course: Hello and welcome to this video on setting up and customizing Adam as a text editor to use for developing your python code. I recommend using Adam as your text editor if you are a beginner for the following reasons , and here they are now Adam is very intuitive and easy to use, which makes it great for beginners. It's completely free, and it's very well supported and robust. It was built by the people that get up, and it comes with the package manager, which, as a beginner, is very easy and intuitive to use in essence, what that means. It is very easy to customize the look and feel off your editor to your liking, so let's go ahead and download this. To download Adam, pull up a browser window and navigate to adam dot io. And once you're there, there is this download option. It'll pop up for the system that you're using. Since I'm using a Mac, it's giving me the Mac download option, so I'm gonna click on this to download it, and once it's downloaded, I'm going to click on it to open the ZIP file. And here is my Downloads folder and after its decompressed A zip file. Now I'm doing this in a Mac. Therefore, I'm going to drag this application from downloads into my applications folder. So it's available there, and I already have an installation of that, so I'm simply going to replace it. If you're using Windows, this installation process will be slightly different. But you can simply follow the instructions there. And then I'm gonna close my downloads folder and from my applications. Now I can launch Adam. So in my applications now there is Adam. I'm gonna double take on it to launch it. This is the first time I'm opening this installation. It's going to ask me to verify that I trust the source. So I will say open. Since I do now, here we go. There is the welcome guide. I'm going to close this, but feel free to read through this at a later time if you choose. And over here, the welcome page has this little option offshore Welcome guide. When opening Adam, I'm going to uncheck this. Otherwise, this will show of every time I open Adam. So I'm going to uncheck this and then close this. Okay? Perfect. Now, in my desktop I created. Ah, hello, world dot pie file for display. I'm gonna pull up the folder where I have it for here. I'm gonna go to file open, and that was in my desktop. And there is the python course, and within it, I have this code folder. There are my three files, so I can add whatever I want asked the project folder here. I will just add this so I'll select that and open, which will bring it over here. So you have this folder, I can pull up a file and it opens it here. Great. Now, this font size may be different for you. I'm gonna do command. Plus two increased off on size. I can do command minus. So it might be slightly different in your Windows machine might be control, but you can also go to view and then increase or decrease font size and adjusted as you like. I prefer it slightly bigger for the videos. So the first thing I'm going to do is customize the look and feel off this editor area so you can click on file, actually not file Adam and then preferences in windows. It might be under file, take a look and see where it is for Mac. It's under Adam and then Preferences. And this pulls up the settings that I have. And if I scroll down to themes, you can see I have a you I theme already, which is Adam Dark and a sin tax team. I can change this. I can make this Adam light for my syntax and see changes. The look off my editor. I can select any of these other options. For example, one dark over here. So play around with this till you find one that you like. You can do the same for the U. Y. Theme you have Adam dark Adam light one dark, which is slightly different. So you get the idea of how to do this. Now, if you want to use a different you, I are syntax theme that is not part of the package is that already came With your Adam installation, you can go to install and then you can search for packages or themes over here. Okay, so feel free to do that if you already know off a package or theme that you would like to use. But for me. I'm gonna stick to the existing u I and syntax themes. So what if we wanted to install a package right now you see, on the left here, these files, they simply have this icon off a file next to them. What I want to do is I want to change that look and make it look nicer. So there is a package available for that. It's called file icons. So I'm gonna look for that here, file dash icons and notice how I'm looking for the package is not the themes for file icons . So under here, if I scroll down there is this very popular one. You can tell by the 6.6 million downloads I'm going to install this. So if I click on install, it's going to install this package for me. Okay, Great. Now, if you take a look, the icons have changed. Since these are python files. They have these nice little python logos next to them and over here on top as well. Ok, so that's one package that I like. Another package that I like is called script. Now, if you remember to run this file my hello world pie I usually pull up my terminal, which is here. I'm going to move this down just a little bit, okay? And I'll usually do this. Python Hello, world pie. And that runs the code that I have in this file. And this works great from a video perspective, because I can have this over here to the right and then take this to the left like this so I can have a nice side by side view off writing code and then simply running it from here. But there is an option off running the code directly from your editor. And for that, we're not going to need the script package. So let's go back to settings over here. So if you type in script and then you see the first option, it says run code and Adam and it has 1.7 million downloads. So I'm gonna go ahead and install this now, once it's installed, you see that you have settings on install and disabled options. I'm going to go to settings, and here you can kind of browse through the settings for that package that you installed. Now what I'm interested in is this right here you see, these are some shortcuts. The key barn ings. If I hit command, I in my Mac, then he will run the script and pop up on the screen itself at the bottom. If you want to look for options for Windows are the system that you're using You can scroll down further under, read me, and then keep scrolling. There should be a link for shortcuts. There you go. Command and short cut reference. You see, command to run the script that you are in for Mac command I for Lennox or Windows shift control. Be okay. So there's all this helpful information that you can reference from here. And of course, once you installed a theme or package, it will show up under your installed packages. You see, Now I'm in the packages tab and it's showing up right here. Okay, so let's test this out. I'm gonna go to my hello world, and I want this to pop up at the bottom. So I'm going to click Command I And there it is. It shows up at the bottom. It's very small. So I think you're gonna have a difficult time following this. If I ran my files this way. So my preferred way is I'm simply going to run the scripts here. But for your local development, feel free to use this because I find it very helpful. Now I'll go back to my settings. And now that you've seen how to work with packages and themes, let's switch our attention to the editor settings right here. You can adjust the settings as you need over here. I have my phone size set really high. This is for the videos. Obviously you're gonna just it from here. You can also select a foreign family if you have a custom one that you would like to use if you scroll down, there is one setting scroll past end. What this allows me to do is it allows me to scroll past the bottom off the file. If I have a file and I have some code here and it goes all the way to the bottom, usually it wouldn't allow me just scroll past the bottom. But if you have this scroll past end option checked, then it will allow you to scroll past the bottom. So I find that pretty useful. If you scroll down further we have the tab length default is to I'm gonna set this to four simply because I'm using python and different languages have different preferences. Ruby, for example. The default is too. So it's up to you. Which one you want to use, and then some other preferential things like soft tabs are already checked here. So if you have any customization that you want to do, this is the place that you would want to do it. And the last thing I want to do is talk about auto complete. And usually, when you're working with a customizable editors such as Adam, when you start typing something, it gives you these auto complete options, and some of them aren't really that useful. So what I'll do is first disable them. Then I will find it. Install one that's actually very useful for Python. It's auto complete specific to Python, which I think will be better use for us. So let's go and look for it in my settings. I'm gonna go back to install. Actually, let me remove the packages that I don't want. So if I scroll down, it's basically this one auto complete, plus an auto complete snippets, which I'm going to disable. So I'll disable this and disabled this as well. Now, if I go back here and start typing something, notice how those options don't come up. Now I'm going to enable one for Python. So back here, I'm gonna go to install and look for auto complete python. And there it is, has over two million downloads. So it's very popular. I'm gonna go ahead and install this. And during the installation process, it's giving me this option. It's saying Level up your completions with Kyte. Kyte is a native app that runs locally on your computer and uses machine learning to provide advanced completions saying all features auto complete python love a block 100% free to use. Sure. Why not? If we don't like it, we can always remove it later. So I'm going to add kite. Great. Create an account with your email address. Continue without email. I'm going to continue without email. Kite is installing on your machine, please, in our closes tab until installation has finished. Okay? Great elegance. Skip this whole thing and not use kite totally up to you. And I have not used kite before so if I don't like it, I'm simply gonna disable it from my settings. Okay, so this popped up. It says kite is not configured properly. Mustard off Adam's tree sitter Par surfer kite to show you information how to call functions. Restart will occur. Turn off and restart. Okay, let's do that. All right. Great. I guess you could look at how to make this work from here. I don't really want to spend any more time on this at this time, so I'm gonna close this close kite on boarding, and I'm gonna close out of settings as well. Okay, so let's try out Python specific function. I'm gonna say, Len, and we'll discuss what? This is later, but I see that the land function shows up, OK, And if I open close parentheses, it gives some more information. And as we can tell, this is python specific. Great. So that's all I wanted to cover in this Adam set up video. We looked at how to install and remove packages, themes and change settings to customize the look and feel of our code editor, Feel free to continue playing around with this and customize it further if you like. In the next video, we'll take a look at Jupiter notebooks set up. That video is optional if you prefer not to use Jupiter notebooks. But I would recommend you scan through it, even if you intend not to use notebooks just to get familiar with it. Perhaps you can run the video at a faster speed if you like, or feel free to skip it totally up to you. All right. I hope you enjoyed this video. I'll see you there. 5. Explore Jupyter notebooks (optional): Hello, everyone. And welcome to this video on the usage off Jupiter notebooks. This video is optional required only if you want to use Jupiter notebooks for this course which you can. But I strongly recommend you take a look at this. Either way, let's first take a look at how we can launch Jupiter notebooks. And if you got the anaconda distribution, then you can pull up the Anaconda Navigator app, which I'm going to do from my applications. And here you go. It pulled it up. And from here I can directly launched Jupiter notebook by clicking on this launch button. And you can see there are other things you can launch from Here is well, like Spider, our studio which we won't cover at this time. The other way is you condone launched. You've been a notebook from your command line or terminal window. So I'm gonna love my terminal. I wanna quit Navigator here is And first you would want to navigate to the directory where you want to launch this from. Remember, I'm using the python course directory. So if I do pwd for print working directory You see, I'm not in that directory and I know it's in my desktop somewhere, So I'm gonna go to Seedy Desktop. And then if I do ls there is my python course so seedy. I thin. And I'm hitting tab to complete Martin course. And there is my code directory, so I'll go to code. And if I do ls over here for listing all my files. You see, I have some tests. Hello, World Pothen scripts here. So I'm gonna go ahead and launch to better notebooks from here. And the way to do that is you simply type in Jupiter space notebook it enter, and this starts the notebook server, and it also pulls up a tab in your browser. And here we are. If I look back in my terminal, then you can see that the server is running over here and you have to let this keep on running, otherwise you won't be able to use this. Okay, so if you need to use the terminal, you can open up a new terminal by simply doing command t for a new one and to work out of this to shut down the server at any point, you can use control, See? But we're not going to do that at this time. Okay, So back here, it lists out the files in my current to directory from where I launched. So first, we're gonna take a look at creating a new notebook to do that scroll all the way to the right to new over here. Click on it and then you see under notebook. Python three is the version I have. So I'm gonna click on this, and it creates a new notebook. Perfect. So the first thing I'm going to do on top here has changed the title. You see, this is untitled. And if I look back at my home screen, notice how the title is entitled here as well. So I'm gonna call this simply by clicking on it. Jupiter Intro Demo and rename. OK, notice how the title changes. And back here also the title off. That notebook has changed to Jupiter Intro Demo. Another thing because my notebook is running over here. If I go to this running tab, the notebook I'm working on is showing up here as running. Okay, back to my notebook. The first thing I'm going to do is over here on top. You see this header and tools area to remove this, you can go to view and then click on Toggle Header. That gives you some more space. You also remove this tools area by clicking on toggle toolbar. It removes that as well, and to bring them back, you can just go back to view and then toggle, header and toolbar. Now let's look at the cell. This is a cell, and if I click on it, notice how it turns green, which means I'm in edit mode if I click somewhere else or while it's green. If I click escape, notice how it's blue Blue means command mode, and that just means that I can add more cells here. I can go to insert, insert cell above insert, sell below. Let's insert a cell below. Notice how now I have another cell. Okay, so while in edit mode, which is when the cell turns green, I can write some code in here, so let's write some python code real quick. I'm going to declare a variable called name and same assure Hussein, then language. I'll say python, and then I will say print if and within quotes. Welcome, Open, Curly brace. And within it, I'll say name to the But then Carly braces. Language course. Okay, so I have some python code there now to run the code in this cell. I have several options. Here is this run button. I can utilize this. Notice how the output showed up. Welcome, musher saying to the Parthenon course. Okay, great. Now, if I want to edit something within that cell again, I can simply click on it, and it puts me back in edit mode on that self. So let me go ahead and make an edit right here and let's rerun this. But let's use another method. I can also run this cell by going to sell run cells. Okay, If I click that notice how it ran it again and the edit showed up. Welcome. Assure to the python course and notice how, after it ran, it remained in that cell. Okay, so when I went to sell, Ron sells it remained here. Another thing I want you to notice at this time is this number right here. This number is associated with which cell has run at which time and every time a new cell is run it increments by one. So if I run the same cell again, see the number increments by one and will come back to this in a bit. So a few other things about running cells is if I go back here, Actually, I'll go to the next cell to do this. Let's say five plus 10. A couple of their options off running. This is if I go to sell. Instead of run cells, you see the ones below Ron cells and selected below run cells and insert below. If I click this one run cells and select below, I click on it. It runs the cell, and then it goes on to the next cell. If I do that again, if I go back here and then sell run cells and select below, check it out, it goes to the next cell. The other option. I can go to run cells and insert below. Then it inserts another cell. See the original cell over here. It didn't do anything to after running to sell it, inserted a new one and then went to it. And to demonstrate that a little more clearly, let's say I'll print too low over here okay. And I want to run it, and then I will delete this cell. So delete cell. Okay. Now, if I go back to this cell and go to sell and then run cell and insert below notice how it left this cell, which has print alot unchanged, and it just inserted a new cell that might come in handy. And to do these actions, I'm not going to use the menu over here. I'm going to use shortcuts that are very easy to use and quicken this process up significantly. For example, the first option of simply running the cell and staying in it. I can go back here and then simply hit control, return or control. Enter. It does the same thing, and it remains in that cell. Now, the next option off executing this, but going to the next line or next cell Aiken do by clicking shift. Enter. Check it out. It ran this. It went to the next cell. The other option off Inserting a new cell over here. Let me just copy paste this Command X and then paste this year for demo purposes. So if I want a new cell inserted instead of going on to this cell. After I run the existing cell, I can type an option. Enter. Okay, check it out. And if you need to reference these shortcuts at any point, you can go to help and then keyboard shortcuts, and they will show the shortcuts for your system. So command mode simply means that the cell is blue and you can run any of these and then edit mode means when it's green, you can edit the code and run the cell, move on to other cells and stuff like that. All right, so I'm gonna close this another way off. Entering edit mode is simply hitting. Enter. So you noticed it went from blue to green, and I'm in the cell. If you're using windows, your shortcuts may be slightly different from mine, but you can always reference help and take a look at what they are over here. All right, great. So now we've taken a look at running python code cells. But very important functionality that Jupiter notebooks provides is the ability to add text cells where you can use marked down to write informational stuff about what it is you're doing or anything you want and their text cells. So right here. If I wanted to convert this right now when it went green, notice how it says code over here so I can go here and then change this to mark down. Notice how this in label goes away from the cell. Now, when I'm in here, I can simply type in some mark down codes. So I'll give it heading some marked down example. And then let's write some italics, a little world example and Jupiter notebooks. And when I do this, it shows up in markdown format. You get a little display off. What it would look like is a heading to adding over here so you can see it's slightly larger but still looks like raw markdown code. To convert this again, you have to run the cell. So I'm simply gonna do control, enter and check it out. Now it looks like nice text which is now converted to HTML for the display. And if I want to edit it, I can go back here and then hit, return or click on it to update whatever I need to. And then I can also hit, shift enter as well to run the cell, okay? And I find myself using this feature quite a lot when I provide instructions or explanations or anything else that's informative about the workbook or the cells, and you can do the same. I think the more you use notebooks, you'll find this option absolutely amazing. Now, one thing I want to show you here that's slightly different from running a regular Python script is normally a python script goes top down. So whatever, let's say you have this variable declaration here. If you declare it again at a later part in the script, then have a print below that. Let's say off that variable it's going to print to that value, the latest one that it found. But Jupiter notebooks doesn't necessarily run like that simply because off this execution flow that it has with the cells, it depends on which cell has the greater execution number. Over here, let me show you a quick example of this. I'm going to get rid of this print alot, and let's say I declare a variable a equal step, and then I'll go on to the next cell and say print A Okay, so you see it prints out 10. Now I can reassign a to B 20 and if I run this cell, see, this cell has the number off 14 which means it ran after this cell over here, which has 12. Now, if I rerun the cell even though the declaration off equals 20 has happened below this cell , if I rerun this print, check it out. It says 20. It has the latest value because this cell was executed at a later time than this one. Okay, so if at any time you got unusual results for variable values that you're trying to use, make sure that you look at the output or the execution flow for these numbers and see that they are in the order that you expect them to be. Basically, they don't work in a top down order like regular python scripts. And if you want to simply run all of them, rerun all of them in order you can always go to sell and then run all. If I run all, it will run all in order. Check it out Now. Print A over here is printing out 10 because this equals 20 ran after this print function along those lines. If you are at any point in a workbook in any cell and you don't want to run, what's above it? If you want to run on Lee, the cells that are below Let's say you have 50 cells below and the code here takes a lot of time to run. Then you can simply go to sell and then run all below. This will simply rerun all the cells below the cell that I'm in. So check it out. It grand. Just these three cells. I can also run all above notice how the latest cell that executed, what has the number 23? If I go to this and then run all cells above these will have a later execution number than this cell. So I'm expecting this to be 24 25. If I do that, if I go to sell and then run all above, check it out. 24 25. It basically ran just these two cells above the cell I was in and did not run anything else after it. And in terms of cell execution, if you ever run into trouble with an infinite loop, Let's say, then it's going to show up with an asterisk next to this execution number. Over here. You're not going to get a number. Let's take a look over here. I will do some damage, all right. An infinite loop. And if you don't know what's going on here, don't worry about it. We'll explore this later when we talk about loops. So while true, I'm going to print Uh oh, okay. And if I accidentally run something like this then is going to start an infinite loop and see it keeps printing this and there's a star, meaning it's going on executing it without ending. To get out of this problem, you can hit carnal and then interrupt, which will stop this carnal from executing. Now that should work most of the time. But for some reason, if that doesn't work, you can always go. Let's say, let me run this again. I can go to Carnal and then restart and clear output. If I do that. Restart unclear. All outputs. That should do the trick as well. But notice how, Then all the output has disappeared. Okay. And then to run everything again, I can go to sell and then run all if I wanted to run all of them. But again, I've started my infinite loop. So I'm gonna do carnal and then interrupt to stop it. So I'm gonna go up and get rid of this, okay? All right. Now, if you want to share your work or share, your workbook are simply have, let's say, ah, presentation that you want to create out of a workbook. Then you have a lot of options to download this. Let's take a look. You can go to file. And then if you scroll down to download as check out all these options you have, you can download this as a notebook itself. You can download this as a Python script. You can download this as HTML. If you want to use this as a presentation, let's say a block post. If I click on this and once it's done downloading, if I open it, check it out. It shows up here as rendered HTML. You can see here Jupiter intro demo dot html. Anyway, that's a cool feature to have. If you ever want to use the HTML for anything, you can obviously edit this file by going in it. I'm gonna close out of this. Okay? And that's all I wanted to cover in this video where we took a look at Jupiter's interface . There are more features in notebooks, like displaying charts and graphs very easily, but we won't be using them in the course, so I'm not gonna cover them here. Now, you can use doing books for this course if you are comfortable with it. But as I mentioned earlier for the course videos, I'll be using Adam and to the terminal or command line. Okay. Great. Hope you enjoyed this section on setting up and customizing the development area for python in the next section will jump right in and start writing some code. See you there. 6. Command line: hello and welcome in this video, we'll take a quick look at using the terminal in a Mac or Linux system or the command line or partial would know if you're using Windows. What we're interested in knowing are the following. We want to be able to create directories using commands from the command line. We want to be able to navigate our way through directories. We want to be able to view files and folders in the directory that we're currently in and run. Our Python files are scripts from there. Now, if you already know how to do these four things, feel free to skip this video and move on to the next one. So let's dive in. Here is a view off my desktop and the folders that I have in it. Now I'm using a Mac, and this is in my finder window. But in Windows, the equivalent would be Windows Explorer. Let's get to this view through the command line in your window search menu, type in CMD or in the list of applications, find command line or your power shell window, whichever you prefer. In my Mac, I can pull up my applications and start typing in TRM, and then the terminal will show up when I launch it. This is the terminal window that pops up, and by default it starts off in the home directory to see which directory I'm currently in . Because remember, I want to be in my desktop. I can type in P W D for print working directory in Windows, it's C D, which usually stands for change directory, but can also mean current directory in this case and then hit, enter or return. You see, this is my home directory to view the files or folders that I have listed under this directory, I can type in l s in my system. In Windows, it's D I R and then hit, Enter or return. And you see, I have all of these files and folders listed, and one of them right here, you see, is Death Top. So I want to navigate to this folder. To do that, I can type in C D space and that C D stands for change directory and then the name off the folder. So desktop. And since my D over here is capitalized for desktop, I'm going to make sure my D is capital over here as well. It enter now. I'm in my death top. I can again use PWD, which is CD in the window system. And if I hit enter. You see now my path says desktop right here. And the view of that through my finder window is this. And to prove it further, I can list the files and folders I have in desktop by tapping in ls and hit. Enter. There you go. You see, the same folders I have listed here are here. Okay. You see, I have all this clutter showing up in my terminal scream. What if I wanted to clear it and move all the way to the top? I can do that in my Mac by typing in clear in windows. It's CLS and hit Enter And there you go. It clears on the screen Now What if I wanted to move one directory up or the directory that I was in before I was in desperate? For example, If I type in pwd, you see, I am in my desktop. What if I wanted to move to the previous directory To do that, I can type in CD space dot Don't Okay, Hit, enter or return. Now, if I type in PWD You see, I'm in the prior directory. Okay, so now that I know how to move in and out of directories, what I want to do is go to my desktop directory and create a new folder here called Python Crash Course. To do that, I'll first navigate to my desk up by typing in seedy space Death Top it. Enter pwd again you see in my desktop now. And to create a new directory, I will use this command m k d i r. And is the same for Mac, Linux and Windows and stands for make directory. So M k D I r. Space and the name of the directory I want to create. I'll call it Python Underscore crash underscore. Of course it enter our return and you see a new folder has shown up in my desktop view right here. Now, if I type in l s u C, this folder is showing up. Okay, let's navigate to the python Crash course folder CD bison underscore. Crash underscore course. Now, if I type in ls here. You see, nothing shows up because this folder is empty. There's nothing in it. What I want to do is create a file, save it in this folder and then see if it shows up when we type in LS or CD in your Windows system again. So let's try it out. I'm gonna pull up my editor. Here we go. This is Adam. I'll go to file, create a new file and say, this is a test file and then I'll go to file and then save as, and I will navigate to that directory. Here we go. See, I'm in my desktop and there is my pots and crash course directory. I'll double click on it, and I will save my file here, and I'll call it first underscore lecture dot pie. Okay. And the dot pie stands for ah python file going to click on save. Okay, this is now saved as a python file. Now, if I type in less over here, you see forced lecture dark p y shows up great. And since it is a possum filed, we can actually run it using python. But if we ran it right now as it is, it will give me an error. What I'll do is put in this pound sign and then save this and we'll find out what the stands for in the next video. If I save it now to run this file, I can type in python space and the name off the files. A first underscore lecture dot pie. There we go. It ran successfully with no heirs. And, of course, there was the output because there's no code in here, and this line is actually ah, comment line. So adding this pound sign to the front of this line actually turned this line into a comment. Okay, Great. And these are all the commence that you'll need to know to work with the command line in this course. Hope you enjoyed this video. I'll see you in the next one. 7. Strings, variables, top down execution flow: hello and welcome. In this video, we'll learn how to work with text and text in Python is represented by Strings, which is the first item on our crash course syllabus here. So let's dive right in. Strings in python can be represented by wrapping them in single double or triple quotes. As you see in these three scenarios, all three are valiant strings, and there's very little difference between the first and the second cases that you see here with the single and double quotes. This 3rd 1 right here, using triple quotes, is special. It could be used to represent multi line strings. As you see here, the string is broken up into three different lines, and it will work without any errors. Now, if you had a pipes and file with simply these three listed as is in it and ran it, it would run, but it wouldn't produce any output. It would look like this, but it wouldn't produce any errors either, since all the code here is valid python code with no errors. But there's nothing in this file dictating that any output needs to be produced to display these strings to the screen in other words. To display the output, you need to use the print function that is provided by python and wrap your string in it for the first string. You could use this. You'd wrap your string, which is within single quotes in this print function. So you type in print, open parentheses, put in your string, and then at the end of it, put closing parentheses. And if you did it for all three, your file would look like this. You would have print hello world using single quotes, then the 2nd 1 and then the 3rd 1 And if you ran this file, then it would produce output like this. You see, all three strings are printed out in here. Okay, so let's take a look at this in the editor and the terminal and see what it looks like. Here we are in my editor. Here are my three strings in three different print statements. And if you look at the top of the file, I have a comment that says Strings. And we briefly saw this in the previous video on the command line. You can write comments in python using this pound sign. It's also called a hash or an octo Thorpe, Whatever you wanna call it. Anything you put after that in a line will be ignored by the Python interpreter. And it will simply move on to the next line. All right, now, I've named this file a lecture, underscore one dot pie. And this file is in the directory that I'm currently in in my terminal. So I can run this simply by typing in python space and then the name off the file. So lecture underscore one dot pie. If I run it, you see, we get the output that we were expecting. Okay, great. Now, temporarily, I'm going to remove this third prince statement with the triple quotes, since they're not used that often and will use them in some special scenarios which will find out when we get to the video on functions where we used triple quoted strings as doctoring. But again, we're gonna explore that later. For now, we don't really need to look at them, so I'm going to remove it All right now, among these 1st 2 scenarios where we have single and double quotes, there is very little difference between them. But let's say you wanted to use an apostrophe in your string. And instead of saying hello world using single quotes, you wanted to say Hello, world. I'm using single quotes so it would look something like this right now. You see, my text editor already know something's off here, and it's displaying it with this discoloration. And if I ran it like this, it would actually give me an error. Since this single quote here, which I'm using as an apostrophe python, sees this as a single quote that signifying the end off this string, which began here with this single quote. So it doesn't know what to do with the rest off this statement. So if I run it, I'm gonna save that and run it. You see, it says invalid syntax, and it's pointing out exactly where the invalid syntax is. So this is a scenario where you would wrap your string in double quotes. So if I switched my single quotes to double quotes over here in the beginning, and in the end, I save it and run it. No more errors works perfectly OK, and similarly with our double quotes over here, let's say you wanted to print an actual quote in your string and say something like Hello World using quotes, year double quotes you see again. My text editor knows something's off here, but it's the same scenario as the first case because I started off my string with double quotes and Python sees this double quote as the end off the string and it doesn't know what to do with the rest off the line. So this is a scenario where I would wrap the outside quotes with single quotes. And now you see, there are no more issues. And if I save it and run it, there you go. This works as well. Now, if you were adamant about using single quotes inside your string but also using single quotes outside right here or in this case using double quotes outside to wrap your string but also using double quotes here, what you can do is use the escape character, which is Ah, backslash. Let me show you what it does over here. I'll move this back to being single quotes and if I put a backslash right before this apostrophe, you see, this is no longer discolored. So what's happening here? The back slash is known as an escape character, and the Escape character just says that removed a special meaning from the character immediately after it and treated just as a regular part of the string. So without it, this apostrophe has special meaning because it signifies the end of the string. However, with this backslash that special meaning is removed. Similarly, in this case, if I had double quotes here, this double quote now has special meaning. So to escape it, I can put the backslash, which removes the special meaning for this double quote. But then we have another one here, so I'll put another one before it. Now you see the text discoloration is gone from the string, so if I save this and run it, there you go. No errors in either case, and both of these work in their old formats with the single foot and double quotes. All right, great. Now let's talk about variables. So variables are memory location references, which store values? It sounds a little complicated. We'll think of them as addresses to values in your computer's memory. So take the two strings that we were working with Hello world. Using single quotes and Hello world. Using double quotes, you can reference them using variables like this, you simply give the variable a name. In this case, I've called the 1st 1 my message and then you use this assignment operator, which is the equal sign. And then you put in the string that you want your variable to reference and we're using strings in both of these cases. But they can be used for any objects. In python, you can have variables, referencing numbers, functions, other data types and python. And we're going to see that a lot as we work through the course now in python, the variable names are snake case by convention, and snake is just means lower case words separated by underscores. And you also want your variable name to be fairly descriptive without being too long. Okay, so in here my message is a pretty descriptive variable name for this string right here which says hello world using single quotes. However, if I had just called this Z, which is also ah, valid variable name, it wouldn't really tell me what the variable is referencing. So in this case, my message is a significantly better variable name than the letter C. Okay, now that we've seen what variables are instead off printing out the strings that we had before using our print functions here to get the output we see here, we can use the variable names instead like this. So you have your variable assignments right here, my message and then other message. And instead of providing the strings to your print function, you simply provide the variable name okay And that produces this output as well, without any issues. And this assignment right here, assigning the variables before actually referencing them in my print function is very important because Faison runs top down. So when you run this program, it'll go to the first line and see that my message is a variable. And it's referencing this value, which is strength. Hello world. Using single quotes and you see on top here, Python is aware off this my message variable. And then it's going to go to the next line and see that there's another object, other message, and become aware of that as well. Then it's gonna go to the next line, see the print function and my message, and it will simply print that out to the screen, then is going to go to the next line and see another print function. Call with other message, and we'll print that out to the screen as well. Now, if you did not assign the variables up here first and reverse the order in how you wrote this program and made it like this pocket is going to come to this first line and you see it's not aware off any objects. So when the print function gets my message, it doesn't know what my messages and he will throw this error this name error and will say My message is not defined. So very important to keep this in mind that python programs run top to bottom and we'll see Mawr and Mawr examples of this as we move on to advance topics in this course as well. Okay, so that's a decent amount we've covered in this video in our introductory look at strings and variables. Hope you enjoyed it. In the next video, we'll continue working with strings and learn about string concatenation, interrelation, formatting and much more. So you there 8. Strings: concatenation, indexing, slicing, python console: Helen Waffle. And this video will take a deeper look at working with strings specifically string, concatenation, indexing and slicing, and we're gonna start off with concatenation and string. Concatenation simply means adding strings together. Take these two separate strings, one saying stock price for the text talk is with a colon after it and the second string saying $1100. You can add these two together, using the plus operator and get a combined strength like this. This third string is a combination off the previous two, and when you add strings like this using the plus operator, you don't get any spaces in between the strings unless you explicitly added within your quotes so you can add in an empty space in between. Like this So you have your first string, followed by the plus operator, plus an empty space plus the third string. And when you add the three together, you end up with a string like this, with the space showing up in between. Now let's take a look at this in our editor. Here we go. Here is my possum file and I have to terminal windows open, and I intends to put them to use later on in this video. First off, let's move on to this part and script, and we saw these three in our presentation. We have are two variables and we're adding them together with a space in between. If I run this, you see, we get the output in the format that we were looking for. Now, let's go ahead and reassign this combination to a new message and then print that out so I would do something like this. Instead of printing this, I'll say new message equals this contaminated string. And then I will print out new message. If I save it and run it, I get the same output. Okay, great. Now, what if I wanted to re assign this to the same message variable that I had here? Let's say the way I was running my program, I was like, Okay, you know what? I need my message now to reflect to the prices. Well, then I can simply reassign message to be the older message, plus the space and price. And then I can print out like this if I were on this now. Perfect. But one thing to note here is that this message object even though it's the same name, Same variable name. It's not the same message object as this previous one. And that is because strings are immutable. It means they cannot be changed. So when you did this reassignment right here, essentially you created a new string or a new variable with the same name. However, they are different objects, they're not the same. And we contest this out by using the I d function that bison gives us, and we're gonna see more functions in the next video. But for now, let's go ahead and use. I'd function on you simply type in i d and put the object that you want the i. D four within parentheses. So, in our case, the message variable right here. I'll check the i d off that. But python remember, runs top to bottom. So this message is going to be the idea off this message, variable. I want the I d off this message variable as well. To get that, I will do the same print command see on top here. So I get the I d off this message variable and then this message variable. Let's see what we get when we run it. There you go. You see different memory locations for the two message objects, all right, and we're going to see another example of this. After this next topic, we're gonna cover which is indexing and what is indexing. So strings are sequences of characters, and since it is a sequence, they are indexed. For example, take this string interstellar. The Indus is for this string looked like this. The character I is at index zero. And is that index one all the way to the end, where the character are is at Index 11 and you can reference individual characters in the string using their index. Let's assign ah, variable name to be equal to the string. So let's a name equals interstellar, and I've left out the quotes from our string here to keep it looking clean. Now let's say we want to access the letter I and we see that it's at Index zero, and we can access it using the index notation, which is the open and close square brackets. So name followed by open and close square brackets, and within it within these square brackets, we want to enter the index off the item that we're looking for. So since we're looking for I, which is that Index zero, we put the index zero within the square brackets and this will give us the output off I and we can enter another index here. If you want. Let's say we enter index off six and they'll give us the character at Index six, which is t Similarly, if we put in index off three, we get out, Put off e. And if we want to get the last character are which we see is at index 11 we can simply enter in. Index off 11 over here, and it will give us our But now what if you don't know the length off your string so you don't know the last index? Basically, you can then use this negative one to access the last character off your string. You see each off your characters have a reverse index as well, so minus one for the last one, minus two for the one before that. So if we enter in minus two, then we get the output off a right here. Now, let's take a look at this in our terminal back here instead, off using print like this and typing out the names here. I'm going to launch ah Python Interactive Shell by typing in python over here. Let's take a look. I'm going to clear this up type in python and hit return, and this loads a python interactive environment. Our consul that comes with every path, an installation, and you can directly type in Python code here. So I'll paste in my variable assignment name and I'll assign it to the string interstellar if I hit return. Now if I type in name, you see it's interstellar. And like we saw in the presentation, if I do name open close square brackets zero. So the zeroth index, it'll give me an I name at six. Which we saw will give me a T and to access the last element I can use. Name at index 11 gives me are, but also like we saw, we can use minus one here as well. All right, now you see, we can use this notation this indexing notation to access an element from our string or access a character from our strength. What if we tried to reassign the character at that location, for example, Name at index minus one is our What if I tried to reassign it? If I did name at index minus one, let's reassign it to end. This is not going to work. I hit. Enter. You see Python throws an error and it says str object does not support item assignment. Basically, it's telling us that strings are immutable. You cannot modify it. And if you want to modify, you have to reassign it something like we did over here, where we re assigned the message. Variable. Okay, now that we've seen indexing, let's move on to slicing. Here we go and slicing uses the same open and close square bracket notation we see here as indexing does. And as the name implies, it gives us a slice or peace or a sub string off the original string based on which slice were looking for. Let's say we want the 1st 5 characters off the string, so we want this sub string enter. How would we get this using slicing notation, we see that it starts at index zero. So we entered this start value first within the square brackets. Then we have to enter the stop value or the stopping index and we see that it stops at index for However, the stop index we provide won't be included in the slice we receive. Therefore, we have to provide the index off stop plus one, which is five in this case. So we have our object name with a start index off zero. So start at the beginning and an end index off five and this will give us the output off Inter. Now let's say we wanted stellar instead and we see that it starts at index off five. So we enter five as the start value. But you see, there's no stop value since it stops all the way to the end of the string and stop plus one index off that is non existent. So to go from any point of the string to the end of the string, you can simply leave the end slot empty like we did here. And this will give you the output off. Stellar. Now this idea off leaving a slot open. We can do this for our starting index as well. Remember when we were looking at Inter we entered start index off zero and stop index off five. And when the START index is at zero like this or starting from the beginning of the string , you can leave that slot empty as well, so simply providing an end index off five will still give us the output off. Enter. So beginning can be left empty if we start all the way at the beginning. And ending can be left empty if we go all the way to the end, which we saw earlier. So if you leave both the beginning and ending empty like this, then it will give you the whole string. OK, now there's one more optional item to slicing, and we've seen this start and stop plus one in our slicing notation. So far, you can provide an optional third argument here after another colon, and that is for the step size. Let's take a look at what that is, so we have this string called nuns, and it goes from a zero through nine. If we put in a start index off too, and an end index off six, then we'll get the output or sub string slice off 234 and five, and we're not mentioning the step size here. If you don't provide a step size, which we haven't in this case, it is one by default. So it goes to each index starting with two and gives you all of the items at every index till we get to the end. So you end up with 2345 But if I actually provided a step size off, too, then it's going to start at the index that I provide. Give me too. But then it'll take a step size off to. So instead of going to the next index, it's going to skip it and go to the index after that, which is four. So we get two and four, so it's kept three in between, and now it will take another step size of two and go to six by skipping five. But we see that six is our stopping point, so that's it. We get to four as our output as an example, if we started at index zero instead off in next to with a step size off to would get output off 02 and four skipping one and three and you can specify other step sizes too you can specify step size 34 or whatever you want. Now what if we left the start and stop empty and just left the steps? Eyes off to like this. Then you get this as an output because it goes all the way from the beginning to the end with a step size off, too. And you end up with 02468 What about step size off one which is set by default. Even if we don't specify it, it would give us the whole string. Right? But what if we switch this to minus one like this? Then what happens? This basically implies start from the beginning, go all the way to the end and take a step backward or reverse at every step, starting with the last element. So the first elements gonna be nine than eight than seven than six. And so long. So what happens is you end up with a reverse string as your output, and we'll see this little slicing trick to reverse elements like this in other data structures later on in this section as well. Okay, so that completes our look at slicing out, encourage you to play around with this notation in the python console and see if you can get sub strings like this, as you want from bringer strings. There's also some practice code in the lecture to text notes. That pie file that's attached to the resource is off this video if you want to get some practice using that. So good luck. Hope he enjoyed this in depth. Look at concatenation, indexing and slicing, and the next video We'll look at some functions and methods we can run on strings, so you there. 9. String methods, functions and import statements: alone. Welcome. In this video, we'll look at some built in functions and methods We can run on strings. I've listed some of them out here on top, which will look at. But first, let's look at the official python documentation on the Python Standard Library, which I have pulled up over here in my browser. And the link is here in my comments. But you can also Google the Python Standard Library, and this link will show up. And this is a very good reference to have as you develop code with Python and I find myself checking it out quite often. I'm going to scroll down to Python's built in functions that are listed here. Here we go. And we've used some of these already. If you look at the list year, the print function, we've been using quite a lot, and we've also seen I d being used in the last video right here. Let's take a look at a few more, starting with the Len function right here. Okay. And Lynn will give you the number of characters in a string. And the way to use it is you type in Lynn, which is the name of the function and within parentheses provide the string for which you want the length off. So let's start with greeting Greeting. Is this variable right here? This is hello, which is 123455 characters long. So I'm gonna print this out and they should give me five. Let's see, Here's my terminal. I'll run it. There you go. There is five and the 1st 1 right here. Alomar. Sure. Welcome to dollar. This course is through this print function right here where I'm printing out all off my variables, one after the other, separated by comma. So if I run this on user, which is mature, it should say seven because my sure has seven characters in it. There you go, seven. But this also counts white space. So if I run it on message, let's see, it's going to give me the length off message inclusive off all these spaces. So 123 and four spaces that we have in message are going to be counted toward this length. There you go. 32 characters, including whitespace. Okay, so let's now try Type, which is the next one listed and tight will tell me what type off object it is. And we're working with streams here. So instead, off letting if I say type over here, type off message, it should give me str for string. And I'm temporarily going to comment this out because I don't need to print this every time . Okay, fare on it. There you go, class. Str So it's saying my message is off time String Now if I change this to another data type for example let's say an integer value five This five is a number It's not a string notice . It does not have any quotes around it. It will say in foreign Bijur let me run it. There you go class end and we'll explore integers in our video on numbers after we complete our look at strings and print for money All right, so moving on the next one I have listed is I d And we saw I d being used already in the last video and it tells us the memory location off our object and I keep referring to the strings as objects. Everything in python is an object, so strings, numbers, dysfunction, sprained Everything that you see here is an object, so I d gives us the integer representation off the memory location off whatever object I'm passing it. So if I replace this with I D and give it greeting and I'll copy this Koeman c Command V and make this user, it will give me the into your values for the memory locations off these two objects. There you go. And if we look back at the documentation we see there are other ones here and there will be more functions we get exposed to as we move forward in this section in not only the section but throughout the rest of the course as well. Let's now look at building methods available to string objects. Now, you may be wondering what I mean by methods, whereas for these three, I was referring to them as functions along with these built in functions. So think of functions as not tied to your object and you can tell by the fact that we're entering in the name of the function first in this case I d and then passing in our object within parentheses to the function as an argument. Okay, so you can tell what's a function by that construct the name of the function first, and then you pass in whatever you want. The function to process as input methods, on the other hand, are tied to the objects themselves. And here we have string objects and to run a method off, first, provide the screen object and then a dot to change the method name to it. So I'm gonna get rid of this. Let's take a look as an example or bring back my previous print. You see, when I print this, I'm going to clear this up. It prints out Hello, mature. Welcome to the algorithms course. Now mature is a name. What if I want em to be capitalized? Then I can run the capitalized method on it. And mature is here, my user, which is my string object. So after listing the object, I'll put a dot and say capitalize and then open close parentheses. All right, save it on. If I run it, you see, a sure is now capitalized. Don't forget to put the open close parentheses at the end off your method name. Otherwise it won't work. Now, this is a little confusing at first, but don't worry it'll get clearer as we move forward in the course and it will get extremely clear. In fact, you won't have any problems with it at all once we build our own custom functions and eventually our own objects and those objects will have methods associated with them. And we'll do that toward the end of this section. Okay, now we can get a listing off some of the methods available to a particular class off object by using the de ir function. So I'll go to the next line and put in de ir. And as you can tell, since I wrote the name out first that this is a function and within parentheses, I'm going to provide the object which is my string object user. If I save it and run it, you see all the methods, the building methods that are available to my string object, and I have some of them listed here. We already saw usage off capitalized, but we're going to see how some of these other ones work as well. But I also want to show you where you can find this in the documentation Here we are, instead of built in functions I'm gonna move back to the Standard Library and if I scroll down under built in types, you see text sequence type str If I click on it, it's going to give me the methods available for strings. She right here capitalize case fold, center count and code and there's a listing off a lot of them. Alright, So back to our code, the next method I have listed is upper and upper turns, all characters in the string to upper case. So let's take greeting It says hello in lower case and in my print function I'm printing it here. So to turn hello to all other case, I'll say greeting dot upper open close parentheses. Save it and I'll get rid off the de ir print right here. All right, let's run it. Clear this up. There you go. You see? Hello is now all uppercase. Similarly, the next one lower is the exact opposite. It will turn everything to lower case. So in this string message, we see that a is capital. Let's run the lower method on this message string and turned this to lower case so message Dark, lower open, close parentheses. Now, if I run it. There you go. A is now. Lower case. Great. Now, the next one I have listed is a good one to know. Right here. Strip. It basically removes whitespace from before and after the characters in a strength. So instead, off my message being this way. What if it was this way like this? And we have all this empty space in the beginning. And at the end, If I print it as it is, then you see, I get all this wasted space. So what I can do is run the strip method on the string. So right here, message. I'll remove the doc lower. Actually, I can chain it to this as well, but I'll show that later. Might be a little confusing right now. I'll say dot Strip. Okay. Well, then close parentheses. Save it. Now, if I run this There you go. That extra space is gone. Now, I mentioned chaining methods, and you can do that. So, after running the strip method on this message string, I can still lower case A by passing in or chaining the lower method. So after strip open close parentheses, I'll say dot Lower open close parentheses okay. And this is called Method Cheney. If I run it, there you go. It works, All right. So I'm going to go back here and remove all this base and I'll comment this out. All right? So the next one I want to look at is find and find will return the index off the object you're looking for. For example, in this message, let's say I'm looking for the word course. What I'll do is give my object message dot find and within parentheses, I'll provide what I'm looking for. So within quotes, I'm looking for the string course. So if I save this and of course I want to print this out, so I'll wrap it in my print function. And if I run it, There you go. It found course on index 26. So this sea is on index 26 off the string. Now what if I look for a character that doesn't exist a character or word or something like that? That's I'm looking for a Z right Z doesn't exist in message. If I do that, save it and then run it, it will give me a negative one. So when it can find that the object that we're looking for it returns negative one. All right, great. Now the next to I have listed. Split and join are very interesting and used quite often and will also introduce lists to us. Take this string message. If I ran the split method on this message, then it'll give me a list off all the individual words in this string. Let's take a look. So I'll say message dot split open close parentheses If I print this out and run it, There you go. You see individual strings. Welcome to the algorithms course, all separated by commas. And this is a list data structure, and we're gonna explore lists in quite a bit of depth a few videos down the road. But for now, just think of it as a list off strings. I'm getting back by using the split method and by default. This split method separates based on white space. So you have these spaces and you see it's separated out the string based on those spaces to give me these individual strengths in the list. What if the string was different? For example, if it looked like this, you see now I have no white spaces in my string. So if I ran the split method now I get a list. But with only one string, I no longer I'm getting multiple strings. But thankfully for us, you can actually specify what to split on with the split method. So in this case, we want to split based on the dash is so within my parentheses for the split method, I'll put in a dash within fault. So within faults, I'll specify to split on the dash if I save it. And now, if I were on this, check it out, it works. It splits based on the dash. And you can spit on anything else if you want on any other character in the string. Okay, The last method we're gonna look at is join right here and join gives you the exact opposite off. What split gave you? You basically take in the different items in a list or other interval collections like lists, and you can create a string out of them. So let me go ahead and paste a list and then put the items back together to a string. Here you go. I have this list off languages. Three of them are listed out here as individual strings. So I'm going to use the joint method to create one string out of them. And the way to do that first with in double quotes, you specify what you want to join on. And I want to join basically the glue. I wanted to be a space, so I'll put an empty space in there. Then after that, you put a dot join and you pass in the honorable, which is the list. My languages in this case. Okay, If I save this and then run it, check it out. Python ruby javascript as one string instead off a list like this. All right? And you can join on other things as well. For example, if I wanted to join on dashes, I put a dash in between the clothes, save it and run it. There you go. Perfect. And the last thing I want to cover in this video is this concept off importing things to our program. So back to our documentation. You see, if I scroll down and look at text processing services and string common string operations, if I click on it it lists out these things that are available in this string module. These are not available by default. For example, Take a look at this string dot ask e lower case. This gives us the alphabet in lower case. So the letters a through Z. So if I copy this command, see and then print it out, command V and then save it unless you're on it. It gives me an error. Saying named String is not defined. It basically can't find this anywhere, since it's not available by default. In this case, while we have to do is import the string module and usually you type in the import statement on top off your file. So I'm going to say import string if I save it and now running, check it out. Now it's available. It's no longer giving me an error. There's a different way I can do this. For example, I'm looking for just this constant asking lower case, so I don't need to import everything else from the string module, which this will do for us. This is importing everything from the documentation that we looked at. So everything from here this module is being made available through this line. If I just wanted this asking lower case, I can instead type in from string import, asking lower keys. If I saved that, then I don't need to reference this with string anymore. I can simply reference it as asking lower case if I save it and run it in my terminal. Here we go When you run this. There you go. Still works. Okay, Great. That's a lot we've covered in this video. A lot of functions and methods that we can run on strings. Hope you enjoyed it. My suggestion is to play around with these methods and other ones from the documentation on different strings and try to make them work and see what they do. OK, good luck. And I'll see you in the next video. 10. Print formatting and special characters: hello and welcome. And this video will look at different ways off formatting the output coming out off our print statements. So far, we mostly just printed out the strings themselves or variable values in their place in this video will explore three ways off print formatting. Now, the one I have listed here is simply using a string concatenation and adding these two strings together. So if we run it, there you go. We get the output that we want with the stock price added to the end off my statement. Now, the other one which you briefly saw in the last video, was instead off using the plus sign, we can put a combine here, and if we did this, then this comma will automatically add a space in here. So I don't need to add this extra space within my string. So I'm going to remove that. Save it if we run it. There you go. We get the same output. Now let's look at some advanced print formatting, and the 1st 1 we're gonna look at is the format method and instead off separating out our two strings. What we can do is within the string itself over here. I'm going to say open close, Curly brace like this. And at the end of my string instead of the Kama I'm going to say dot format. So this dot format method is going to run on this string object that I have and within parentheses, I will put in the stock price right here. Okay, So what this will do is it will take the stock price and then just inserted here while printing. Let's see what that looks like if I run it. There you go. We get the same output. And this used to be a very popular way off doing print formatting using this dot format method. And the last one we're gonna look at is using what's called f strings. And this is the one that I'll use most often throughout the rest of this course. Instead, off typing in doc format over here. I'm going to get rid of all this. Okay. I'm gonna copy my stock price. Variable name right here. Get rid of the extra parentheses. And you see, we have the string with these Carly braces. So what I'll do is put my stock price variable within the Curly braces themselves directly . But in order for Python to treat this as a special case, we have to put in an F at the beginning off the string, thus resulting in the name F string. And if I save it like this, what Pathan is going to do now is see these Carly braces and whatever it finds inside them , it's going to evaluate it in this case is a variable. So who should get the same output? If I run this There you go perfect. And see how clean this looks. There's no additional methods. There's nothing of the sort were simply embedding the variable within our string, and this is also known as string interpolation. And here stock price is just a variable. But this is actually going to evaluate whatever you put within these Carly races. For example, I can put in four plus five, so Pathan is going to evaluate this value, and this sums to nine and then it's gonna print nine to the screen in this place. If I save this and run it, check it out. It does the evaluation for us and we'll see this used a lot. This type of notation used a lot in this course. Now this was a case. We're embedding a single value. We can embed multiple variables and values to let's take a look instead of having just a stock price. What if we had to stock prices? I'm gonna paste in some code here. There you go. I have today price. I have yesterday's price and then I have a print statement using commas, and you can already see some challenges with this type off formatting. When you use commas, it's looking fluttery. There are too many commas in here. There's a lot going on. Plus, you aren't able to control whether the comma adds a space or not. It will do it by default. So if I ran this, there you go. Today's price. 1100. Yesterday's price. 1000 still works, but not very clean. In my opinion, if I did the same thing with the dot format method, you will find it much cleaner. So let's do that. I'll simply copy this command C Command V and then remove the closing quote here, this one as well and all of this. Okay, so today's price. Then I'll put a space in there and then open close. Carly Brace and I can also add in a comma here for a better look. And then yesterday's price again. Put a space open. Close, Carly Brace. All right, that I'll say dot format. And now, whatever. I want to go to my first set of curly braces. I will put in first and then I put the 2nd 1 which is the one I want to go in my second set of Carly races. So I'll say today, Price and then yesterday, Price. All right, so basically, within the arguments off the format method, this 1st 1 goes to this first Carly brace and the 2nd 1 goes to the second curly brace. If I run it, there you go. There is the second output produced by the format method. And you see, we were able to add this comma and make it look nicer than in this case. If I had to do the same here, it would get a little complicated. I would have to use concatenation and all that other stuff. All right. And now let's do the same thing with our F string, which in my opinion, is the cleanest since we don't even have to write out this format or any of this other stuff. So I'm gonna copy this Command C Command V. I will get rid off all of this at the end here. I'll directly put in today Price. And here I'll put in yesterday, Price. And for this to work, put an F here. Okay, so you see how clean this already looks in comparison to the other two. All right, so let's run it. There you go. Perfect. Working exactly as we expect. Okay. Great. And we'll see lots of usage off F strings like this and string interpolation and print formatting as we progress to the course as an example. Let's take a look at this print statement from our analyzer program, which will build in the fording algorithm section. I'm gonna pull it up. There you go. And here is an example. Often f string that we're going to build and check it out. There's a lot going on here. If we run this, I'll run it in my terminal below. The program needs some set up variable from me. So I love that in real quick. Okay. And check out this output that's produced. You see, all of these lines is nicely formatted lines with the tabs and this nice, clean output. This is all produced by this line right here. So you can kind of see the power off print formatting. Now, one thing to notice here is you see the space, how it's consistent for all of these right here. But if you look at our stream over here are f string were not embedding any of the space in here. So how are we getting this That's produced by this slash t character or here And this is a special character for town and having this in the string ads in a tab like this to all our print statements. And this brings us to our next topic, which is special characters within strings. And you've already seen the backslash character being used. So I'm gonna close out of this and I'll paste in some special characters. There we go. So you've already seen the backslash being used and it is an escape character. It basically escapes the special character following it in a string. And we saw this used when we were trying to escape the special meaning often apostrophe, signifying the end off the string. We're also gonna look at the new line, character slash end and the tab character slash T, which you saw in the program that we just viewed. Let's start with this backslash for the escape character. I'm gonna pace in a string here and see another example of it being used. Take this string right here. You see, it is pretty long. And if I want to look at the whole thing, I have to scroll all the way to the right. So this is a scenario where we can actually use the backslash or escape character to break it up like this. Let's say we want to Onley see up to here in each line, so I'll put a backslash in here. Go to the next line, then I'll put a backslash in here as well. Go to the next line. If I save it and then run this, check it out. It shows up in one line. It's not broken up in multiple lines, so this is very convenient for our viewing purposes. So what's going on here? This backslash is telling Python to escape the move to the new line that it's seen here. All right, so it seemed these three lines, essentially as one straight line, resulting in this output. Okay, And you can say, Well, this could be accomplished using multi line strings as well if we use triple quotes, which we saw briefly in our first video. If I do that and get rid of this backslash, you may think this would work as well. But if I print it, check it out. It's broken out into multiple lines. What's happening is multi line strings saves any special characters that you have in this. And we have these new lines that are embedded anytime we move to a new line. So it's showing up over here, and that's one feature off multi line strings. For example, if I moved this line like this kind off far into this line and print it, you see all the space shows up. Okay, the next thing I'm gonna look at is the new line character. So I'm going to paste in a string over here. There you go. Now, if I ran this you see, I get this printed out in one line. What if I wanted to split out this output into multiple lines, then what do I do? I can use multi line strings as you saw, but then the result in formatting and everything, or I can simply embed the new line special character. So let's say I enter in slash n right here, which is the new line character. And then again after this. What this will do is any time I have a new line, it's going to move the next bit to the next line. Let's see what this looks like. I'll run it. There you go. And we see this additional space because I'm leaving the space here. So let's eliminate that and run it. There you go, broken out into three lines, and that's essentially what the new line character does. Now let's move on to the slash t and you already saw that being used in this program. But let's embed some tabs here. Let's say over here and then after this, a couple off other taps over here. All right, so each one is going to give me a tab. If I ran this, check it out. I have one tab in here from this one and in the next one. I have two taps, and you could have some fun with this. For example, I'll print this with a couple of tabs and new lines, and if I run it, check it out there some additional tabs and new lines embedded in this. So, as you can see, you can play around with it to get the type of format that you want and in terms of actual programs, this type off formatting will be very useful, since it will present a very nice output to the user using your program. Okay, the last thing I want to look at is what if you wanted to show the special character that's being used in your string, Take this line, for example, right here in this statement. What I'm essentially saying is, I'm using the slash and special character to create new lines. This is a scenario where I want this slash and to actually show up in my output. But if I ran this, then it doesn't show up. It simply does whatever the special character is designed to do, which is moved to the new line. So in this case, we can use our trusted backslash or escape character right before the special character. And then that is going to escape the special meaning off their special character immediately after it. If I save this and run it, there you go. It works and slash m shows up. Okay, great. And that's a very decent amount. We've covered in print formatting and special characters will see them specifically F strings used. Ah, locked through the rest of this course. There are a few other ways off using print formatting as well. But these are very commonly used and quite popular and will set us up very nicely for our printing needs. Moving forward. Hope you enjoyed this video. Now we're gonna move on to numbers and working with numbers starting in the next video. See you there. 11. Numbers, math, type casting and input: alone. Welcome back in this video, we're going to take a look at numbers and how to work with them. Specifically. We're gonna look at integers and floats. Let's quickly jumped to the documentation. Here we go. And from this standard library reference, if you scroll down under built in types, numeric types, if you click on it, here is some more information on integers floats, complex numbers. So if you wants to, this is a good reference points to learn more about what you can do. And we're gonna look at some of these operations that are common. But so it was good to know that you have this as back up for reference any time you need to look anything up. All right, So let's look at our editor. Here we go. And this is my agenda for this video or and do some masked we're gonna look at what typecasting is, and then get some input from the user. Here, I have to terminal windows open. This one has the python interactive shell, and below it just a regular tab. Work and run this file from this electorate. Three that pie. So before we get down to doing some math. Let's talk about what an integer is. An integer is basically ah, whole number. Okay, so no decimals over here. Four. That's an integer. So if I type in type four, you see it says class and floats are 14 point numbers are slightly different. They have decimal, so you have 3.5. For example, if you do type off 3.5, you see, that's a class float, and there are some fundamental differences in their constructs. But we don't really have to explore that too much of this time. But we need to be aware that when you have an integer, let's say four and then you added to another integer that gives you an integer. Let's say result equals four plus floor. If I type in type of result, you see, it's also class in. And then, of course, if I printed results, you see I get eight. What if I wanted to add four more? To result, I can do result plus four. I don't have to do four plus horrible four. Since result is already eight, they go 12. Now let's look at some other operations. We could do subtraction so let's say 12 minus four. That gives me eight standard subtraction. If I do five minus 10 that I get negative five. I can also use dysfunction called a B s are absolute value. It basically removes the negative from a negative number. So if I do a B s than minus 10 it'll give me 10. Moving on. I can do multiplication using the asterisk sign. So that is a sign for multiplication. Let's multiply 10 with five, we get 50 okay? And all of these have been integers. Except for now. When I get into division, if I do 10 divided by five I'm gonna store this as a result equals 10 divided by five. And then I do type off result. You see, it's class float. Anytime you perform a division starting with python three, it's going to give you type float because you might have decimal points in there. So instead of 10 divide by five, which is nice and even to if I do 10 divided by three. You see, it's 3.3333 so python automatically will not drop these numbers after the decimal. When you perform division to do that you have to do floor division which essentially drops the decimal. So if you did 10 and instead off one slash for the division sign If you did two slashes. That's floor division. So that gives you three. Okay, What if you added an integer like 10 with afloat 10 plus 2.5. This result is automatically afloat because you need to represent the 0.5. But what if you did 10 plus 2.0, You still get afloat. So anytime you introduce a float into the mix, the result is going to give you a float. The next thing I want to look at is the mod operator, which simply gives you the remainder. So if you did 10 marred off three, it gives you a remainder off one. So three goes into 10 3 times and you are left with a remainder off one. So if you do 10 mod of to you get zero because to even legals into 10 2 times five is 10 so you don't have a remainder. Similarly, 15 Model three will give you zero because 15 is divisible by three. What about 23? Mod off five gives you three because five times four is 20 year left with three. Okay, so if you're trying to find numbers that are divisible by other numbers, Mott is a good operator to use. Also, if you're trying to see if the number is even, let's say some random number like this. If you do that model to if it gives you zero, then you know that the number is even. But if you do something like this, that's not even mod of two will always give you a remainder off one. So it's a good test, for if a number is even or not, the next thing is, let's look at the power So five to the power of to the five square. Essentially, to do that, you news two asterisks. So five Star Star two. That's five square, basically 25. What about five Q. I can do five star star three. So 10 to the power off five 100,000. OK, there's a different way you can do this. You can import the math module, and then you can do math dot pau and then 10 5 should give you 100,000 as well. You can also do other interesting calculations using the math module. Let's say you needed to find Log base to You can do math dot log base to so locked, too. And then, let's say 10,000,010. 10 million gives you 23. And if you don't know what log is or log ways to is, don't worry about it. We're gonna cover this in the algorithm section because there's going to come into play. When we try to analyze some algorithm performances, you can do other interesting things with other modules. Let's say I wanted to generate a random integer I can import around the module so import random and then I can do random dark rand int. And let's say I want to generate a number between zero and 1000. I can do zero and 1000. Okay, I can keep doing that, and I will keep generating random numbers. All right, so there's lots of interesting things we can do with math and numbers integers that we're gonna find out as we make progress through the core, especially when we get to algorithms analysis and all of that for now, knowing the basic math operations are good enough. So the next thing I want to do is look at typecasting. So for this I'll come here. You saw that the type for int and float was displayed when we used the type function. So if I do print, type off, let's say a string with 10 in there. So if you notice this is not a number, this is a string. So if I run this you see it says class string. What's interesting is that due to string concatenation, I can actually add a string with another string. So what I can do is result equals 10 plus 10 and you think the number 10 plus the number 10 would give you 20. But this will actually give you 10 10 because he will take 10 and then add it to the end of 10 because Python sees these as strings. So if I simply print out result, you see, it's 10. 10 now what if you actually wanted to add to the number 10 to the number 10 and let's say whatever you got these numbers from the source, they were giving it as string to you. But you need to perform this addition then what you need to do is you need to convert these two integers are floats, basically convert them to a number and then performed this addition. So in python is very easy to do this. What you do is called typecasting, meaning you convert a string to an end. So one way to do this is I can do this. I can wrap it around with an end so into open parentheses, then the string that I want to convert. Now, if I do, this is gonna result in 20. You see 20 also, if I look at the type off result you see, it's inch now. All right, So, usually when this would occur is not when you're physically typing in string, you would probably be working with variables. So let's say numb one equals the string 10 and then numb two equals the string instead of 10. Let's use 20. All right, so we'll replace this with number one. I forgot the underscore there. And then this, with no to and instead of type, will just print out result. It's clear this up. Okay, I'm getting the string output. So what if I do the conversion here? For example, if I cast this result to an end. What would happen if I did this? I would still get 10. 20. Because you see, the string concatenation has already happened here. So result is 10. 20 and then I'm converting 10 20 to an end. So it doesn't really matter if I converted to an Inter at that point. What I have to do is I have to do this conversion before before I actually perform the arithmetic on these numbers. Okay. And you will see if I actually type in the type of this, it'll give me end, which is what it converted to. But still, it doesn't matter, because we did the conversion too late. All right, so just like you can couldn't fort string to an anti. You can also convert numbers two strings, for example. The print function already does it. If these were actual integers right here in order to print this to the screen, the print function actually calls on the string representation off this object, whatever it ISS and then prints that out. So if I print result, this is automatically getting converted to a string. But let's do that manually on the way to cast something to string is you can simply say S T r and within the parentheses. Put in what you want to convert. I can do that. And then now if I type in type off result, you'll see that it will tell me it's a string, even though everything about it the numbers are used for the operation, and initially it was all ends. Yet when I do the conversion, it converts to string. All right, so that's typecasting for you. Obviously you can't castings that are not cast a ball. It would work for string because you can virtually take anything and have a string representation off it. But what if you tried to take the string mature and convert to an end? That's not gonna work because there's no integer or number representation from assure. So let's take a look at this and see what happens if I run this. See, the first air I get is must be str not int. So I wasn't able to add a number to a string. That's the first thing basically tried to perform concatenation, and it failed instead, if I try to couldn't work, our cast mature as an end and then run it. Clear this up, you see Invalid literal for end with base 10. Basically, there's no integer representation off the string. Mature on. The same thing will happen if I try to do this with Float. Could not convert string to float. Mature. Okay, The last thing I want to cover in this video is getting input from the user. Let's say we have, ah, multiplication program. I'll paste in some code over here. A couple of print lines. All right, let's save this and I'll clear this up. OK, so we're all set. Welcome to the multiplication program. I print this dash 30 times. A little trick to create a line and then number one I don't want this temporarily. I'm going to Ah, hard code of value. And over here num one times number 2 10 times 20 Print Result directly. I don't need the type, so I'm expecting this to multiply 10 times 20. Let's see. There you go. Welcome to the Multiplication Program 200 which is 10 times 20. Now, These numbers I want to get from the user who is running this program right here and we can do that in python using the input function and the way it works is this. Instead of print type and input and within quotes, say what you want the user to do in the line. So what I'll say is enter a number to multiply and then put a dash in there than a space. So this is going to show up with a prompt over here right afterwards. So it's good to have a space there and then I want a second number. Come and see command. We enter the second number to multiply. Okay, so if I just left it like this and run it, you see how it prompts me. The user was running this program to enter a number to multiply, and that's what input gives us. So if I enter a number, let's say 10 and then a second number, Let's say 50. Okay, so all I did was enter the numbers. I didn't actually do anything with them. Two things. First, I need to change this hard coded numbers with this prompt, so it saves whatever entering into that variable or references it with that variable. The second thing is, whenever you enter something through the input function like this, It gives you a string automatically. So even if this looks like a number, it's gonna be a string, and then you have to convert it. So what I'll do is I'll copy this, Command X. Put it here. Command three. Same thing here. Command X. Come on, V. All right. This will always be a string limit. Cleared supper, quick. And then when I come down to calculating this, this is going to give me an error. Because while Pathan knows what to do, if this was ah, plus, it would simply do string concatenation. When it comes to multiplication, it can't multiply two strings. It can multiply a string with a number because that just means 30 occurrences off the dash . But if you try to do 30 times the string dash, it would throw an error because you can't have dash occurrences off 30. That doesn't make sense. So similarly here to make this work, I'm going to convert this to an end. And this is a little dangerous in terms of code, because if I accidentally typed in a string, you would give me an error, but we're gonna check for things like that later on. For now. Let's see if this works. Here we go into a number to multiply. 10. Second number to multiply. 50. There you go. 500. Perfect. All right. Great. So we've covered a lot in this video and how to deal with integers, floats and numbers. In general, we looked at how to do computations. A couple of modules, couple off. Interesting functions that we can use. I hope you enjoyed it. Thanks for watching. And I'll see you in the next video. 12. Introduction to branching (if, elif, else) and conditionals: Hello and welcome back. And this video will look at how to control the execution flow off programs using Boolean and conditional tests along with branching and to understand what that is. Let's start off by seeing the type of code we've written in the section so far in the last few videos. Let's take a look. I pulled up some of the notes files from the previous lectures here. This is from lecture one and you see, this follows top down execution flow where all the lines in this program in this entire script are executed in order from the top to the bottom and nothing is skipped and we see the same in the other lecture notes as well. This is from lecture to notes where we look at indexing and slicing each and every line is executed. Then we see this is from the print formatting lecture and also with our numbers lecture where all the lines were executed top to bottom and notice also how all of them each and every line started in the beginning. Off the line Nothing is tabbed in now in this numbs video toward the end we ended up with this multiplication program. Now what if we wanted to give the user the option to choose multiplication or division? This program simply performs multiplication without giving the user adoption to choose. Something else in that case would have to somehow segment our code into blocks where if the user chooses multiplication, then this block of code is executed. But if the user chooses division, then a different block of code would be executed, and this multiplication code would be skipped by our program and not executed. And we can control that and implement this functionality using if LF and else blocks with what is known as branching and with branching, we can control the flow off our programs. Let's take a look back here if you take the billions and conditions and branching you felt and split them up. If you look to their right, this is what an NFL's condition looks like you have, if some condition so in our program. If the user chooses multiplication, then we would write some code that performs the multiplication else, execute some other code. Ah, variation off. This is if, LF and else so, if a condition has chosen that executes some code L. If some other condition has chosen, for example, let's say there's division and subtraction that you want to offer. Then the user chooses division else. Perform the subtraction or something else. Okay, so using if LF and else you can control the flow of your program and split it up into segments depending on what your requirements are. So what are these conditions and how do they work? So basically, these conditions are controlled by statements that evaluate to true or false, and if they value to true, then you enter that if block. If they don't, then you move on and don't execute the code in that if block. So, basically, conditions evaluate to true or false, which, as you know, are known as billions. And these are the conditional. You have greater than less than and greater than or equal to less than or equal to equal, to not equal to, and you can also choose combinations of them. But the signs for these in Python are these. So for greater than is just the right arrow less than left arrow greater than and less than equal to have an equals after the arrows and equal to That's the tricky one. Number five. Because you see, if you're testing for equality, then you use to equal signs. So far, we've used the equals as an assignment operator, meaning this variable is assigned to this value, and it's very easy to confuse that with the quality and believe it or not, Sometimes I do it as well. So something to keep in mind person will throw an error. If you try to do an assignment in your conditional test, okay, and then moving on, you have the not equal to which is the exclamation mark, followed by the equal sign. So let's use this the conditions and billions to see an example off the program that we built to multiply and what it would look like if we actually offered up adopting to multiply or divide. Here we go. I have the same program that we built here. Welcome to the multiplication program with the inputs and the operation here. I've changed it to welcome to the Cal program and then I've introduced this additional input where you choose one to multiply two to divide. I get the two inputs and then, if choices one performed this multiplication LF choices to perform division. And if neither one or two are chosen, then you've made an invalid selection. All right, so if I run this there you go. Welcome to the Cal program. Let's choose one to multiply that center. The first number five Next number 10 five, multiplied by 10 is 50. Great. Now let's choose Division two to divide. Okay, and your first number, Let's say 18. Next number was divided by three 18 divided by 36 So that's us controlling the flow at a basic level. Now, if you look at this program, there is a problem. Because if I make an invalid selection, let's say I choose five. Then it still prompts me for the first number the way this is written. So regardless it's gonna go through and give me the two. And then it says you've made an invalid selection. So how do we fix it here? We can use a nested. If so, you can have nested. If conditions I can test for an if condition and within it I can have this code. If an LF run inside that, let's take a look at that example, pacing it in so with just minor modification. You see, I'm checking for if choice is one or two when the user enters their choice, then I'm entering this block right here where I asked for the first number on the second number. And if the choice is not one or choices not to, then I immediately go to the elsewhere. You've made an invalid selection. So if I run this you see if I enter seven here, it immediately says you've made it invalid selection. So I only entered this block of code. If a valid choices made and then you see if here and then if nested inside it now, one thing to keep in mind that's very important from a syntax perspective is the indentation. You see this tab right here? This is how you indicate a block of code in python. So if something whatever you want to include inside this if condition, it has to be tabbed in. So you kick it off with this colon right here. You see, right here you add a colon after that and then you Tabin, whatever you want to be part off that if statement if you don't do it, hyphen will not recognize this as part of that. A lot of languages have curly braces like this. You open close and put whatever code inside there. So you would put code in here like print here. If this is the choice, etcetera, etcetera, other quoting languages will have an end to the block or something like that. Python does not. Python simply operates based on indentation. So indentation is very important. You see here when I'm inside this nested if condition, whatever is inside there is tapped in by one more tap. Okay. And this else condition is part of this. If else so you see, it starts from the beginning. And as an example, if you look at the 1st 3 lectures, all the code we wrote started at the beginning off the line. Nothing was tapped in. So because we are not using any blocks, OK, so that's something very important to remember. Functions operate the same way in python. There is no end. Are closing brace or anything like that. You'll have to simply remember to track the indentation. Okay, Now, the second thing I want you to keep in mind is look at this condition right here. if choice equals one or choice equals two. You see, I've added and or here you can also combine based on end if and obviously this makes no sense in this condition. But this would check for if the response was both one and two, otherwise it wouldn't enter this block of code. There's also not that you can use and we're gonna explore that very soon. I leave that as or okay, so now let's move on to show some examples the schools need, but I'm gonna show you right now is taken from later on in the course where we reverse a linked list. If you don't know what that is, don't worry about it. It's basically a recursive method, but it utilizes if, LF and else let's take a look. I'll paste it in here and this is what it looks like. So if one condition LF another condition and then else do something else and this is the type of code they're going to be able to build pretty easily toward the latter part of this course. So I hope you're excited about that. And there is a pretty simple one, actually, since its if, LF else. Let's take a look at a more complex one. There's gonna be a lot more clutter. But if you look past the clutter to the actual logic, then it also brings down to if, LF and else blocks let's take a look. And here we go. So this is part off a job scheduler project that we're gonna build much later on in the course. And if you scroll down to where we are taking input from the user, I'm actually gonna show you how this run. So let me clear this up and run it. Pi thin job, Scheduler DuPuy! Okay, we're gonna escape what's going on on top over here. And you see, this is the menu that's presented to the user Press one to view today, Scheduled jobs press two to add a new job, press three to removal job and press four to quit. So if you look at this, here is the menu. If selection is one, then we do something. That's the 1st 1 right here. So if I select one you see all these jobs for the day are displayed, then selection to you can add a job. I'm not gonna do it simply because it will take too much time. But then you have selection three to remove a job. You can enter that here. And you see all of these air handled by if l if right here. LF three if you scroll down to L f selection for exiting program, and then you haven't else that says that you made an invalid choice. So if I enter in seven, you see, please enter a number between one and four. And that's happening because off this else right here. So this again is type of cold. You'll be ableto build by the end of this course, and there's a lot going on. But I wanted to give you an example off how often we use branching and branching. Pretty much is a cornerstone off programming. You're gonna use it all over the place. Very important to master this. All right, so I'm gonna press four here to quit. Then clear this up and then remove this from here and removed other examples as well. Okay, great. Hope you enjoyed this introduction to branching and seeing some example uses in real projects, which we're gonna build later on in the course And in the next video, we're going to take a look at using some of these conditional tests that evaluate to true or false and some combinations off some of these conditional tests to build some of these. If LF and else blocks OK, hope you're excited. Thanks for watching. And I'll see you in the next video. 13. Building if, elif, else blocks incrementally: Hello and welcome back. Carrying on from the examples we saw off control flow and branching using if, LF and else blocks in the last video we will look at building such blocks step by step In this video here I have a script set up where offset this Boolean variable truth condition to true and the way that if condition works, is it starts with the keyword if then the condition, then the colon. And if this condition is true, then it goes to the indented block of code right underneath it. You could have multiple prints or other code down here and as long as it's indented, it'll be considered part off this if condition. So let's go ahead and run this. I'm going to go to my terminal and we see since we've said truth condition to true, this condition is true. It went and it printed out truth. Okay, if we set this to false, save it and run it, we see nothing happens because we didn't enter this block of code. And while you may have billions that you test for like this with if conditions usually you'll be using expressions that evaluate the true or false. So let's say I have a variable choice that equals the string off one. Then we want to execute some code. If the choice is one. So that would look like this. If choice equals one, then print. You have chosen option one. If I run this, you have chosen option one. Now, if I change choice to to and if I run it, we see that I get no output. Usually, in a scenario like this, you may want to let the user know that they made an invalid choice. And since we only have a choice off one that we're checking for, we can capture all other scenarios with an else clause. So I'll go to the next line and start my else in the same indentation as my if block. Since this else correspondences if it has to be aligned, I can't have the else tab day, right? So else you have made an invalid choice. I save it and then run it. You have made an invalid choice Much better Now. What if we wanted to actually provide the choice off to and added to our menu, then the choice off one and an else clause capturing all other choices does not make sense because we have to account for two. That is where we can use an l f will say l if choice equals two we can print, you have chosen option two. And now if we run this there you go. You have chosen option to right here. So that's a basic if and left and else block that we can use for branching to control the flow off our program. Now, if you had other choices, you could simply add more LF blocks over here as many as you need. All right. So you can account for multiple scenarios and you can also modify or combine tests like these by using logic operators which are and not and or let's take a look at them by hopping on to the console. So here I have my python consul in another tab and basically these expressions right here these expressions are evaluating two Boolean values off true or false. So I'm going to try out some of these true or false conditions. So let's start off with what if we have a true and a true then it gives us true Okay. What about true and false? That gives us false. So if we had something, let's say I'll add this additional variable called made payment equals false and we only want to enter choice. One if made payment is true. We can just for this by saying if choice equals one and made payment equals true and made payments equals true. You can actually shorten it by simply saying made payment. So if choice equals one and made payment, then you have chosen option one. But you see me payment is false. So if I make a choice one, we have this scenario off true and false. Since this will evaluate to true and this will evaluate to false so true and false will give us false and it will not enter this scenario and go to the else right here. Let's try it out. I'll go back to my terminal. You have made an invalid choice, OK, which is the else clause? Alright, So back to our condition ALS right here. If we have false and forth logically, that's going to be false. If we have true or false, that's going to be true. If we have false or false. That's going to be false. And we also have not false, which will be true and then not true, which will be false. Okay, so let's take a look at an example off this not operator and how we can use it. I'm gonna modify this code over here on based in some variables. Okay, So made payment equals true. And I have this string please pay monthly premium represented by a Welcome to your home page represented by B. So what I can do is, if not made payment, then print day bills, friend, be okay. So whatever made payment is then struggle it to opposite off that. So if made payment is true, check for not true, which would be false then Print day else print be so in this scenario, made payment is true. So there you go. True. And I'm saying check. Not true. So this one Not true. And that evaluates to false. Therefore, this condition will not happen. And I'll go to the else clause and print B, which is welcome to your home page. Let's see how that looks over here. I'll run it. There you go. Welcome to your home page. and this code block right here. We can actually simplify this and write it in one line using what's known as Turnberry operators. And we're going to see this later on in this video. Now back to our logic operators, off and or or not and let's see some examples using into variables. Here he goes. Okay, so I is 20. Jay's 10 gave 30. Let's start with end. What if I wanted to see if I waas less than J and less than K? Then I would have this condition If I is less than J and I is less than K Brent. I is less than J and K. All right, so in this scenario this is not true So it's not going to work. But I will change I 25 And if I run this you see I is less than J and K. Now what about to equality tests we want to test for? If I is equal to J and K, then what? Weaken Add this LF I is equal d j and I is equal Okay then I is equal to J and K So if we make all the values equal 10 10. Let's say 10 and run this that branches working. OK, now next. What if we want to see if I was equal to J or if I was equal to K so using the or operator In that case, we could do this. LF I is equal to J or I is equal to okay, then print I is equal to either J or K else Bridge something else. All right. You see, this scenario is interesting because all three values are equal and I equals J or I equals K. Both are true, So true or true should give me true. So technically we would think that this condition or block of code would be entered. However you see the one above it, l f I equals J and I equals K. We're saying print I is equal to J and K. This one is true. Therefore, I'm entering this block And if LF else branch like this with multiple ranches, you're going top down in terms of your code. If you enter a branch, then that is the only branch that's going to execute. So because we're entering this branch first, I'm only going to get this output. And even though this one is true as well, it's not even going to check this from here. After this print, it's simply going to exit out off this if LF else block of code over here. All right, so let's take a look. I'm going to clear this up on Run it. There you go. I is equal to J and K. However, if I switched the order of this so command X and then pasted this year, save it. Now. If I run this C, I is equal to either J or K. So again it entered the first condition that was true. And then it skipped all the rest. All right, so let's now quickly take a look at the coronary operator, which I had briefly mentioned earlier and how it works. It's basically taking a simple if else block and compressing it to one line. So let me hasten an example. I want to paste this in over here. Okay, so you have courses. Python A is enrolled in part. Of course. Be enrolled in some other course. And I'm doing this test. If courses Faison then from day else print be so this expression right here can be expressed using coronary operators in one line. Let's see how to do that. First, let's start with the quality test and what the result is print day. Okay, so we'll say friend. A actually let me make some room here. So it's clear. Okay, then we take the if condition. So print day. If course equals typhon, I'll copy that. Tasted here. If course equals bison else print to be okay, and that's it. So I'm going to get rid of this code. Save it running. There you go. Enrolled in part. Of course. If I change this to Java, save it, run it. Enrolled in some other course that works as well. Okay, now let me paste in the code that we had seen before from our example with made payment we had this piece of code right here. So made payment was true. And then we had a and B if not made payment. Print a l sprint Be so we can do the same thing here. We'll get rid of this and simply say print day if not made payment else. Print me if I save it. Run it. Welcome to your home page since made payment is true. Okay? And this logic, I can change the ordering off it without using the not and simply checking for mai payment . I can say print be if made payment else frente on both of them should say Welcome to your homepage. There you go. Perfect. And that concludes our look at branching with FL statements condition ALS and Julian's. Hope you enjoyed it. We're going to use branching quite a lot in this course, and it's pretty much a staple of programming since it allows us to control the flow off our programs. Okay, great. Thanks for watching. And I'll see you in the next video. 14. Lists, dicts, sets and tuples - Intro to compound data types in Python: Hello and welcome back in this video, we'll take a look at compound data types in Piketon, represented by lists, dictionaries, two pools and sets. In the last few videos, we've been working with strings, integers and floats, and these are known as scaler data types. They're basically one object you see. An INT is a number, Ah string, no matter how long, is one string. So these are scaler lists, dictionary sets and two balls, on the other hand, are not scaler. Their compound data types made up off collections off elements so you could have multiple strings. Integers, floats, functions, other lists, dictionary sets. All of these could be part off a single data type. That's what makes them collections. And I've listed out some tools in the bottom here to work with compound data types, things like it aerators four loops while loops and other helpful functions. And we're going to explore what their individual characteristics are and what separates them one from another in the upcoming videos. But first, let's take a look at what they look like, and we'll start off with lists, and this is what a list looks like. You have an opening square bracket and clothing square bracket and everything within it is part of the list. And each element in the list is separated by commas, and the elements themselves can be comprised off various data types themselves. Here I have integers, I have a boolean, I have a string, I have the non type. I have a custom object I'm referencing as a node and also have a float, and you could also have other lists part off the list. You could have dictionaries sets to pull all of them part off a list, but for now, let's keep it simple and deal with these types. So let's take a look at this in our editor. Here we go. I have a list defined here. I'm referencing it with variable called my data type, and right below it, I have print my data type so it's gonna give me a printout of the list, and then I'm gonna print out the type off my data type. And what's dictating this to be a list are the open and close square brackets and in terms off node one without discussing what a custom object is and how we can build one using classes. I didn't want to get into all that complication right now, but for simple demo purposes, I've just named it a string called Custom Object. All right, so let's bring this out and see what happens. There we go. You see, my list is printed out, each off the elements are shown here. And then it says class list as the data type. All right, and one of the key features off lists are how you access elements in the list. A list is an ordered collection off elements and each off the elements are indexed. For example, this number one this ain't one is at index zero. This one is that in next one. This one is that index two and so on and so forth so you can access any element in the list based on their index number. Let's say I wanted to access the string mature. What would I do? It's that index 01234 So what I can do is instead off referencing my entire list. I can put in square brackets, so that's the notation. And then put in the number four. Let's see what that does if I run this. Now you see the element at index four, which is my sure, all right. And as I mentioned before, we're going to look at other operations and how we can work with lists later on an upcoming videos. For now, let's move on to the next data type. And next on our list are dictionaries and this is how dictionaries look. You open with a curly brace, open curly brace and then you close the dictionary with a clothing curly. Brace the elements within dictionaries. This particular dictionary has two key value pairs. They're separated by this comma. So what I can say is my dictionary has two key value pairs. They don't come as individual items and this is what they look like. You see, for this first key value pair, the key is name. And then the value is mature and they're separated by this colon. In the second key value pair. I have my key as course, and then my value for the course being python separated by the colon and the keys can be other data types. Here I have chosen strings. You can also have inch as your key, but what you want to ensure our that your keys are immutable data types. OK. List, for example, are not a good key to have because they can be changed. So you want the keys to be stable. So let's take a look and dictionaries in our editor. So I'm gonna paste it. A dictionary over here, Command V. All right. So here I have several key value pairs. I have my keys as integers. 12345 And values strings a nun type and our custom object and afloat. All right, so let's bring this out. I'm going to remove this indexing notation. There you go. There is my dictionary and you see it says class dicked. That's the dictionary type. So dictionaries, unlike lists, are not indexed. Okay, So to access an element in the dictionary, let's say I want a value. I would have to give it the key associated with that value. For example, if I wanted to get the Valium assure, you see, the key associated with that is to So what I would do is within square brackets. Put in to all right notice. Since this is an integer, I'm putting in an interview or too I'm not putting it as a strength. So if I run this now, you see, Assures, returned as we expect now, the ordering dictionaries used to not maintain their order in the past, but starting with Python 34 I believe or 36 I'm not hundreds ensure dictionaries now maintain order. So if I keep printing the dictionary again and again, the same order that I created it in is going to keep showing up. See, every time it's the same ordering. All right. Now let's move on to the next data type. So next on our list or sets, And if you look at the set opening and closings Carly braces, it almost resembles dictionaries, right, because you have opening brace and closing Carly race. But sets are not key value pairs. You see all of them are individual objects, and they're separated by commas, so they kind of look a lot like lists. Except for there are some differences, which we're going to explore later on. And also, of course, the notable difference off having Carly race instead off a list square bracket. The one fundamental difference that we can actually talk about now that separate sets from list is that sets don't allow for duplicate values. Let's take a look at this in our editor. Let's take our list and then paste it here over here. And then let's change these square brackets to Carly braces. So that's what converts this to a set. But notice I have the individual a one. Then I have another and is your one. If I run this right now, over here, you see that on Lee one into your one has shown up on Lee. One instance of this. The 2nd 1 is not here. So sets get rid off duplicates, and this is a very useful feature. Offsets. So if you have ah, big list, for example, and you want to just get rid off all duplicates, you can simply cast it to a set. And you're gonna end up with all the duplicates removed and you see the class says set. Another thing that's unique about sets is that there's no ordering. Not only is there no indexing, but there's no ordering either. If I keep running this see every time the ordering is different. First time I sure showed up over here. Second time over here custom object was here. Got some objects there, so there's no guarantee for ordering every time it's gonna be random. And because of the new ordering and no indexing and also not being key value pairs. There are different ways off accessing elements in a set. For example, he could loop through, print out the values, perform comparisons, etcetera. But sets are used for other optimization is, and we're gonna explore them later on. Let's now move on to the next data type, and next on our list are tools. And if you look at the to pull notation, they start with open parentheses and end with closing parentheses. And they're very similar to lists. And they behave very similar to lists as well, with some notable differences being that two bulls are immutable. Unlike Lis, you can't change the value off an element to be something else. So let's take a look at them back here. To convert this to a triple, I need to change them to parentheses, opening and closing parentheses, and then let me clear this up. It was getting a little flattery. There you go. So there is my to pull. You see, it shows up and it says it's class to bowl and the elements in a two bowl are indexed and they maintain order. You see, every time it's the same order off elements. And also, if I access an element, I can index into it. So let's say I want the nun type, which is 012345 So if I do five and then run this There you go. I get the nun type. OK, so the interesting thing about two polls that's different from the other ones is that it is immutable. Let's say I tried to reset the element at Index five. So I'm going to copy this command, see, and then try to reset Element there said it too. Let's a python save it. If I try to run this, you see, to pull object does not support item reassignment. So two bulls are immutable and that makes them very useful. All right, so there you have it. Those are the collection types that we're going to explore in the upcoming few videos, hoping enjoyed this introductory look at collections which are compound data types and python. Next, we're going to dive deeper into each of these, starting with lists. So you there 15. Lists - an in-depth look 1: Hello and welcome back in this video, we're gonna continue our look at compound data types and focus on lists. Let's take a look. So here I have to List declared. The 1st 1 is a list of integers, and the 2nd 1 is the list off strengths, and obviously they don't have to be this way. They can be composed off other objects, but I have them listed here for simplicity as we work through this video. So what are some of the things you could do with lists you can sort the values in ascending or descending order? You could find values in the lists or details about the list, things like how long the lift is etcetera. You could insert or remove values from the list, including inserting other lists or other data types. You could grab sub list from the list to work with, for whatever requirement that you're working with and you could literate through and perform. Functions are checks as you look through each and every item. All right, so let's formalize this. These are some of the functions or methods that you could be working with. We're gonna look at the sort method and then the sword head function, and this will be nice. Prep for our algorithm sections is the first part of our algorithm sections. It's focused on sorting for finding values in the list or finding information about the list. We're gonna be working with Len men Max in for finding than we look at indexing, slicing and count for inserting and removing. We'll look at the upend method along with insert, extend and remove Pop for working with sub lists were and look at slicing and then in place and copying off lists. We're gonna look at this in combo with sorting simply because I want to cover what in place is forces working with a new object off the list and we'll see what that does. And for iteration, we're going to see a simple demonstration, often generation a four loop that we can use. But we're gonna cover that in a separate video all by itself after we've looked at some of the other data types, like dictionaries, two poles and sets. With that in mind. First, let's take a look at the documentation here we are in my part in standard library reference . If you scroll down to build in types. Scroll down to sequence types list to pull range if you click on it. Here is a good starting point to look at functions and other information that you may need to get started with lists or just look for reference. Okay, so now that that's out of the way, let's jump right into the editor and start working with them. Here we go. Here is a star, a script that I have. I have the interest your list defined. The order is shuffle so I can sort them to see the effect of Thorning. I have my strings list. I have to print outs for the list as they are, and then a couple of other prints right here to display what the list would look like after what I were function, we perform on them. If I run it right now, the initial list and the sorted list looks the same because we're not performing any sorting. All right, so let's first use the sore Ted function. And here it is sore Ted, and this function requires the objects to be passed in that you want to sort so my list and the other thing to note is that this function does not sort in place. For example, my list object that I have that is this list. It's not going to sort that in place. For example, if I run this as it is right here, you see, it's still not sorted. So in order to get and view assorted list like this, you can either do print over here. Actually, I'm gonna copy this and then paste it under sorting right here. If I run it, There you go. You get the sorted list. The other option is you can basically grab another valuable, say sorted list equals and then sorted and pass in my list. And then I don't have to do this anymore. What I can simply say is sorted list. Okay, there you go. Let's run it. Perfect. There is my sorted list. OK, now let's look at the sort method and the sort method is actually going to sort this list in place because it is a method. It will run on this. My list object. What am I talking about? Let's take a look. I'm going to say my list don't sort open close parentheses and Now, if I run this as it is, my list is actually going to be sorted. And then this print, which has been printing the unsorted my list, will actually print the sorted list. Offense. Let me run this year. There you go. My list has actually gotten sorted. It's up, OK, and if you're wondering what I meant by method versus function because I was referring to sort as a method but sore 10 as a function, we're gonna discuss that soon, but for now, notice the difference in how these methods or functions were called my list dot sort. So this sort method ran on my list object that I have here, and that is a giveaway, that this is a method when it runs on an object to that you're providing sorted. On the other hand, you see, there are no docks before it, and you also saw that Sorted did not sort my list in place, and I had to provide my list as an argument for my sorted function. So that's a giveaway for functions, and we're gonna cover what that means in detail in a later video. But for now, just know that sort sorts in place and sorted does not. And if you actually wanted further details off this you see, I have this sorted list If I print the I d, which will give me the memory location for this object in my computer. And I also print out the i d off my list, my list, then you see, that's different. But this I d will be the same as my my list right here because it's the same object. So I'll print my i d off my list before I perform the sorting. I save it. I run this. There you go. You see, there is my initial i d off my list, and that is the same as after I performed the sort right here. See, these two into your values are the same because it's in the same memory location. However, this one this is the I d off my sordid list, and this is different. Then my list. Okay, so that sorting. Now, let's take a look at finding information about the list and working with it. So I'm gonna get rid of all of this. Andi, that is well, alright. Instead, off sorting, I'm going to say finding involved. So let's start with seeing if physics exists in my strings list and we can use in for that . The way to do that would be print. I'll say physics the strength in my strings list. If I do that and then run this you see it says True. Okay, so physics does exist in my strings list. Similarly, I can give a number, Let's say 35 and make this my list So that's 35 exists in my list. True. How about 50 False? Okay, so that's a good way of finding if an object or value exists in the list. However, what if you want to actually find the location off that object in your list? So back to physics? How do we find out where in our list physics exists? Let's take a look. I'll move this and say my strings list dot index and within parentheses. I'm going to say physics, huh? If I do that and then run it, let me clear this up first. There you go. It gives you the index where physics exists. So index off. One. It's physics, and if you remember, index starts at zero, so in X one is physics. Great. Now what about the length off my lists is a function you're gonna find yourself using quite often. And to do that we use the l E N function. So if I say L e n and then my list, save it and then run it, you see nine. That means I have nine integers in my list. What about my strings list? 41234 There are four elements in my strings list. Great. So let's say you wanted the value off the last element in your list and you wanted to use the land function. So in terms off our integer list, that would be nine. But if you look at our list 10 is that index eight. Since indexing starts at zero, if you're gonna use Len Tau, find an index, you have to subtract one from it. So I'll say my list, then length off my list minus one. Okay, so that's gonna give me the length nine minus one index age and that should give me test. I run this. There you go. There is 10 but you can also index it directly into finding the last element in your list. And that's simply by using the index off minus one. I'll also give you 10. There you go. Okay. Let me clear this up. Okay, let's take a look at a couple more functions and methods that we could use on our lists. What if we wanted to find the main value off my list? Over here, I can use the main function, so I'll say men and put my list within parentheses. Pass it in as an argument for my main function. And if I run this? There you go. It found four, which is the minimum value in my list. What about the max? Similarly, I can say max 35 which is the maximum value in my list and for the strings list. Strings compare in alphabetical order based on asking to values. So physics is going to show up for Max and for men. You're gonna get calm. Size and C is the earliest. If you look at this in alphabetical order, okay. Moving on to the next function. If you actually want to see the methods that are available to your object or your data type , what you can do is use the D I R function. So if I say d I r and pass in my list, which is a list object, and run this, it's going to give me all the built in methods that are available for lists. So we've used some of these already, and we're gonna use some other ones as well. Let's take a look at count. If you had, let's say another instance off 15 in your list and you wanted to count to the occurrences off 15 in your list. Then you would simply say my list count and then the value you want to count occurrences off. So if I ran this There you go. There are two occurrences of 15 in my list. OK, now we're gonna move on from finding in folk to adding and removing info next. But we have covered a lot in this video already, so we'll stop here and continue in the next one. So you there 16. Lists - an in-depth look 2: Hello And welcome back in this video, we're gonna carry on where we left off in the last video and start with adding items too, and removing items from lists. So add room move and the three methods we're gonna look at our upend, insert and extend, and I'm gonna paste them in Over here. There you go. Let's take a look at how they work. Starting with a pent. So upend simply adds the element you want to add to the end of the list. So if I did my list dot append and let's choose another number 25 then this will add 25 to the end of my list and printing this will simply return none. So I'm gonna print this in the next line. My list. Okay, let's run it and see what happens. There you go. 25 has been appended to the end of the list. Now, if you didn't want to appended to the end of the list but you wanted to upend somewhere else, then you can use the insert method With the insert method, you can provide the index and then the item you want to upend. So instead of upend if I used insert and let's say I want to insert somewhere in the middle over here. 0123 How about at Index four? So after eight and before 35 which isn't next four, I want to add 25 to index four. And if you see here in my information first, you provide the index than the object. If I run this, there you go. 25 has been added after eight and before 35 which is exactly what we want it. OK, now let's look at extent, which is the third method over here and for extend. I'm going to paste in another list. Here we go after my strings list. I'm going to based in this new list, and it has values, art and economics. So instead, off my list, I'm going to use my strings list. And over here, instead of printing my list, I'll print my strings list. Okay, so what happens when you use append to insert a list into an existing list? So if I do upend over here and then append my new list, let's take a look. You see this list? My new list gets appended as a list within my list. So if that's the functionality you're looking for, that's great. Are a lot of times. That's not the functionality that you're looking for. You simply want to upend the items that are in your list to the list that you're looking to upend, too. So in that case, what you want to do is use extent if you use extend here instead of a pent and do the same thing you see at the end instead of inserting it as a list within a list. As was the last case, it simply upended the two elements off this new list to my existing list. All right, so that's the difference between extent Onda append and it's very useful when you are adding lists to existing lists. Now let's look at removing values from our list, so I'm going to paste in the two methods. We're gonna look at what has popped and one is removed. So from my strings list, let's remove a value. Let's say we remove Kansai, then I'll say, calm, sigh. Okay, if I do that and run it, you see this list now does not include Kansai anymore. It's been removed from it. But this doesn't return anything. For example, whatever you're looking to remove just simply gets removed from your list. If you actually wanted to do something with the value you're removing that you can use the pop method. And if you do provide this value, let's see what happens. You got an error. Okay, so for pop, the laid works is you provide nothing at all, and it simply removes the last object in your list. So in our case, philosophy is gonna be removed. Let's run it. There you go. You see, philosophy has been removed and pop actually returns what it removes. So if you print this out, then he will actually print it. You can also reference it using a variable if you want to work with it. So if I run this, you see, it prints out what it pop, which is philosophy. Okay, great. The next thing I'm going to look at our working with sub lists. So when you say sub lists over here, which essentially means looking a little more at indexing and slicing. So for that, I'm actually gonna based in the indices for this list. Over here. There you go. So it's easy to reference where the indices are for all the elements in my list. I'm going to remove these and I'll change this to my lift since I'll be working with the injured your lists. So you saw how we were able to access the last element in our list simply by providing the index off minus one. So minus one. Give us access to the last element in our list. And what if you actually wanted to update that element, which is 15 in this case? What if you wanted to update it? Then you can directly index into that element and change it. So what? Aiken Dio right here. I can say my list index of minus one, and I could set it to, let's say 1000 if I did that mean clear this up and run it. Now the last element is 1000 and you can do it for any of the other indices to you can you can look at the value you can update the value and so on. Remember, lists, as we saw before, our mutable. And all of this is happening to the same list without actually being copied over to a new list. Now, that may not be the results you're looking for. Especially when you are working with algorithms and stuff. You may be working with some lists. OK, so for that we're gonna use slicing notation. So I'm going to get rid off this over here. And if you look at the index index at minus one is the last element. What about the element at index four? If I run this, you see, it gives me 35. So what if I wanted to grab old elements from the beginning of the list to this element? Then we can use slicing. So I'll start with zero as the first element beginning of the list and then colon, and then I can give the index off where I want this to end. However, this stop index is not included in the slice. So if I run it like this, it's gonna grab 15 67 and eight, and it won't give me 35. I run this. Check it out. 15 67 and eight didn't give me 35. For that to happen, you have to actually include the stop plus one as the index. So in order to grab up to 35 I have to go from 0 to 5. If I do that, check it out. It grabs half of the list. And when you have the first at zero, you don't actually don't need to provide it. So just Colon and then five will give me from the beginning to this element. OK? Similarly, if I want to go from the index off five, which is 12 all the way to the end of the list, I can start it at five and then leave the last one empty. If I do that, check it out. 12. All the way to the end of the list. Okay, let me clear this up. And then what if I remove five and put a Poland so beginning to the end? Okay, So colon and Colon, if I save this and run it, it gives me the full list. But when it's something like this, you can also just put one colon beginning to end. It will give you the same the full list. Okay. I'm gonna leave it as beginning to beginning and end The last item you can provide to your slicing notation, which is optional, is a step size. So if I give a step size off to by default, it's one. Then it's going to grab every other element in the list. If I run this, he grabbed 15 7 35 14 and 10. So it skipped every other element since I gave step size of two. Okay, so now I hope the minus one is becoming clearer because what this is saying is go from beginning, beginning everything and everything, and then step size off minus one. So you're starting at the last element and then moving back by one and displaying it. So that's why if you do that, you get a reversed list. And of course, you can also use the reverse method for this and get the same result. Let me clear this up. Actually, I had this done in my print, and the result was none. But you see that my list got reversed over here. Okay, so reversing the list would be something like this. Then I won't get the non. There you go. All right. So that's a lot we have covered in this video in terms off functions and methods that we get used on lists, and it was very important to go through in depth on lists because we're gonna use them a lot when we build our algorithms. One of the big items we have not covered yet is it oration. And I mentioned at the beginning of the video that there will be a video on it after we finished looking at other data types. But for now, let's take a look at the most basic for loop to iterated through or loop through all of the elements in our list and simply print it out on the way to do that. Is this When you remove this and say four, that's the key work to start a four loop and I'm gonna put a variable name. I'll say, I don't in the name off my list, which is my list, Colon. I simply want to print the item, but remember, this is a code block. Therefore, I have to tap this in. So what I'm saying essentially is look at my list and jittery through each item, and as you're looking through each item, reference them with a variable name item. So the first time The variable item is 15 next time with six. Next time in 78 And so long. And as I'm looking at those items, I'm printing them out to the screen. So if I run this chicken out, each of the items got printed out, okay? And we're gonna look more in depth at working with four. And while loops later on. Okay, great. Hope you enjoy this in depth Look at lists and how to work with them. In the next video, we're gonna look at working with dictionary sets and two poles, so you there. 17. Dictionaries, sets and tuples: Hello and welcome back in this video, we'll look at other compound data structures, which are dictionaries, sets and two pools, and we're going to start off with dictionaries. And here are some examples. All these three are valid dictionary structures. You see, they all start and end with Carly races, and within each one you have key value pairs separated by comments. So in the first case you have keys off, name and course, then the values associated with them name having the Valium assure course. Having the value python In this phone Dict dictionary, I have the key value pairs listed in separate lines, with the keys being the names and then the phone numbers. And then I have a work addict basically trying to resemble dictionary with the words, starting with a listed within a dictionary in the original dictionary, and then be, and so on and so forth so you can have other data structures as values for your keys within dictionaries on this can keep investing like this. One thing to keep in mind is that the keys right here? I've used strings as keys for all of these. The keys have to be immutable data types, so strings are a good option, as are integers, and those are very widely used as keeps and dictionary data structures are so popular. And you so frequently, in fact, that in the algorithm section in this course will build our own dictionary data structure from scratch. That's right. And here's a quick look at what that's gonna look like. Here we go. We're gonna investigate what goes on behind the scenes and build a structure all by ourselves based on the functionality off a dictionary or, ah, hash map. And it's gonna have the optimization that come with a dictionary data structures such as the fastest search and retrieval functions which are done in constant time or in one operation. But for now, let's look at some basic functions of dictionaries and start off with the three that we were looking at before. Here we go and you see that base it in all 34 months that we were looking at before she wanted to print a dictionary. I can simply say print my dictionary, the name of it, and this will print out the whole dictionary. So if I run this, you see, it prints out the entire structure. And for the structure we have year, it'll still print it out in this format. So if I printed this instead, you see, the format is back to key value pair. Even though we have all this white space in here, it just ignores that. Okay, so how do we retrieve a value associated with a key in a dictionary? For example? In our word, Dick, I have the key off a and all these words associated with a So to get all the values associated with a I can used a square bracket notation and provide the key. And if I run this, it gives me the two key value. Pairs are elements that I have associate id with this key, and I can do the same for the other key. So if I say be and run it, There you go. It gives me the words associated with B. Now, what if I wanted a specific word within B So the meaning of the word business, for example. Then I could put another square bracket after the initial one and give the keys off business. And this will give me the value associated with business, which for us is the meeting. So if we run this season eight off bot, okay. And then we can combine values so I can put a comma in here and then print out another one . Let's say I wanted the first key. So be And then the value associated with bad. If I save this and then on it, you see season eight of G o t off. Poor quality or low standard. Okay. So you can see that you can get values this way. Another way to get values is by using a method. Let's use our first example for this. So I will change this to my dictionary. Okay. And then if I put a dot You see, it tells me all these functions that are available or methods associated with the structure . So how about get if I put get and then the key so name it will give me the same result. There you go. My sure it gives you the value associated with name. Now what if I provide a key? Doesn't that doesn't exist? I can say job. Save this and run it. You see, it just says not. It returns not OK? Because it doesn't exist. Okay, I can also said values for my dictionary. Let's say I wanted to add a job here. Then I'll move this down and what I can say is my dictionary. And within square brackets, I'll say Job as the key and I will set it to I thin programmer If I do that and then I print my dictionary. Don't get job. This should work. Let's run it. There you go. It returns parts and programmer and you'll see if I print the whole dictionary at this time , then the job has been added. There you go, job Barth and programmer. Similarly, I can update existing values. That's I wanted to update the value associated with the key off course to be Java. Then what I can do is say course Java. If I run this now, you see course has changed to Java instead off python. Okay, so those are some of the basic operations. Let's run some additional methods than to get rid of this. Okay? My dictionary. If I do dot The keys function right. Here are the keys method. This will give me all the keys that I have in that dictionary. So if I run this, I'm gonna clear this up. Check it out. It just lists out the keys, name, course and favorite food. Similarly, I can do values, and this will print out all the values. Assure python and ice cream. Okay. And then I can use this items method. And this will list out all the key value pairs name and mature course, and Pathan and favorite food and ice cream. And these are actually listed out as two bulls, which we're going to explore soon. So in terms of federation will cover this in depth later on. But for now, let's use items that we use here, since they are key value pairs and list them out and we'll run a simple form. And the way to do that wouldn't be four kcom, Avi. And I'm gonna use these as two variables for key value pairs. I can just have just cake because that will give me just a keys. So two values, therefore kv in my dictionary dot items and put a colon. I simply want to print K and V if I do this. And if I run it There you go. Name mature core Fothen, favorite food, ice cream, and we'll explore Maurin depth as to why we're used items here in the Generators video. OK, so moving on to two polls, I'm going to paste in a couple of two poles here. There you go, and two polls are very similar to lists, except for a couple of differences there. Immutable, which is the most important thing for them. So you can't change a triple once you have assigned it. And the other thing is the visual difference in how you create them, using parentheses instead off square brackets, which you would use in list. But beyond that, other than mutability related functionality like ads, updates and removes to oppose, behave almost the same as lists. For example, you can index into your two full so I can say print my let's say, random to pull and get the first element are using the index off zero fire on this. You see, it gives me the first element here. Similarly, I can get the last one minus one. There you go, and I can slicing and get a reverse view off, My truthful. So there you go. We get a display off the triple reversed so you can see very similar to list. OK, now let's look at some methods available to them. If I go here and I'll print out de IR to list out all the methods, okay, the methods below count and index you see significantly lower amount of methods building methods that are available simply because off their mutability so you can't change values, which you can do with lists, which allows for a lot more functionality. But we can still run some basic functions on them and methods. Let's take a look. For example, if I wanted to know how many elements there are in my pupil, I can run the land function and you see there are 16 elements in this random trouble. I can also run methods on them. For example, if I do dot and then I can count the occurrences off a specific element. For example, five. I have multiple values of five in my triple, so I can use that you see two occurrences. I confined the index associated with a certain element. For example, if I wanted to find the index off hi there and where it is in my two full. I can do that. It will give me the index, which is seven now. One of the things one of the most important things associated with their mutability is actually very useful when passing values. You don't want to be changed. For example, functions in python When they return multiple values, they returned them as two bulls. I know we haven't covered functions yet, but let's take a quick look at that. Here is a function, and if we scroll down this function returns three values at the bottom here, start time, duration of job and job name. And this is a function we're gonna build toward the latter part of this course for jobs. Kathy Lohr Project. And these three are returned out of this function as a to pull, and it's returned to whoever or wherever in the program we call this, so if I scroll down, this is the line where we are calling that function. And since it's returning a couple three values, I can actually unpack the triples and the three values over here using this notation and use them. So let's take a look at this in a simpler way, since there's a lot of clutter here. Over here. You see, I have this to people that has these three values in it. First value, second value and third value. What I can do is, say, first of our second bar. And it could be whatever you want to call this. These are variables equals my trouble. And if I do this, what it does is it assigns forest value to first far second value to second bar and third value to third bar. Then I can do whatever I want in my program using these variables. Okay, so here I'm just printing out third bar, which should give me third value. There you go. So this is an example off to pull on packing, basically unpacking the values in your tool for your use now to other important things in terms off getting information from two poles you can use in to find values into bull, for example, I can say first in my random truthful And if I do this you see, it says true because the string first exists in my random to pull and then for Iterating through to pull, we can use the simple for loop for item in my random to pull print item. So the same thing that works in our list works here as well. It lists out all of the elements in my trouble. Okay, great. So we're gonna move on to looking at sets and sets are a non ordered collections, off elements. Let's take a look. Going to paste it in. There you go. Okay. Signified by the opening curly brace and then the closing curly brace. And within it, we have all the elements listed out, separated by commas. And remember, sets are on ordered. So if I print my set and save this and let me clear this up, let's run it. You see, it lists out the elements in my set, but not in the same order as I've listed here. And if I run it again, you see a different order, and every time the order changes, Okay, So because of this, a northern nature offsets, you can't index into any of the elements like lists or two bulls. Another key feature offsets is that you cannot have duplicates. So if you had a situation, let's say where you have an additional six over here and then print out the set, you still get only one occurrence off. Six. It just discards the duplicate six. And this feature of sets can be very useful. For example, if you have a list, I wanna paste it in over here. I'll pay. Sit right here. Okay, So I have a list like this, and then I have a print function printing out the list. If you wanted to discard all the duplicates are, get rid of them here. You see, I have a couple of sixes and a couple of jobs as you want to discard duplicates. What I can do is cast it to a set and say, Let's say my set is set off my list. It's simply converting it to a set. And then let's print out my set. Save that if I run it. You see, the first instance is the list with the duplicates. The second instances, the set has removed all the duplicates. Okay, so that's a very useful feature. Now, sets are optimized for two things. One is finding information in them. So I'm gonna get off this list stuff over here, Okay? If I want to find information in my set I can use my in notation so Java in my set If I run this me clear this up, check it out It says true. And this, while available in other data structures as well is highly optimized. It sets and the other things that are optimized and sets are mathematical operations. So if I look at my set and then put a dot in there, you see these methods union intersection difference. These are all mathematical operations. But let's explore three over here and I'll pay. Start in. There you go. And to a floor, these mathematical operations, I'm going to put in a new set over here as well a different set programming set with a list of programming languages here. And let's run this to see what it does. Whoops. I haven't saved this. I'm gonna save this. First, it's run it again. Okay, The 1st 1 intersection off my set with programming set gives me the three elements that are common between the two sets and you see Java. Ruby and python are in both sets, so it gives me ruby, java and python. The 2nd 1 is my set union with programming set, and that is all the elements off my set and all the elements off programming set put together, including common ones. But again, you're not gonna have any duplicates. So you see, old elements this out here between the two sets and the 3rd 1 is the difference. My set difference with programming sets old elements that exist in my set that don't exist in programming set. Similarly, you could reverse this order if I instead make this programming set and the difference with my set. Then this is going to list out all off the elements that exists in programming said that don't exist in myself. We're on this. You see, It's javascript and C because programming said has JavaScript and C which don't exist in my set. So those are some of the key optimization in sets associated with mathematical functions. And the last thing we're gonna look at is to reiterate through a set, we can use our simple for loop for item in my set. Let's print the item, but I clear this up and running. There you go. All of the elements from my set printed out, but not in the same order. Okay, so that concludes our look at sets and that dictionaries and two bulls and some of the features associated with them as well. Hope you enjoyed it. Now that we've covered all of these compound data structures, we're going to move on to it. Aerators and four loops. And why Loops starting in the next video. And if you look at our crash course syllabus, we're making some solid progress. Hope you're excited. I'll see you in the next video. 18. Iterators, for loops, generators, list comprehension: Hello. Welcome back in this video, we're going to look at iteration with four loops and generators. You have already seen how to print out each element in a list or a dictionary. The key value pairs are using a simple for loop. So let's look at how we can use a for loop to give me the some off all the integers in this list. How would we go about doing this walk? We can start a variable. Some set it to zero to start, and then we can simply iterated through each element in the list and keep adding that to are some so I can say four numb in l some equals whatever the sun was before, plus no. Okay, so let's look at what this is doing. I'm setting some things here. Also initially Summit zero, then four numb in. L basically says Iran a four loop in this honorable right here, which is L with us. My list and the first time Numb is going to be six. The second time I'm is going to be eight. The third time I was going to be one, and it's gonna keep going till it gets to the last element in the list. So some in the first case zero will be equal to some plus numb some which was zero plus numb, which is six the second time. Some equal someplace numb. So some is six plus numb, which is this time eight. So that's 14 3rd time, some is 14 plus numb is 1 15 and so on ill go all the way to the end. So this is how you might be able to get the some of old injured your values in your list and to print this out, I'm gonna print this out outside off my for loop block so it only prints out after liberation is complete, I can simply say some using list and then the some. Okay, I run this some using list 63. So that's the value off all the integers in my list Added up. All right, Now, what is a different way off running and adoration, for example, this one is running on this miserable, which is our list. We don't really have to use an honorable to do this. For example, we know our list has 11 elements. I can run. Ah, four loop all I'll need to do is provide an honorable that has 11 numbers in it or potentially 11 numbers in it. How do we do that? We can use the range function for this arrange function is a generator that gives you an object that you can iterated through, and the race generator is a quick way to generate numbers. Let's take a look at how it works in the console. Over here, I have a new tab open on the side, and I have my Python consul going, and the way to use it is, let's say range and then I'll give it a number. This is going to give me a range object between zero and 10. This is simply an object. This is not a list off numbers to turn this into a list. What I can do is cast it to a list, so list and then range 10 and you see it gives me 10 numbers between zero and nine in prior versions off bison. If you did just range 10 it would give you the list of 10 numbers, but that's no longer the case, all right, so if I save this, let's say my list equals underscore on my list, and this is a shortcut. Just so you're aware and basically says a sign in whatever value I had in my previous line in the console. So this essentially means my list equals list arranged him. If I look at the type off my list, you see, this is now a list off 10 numbers. But if I look at the type off a range 10 you see it's a class range, which is a generator, and it's important to distinguish the tooth and we're gonna look at more generators later on. So, you see, we were able to generate this list off numbers. If I used this functionality here, I can say for numb in range 10 which is what we used here. If I do print numb, and if I run this, let me call this out. Check it out. It gives me the 10 numbers, all right. So instead of printing out each number, what I can do is perform some function each time I can. Instead of printing out the number, I can just say for him too low. What does that do? It'll simply print out Hello, 10 times. Similarly, you see these starting at zero, going all the way to nine, see how easily they fall into the indices off my list. For example, zero is the first element. One is the second element, and so on and so forth. So I can easily use this to reference each element in my list at every adoration. And if I did that, then instead off saying print Hello, I can say print l, which is my list name at number, which is my index. If I do that, clear this up, let's run it. You see, it gives me the same result off all the values or elements in my list, as in this case. So if you wanted to grab the 1st 5 numbers, you can say range five. And then if I run that you see it grabs the 1st 5 numbers. So if I were to use a range to find the sum, then I would need to know how many elements are numbers there are in my list and that you know, I can get using my length function. So if I do Len off l that essentially saying range off. However many elements I have. I think there's 11 here, So range 11. And instead of printing the value at that element, what I can do is use this notation to calculate the sum. So some equals sum plus l at no. All right. And I'm gonna have to reset some here simply because I'm working with the same variable. Some here. Otherwise it would just add on on top of it. So after I do that, let me print out this value. There you go. Some using range generator, and then I will uncommon this some using list. Okay, if I run this, There you go. We get some using lists. Amusing Rain Jr. 63 on both occasions. So this is something you will find a lot in code because you may not have the list or values pre defined. Let's say you're asking the user for input than the user is going to provide that number, and you may have to run something that many times, so you will not have an honorable like a list. To do that, you may also need to deal with half of the list or perform some function using only half of that list then this is very useful and we're going to see that in the algorithm section. Now, one thing I want to point out is some equals sum plus numb. This notation is very common and use all the time where you're implementing the value off of variable using its existing value. You can write the short form for this and basically removed this part and simply say some plus equal to numb. Same here, some plus equal to l at. Not if I save it and run it. You'll see the same results. Perfect. Now back to what I was saying about not knowing how many times you may need to run something and we're going to see this in our algorithm section as well in the project where we asked the user how many times we want to run a performance test in that scenario going to get the input from the user and this is what it's gonna look like. I'm gonna get rid of all this. There you go. So I have this variable run times equals in value, and I'm asking the user for input. How many times do you want to run the program? Let's say. And the way you would do something like this is you have this run times available to you. So for numb in range run times, you can say print F run number and then provide the number. But one thing that's gonna happen here is that run times range as we saw Ghost from zero to the number here, not including the stopping index. If you're trying to show the run number like this, you're going to start with zero and you don't want to have around zero. So I'll just add a number plus one. Good. And if I run this code, how many times do you want to run? Let's say five. There you go. Run! 12345 If I did not provide this plus one, then it would start at zero and go to four. There you go. You don't want to have a situation like run zero, because that doesn't make sense. Okay, Now, before I move on to working with the dictionary and entering through it, I want to mention something else about the range function or the range generator and how it works. So far, I've been providing it. The top value, and the start value has been zero every time. But you can provide the start value as well, so you don't have to use the default zero. For example, I'm gonna go to my five console instead off doing range. 10. What if I started at zero and went all the way to 10? And, of course, I have to cast us to a list to rent it. If I do that, see, it goes from 0 to 9, but this is done by default. Now I can change that and say, instead of going from 0 to 10 go from 1 to 11 then you see it starts off at one instead off zero. I can also provide a step size as the third argument to this. So let's say 1 to 20 and then step size off, too. So print out all the odd numbers between one and 20 and you see 13579 11 13 15 17 and 19. So ranges you can see is a very useful and powerful generator and is used in a lot of places in Python. Okay, so now let's move on to working with this dictionary. I'll go back to the other screen in my terminal. Set this up. All right, so we use the items generator before in order to generate through in our simple for loop for dictionaries. Let's see why we did that. Okay, so if I do four item in my day, it let's say and simply print out the item my dick to remember is my terrible in this case , which is the dictionary. If I ran this, then you see it on Lee gives me the keys high R b and Js. So that's why we used my dicked, not items. Because if I print out my dicked dog items, then you see we get this terrible off dicked items for each key value pair in my dictionary are turned into a triple. Therefore, if I take this honorable and place it in place off just the My Dict Dictionary reference. So now we have this honorable that has these key value pairs for each of them. So if I save this and run it, then you see, I get each off the troubles. So pi Pothen, RB, Ruby Js and javascript and each one is a two people. I remember from our video where we looked at troubles, we can unpack troubles. So if item is a two bowl, then we can say key and value equals item, and then I can print out He is okay. And then value is value. Right? And this is an F strings after you put the F in there. Okay, if I did this, see item at each time being the to pull key is going to get the first item in the to bowl and value is going to get the 2nd 1 If I ran this, check it out. I'm able to use the key and value separately. And instead of doing it here like this, what? Aiken Dio is simply copy these two and do the unpacking in this four loop itself. All right, so then I don't have to do it here that way. I have access to the key and value right away. I ran this. Now check it out. Same thing. Perfect. And you will only be able to do this, which is unpacked to pull values like this when you have unendurable. That's actually giving you two polls as the object. And if items actually gave you, Let's say to pull with three values in it, then you could use something like this. You could actually unpacked the 3rd 1 as well. But that's not gonna work in this case, because we only have two values in our trouble. Okay? And the last thing we're gonna look at in this video is we're gonna take a look at list comprehension and how that works. So let's take a look at our problem statement were after generate 100 random integers between one and 100. Now, when you're presented with a problem like this, you may be tempted to write a for loop a regular four loop like this for numb in a range 100 which is the interval. So 100 times let's say we have a list and we want to upend something to that list. So let's start an empty list. L one equals empty list. And then l one dot upend will upend a random integer over here. And to generate a random integer, we can use the randon function provided by a random module. So I'm going to import random over here. Actually, I won't do for directly. I'll say from random import rand int. So basically from the round a module have access to this rand and function. So what I can do is, say, Rand int between one and 100 then let's print out one. If I do this and run it, you see, it works. I get my list off 100 numbers. But when you have a scenario like this where you're generating numbers in a list in an orderly way, what you can do is use a list comprehension instead. And the way to do that is see here where I'm starting off my empty list. I will place this four loop notation in there, so four numb in range 100. I'll place it here. Okay. For numb in range 100. And then in my for loop, You see, I'm a pending this rand into between one and 100 so a random injured that's generated and since less comprehension is a quick way to generate lists, this upend is implied. So what I simply need to do is provide the value in the beginning for what I want the list to include. So this is the part that's important that's doing the generation. I'm going to copy this and then paste it here. Okay? If I save this and actually get rid off my for loop entirely and run it, check it out. Same result. Alright, I get my list off 100 random integers and this rand int 1 100 can be anything. For example, I can simply get the numb in my list as well. This will give me zero through 99 or 100 elements. I can even get the square off those elements so numb to the power to zero square, one square to square three square and so long and you're not necessarily limited to just numbers. You can generate lists off other values as well. For example, if I wanted random lower case characters over here for my alphabet eight Rosie, I can use that. So for that, I'm going to get the ask a lower case constant. So from string import asking lower case, I'll also import the choice function from random. And what choice does is whatever you provide it. It just randomly chooses an element from there. So from my asking lower case, I want to randomly choose a character. I can simply say Choice asking lower case for numb in range 100. If I do that, check it out. I get 100 random character choices between a through Z in my list, and that's list comprehension for you. All right, so that's a lot we've covered in this video on four loops, lift comprehension and generators. Hope you enjoyed it. In the next video. We're gonna look at more generation with wild loops. See you there. 19. While loops, enumerate, zip: Hello. I'm looking back in this video. We'll look at why loops and how to use them, along with the break keyword and another generator, which is the zip function to round off our look at generators, loops and generators. So let's start with why loose and this is what they look like. You start off with the keyword while then a space and then a condition that evaluates to the Boolean values off, true or false. And if that condition is true, it gets into the code lock. As you can tell by this indentation that whatever I include here is part off this while loop you'll execute this code, it will go back to the condition, see if it's true, ill executed again, go back, executed again. And it's gonna keep doing that till this condition is truth condition either turns false or within the code block. It encounters Ah, break keyword, which will break out off the closest loop that it's inside off. All right, so the code, as it's written here, is actually going to have an infinite loop because, you see, I'm setting this truth condition variable as a Boolean with the value of true So this condition is going to be true at all times, and it's just gonna keep printing hello without either breaking out or ever turning to false. If I run this and if you get into a situation where you're running a while, loop like this and get stuck with an infinite loop, then you can hit control C and you see it says keyboard interrupt and breaks out off the program. If you're using Jupiter notebooks, you can restart your kernel and accomplish the same result off breaking out of the loop. And if you want to see how to do that, it's provided in the development overview section where I have to Jupiter notebook Familiarization video. Okay, so let's put a brake keyword in here to break out of the loop. If I run this now, check it out. It basically sees that this condition is true, prints out hello and then breaks out of it. So hello and then breaks up. OK, so let's set up an example. I'm going to set a variable. I equals 20 and then let's enter a condition while I is less than 10. Then I want to print I so the value off I and then I don't need to break out of here because this condition at some point is going to turn to falls. But in order for that to happen, I have to increments I every time. So we're going to say I plus equals one. So let's look at what happens. First time I's gonna be zero. So zero is less than 10. It's gonna print zero than I is going to instrument by one. So I will become one. One is less than 10. It's going to print one and then increment I by 1 to 2 and so on and so forth till it gets too. I being 10 and then 10 is less than 10 will prove false. It's going to exit out off the loop so the last value is going to be nine. Let's see if I run this. There you go. Zero through nine. Great. So here we saw how this condition has turned to false at some point, and then we broke out of the loop. So let's look at an example off using break to break out of the loop. If a certain condition within the while loop is met. So let me paste in a couple of lines of code Here, here we go. So I'm creating a list calling it l one random integers Our values between one and 100 1000 of them and for this code ran into work. I have to import rounded from random. So I'm gonna do that from Random Import Rand int. And let's say I want to look through my list l one and search for the number 25. And if and when I find the number, I also want to say what index? I found the number 25 on in my list. Okay, let's modify our code to accomplish that, I'm going to say numb to search equals 25. And instead, off I less than 10 I'm going to give the condition off Iterating through all the 1000 numbers. Once it's looked through 1000 then it's going to exit out. So my false condition will be I less than Len off l one, which is going to give me 1000. So while I is less than 1000 then instead of printing I what I want to do is check for If l one at index off, I equals numb to search. And if that happens, I want to say print and I'm gonna paste in an f string over here. There you go. Numb to search, found at index. And I would be the index, all right. And then I plus equals one. So it keeps going to the next element. And if I do this, what happens? Let's see. You see, 25 was found at all of these different indices. Another thing you notice is that even after the first case where 25 was found, it kept going and iterating through the remaining numbers in my list off 1000 numbers. It only stops once this turns to false. So when I gets to 1000 this terms of false and you may not want to do that, you may want to exit out off your loop once the first instance off, 25 has found. So within this, if block if this is found, you may want to exit out of the loop right away. To do that, you can simply put in the break your word here, and it will exit out of this world. Let's see. There you go. The first instance of 25 founded 76. And we did not look through any of the remaining items in the list. Perfect. And you are going to come across code like this extensively in the algorithm section because we're gonna be searching for when certain conditions are met and once they are met , exit out of those scenarios. Okay. And this break keyword, it works not just with wild loops, but for four loops as well. For example, if you are doing the exact same thing using a for loop instead of a while loop how would that work? Let's take a look. I'm going to remove this. So four numb in l one, we can say if numb equals numb to search. Then we faced in our print statement and I'm the search, found that index I and then break out and this again will break out off the closest or nearest loop that it's within. So in this case for this four loop, So if you are in a situation where you have nested loops and you come across a break statement, look for the closest loop above it and that's what is going to break out off, all right, But here, if we ran it like this, there would be one issue that you run into. And that is how do you get this value off? I I'm starting off I at zero, and I'm not implementing I at any point. So what I can do is each time this generation runs, I can say I plus equals one. So then it's going to give me the index where I was found, and there's a cleaner way to do this, using another a terrible and I'll show you that next. But let's run this and see if it works. There you go, 25 Founder in next 23 at 2 75 18 Perfect. So what is this other a terrible of talking about? What you can do here is use the enumerated function, which gives you the index associated with an item. So instead of having to start my variable I over here and setting it to zero, I don't need that. I don't know this either, and here I'll say, for Index and numb in and numerator, it's L one. Okay, so it's the enumerated function and it takes in an honorable for us. That's the list. If numb equals done to search, then we want to print. Numb to search. Found that index here. We don't have any more will simply say Index. Of course, I could have called this I, but it would have been less clear. So let's run it. There you go. Still works. Okay, so that's a look at the enumerated function, and we are going to use this later on in the course. Great. So I want to show you an example off when while loops, which we were working on before this are most useful and used most of the time. And that's when you don't really know ahead of time when the loop is going to end. For example, here we have lists that we're working with off a fixed length, so we're able to use a for loop nicely to go through that list. But what if I was working with program execution flow that dependent on a user to exit out at some point, but to keep the program running while that was happening? Let's take a look at such a program and is going to be a menu. I'm going to paste it in over here. Actually, I don't need any of these. So right here. Okay. So while true print, please choose an option that I have press one for selection 12 for selection to three to quit. Then I'm taking the input from the user as their choice and then referencing it with the selection variable. And if that input is equal to three, then I'm breaking out of the loop. Otherwise, it's gonna keep continuing to execute this program or this piece of code. And you're going to see this in use later on in the course as well. So if I run this Whoops. What happened? Oh, I didn't save this. I'm gonna save it and then run it. Okay? See, Please choose an option from the list below. But you six that she was one to it keeps going, is gonna keep going till I hit three to quit the program, and then you see it exited the program. Okay, So this is a scenario Where while loops are widely used where you don't really know how many generations are going to take place. Okay, so the last thing I want to cover in this video before moving on is ah, generator, which is called ZIP. So it's the same function. It's used quite often, and it's used when you're trying to take values from two separate intervals like lists and turn them into a list of troubles with each Tubo containing values from each honorable Let me paste in some cold. Here, Command V. Okay, so here I have a list off extensions. And here in l two, I have a list off programming languages. So what if I wanted to pulls off the programming language and the extension? So python with Doc B. Y JavaScript with Dr J. S. What if I wanted to create an object such as that? And this is an ideal scenario where I can use the zip function so I can say too bold. List equals zip L two and L one. But if I do this, then this to pull list is actually going to be the generator object or the zip object, and we can see that by printing out two pulled list. If I save it and if I run, it could clear this up. You see, it says zip object at the memory location. So this is the zip object. It's just sitting there in order to actually convert this and print it out. We can cast it to a list, so I'll do this if I save it. Okay, let's run it. There you go. You see, Python doc pie javascript dot Js Ruby Darby, Java, java c dot c. Okay, so you get this nice list off two balls. All right, So that's it for our look at it. Aerators for loops while loops and a few generators that we've seen will be enjoyed it. We've covered a lot of material in these last few videos, and we had to since will use a lot of them quite a bit, both in the remainder of the course and in programming in general. So don't forget to practice these concepts. We're going to move on now to functions and building our own functions. And we're to start in the next video. See you there 20. Functions - an introductory look: hello and welcome in this video will start looking at functions, as you can see from the crash course syllabus. So far, you've made some very good progress to get to this point. Congratulations. And now onto functions. And you've already been using functions built in once like Len Input, Print, Zip and the rest on the screen here, which you have used in this section. We've also used functions which we imported from the math module we used along to and power . We also used Brandon and choice from the random module. And these were all functions that came with our insulation off python. We didn't really have to build any of it all. We had to know what to do. To use these functions was what to providers, input and what they would give us back as output. And then we were able to use them. But now we're going to focus on building functions ourselves. So how do we build functions like these for our custom requirements that we may have and we're going to start off with the structure off a function? This is what a function looks like. It starts off with this keyword off deaf for define or definition whatever you want to call it, then a space, then the name off the function and the convention in Python is to use snake case for it. So warrants should be separated by underscores, and also it needs to be something descriptive. For example, you could define a function called ABC, but that doesn't really tell us much about the function. So you wanted to be nice and clear. Then you have these to open and close parentheses right after the name. And this is where you can provide input values to the function which we call parameters to use within the function. And we'll talk about what they are soon followed by this colon. After that, we get into the code off our function, and this code needs to be indented it to be considered part of the function, and it captures the logic that you want the function to perform, and that's it. That's the general structure off a function. Now let's check out some characteristics of functions, so a function may or may not include parameters. So remember what I was talking about about including parameters here within these parentheses. Let's take a look at two examples of functions one that includes parameters and one that does not include powders. Here we go. This is a function that adds to numbers we've called. It adds to numbs right after the death keyword and within parentheses, you see, variables numb underscore one followed by a comma and numb underscore too. So this common signifies that they're separate. Arguments are parameters. And what this function does is it simply prints out numb one plus numb to to the screen. So when we run this function, we're going to provide to numbers to this function in order to run it dysfunction right below. It does not include parameters. You see, we've called it say hello and within parentheses. This area is empty and all this is doing is printing Hello world. So anytime you call this function, we don't need to provide it any input values We could just say, Say hello and you will print out hello world to the screen. Okay, moving on. All functions might have a return value that you specify. Otherwise they will return none by default. If you don't specify anything, that's a little bit a couple examples. We have modified our ads to Nam's function over here, instead of printing this out to the screen, were actually returning the some off the two numbers that we provide. So whoever made the call to this function will have this some available. Now. The second case is when you don't have a statement like return in it, then the return is implied by the function, and the value it returns is the non data type. So in this case, return value off none. You see our say hello function. It's simply prints out Hello, world to the screen. There is no return value specified. So I before Python is going to return. Not so. Print out Hello World and returned. Not so. Let's take a look at the actual output and what this would be like. There are two examples off this function being called first. I'm saying print calling the function by its name at two numbs with these two integers five and six, and in the second case, I'm actually calling the function. Add to numbs with the same integers five and six, but I'm not printing it out to the screen. I am storing the return value as this result variable. And then I'm printing out the value off the result variable. And both of these would produce the same output off 11 and printed to the screen. And that's an example off using the value that's returned from a function. Now let's take a look at our say hello program. You see, when we call our say hello program right here since its printing hello world to the screen , the return value being none. You see, I'm not using a print. I'm simply calling the function. In the prior case, I had to print out the result to the screen for it to show up. But here a function itself is doing the printing, so I don't have to use print over here where I call it. So the output for this would be simply hello world. However, remember, this function does return the non data type. So instead off just calling the function. If I had actually printed it out like this, you would get the hello world which is being printed by the function, and then we would also print out the non type to the screen. Since that is what was returned by our function. So you're gonna have this output Hello world, followed by none. Okay, let's take a look at some other notes. It's very good practice to include a dock string in the function to provide additional information about it while it's optional. It's good to do because you may not remember later on what your function was used for, or you may forget the context of it or someone else looking at your code may not know what you are trying to do. It could be a lot of scenarios where the doctoring would be useful and again, the Doc string. We call it the Doc String. It provides information about your function. So here is an example off a doctoring its put within triple quotes. So it's a string, but you're not really doing anything with the string. It's just within triple quotes sitting there right after your function definition and is an example for a possible doctoring that you could include with your say hello function this function principal world, and then you have your execution code off until the world and the doc string could be more detailed than this. You could also provide information on The input and output values, for example, are add to numbs function. You could have a summary dysfunction ads to numbers followed by the second line. The input provides information on the input values that we're taking him or the parameters right here. Two inches, your values to add. And then we have information on the output. What the function returns to some off the two input integers. So this is an example off a detailed doc string. Now some other thoughts on functions You always want to try to limit a function to perform on Lee one defined function that is intended for. For example, if you are trying to build an ad function, your function should only perform edition. It shouldn't perform addition, multiplication and other things, and this may not be possible in some occasions. Bucks try to stick to this principle because it will be very helpful for having nice clean coat. Now the function could be very big and perform a lot of operations. But the intention You only be used for what it was intended, and usually it's one thing okay, and functions can return multiple values in python. This is done as two Bulls. Let's take a look at an example. There's a meat belief function that takes in some parameters and then returns a list off ends and a custom dictionary based on whatever function it's expected to perform. When you have a situation like that, and expectation is, you're gonna have multiple return values. This is the way it's listed. Usually have the return objects separated by commas, and you could have other ones here, too, if that was the requirement for dysfunction and these values, these objects are returned as two poles remember. Pupils are immutable, so that characteristic off two balls comes in handy in this type of scenario. So now that we have a basic understanding off what functions are like, let's take a look at some examples off functions and methods that we're gonna build throughout this course Here we are. This is the first sorting out of them that we're going to build in the sorting out er than section, and it's called a bubble sort. As you can see, we have the function definition on top. We have some information on what this function does, and then we have the function code, and this is one of the easiest sorting algorithms to develop. And it will be a nice introduction to how we write functions for our outer those and there will be others. We're gonna build this selection sort out of them after that, after learning how it works that eventually we're gonna move on to recursive functions, we're gonna learn how to build them from scratch. If you don't know what recursive is, that's totally fine. We'll explore all of that. Came the algorithm section before we use them. This is a recursive function that calculates the factorial. We're gonna look at how to find a number in the Fibonacci sequence, and then we're gonna move on to high performance, sorting out their them. So this is the quick sort function that we're gonna build. There will be mark sort as well. And then we will build projects such as these projects scripts and learn how to build functions such as this to run the project code. Then in the searching section, searching algorithms, we're gonna look at by section search to kick it off. And here is the iterative by section search function that we're gonna build and then we're gonna move on to building our custom objects and functions within them. And when we have custom objects that we build, the functions associated with them are called methods. And this will happen when we start building our own data structures from scratch. And whenever we have these data structures and projects, you're always gonna have project scripts like this, where we use custom functions that we build to utilize what we build in the data structures . For example, this is a linked list, and there's a lot of functionality that we're gonna apply to this. But these will be again methods that we build Here is another example off using the linked list, modifying it for building a stack who can also build a Q And this is a binary search tree and this will be toward the end of the course. And just to give you an example, the most complicated function in terms of functionality, which will be delete method for our binary source tree class, which again you'll be able to build will look something like this if I scroll down. Here is the delete method for our binary source street. Check out all this code here for one method and you'll be able to build this by the end of this course. So, as you can see, there is a lot off practice that we're gonna get as we work through all the content of our course. So don't worry. If all of this seems a little intimidating at this time, we'll get tons of practice, and we're gonna start with a very nice clean sorting out of them called Bubble Sort and work our way through two more complicated ones. And if there's anything new that comes up will cover as we go through. All right. So I hope you enjoyed our introductory look at functions and a look at some of the functions and methods that we're gonna build to the rest. Of course, in the next video, we're going to start building our own custom function from scratch and see a few of the wise for functions, some of the wise for some of the characteristics that functions actually have as we build out our function through the video. All right, well, we're excited. Thanks for watching. And I'll see you there 21. Functions - implementation step by step: alone. Welcome back. And this video will build a function and then modify it in several steps to get a clear picture off some of the characteristics off functions that we discussed in the last video. So I have this starter program over here if you take a look. And this program asked the users a few questions, takes their input and simply displays what? Their answer waas to those questions afterward. So it's a pretty simple program, but it will demonstrate the need for functions and some of the characteristics that we're talking about. OK, so if I run this right now, there you go. Welcome to the program. What is your name? I'll say. Sure you're responsible for sure. Okay. What do you think of the food you ate today? Great. Get your responses. Great. What TV show Ending. Did you just like the most ever? I'll say G o t. All right. Response was duty. So pretty simple program. Now, if you look at the code, there is a lot of repetition going on. You see here I'm saying enter your response here, which waas for my first question. Then your response. Was this the same thing? for the second question injure your response here. Your response was this same thing. For the third question into your response here, response was this. So any time you see code like this, you have to ask yourself, Can we extract away this redundant code and package it as a function so we can reuse it instead of having to write it out every single time? And in our examples for functions, we saw that we were building algorithms. Let's say the bubble sort algorithm and packaging them as the function bubble sort. So any time later on, I would need to call the whole sort. I could simply call the function instead of writing all the function called out again. So similarly, in this situation, what I could do is defined a function. So I'll start with the keyword D e f space and then the name off my function. And I want a nice, concise name, you see, for the code I'm looking to package in my function, it seems to be getting input from the user. So what I'll call my function is get underscore input underscore from underscore user, and you can call it something else. But that's pretty accurate, in my opinion, in terms of definition and when you define a function. At first, let's say I just chose to define this function, but I don't want to write it yet, but I still want my program to execute like this. See if I had left this like this and saved it and then tried to run it. I get this indentation error expected, an indented block, and that's because it's expecting me to write something here. In this scenario, what you can do is use the keyword pass. If I save this now, Python is gonna come in here, expect some code for the function, encounter this past keyword, and they'll say, Okay, I can ignore this now, and it will just move on to executing the program. So if you see if I run this again, it runs all right, I'm not gonna go through it. I'll just interrupt out of it. Okay, so moving on, these are the two lines that seem to be redundant in all three cases. So I'm simply going to copy this from my first instance. So Command X and then paste it here, all right, and it's the same quote. There's nothing really special I need to provide here. But in order for this to work now, after my print off the question, what is your name? I have to call my function. Otherwise, it's simply gonna go onto the next print, right? Nothing is calling the function in my script. It's just sitting there as an object Hyphen is gonna know. Okay, yeah, there's a function definition, but in order to actually use this function, you need to call it Python won't do anything with it automatically. And to call this what I'll do is simply say, Get input from user. That's it. Since the getting input and printing is done in the function itself, I can simply say this. We don't want this go to be indented in. So let's go ahead and run this. Now back to my terminal. There you go. It works. Read you t OK, so now that we know it works for this part of my code, I know it's the same thing repeated for both of them. Even though the variables are different, it doesn't really matter, and we'll find out why very soon. So I'm simply going to remove this code and calling my function okay. And if I run it, There you go. Still works. Okay, Great. All the logic is still working. Now let's move on to modifying some of the stuff we have done here. For example, let's look at first why the variable name does not matter anymore because I had three separate variable names here. Yet in my function, I'm using just one variable name. So what happens is whenever you have a function, python creates a separate frame and we're gonna cover frames in the next video. Think of it as this function, having its own space that's separate from the space available to your main program execution. So whatever variable is defined within that space when the function is called, that is unique to just that function. So when I'm calling the function the first time, it's saying, OK, here is my function call. I have my own space. I have my own name Result variable, and I'm going to just use this second time. The first times result is all discarded because now it's a separate call to this function. So this call has its own frame and the same thing repeats itself the third time as well. Okay, and that's called variable scope. Again, we're going to look at this in the next video as to how exactly that's possible behind the scenes. All right, But in this case, you see, name result is no longer our valiant variable name, right, Because we're using it. Not just for the first instance were using it for food and for disliking a shows ending, so we'll just change it to result. That seems more appropriate. This is obviously optional because the variable name doesn't really matter. But you want to have variable names that are representative off what you're trying to do now. The next thing is, what if we wanted to actually provide or use what the user is providing as an input and perform some operation with it based on those input results? What if that was the case right now we're simply printing it out, and that's not really useful, right? What if we wanted to construct something with whatever the user was providing as an input? How do we do that? For example, I'm gonna paste in ah print right here that utilizes their input from all three off my questions to construct a response from the program. They sitting right here. Okay, so this is to summarize your name is this. You ate this food today and you hated the ending off the show. And if I run this now, I'm going to get errors from this because name result isn't defined. Food result isn't defined. Show result isn't defined. If I run it, I'll same assure good G o t. I hit an error named result is not defined. Which is it? Executed. All this code came down here and then hit an error. So this is a scenario where I want to actually use the input that I get from the user in my program execution code, which is outside of the function. And if you remember from the previous video by default, if you don't provide a return value in your function than the return is the non data type. So if I try to print out where I'm calling this function right, if I try to print this out and go through it, let's say blah, blah, blah this quickly. Fill this in. You see the first result. Your response was whatever and then it printed none, which is what we were expecting since the return value was not so. Let's go ahead and specify a return. I'm going to clear this up and the return can be anything we want. What if we did return? Hello? The string. Hello. It doesn't have to be whatever that's useful. It could be anything that the program returns. And I still have my prince statement over here. So now what happens if I wrong this If I say my sure you see your response was mature and then it prints out Hello. So this print function got a valid object, no longer the nun data type, it actually got this string object, and it was able to print it out to the screen So you can see the benefits off having a return value, since you can use it in your program out off a function. So instead off printing out your response waas result. What we can do is we can return the string that we want printed out and simply printed out here if we want. If that's what we're looking to do. So let's go ahead and do that. I will simply remove the print from here. Instead, return this f straight and get rid off my Hello. All right, so now this function is going to return this entire F string. So when print gets it, it'll print it out to the screen and then I can do the same for the other two. I'll print out what I get back. I'll save it on. Let me cancel out of this. Run it again. I'm sure your responses mature. There you go. What did you think of the food you ate today? Great. G o T. Ok, now we still hit our error name. Result in the other variables from this bottom print, there's not defined. However, this functionality is working in a better way so that we can actually use this result. So what we can do instead and see of called name Result food result and show results as my variables, we can instead save our response instead of printing it out too. The variables that we need so named result equals get input from user. So this name result will be the string with the response. Similarly, the food result we can say here food result equals get input from user. We can do the same here. Well, say show results. Okay, Now, if I run, this is not gonna be very nice, because this string is not useful in the statement. But let's run it first and see that it works. Okay? Sure. Ray, T okay. To summarize your name is your response Was my sure because it basically took this whole string. And while that's useful here, if we printed it here is not useful in our summary in our program. So what we can do is simply return result. Because whatever I input here works very nicely in the statement. So I'll get rid off all of this instead off the string and any of that I know result is already a string because it's an input value I'm getting from the user. So now what happens? I save this and run it. There you go. To summarize Your name is mature. You ate great food today and hated bending of g o t perfect. You see how clean this implementation and riding our function this way is turning out to be Now there is actually something more we can do here. You see, the input from the user that we're getting at response we know is a string already. What we're doing here is saving that to this result variable and then we are returning that result variable, which is this string object. However we know they input from the user is already a string that we're looking for. So saving it to a variable then returning the variable is not really necessary. We can directly return the string that they user inputs. So what we can do is remove this line fully remove all of this and simply say, return input. Enter your response here. So we're returning. Whatever the user enters as input and I'll get rid of this extra space. Let's save it. Let's run it! Clear this up. What is your name? Assure food, Greg G O T Perfect. Still working exactly as we expect And look at how much cleaner this code is. And now the really benefits off doing things this way and returning values. See, we have access to these string objects that return instead of just printing it out to the screen, we can run other methods are functions on them to improve our program. for example, you see in my out put off my program. My name is not capitalized. And for a name you might want it capitalized. And then to emphasize the name of the show that you dislike the ending off you can use upper case to make it really stand out. I'm bringing out the name here so I can simply say dot Capitalize open close parentheses and then for the show result, I could say docked upper to make all my character's upper case. See if that running again, even though I'm entering lower case mature, it's going to capitalize it. You go perfect. This is exactly what we were looking for, and this was a simple example off simply using capitalized and upper. But you can kind of see the benefits of doing it this way. Now let's say you had to use whatever you got back from your function throughout the rest of your program for input to other functions or things like that. You could easily design it this way and make it work. Perfect. So that's all I wanted to cover in this video, and we've covered a lot of material on functions and, like I said in the last video. Don't worry if all of it isn't clear fully as yet, with continued practice and building and using functions and methods, and we're going to build a lot of them in this course, you'll get a lot of practice and be a pro in no time. All right, I hope you enjoyed this video and I'll see you in the next one. 22. Functions - execution context, frames, mutable vs. immutable arguments in-depth: Hello and welcome back in this video, we'll look at the execution context, off python programs and what happens when we run an actual program. Specifically with functions. Here is the Python script or file, which we developed in the last video. Now, when we run a program like this, hyphen creates what's called a global frame for your program. And now that your program is running, think of this area as the execution context off your program. Right now, it only has the global friend, and then the Python interpreter starts interpreting your code. And Pothen, as we know, takes a top down approach. So it starts reading your code at the top of the file and works its way down. The first thing it encounters here is your code for the function and then simply says, Okay, here's a function. I'm going to store this as a function object in my global frame, and since you're not calling this function or anything, it's simply stores it as a function object. Then it comes to the print. It handles the print, which I won't show here, since it's just a print statement for the user and then it comes to this line where the function is called and referenced by the variable name name result as soon as it reads the function call. It creates a new frame for this function, and this is totally separate from the global frame and moves on to see what the code is for this function and in the function, it simply prompts the user to input some value. And once the user input STIs dysfunction simply returns it to wherever the function call was made. And in our case, we referenced it with the name result variable in our global frame, which we can see here. So that's where it shows up. And that's the end off the function code as well, so it simply discards that frame. It's done. We're done with it and back to the global frame. Our interpreter is then going to go to the next piece of code to execute, and after handling the print, we encounter a new function call. So a new frame for the function is created again and the process repeats itself, resulting in the food result variable having whatever the user had input. Then it moves on to the third function. Call a new frame for the function is created, and it results in getting input from the user and the global frame. Now, having show results as a string object as well. And then it does some prints stuff, which I've simply called it the summary. And then we reached the end of our program and the global frame disappears. So that was a simple case off three function calls and what happens with the frame being created. Now let's explore a different program, this one and here will be returning some variable values integers to be more specific and passing them around as the program executes to arrive. At a certain result, let's actually see this program being run in our terminal before we return to review the execution context and what happens behind the scenes. Here we go. There are my two functions, and then I'm using this start non variable, setting it to the integer one. I print out what the value is off starting. Um, then I'm calling funk zero passing in this start numb as the parameter, and if you see in function zero I'm using start numb as well as my variable name. I'm implementing start numb by one. Then I'm calling function one with start numb and here in function, one I'm receiving start numb as a parameter and I'm in preventing start numb again by one. Then I'm returning. Start numb from here and this will be returned from where the call was made. And then I'm storing all of this as finished numb in my main program and then printing out , finish numb and start now. And if I run this you see, we have started. I'm starting off as one Calvin, um which is the finish numb with a value of three. And that has gone through all these increments with the variable name off starting. Um, but we see that when we print out start numb again. Over here, it still has the value off one. So even though we have the same variable named start numb plastered all over this program and we're implementing it in multiple function calls, the initial one is not impacted at all and remains the same value off one. This shows that these variables right here in the functions they are local do these functions on Lee and the global frame does not have access to them or access to many to leave them. Let's now head back to our visual representation off the function calls and see what happens behind the scenes and keep in mind this is an integer, so it's an immutable data type back here we start off with our global frame when we run our script and it recognizes the to function objects right here. So we have our function objects, and then as it works its way down we see start numb is one. So it recognises the int objects start numb as one. Then it prints the value off starting, um, and moves on to the next line where we encounter our first function call. And it's calling funk zero passing in this variable start numb as the parameter. So there we go. Fund zero now has its own frame since it was just called and has its own copy off the start numb variable. And since one was passed in, this also has the value off integer one. Then we move on to the code within the function says to incriminate by one. So now start numb for this frame is, too, and then it moves to the return statement, and this return statement has a function called to funk One passing in this start numb right here. This dark numb is being passed in to my funk one right here. Okay, So funk, once frame is now created and the same thing happens and it has its own start numb with the value off to then go to the next line sees to increment it to three, which it does, then encounters this line to return this value off start numb, which is three to wherever it was called from. And he was called from funk zeros frame. So it returns the value off three to funk zero, and we're done with funk one and informed zero. You see, we encounter the return statement here where that function call had taken place. So it's going to return the value three, which we have here back to wherever this was called, and that was called from the global frame right here. But keep in mind, this is returning three, which was returned from Frank Juan, even though the start numb for this funks frame is too. Okay, so we move on back to the global frame and we see that finish. Nam has value off three. Since we're done executing the code and Fung zero, the frame for Fung zero disappears. So now we can reference finish numb in our print statement which happens in the line immediately afterward. And then also we're printing out. Start numb. And if you notice in our global frame, start numb still has value off one. And that is why when this program is run, we get the value off. Start numb as one, even after execution off all the function calls right here, Captain on three, which is finished now and then start. Um, is still one. Okay. And this was a case for an immutable data type, which is an integer. What if we had a mutable data type here, for example? What if this waas a list instead often end then a lot of things about our program execution changes. So I'm going to convert this to a list simply by adding square brackets over here. So now start number is a list with the injured, your one as the value at index zero on the remaining code here is still fine, but this code right here is not going to work since I have to increment the value at index zero by one instead off simply having the list instrument by one, which doesn't make sense. Okay? And this code would work. But in order to demonstrate the difference, I'm actually going to change these variable names. Start now, So let me paste in some code here with different variable names. So in function zero of reference this as other number and I'm incriminating. Other nominated eg zero by one and in function one. I'm calling this another numb and I'm incremental. Another nominee zero I want all the remaining code is the same. But if I run this now, I'm gonna save it and run it. You see, In this case, even though all these variable names were different, it didn't matter. Start numb on one, Captain. Um, which is the finish, Nam? Right here after the increments is three. So far the same as with the immutable data type. But then you see, start numb here. This third print right here. This actually has the integer three in the list. Ok, so this is where it's different from our initial case where we ran this with the integer. So why is this the case? Even though we use different variable names here to refer to our list? To understand this, we have to look at the execution context again for this program. So here we go. Here's our program, and when we run it, the global frame is created. You see the same as before. We have our to function objects, and we have a list object. Start numb, however, will view this list object outside the global frame, since it's treated differently being mutable and the references work differently when you pass in this variable, start numb as a parameter to, ah function call. So we're gonna view it here. Okay, so when we encounter our first function, call for function zero and the frame is created. What's passed to this function over here with Start Numb, which is received by this function as other nominees, the parameter is a reference to the list object. So the other numb here is pointing to that same list object that start now was pointing to , since it's a reference and it does not have its own copy off this list and the next line of code. We see it increments the value at this index by one. So now our list object as the value off to in the zero index. Then we move on and encounter the call to funk one. The frame for funk one is created, and this one's variable called Another Numb, is referencing the same list object and in the next line in increments, this value by one and then the line after that returns this list object reference. So the return value is a reference to this list object, and we can see it right here by returning another numb. So we're done with the frame for Function one and then for funk zero. We see it's returning this list object reference again as its returned value that it received from Funk one. And then this was called from our Global frame and his referenced by the finish numb in that frame. You see, both start numb and finish numb are pointing to the same list object, and that has value off three at its zero index. And that is why we get this value off. Three for both start numb and captain um, and if we actually put a Boolean conditional test for finish numb and start none will see that the quality test returns true. So I'm gonna put it right here. So this one is simply going to print out a finished now equal start Nam, if this returns true, if I run this, check it up returns true, since they're referencing the same list object. And if this behavior is not what you wanted and if you wanted the function calls to have their own copy, you could do one of two things over here when you are invoking or calling function zero, you could pass in a copy off your start num list instead off a reference to the list itself . So you could say dog copy. We did this. This would work if I run it now, check it out. You see 13 What? Stardom is still one, and the equality says false. The other way you can do this instead of using the copy method is you could pass in a slice off, start numb with the whole list. So all you slice notation here open close square bracket, and within it, I'll put a colon for the whole list and This will also give us a copy if I run this. Now you see, the same result are right. So hope you enjoy this video on the introduction to the execution context, global frames and function frames for a very in depth look at what goes on behind the scenes off Pathan programs. And this is going to come in handy as we progress through the course. And this also includes our introduction to functions. We're going to encounter them a lot and get a lot of practice from this point onwards. So if some of these things are not clear, don't worry. They'll get clearer as we progress through the course. In the next video, we'll move on to creating our own custom objects by using classes. Hope you're excited. I'll see you there. 23. Classes and objects - an introductory look: hello and welcome in this video will start working with custom objects usage of classes to build them along with some examples. Now, if you look at the crash course syllabus, we've made some very good progress so far in this section and we've covered all the components we need In order to get started with classes and building our custom objects. Our focus for discourse will be on building. Custom class is based on eight of structures which we're gonna implements toward the later part of this course. I will start off with the basics and a simpler custom object as an example in the section. So what are objects? Everything in python is an object. Each and every item you have worked with in this course so far, like strings, ands, functions, dictionaries. There were all objects off specific types, and we even use the type function to let us know what the type off the objects were when we were working with them. And you can create your own objects very easily with python and that involves using classes . And we usually build our own custom objects when existing or built in one's provided by python or any of their modules are not sufficient enough to write the program or perform the function that we're trying to do. And this last point we mentioned a few times during the section. So far, functions associated with instances of objects are known as methods. They're essentially functions, but just within the class. And we use them on instances off that class that we work with or instances off objects that we work with. And we've seen a lot of methods in use already. We've used upper lower split, find, upend pop, remove all of these associated with strings list dictionaries and all the other data types that we've worked with so far. And they looked different from functions and how they were called functions, which were not methods associated with any instance. For example, when we used a pen method which are associated with instances off list objects or the sort method for that matter, we use this notation off. Whatever the list declaration, WAAS docked a pen or dot sort, whereas when we used functions like Sore Ted, for example, they usually took the form off the function name, followed by the object which we wanted to sort passed in as an arguments to the function, and you can see the methods associated with specific classes or data types by using the de ir function. Let's take a look and we go here I have a list string and a dictionary defined. And if I wanted to find out what methods were available to these types that were built in are provided by python, I could do de ir and then pass in the object. So the i r my list. You see all of these methods that are available to my list object a pen clear copy count removed reverse. And we actually use a lot of them also. And then these ones right here that start off with these double underscores than the method name and then double underscore After that, they are special methods associated with objects, and we look at what they are and implement a couple of them in an upcoming video. So let's take a look at some example classes that we're gonna build in the course to the left of my screen. Here, here is ah, hash table or a hash map data structure that we're gonna build and will try to emulate the construct and behavior. Often actual hyphen, dictionary, object and building a structure such as this will require us to build this custom class. You see, we have the class definition and then we have all the code associated with the class indented in so that it's considered part off that class. Then I have some method definitions here, and I have this special method in it on top and a few other methods associated with the class. Let's think a visual look at the structure and what it is going to try to emulate. And here it is. This is the structure that that class implementation will support is essentially going to be some storage, and we're gonna have indices and we're gonna have data. And then the data attributes are going to be two pulls off key value pairs that we're gonna store so that we can emulate the construct off a dictionary object in python. Moving on to another example. We're going to learn what linked lists are by building them from scratch. So we're gonna build a linked list class that's going to support this type of structure where you have these objects and they have pointers to the next object and each one of these. So the entire linked list is composed off these things called nodes. And to work with such individual knows we're gonna have to build a node class as well. And this is what it's gonna look like. It's going to have a data attributes, and it's going to have a pointer attribute that points to the next note, and the data can contain any kind of information that you want. We're going to use integers as an example. We could have strings or other objects as well, and this structure off a note will be used not just by the linked list, but a couple others as well. Another example structure that we're gonna build is a binary search tree, and this is what it looks like. In fact, this is one of the actual completed trees will build toward the later part of the scores, and each node here, you see, has two pointers instead off one pointer, and they're pointing to the left child and the right child off the note. So you have data that you're representing in the note, along with a couple of pointers or attributes. So each individual note in a binary search tree is going to look like this where you have the data and the left child and right child pointers. And these will be the attributes for each node in our binary source tree that we're gonna use. So let's take a look at what these node classes look like. An actual code. Here we are. This is an individual note from our linked lists Demo. You see, we have our data attributes and the next pointer and this is the innit method, which is used to create an instance off a note. And below it, we have our link list class, which is going to use notes like this to build the linked list. Similarly, we have our node in a bind, a resource street and the node for the vinyl research tree you see look slightly different . You have the data attributes and you also have the two pointers one for the left child and one for the right child, and then blow it. We have the class offline, a research street which utilizes nodes to build and operate the structure. OK, so back to our tree known visual. Since we'll be building these later on in the course, we won't really build them or use them as examples in this particular section in this section. We're gonna work with this student class instead, or the student object. And it's going to have attributes or data associated with each object, which will include first name, last name and the courses they're enrolled. It and each student object is going to be made up of these three components are attributes , and we're going to start building them in the next video now, some concluding thoughts on ah widely used topic called object oriented programming. Now object oriented programming is a programming paradigm or a set off principles, off building and packaging code used in software development. And it uses ah, lot of principles like inheritance, polymorphism, encapsulation and much, much more. It's used extensively and software development everywhere, since virtually every software application you work with beyond an introductory level will involve the use off custom classes and objects that are built, and it is a very nice, clean and efficient way of packaging, reusing and maintaining coat. But it's a very broad topic. It can be a course in itself, and we won't really cover it In depth will learn how to build custom objects that are relevant for our data structures that we learned to build and work with, which will provide a very solid foundation for other topics and old B. And they're also the basis off all off on a journey programming. However again our focus will beam or on building and using classes that we need based on the data structures that we work with. So we're gonna focus on that. There is one concept, though that is very important, which is inheritance. So even though we won't use it much in the course itself or any of our data structures, I will provide an introductory video on it and how we use inheritance and sub classes in our example code using the student class. But it will be more often introductory look. Okay, great. So that's a lot to cover. Hope you're excited. Let's get started in the next video where we start building our student class. So you there 24. Building a custom Student class and intro to special methods: Hello and welcome back in this video, we're going to build our student class. And as a reminder, this is the structure of the class. Each student is going to have Ah, first name a last name and courses after Butte. And I keep referring to these as attributes. Think of them as relevant and identifiable data associated with each student that you will work with or each student object that you'll work with. Okay, so let's go ahead and build this. Here we go. I'm in. My editor. I've called this student demo DuPuy, and the way to create a class is by using the class keyword So class space. Then you want to enter the name off the class. I'm going to call my class student, followed by the colon and notice the S for my student is capitalized. And that's because class names. You want to capitalize each word in it. And that is called Camel case. So you want to use Camel case for classmates? If this class was called a student athlete, for example, then you would capitalize a as well. All right. And then I'm going to move on to the next line and you see, it's automatically indented everything that you have under your class. Definition that's indented will be part off your student class and to run it successfully, I have to put in the past keyword without any code. Remember, otherwise it's going to give me an indented block error because it will be expecting some code associated with the class. To create a new object or instance off our student class. You have to call it by a class name, followed by open close parentheses. Whenever I use code like this, it will create an object off my chute and class, and we want to refer to this object with a variable name so we can reference this. So I'll call this mature, equal student. And then let's go ahead and print out a. Sure I save this and run it. You see, it prints out that I have a student object at this memory location. Great. Now let's create another student. Let's say John equals student and then print out John as well. Check it out. I have to objects off type student that were created and they're stored in different memory locations, and that's what I wanted to show here is, even though they are the same class, they are different instances or different students. Okay, And that's what we mean when we say an instance off an object. So essentially assure is not the same as John. So in thinking of this, think off student the class as the blueprint and each new object built using that blueprint is a different instance off that class. All right, so now let's go ahead and add. Our attributes were going to say, assure the first name equals I'll. Same assure. And then my sure dot last name equals same and courses I'm going to add later on. Let's do the same for John. Okay, so now what I can do is instead of printing out the object reference like this, I can print out the values that their attributes up. For example, I can say mature dot first name, followed by a sure dot last name. And similarly for John, I could say John, first name John. Last name john dot Last name. Okay, so let's see how this looks. I run it, Check it out. Sure. Saying John Doe. Great. So as you are seeing here, this is a lot of code I'm typing in. Every time I'm creating a student class, I'm having to mention the attributes I'm having to use this doc notation this assignment, and that's a lot of repeated work. So instead of doing it this way, what you can do is you can use the special method. It's called the innit method and that essentially initialize is an instance off your object , and it will eliminate a lot of this additional writing, and you can think off the innit method in terms off in Stan, she ate or initialize whatever you like, referring to it as, and the way to do that is underneath your class definition. Make sure it's indented, so it's part of the class. Define two underscores in it too underscores. Okay, then open close parentheses and a colon. Now, these two underscores our methods that have these two underscores on either side. These are special methods in python and sometimes referred to as dunder methods. So in that way, this would be the dunder innit method. Okay. And you see, we're trying to initialize our student with the first name and last name attributes. So what I want to do is when I create the student. I want to pass in the first name and last name and let my student class handled this assignment. Therefore, this dunder method is going to take in three things as arguments and two of them, as I mentioned, we're first name last name. The third item. Very important. It's going to take in the instance off the object that you're trying to assign these four or create this instance off as the first argument. And that is by convention, referred to by the name self. Okay, so the first argument by convention is named self, and that is the instance that's passed in. Now you can call this something else if you want, but by convention it's self and we're going to stick to convention here. And then after that, you can say first and then last. Okay, now, within the method, what we want to do is define these attributes, first name and last name, and assign them to what's passed in when this student is created or initialized. And since the instance being passed in is available to us through the self parameter, we're going to say himself dot first name equals First, to assign the first name. That's fast into our first name attributes. And then self dot last name will be assigned to last. So basically, this first is being assigned to my first name attributes, and this last is assigned to my last name attributes. And again, keep this in mind. Any time you want to refer to something to do with an instance off this class, you have to use this reference to the self so self dark something. Okay. All right. So now that we have this code, what we can do is when we create an instance of our student object, we can simply pass in first name and last name. Now, you may be asking Hey, wait a second. Where self in this, Because our innit method takes three arguments, which is self first and last. And we're calling this with just two arguments, which is first, unless what happened? Yourself self is automatically passed in by python. When you call this, let's aim assure dot first name. This must sure is automatically going to be assigned to self. All right, We don't need these two lines anymore, so I'm gonna get rid of them. Similarly, I'll fill this in for John. I'll copy this. Paste it here, then. Copy this wasted. Here. Get rid of this. Now. If I run this, check it out. Same results. What you're saying, John Doe. Great. So we have successfully created a student class, initialized multiple instances off our class and were able to view attributes associated with those objects. Okay, The next thing I want to cover is remember, in our student blueprint, we also had this horses attributes. And this lists out all the courses that the shooting is enrolled in. Let's go ahead. And at that in, I'm going to paste a list of courses over here. Here we go, off base it in two lists, courses one and courses, too. So what I want to be able to do is I want to be able to pass in a list. Of course, is when I create the student object. And then those courses will be assigned to the object being created. So basically I'll take this course is one on then pasted over here and then courses, too. They sit over here, and then that's print out. I'm sure doc courses and then John course is all right. If I did that and ran this, we're going to get an error over here. It's going to complain that in it takes three positional arguments self, first and last. But four were given because here, you see, in both cases I'm giving first name, last name and courses and four, because self being the first that we're not really seeing here. Okay, so let's account for this. We're going to allow this to take in courses and then self dog courses equals two courses. So the list that's passed in, that's the list as assigned to this courses attributes. There you go. Now it's working. However, What if courses is not past it? Later on, we're going to add functionality to ad courses to an instance off a student object. But what if, during creation, the student has no forces that they're enrolled in? Then we want to give this an option to not provide courses over here when the object is created. So if I did this and ran it, it's going to now complain off the opposite requirement. It's gonna say in it is missing one required positional argument courses. Since I'm not providing it here. So I have to allow for this course is to accept to none as well. Nothing being passed in. So the default for horses here, if nothing is passed in out, set to none. And the way to do that is equals none. All right, So if something is passed in great, it will be used to assign the courses. But if nothing is passed in, then the default for courses will be none. But if this is the case, then I want to be able to handle the course, is being none and simply have the students start off with an empty list right now. You see, that's not going to work right now. If I do this, you see, it does not show an empty list for my first shooting object. It simply says none. Let's build that functionality in our innit method. We can do that using any fellas branch. So if courses equals none themselves, Doc courses equals empty list else. Self doc courses equals courses. Now, if I run this there you go. Much over saying empty list. John Doe has these three courses listed. Perfect. Okay, great. We've covered a very good amount in this video in the structure and set up off our student class. And we were also able to create shooting objects or instances off student objects by utilizing this class. And that's where we're gonna leave it in this video. In the next video, we'll add some methods for additional functionality to our class, like adding and removing courses. All right, hope you're excited. I'll see you there. 25. Add some methods to the class: Hello and welcome back in this video, we're gonna add some functionality to our student class. If you think about a student, object or class and what could be some relevant functions, The first thing that comes to mind for me is their ability to add and remove courses from their curriculum. So let's go ahead and start with the ad course method you see at the bottom. Here I have some execution code that I have commented out, and I'll uncommon them as I add this functionality. So let's start with the ad course method. Define ad underscore course, and this is going to take in self as the first argument, which is the instance that's being passed in and then the course name to add to the course curriculum off that instance. So colon and weaken simply append this course to the courses, attributes off that student object so we can say self, not courses dot append the course that's passed in. But you see, if we do this and in our first case assure, for example, has python rails and JavaScript in his course curriculum already, if I try to add rails again, save this and then print out the courses and run this you see rails shows up twice in the course list, it gets added, and we want to avoid the scenario on the way to do that is to simply see if the course that's been passed in rails in this case already exists in the students course list. And we can take care of that with a simple if else branch. So if course not in self dot courses Colon, then I want to upend the course else. Which means that the course is in the list. Of course, is we want to say print. Let's provide an F string. I'll say self dot first name for the student's name is already enrolled in the course Variable name. That's fast in course, and then put closing. It will quote their closing pregnancies, and this code is extending a little too much to the right. So what? Aiken Dio is escape it, So I'll put a slash year and move this to the next line. But if I leave this like this, then this space is going to show up in my output. I don't want that, so I have to move this to the beginning. Let's save it. And now if we run this there you go. When we try to add rails, it's asthma. Sure is already enrolled in the rails course perfect. And then we can test out of the previous one as well, on uncommon to Java for a legitimate ad. Save that running perfect. It rejected the rails course, but it added Java Great. Now let's go ahead and build the ability to remove courses from courses that they're already enrolled in. So I'm going to define this year. Make some Space York define remove course within parentheses, Samos and four self and then the course I want to remove. So let's go ahead and do this check instead. Off. Not in. We want to check if the course that is being attempted to remove from the curriculum exists in the student's courses, and if not, then the student is not enrolled in the course, right? So if course in self not courses, then I want to remove the course from that list. So self dot courses and we can use the remove method provided by lists simply remove the course else. We want to say something like course not found, so don't say course not found. Let's save it and then I have some code here at the bottom. Let me uncommon to this. See, for John Doe. I'm trying to remove, see from his course list. And if you see here, John Doe gets initiated with courses to and courses to has see in there, so it will remove that. But then you see, I'm trying to remove course see again, and this one should say that the course was not found. And then the third occasion John Doctor move course Python never existed in John's horseless to begin with, so it will also say course not found. After that, I'll print out John's courses, and they should only include java and rails. So let's run it, see if it works. There we go. You see, for John, the first removal of C took place. We didn't have any issues than the second removal of C said See, not found. Then we tried to remove python over here, I think not found, since it's not in John's course list to begin with, and then we end up with simply java and rails as the remaining courses in John Doe's course list. Great. So our add and remove functionalities. Both are working perfectly, so those are the two methods I want to add in this video. But notice here, though the amount off code I'm having to write to print the characteristics or attributes off our objects. See assured First name assure. Last name was short courses and John First name last name courses. We don't really want to do that. If I simply use print, I'm going to comment all of this out and simply try to print our objects. So sure, and then print John and run this. You see, we get some informational stuff about them being shooting objects and their memory location . But this is not really useful for us in any way. What we want is more often out. Put off the first name, the last name and the course list that the students are enrolled in, and to achieve that functionality, we can use a special method called Underscore underscore str underscore underscore or Dunder str and you look something like this. Double underscore str and then double underscore and it's yet another one off by thin special methods and we'll see how we can implement that along with a couple other special methods in the next video. Hope you're excited. I'll see you there. 26. Special methods and what they are: Hello and welcome back In the end off the last video, we saw that if we tried to print our objects like this as our code exists right now, it gives us this output basically some object info and this is provided by default by python which every object in Python inherits. It's implemented using this double underscore str method also referred to as Dunder str method and it gets called every time we try to get a string representation off the object. Thankfully, we can provide our own Dunder str method. So let's go ahead and do it and this one returns a string so at the bottom here, under my definition for remove course, I'm going to say defined space to underscores str to underscores open close parentheses and this one takes ends just self. There's no other arguments to take in because self has access to all the attributes for this object that we need. And basically anything return from here is gonna be printed out when we print to the object . So if I start with return and just a string Hello and if I try to run this now you see it says hello in both cases for Mature and John, because that's what our method says. So it's a good start, but not exactly what we're looking for. We want to do is print out the first name, the last name and the list of courses in three separate lines so we could do that fairly easily. I'll turn this into an F string on, say, first name Colon and then within curly braces. I'll say self, not first name and then in a new line. So say backslash end for New Line last name Colon within Curly braces himself dot last name . And then I'm going to escape this so I can write more clearly here. All right, and then New line character when I say courses, Hole in open close. Carly, Brace on within it. I'll say self, not courses. All right, so let's see what this looks like. I'll save it to bring this up. Let's run it. Okay, Great. First name assure Last name the same courses first in John last name Doe and the courses that he's enrolled in. Great looking much better. But notice how the first name is lower case, and then the courses are showing up in this list format, and we don't want to have this show up. We simply want the course names separated by commas, and we definitely don't want these quotes associated with strings to show up, either. So let's go ahead and start with capitalizing the first name and last name. That's simple enough. We can simply change the capitalized method over here, so self dot first name dot capital lives open, close parentheses and then last name dot Apple eyes open, close parentheses. All right. And I save it and run it. There you go. That problem is fixed. Now the names are showing up capitalized now on to our list of courses. Let's convert the list elements into a string separated by a comma and a space. And we can do that using the joint function. So over here I'm going to say single quote comma space because I want to separate by comma and a space dock, join self, not courses and close parentheses. Okay, I save it and run it. Perfect. Now I'm getting the courses to show up on the course. Names again are not capitalized. So we need to fix this, and I can't simply run the capitalized method on my courses object right here because courses is a list and a list does not have capitalized method associated with it. What I can do is use the map function and provided the capitalize method, and it will run it on each element in the list. And that's how the map function works. Basically, it takes in the function you provide and then applies it to each element off the honorable . Let's take a look at how that works. What I'll say here instead off self don't courses. I'll say map and the first argument for the map function is the function you want to provide, and it's going to be the capitalizing method. So I have to say where that's coming from and that's associated with string objects. So str god capitalize. You don't have to provide the open close parentheses because that will mean it's a function call. I don't want to do that. I simply want to provide the name off the method as the argument. And then the second argument that map takes in is the honorable and our courses object. Being a list is an interval already, so we can simply close that parentheses here and that should be it. So it will take the capitalize method and apply it to each element in our list before it converts it to the strength. So let me clear this up and run it perfect. There you go. Horses and each horse name is capitalized. Looking good. Now there are a lot of special methods like this Dunder str And then before we saw the Dunder in it, we can get a listing off them. We can say print de ir and then provide the object so unsure being an object off the student class, it should give me a listing. There you go. See toward the bottom first name attributes, last name attributes. These are things we have defined. Then we see the ad course remove course methods which we've added ourselves. But then you see a lot of these methods that were inherited simply because this is a python object and we've already seen how we can override these by including them in our class which we did for str and in it. And you see this dictum method? Let's run that and see what that produces going to copy this and over here, I'll say a sure doc double underscore dicked. Double underscore. Save it. And then let's clear this up and run it. You see, it gives a dictionary representation off my object first name, last name and the courses. So, as you can see, there are lots of useful methods over here. Let's take a look at adding a couple more special methods to our class. I'll clear this up. Let's start with Len. We've seen Len used a few times and usually provides the length off an honorable that we've been trying to work with. So I'll go with you. Find double Underscore, Len, double underscore, open close parentheses and self. So what would be a relevant length for our student object? I would think it would be. The number, of course, is that the student is enrolled in so we can simply return the Len off self, not courses, right courses. Being the list, of course, is that the shooting is enrolled in. So if we now provide are objects to the land function, I'll get rid off these two right here. I'll say print Len, and I'll provide mature Let's save it and mature is enrolled in three courses, so it should give me three. There you go. Three. So we have Len Functionality in our class. Good. The 3rd 1 I want to talk about is the double underscore. A rapper method. It's spelled R e p R. And I'm gonna add this year. Death double underscore Rapper double underscore within parentheses I'll say self. And while we won't use Rapper in this course, it is important to know what it does simply because it is infused quite often with the under str method. Because this also provides a string representation off your object. However, this representation is off. How you would like your object off your class to be in san she hated. So if I ran rapper and provided my object to it, I should get an output that looks something like this, or at least close to this, and this is usually not intended for the user off your program. It's more intended for other developers. Let's go ahead and build at it. So I'm simply gonna copy this code from here. Command. See? Go back here and say a return Command V, and I'll put this in an F string, put it within the quotes. And now we have to update some code here. Obviously not. All off. Your instances are going to have a first name assure and last name Hussein and courses one as the list of courses. So we need to provide whatever these attributes are for the object that's being worked with . And we can do that easily by saying self, not first name, but then we have to surround it by open and close curly braces. And since I'm using double quotes here, I'm going to convert this to a single quote. Then I'll copy this code right here. Come and see. Basted here, Command V. And then instead, first name here, I'll say last name. And over here, put open close curly brace and then within it self non courses. Okay, I'm going to scroll to the left here, get rid off this land print out, and I'll print out Sprint Rapper. Sure. And then print Rapper John. Let's save it. Run it. Clear this up. Okay, there you go. You see this line right here? Student mature Hussein. And then the list, of course, is that looks exactly like this line, right? here, of course. Courses One here being this list and then for John. Same thing. Last name, first name, last name and the list of courses. And the interesting thing about rapper is if under str is missing for your class, then Parthenon actually uses rapper to give a string representation off your class. So if I commented this out if I come to doubt my dunder str and removed the rapper code from here, I save it and run it. You see, I'm simply printing out my objects without under str There you go. You see, It uses rappers string representation instead. Okay, I'm going to uncommon this because I don't want to. That functionality. All right. Great. So those are some off the special methods that I wanted to cover. And while there are a few more, you get exposed to them as you build mawr and more code and develop more applications using python in this course. If you come across any other ones, I'll provide an explanation for what they are. But I don't think that will be the case. So I hope you enjoyed that Now. Any time we've worked with this student class or any student objects. We've done it on the fly, basically written some execute herbal code here and they called the class and used methods and so on. But we haven't actually saved any off our information. So every time we run it, it displays this and then that's it is the end of the program. And it would be nice if we could save the object that we're creating when we're creating them and then storing them in a file. And then if we needed to read them off of the file, we could do that as well. So basically using ah file as a storage system that could be pretty beneficial, and we are going to build functionality surrounding that later on in the course. So that's what we're gonna look at in the next video is how to read from and right information to file. I'll see you there 27. Reading from and writing to files: Hello and welcome back in this video, we'll learn how to work with files so we can store and retrieve information when we want about students. And we're going to work with text files to keep things simple. Let's get started here. I have ah, data, not text file. And I've written out three records in it. In the format off first name, followed by a comma in the last name, then Colon and then the course listings listed out in a row, separated by commas as well. And that the format for all of the records in this file and here is the functionality that we're trying to achieve here I have the file name did not not text, which is this file right here. I'm creating a student object with first name, last name and some courses and a student with this same first name and last name exists in this file already. As you can see, the first record right here, I'm then looking for this student object in that file to see if a record already exists. Then I'm trying to add the student to the file that I'm creating a different student who does not exist in this file and repeating the same process. So essentially, this first finding file will be true because this student already exists in the file. Adding to the file will fail. Since the student already exists. We don't want to override the record, but this student right here, the finding file will return false. And then the ad to file will return true and record will be added. So if I run this right now, you see, that's exactly what happened. True record already exists for the 1st 1 then false since it couldn't find it and record added. And if I look at the data in a text file, you see this additional line has been added with this students information. OK, so that's the overall functionality that we're looking to add. And it will involve a few steps back here at my execution code. You see, we have to add these two methods finding file and add to file, and this finding and file will require reading in data from this file. So we have to learn how to read data from text files and then adding to file will require writing to a text file or in our case, a pending to the end off a text file. So we're gonna have to know how to do that as well. We're also gonna need to convert the record That's a red in to a student object so we can compare it to the student object that we have over here. Similarly, when riding to the file, we have to convert it back to this format. So we'll take our student object that's created, converted to a string like this and then write it to this file. So there are a few steps going on. The conversion is pretty much simple python code with splits and stuffs time. I just pay some of it and explain what it does. But in terms of the reading and writing, we have to build it from scratch. So let's go ahead and do it in a separate file right here. I have named this read and write to demo dot pie. You can name it whatever you like, and I have some variable declarations below which I have temporarily quoted out. I'm planning on using these, and this file is in the same directory as my data dot text file if I type in less over here . You see, I have my data, not text, and my read and write demo in this directory. And this is the directory structure we're going to follow throughout this course where if we're working with a text file or any kind of persistent storage like this, we're gonna have it in the same directory. If not, then when we're reading the file, you have to provide the entire half through the file. But since they are both in the same directory, we can simply reference this data, not text file as data text without passing in any other path. Information. Okay, so let's open this file first. How do we open a file the most basic way and this is not the recommended way, but I'll show you nonetheless, Let's say f the variable name equals I will say open and then finally invariable. And for this to work, we need the file invariable declared. So I'm going to paste this over here. Okay, so I'm basically saying open data dot text, and when you open a file like this, make sure that you close it, so I'm going to write that code out right below it f dot clothes. And if you don't do this, you might run into memory problems in your computer. So definitely remember to close your file once you open it. If you follow this format, we're not gonna follow this format. We're going to use a context manager later on. But at least I wanted to show you how this works. So now that I have the file open and I'm referencing it with F, I conceive the contents of the file. So say F underscore Contents equals F dot reid line. Okay, if I do that and then print out the contents, let's see what happens. F underscore contents. Okay, I'll run this read. Write demo. Check it out. It reads the first line from my data doc text file and then adds in a new line after that. Okay, let's look at another method. Let's remove the line and just read the whole thing. Let's see what that does. Check it out. It prints out all the contents from my data doc text file and then at the end of it adds a new line, okay, and there are other methods that you can run on this. What we're going to use is something different. We don't want to read all the content at once. We want to reiterate through line by line through this file, and to do that we can use a for loop. So instead of this, we can say for line in F print line. If I do that and run this, check it out. It goes line by line through every line in this text file, prints it out, then prince a new line and moves on. So and if you want to get rid off this new line at the end off every print, then we can run the strip method on this thoughts trip. And what this will do is get rid of this new line, and you can specify what to get rid off. If you don't provide anything as a parameter, it will by default, get rid off all the white space before and all the white space after a string, and each line over here is being read in as a strength. So let's run it now. I'll clear this up. There you go. You got rid of all the white space after each line perfect. So what were we talking about in terms of the context manager and the process that we want to use to read in or work with files. Well, what you want to do is not have to write this close f dot close. So you don't have to remember to do this. And you can use a block instead so you can use the key word with and then open file name as f. And then I don't need this line anymore. I don't need to open the file here and simply have this code have over. So it runs within this code block and this is called a context manager. And what happens is when whatever the code is within this context, when it gets executed, it closes out of the file and performs any other cleanup if it's necessary. So if we run this now, then you see we get the same output. Everything is working correctly, and we don't have to worry about closing our cleaning anything up. All right, so now we can read from a file and print out whatever we've read to the screen. How do we write to a file? Let's say I have the string record that I want to add to the file. Let's say record too. Andi equals and let's create a string. I'm going to copy one of these a man. See? Okay, Command V. And instead of Joe Schmo, let's say John Show and then life in Ruby Java Script is fine. So how do we add this record to the end off this file? To write to a file, you have to open the file with write permissions. So over here I can copy this code command, see, and then paste it over here with open file name as and I'll say to write instead of f I can keep it as f as well. But I like to know what I'm opening it for. And when you open the file name by default, it gets are for reading permissions. Okay, so it's like this. You see, the second argument and dysfunction says mode. So the mode that we're opening by default is R for read, and we can provide a W for right over here and right will simply replace all the other content we have here with whatever we're trying to write. So I'm going to demonstrate that. Let me copy this so I can write it back and paste it down here. Uncommon. This outs. Okay. And instead, off the four move over here. I'm simply going to say to write dot right is the method that I can use and then I'll say, record to add And then I'll add a new line also so backslash and to the end of it So it goes to the new line. So let's see what happens when we do this. If I run it Unexpected character. Oh, what's I forgot to provide the quotes around my back slash and should have realized based on this index highlighting, But I didn't. So let's run it again. Okay, We have the output over here from this reading in the information. Then we tried to write this to the file. Let's see what happened to the file. Yep. See, all the other information is gone, and we're left with just the new record that we tried to write. And that's definitely not what we want we want to do is we want to append the record to the end off old other information that we have so I'm gonna uncommon this and then copy it based in back to the file. Get rid of this. Save that. Okay, So what I want to do is add this to the end of the file. For that, I can use a pen and instead of w, I'm going to say a plus. Okay, So a will result in the pen and the plus simply means that if my data dot text didn't exist and to create it, All right, so if I save this now, let me clear this up. We run it, go back to the data text. There you go. Perfect. This is a functionality that we were looking for. Okay, so that's a good amounts that we have covered in terms off reading from the file and riding to a file with different permissions and using context managers. So this is where I'm going to stop in this video in the next video. We're going to add this functionality to our student class so we can utilize it in the way that we had intended to, and we're also gonna need a couple other methods which we're gonna use as static methods because you see, when I'm reading in text in this format from the file. So essentially, like a string like this. I have to split it up and convert it so I can create student objects with this information . And similarly, when I am writing to the file, I have to convert the student objects back to this string format. And we're gonna see how to do that conversion as well. Using the concept of static methods. All right. Hope you're excited. I'll see you in the next video. 28. Add read functionality and utilize special and static methods: a lot of looking back, and this video will add the read and write capabilities that we developed in the last video to our student class. Let's start with reading in the data and creating student objects out of them. So here I have three tasks that I've listed out that I'm going to try to cover in this video. And if it runs too long, I'll finish up in the next video. And the 1st 1 is a function to convert the string two parameters for our innit method. What does that mean? You see in our file this each line is being read in as a string by our functionality to read and data from this file. So let's take this first line, for example. This is going to be read in using this line in F. And then if I print out the line, I get this output right here. And this isn't this form a string off this format and what I'm gonna need to do is extract the first name from the string, then the last name from the string, and both of them need to be strings and then I need to create a list with the remaining items for the list off programming languages to enroll the student in. So if you look at our constructor right now or the innit method right here You see, we take in first, last and the courses list. So we're gonna build a function to convert this string. Do this format. Let's get started. And I'm gonna do it right here, since I have my line like this available. So let me code this part out where I'm trying to write, all right. And I'm going to add this year because I have my line read in and I have it available to work with. And the line is in this format. And you see, here this colon separates the name from the list of courses and that is consistent between all of the records. Therefore, I can split the strength by the colon, so that should be my first step. So let me take my line bearable that I have here and assign it to line Dr Split and within parentheses. I'm going to provide the colon to split it on and let's print out the line. So I don't know why that auto populated Okay, so let's run this now. And what I'm expecting is to get a list with my name as the first element in the list and the list of courses as the second element in the list. So let's run it. There you go. I have all these lists and I have the names. And the list, of course, is separated. Great. And there's a lot of clutter here, so it might be difficult to see. So what I'll do is temporarily leave only one record in here. So I'm gonna copy these and then paste them to the bottom off this script, coming them out. Okay, you can clear this up and see. Make sure my data file is saved. All right, So if I run this now, Okay, so I'm getting just this one output. Perfect. Now, the next thing is, I need to take this first element, which is a string, and split it based on this comma over here. So I get two elements. First name and last name in a list. Let's take our line list over here, and we can reference the first element with the index of zero, and we need to split this further based on the comma. So Doc split and let's provide the comma and let friend this out. There you go. It's split up in first name and last name. So now that I have first name and last name instead of printing it out, I can reference them using variables. So what I'll do is say, first name on last name equals this line, not split. So this first element right here, we'll get assigned to my first name, variable and then last is going to get assigned to my last name. Variable. All right, Good. So far now onto the last part, which is my course details. I can do the exact same thing that I did here for first name and last name and apply it to the courses. So I'm gonna base it in the next line. Man C Command V. Ok, but I want to split the first element. So line one, doc split based on the comma. This will give me the three courses in list format. So let's refer to this as course details. And now, instead of finding out the line if I print out first name and then last name and then course details. You see, I get it exactly in the format that I want to have my first name object, my last name object, both our strings and my horse. Details in list format with one problem. You see, this last element in my course list has this new line attached to it. We don't want that. So let's see how we can remove that. And this split is happening here. You see, Now I can grab this line one, which is this part off my list. At that point, this whole thing is a string. Before I run the split method on it. Which gives me this result, I can get rid off this new line character at the end by using the R strip method. So I can do is change the are stripped method First Doc. Our strip and I don't have to pass in any parameters here or arguments. It will automatically get rid off the new line by default, then dark split. So if I save this and right there you go perfect the line at the end off JavaScript is gone . So that's working very well. Let's now convert this code that we wrote to ah function. So we don't have to include it as this piece off, Execute herbal code right here. And to do that pretty simple. Let's call the function prep record. I'll say, define prep record on and it takes in the line object. And I will simply copy all of this. A man X basted in here. Correct the indentation. Okay. And instead of printing these objects like this, I'm going to return them to whoever called dysfunction. So I'm going to say return first name, last name and course details, and this will be received over here where I call the function from so remember functions. When you have a return value with multiple variables or objects like this, they returned them as two poles. So I'm going to receive a couple here with first name, last name and course detail values so I can simply unpack my Topol, so I'll copy this equals prep record with the line. Okay, so this line right here, I'm passing in. So it's going to receive this perform all off the things that we needed to perform and then return these variables back to me. And if I print of these variables now. First name, last name. Andi. Course details. I save this and run it. We should get the same output. Perfect. So the first part is now complete. I can now create student objects based on what I get back from reading in the string off this format from the file. The next part is to convert student objects to string when I want to write to the file. So basically taking a student object in this format first name, last name and course details and converting it to a string like this and it will be the exact same process in reverse. So I'm not going to type out the code for this. I'll simply paste it in here and you'll see it's basically doing the same thing in reverse right here. I'll taste it in. There you go. So I've called the Function Prep to write. I'm giving it first name, last name and courses first, I have this full name bearable, and I'm basically taking the first name. Adding a comma and then the last name to get a string with the full name and courses is being passed in as a list. So I'm basically using the joint function and joining all the elements in courses with the Kama as the blue in between each element and then I'm returning the full name right here. So first name, plus last name string plus the colon plus the courses, which is the string with all the courses. So let's see what this gives us. I'll create a variable to write and I will call the function Prep too, Right? Mr. Rolled Down a little. So this is clear. Okay, so to write, prep to write. And I'll pass in my first name last name and course details to convert it back to the string line. So that will simply copy this in my script. I have these available over here. See if that remember, the reason I have these available in my strip is because this is not happening in a function. If this was happening inside of a function like in here, then these variables would not be available in my main script like this, which we saw in the function Execution context video. All right, so let's print out to right on dsi. What? That looks like. Save it, run it. There you go see converted back to the format that we had over here. Perfect. So now I'm able to perform both of these functions. I'm able to read in from the file and extract the information to create student objects from them. I'm also able to convert student object information to a string which I can then write to this file. So now that I have everything in the format that we need, we can take these functions and add it to my students demo class. So I'll scroll down and I will add the functions that we had sets to create. So I'll scroll down here, make some more room. All right, define find in file self. Then I'll provide the file name for now. I'll leave a passenger on, then define add to file self on, then file me okay. And the way I'm using finding file is I want to take an object that I create and see if that object or that record exists in the file. In this case. For example, if Musharraf Hossain exists in the file right here, so let's read in line by line from the file using this script that we have created this part of the code command. See? Go back here. This is our ability to read from the file. Make some sweet there. All right, so this function expects file name. You see, I'm passing that in. OK, And here of reference this as file underscore names all correct to that with open file name as f for lying in F. I don't need to print this anymore, because I know this functionality works, But remember, I added the strip method to the line in this next line where I go first. Name last name course details equals rep. Record line. I have to actually say line dot strip good. And this is going to give me this format right here. First name, last name and the list of courses after it. And that is exactly what we have here. Right? That's exactly what we need to create student objects. So I can use this info now to create, shoot and objects directly. I'll do that in the next line. This is the student read in on, and I'll create a student object with first name, last name and course details. Okay. And instead, off printing out first name last name. Course details here. What we need to do is we need to compare the instance of the student that were passing in and compare it to the student that is read in from the file to see if they're equal and if they're equal, will return true, otherwise will return false and will return falls only after we've gone through this four. Loop off all of the records in this file and none of them were equal to our student object right here. I can say if and my instances available through self. So if self equals this student read in, then I want to say returned True. That means the student was found in my list of students in this fire right here. Now, if that's not the case, that's fine. Is going to continue going on to the next line and the next line. And once it's exhausted all the lines and exited from this four loop so down here and no matches were found. I'm going to return False. All right now, for this code to work, we need the prep record function. And you see, we don't have this year we have our prep record function over here, So let's go ahead and copy this command. See, I'll bring it over here and I want to pay. Sit down here after my adds to file method. Okay, now I have my prep record function. But see, this prep record function has no association with my student class or any instance off my student class. It's associated with it because it's performing the conversion. That's very specific to the format of students that we have, but it's not really tied to it directly. So when you have a situation like this where you have ah, function, that doesn't really look like a method associated with the class or an instance off the class, but tied to it in some way, you want to call it a static method and to declare it a static method, all you have to do is say at static method on top off the method definition. So now this prep record function is a static method for my class. So when I referenced this within my class anywhere, like right here, I have to say my class name docked prep record. Okay, so let's see if this functionality actually works here. I have my student first name, last name and the three courses. By then we will be Javascript. I scrolled down the student. I'm creating first name, last name Martin Ruby JavaScript. Exact same record. I'm going to code all of this remaining code out. So technically, if I run this, it should find this object that I'm creating over here in the file. Because that same record exists in the file That's run it and see if it works. And this is student demos of pies in student demo Dupuy, it says false. What happened? Even though the record is exactly the same, why didn't return falls? It returned false Because the object that I'm creating out off this line over here right here shoot and red in the object is not the same. This equality test is comparing objects and the object is not the same as this student object. Okay, because this is being created here. This is referenced by mature. Mature is not the same object as the student read an object even though all their details are the same. So this equality test doesn't really work for our class that we're working with here for our shooting class. And thankfully, Python provides us a special method where we can alter the default functionality off this equality operator, our equality test and provide our own definition for it. And we can do that using the Dunder e que method. So another special method define double underscore e que double underscore. And then this takes himself, which is the instance that we're working with and then the other object that we want to compare our instance with. And we get to define what this comparison should be based off. So in our case, we can simply compare the first name and last name on the student read in with the first name and last name of the student object we created. Obviously, this is not going to work in real world scenarios because multiple people can have the same first and last names. But in that case, let's say you're working with Social Security numbers or something else or some identifiable info. You can use the same logic there for us. First name. Last name comparison is good enough, so let's go ahead and return true or false based on this comparison. So I'll say self dot First name equals other Doc. First name and self dot Last name equals other dot last name. And if you are running into ah long conditional test like this, what you can do is you can move it to the next line using our trusted backslash operator. So after this, I'll put the special backslash move this to the next line, and this expression now is going to evaluate to true or false. So what I need to do is return it. All right. So let's see if now it returns true, which is what we expect. There you go. Perfect. So now we are able to find objects that we create if they exist in the file or in persistent memory. So this is very good functionality to have for our student class. And we can actually use this when we are going to try to write records to file to make sure that we're not writing new records for people who already exist so we can perform the fine first, make sure they don't exist, and then we can write the records. All right, so that's where I'm gonna leave it for this video. We've covered a lot. And in the next video, we're going to add the remaining functionality for this class off writing to the file. And by now, you have, ah, very solid introduction to a lot of concepts and build a lot of functionality here. So in the next video, along with writing to the file which will be the last piece for our class, will also briefly take a look at inheritance and sub classes. While we won't use those concepts much in this course they are an important part off objects and how they work. Okay, great. But we're excited. I'll see you in the next video. 29. Inheritance, subclasses and complete example class: Hello and welcome back in this video, we'll finish up our student class functionality with the ad to file method that we have defined here. And then after we're done with this, we're going to take a brief look at inheritance. So for this ad to follow method, we want to first make sure that the student that we're trying to add doesn't already exist in the file so we can utilize the method that we added in the last video, which was Are finding file method to return? True, if the student already exists or false, If it doesn't so, let's start with that remove the past year. So if self dot find in file and I'll simply pass in the file name to find it, then I'll return record already exists. And then I will enter an else clause if it doesn't. But I'll add that afterward because, as it is right now, I can actually test this functionality and see if it works. You see here in my next execution code at the bottom. If I uncommon this, it's trying to add assured, not add to file. So it's gonna call this method, and it should return record already exist because this record is here. So if I save this and run it, there you go. Record already exists. Perfect. Now let's go to the else clause. If the record does not exist in that scenario, we want to take our self, which is our instance that we're working with and primp it to rideable format like this. And we built the functionality for that in our prep to write function right here. So I'm gonna copy this function code command. See, go back here at it as a static method since it matches all the criteria off our prep record method as well in terms off association with the class without any direct links. So static method. There we go and prep to write Takes first name, last name and courses so that we create the record to add records to add equals. And you call this methods of student dot crept to write. And I'm going to pass in self not first name, self last name and self courses, right? So for now, let's just print out record to add, make sure it's in the right format and I'm gonna uncommon ent this student who does not exist in the file right here. This student object. So I should get an output off their first name, last name and the courses in this format in this string format. Let's run it. There you go. Perfect. And this return none is because I'm not returning anything from my method right here. Add to file. And since I'm trying to print this out, it doesn't have any objects to print out except to the non type, which is returned to by default. So now that I know I have the right format, I can use the logic that I developed here for writing. I scroll down. We had quoted this out its logic right here. I'm going to copy this command, see, and then move over here instead of printing this out. Going to say you let me uncommon this first. All right, so with open file name and I'm passing in file name without the underscore over here, and we're gonna depend this so a plus works as to write. And then I'm using the right function to write the record to add object, which I'm creating here. The student object, which is the string plus this new line character. So it goes on to the next line. Let's see if it works here. It's already saved and then this should now be added to the file. When I run it, let's run it perfect. I got fulls and then none. Because again, I'm not returning anything. So over here There it is. The record got at it. Great. So let's fix this last bit instead of none. Let's go with the record added. So here, once it's done, adding this when you say return, record added, Save it. Let's alter this slightly. Let's say John Schmo, So it should be able to have this record. Let me clear this up front. It Perfect. See record at it. I checked the file. Great. There it is. Working perfectly. Okay, great. So that's our class now looking very nice and complete. Obviously, because of how we implemented this ad to file method, it only adds new records. It doesn't update existing records. For example, this condition here of checking for if the student already exists simply exits out off our active file method based on if the student first name and last name matches. So if you're trying to update just a course listing associated with that student. We don't have that functionality, but that is something you can add with update record, and I leave that up to you. If you want to implement that, it might be very good practice for you. And with that, we come to the conclusion off our student class project. Hope you enjoyed it. Now let's move on to inheritance and our brief look at what inheritance is how it works along with sub classes. Let's take a look at inheritance here I have my student class. I've compressed some of the code. If I expand it there, you see all the methods that we built Now inheritance allows us to use code like this that we have built already for a class in a subclass since we built the student class. Imagine if you were to have a student athlete class and that class would share a lot off the attributes and methods with the student class, for example, a shoot. An athlete is also likely to have first name last name courses. In addition to that, maybe some other attributes that you can add on in that class So in that case, you don't want to build all of this code from scratch. Instead, what you do is have the student athletes inherit from the student class and by inheriting from student, they get all off the functionality that's available to the student class. And you have already seen a bit off inheritance, even though it wasn't explicit. All objects in python that you work with, including our student class here they inherit from the base python object. And we can see that hierarchy off our object by using this help function. So I'm going toe uncommon this code and the bottom right here. So I'm creating this object, Jane, off the student class with some parameters, and I'm printing out Jane to the screen. And then I'm providing Jane, which is of class student to the help function. Let's see what happens when we run this code. You see the definition here, class student which we have put in here. But you see this build chains object. That's where student is inheriting from the base object in python, and all data types and python inherit from this object by default. All right, so if we were to build a class off ourselves. Let's call that a student athlete. So I'll say class student athlete and within parentheses. Provide the class I want to inherit from in our case, student, and then put a hole in after it. And then I'll simply put a path temporarily. Just by doing this, I inherit all off the characteristics off student so I can actually do student athlete here . And then Jane will be off type student athletes. Now if I run the help function on Jame and to exit this, you're getting press Q. There you go quits out of it. I want to clear this up and run this Now you see class student athlete, and there is this method resolution order their student athlete. Then there's students. So student athlete inherits from student and then that inherits from object. All right, so that is the hierarchy off the objects that we're working with here. And you see, more information is provided here. Methods inherited from student. We have all the methods that we define the special ones than the regular methods than the static methods. All this information is provided. Okay, So I'm gonna quit out of here. you see, just by doing this, we were able to create a new object off a new class. That's how powerful inheritances here. I'm gonna get rid off this help code right here. And let's say I want to see the courses that James is enrolled in. I could do that. There you go. All right, So all of the attributes for my student available too much of an athlete. So if you were to build additional methods that may be exclusive to student athletes that you don't want all students to have, then you would add that code over here. So now let's explore. How are student athlete accomplished this task? Because when I'm providing this code, I'm calling the classroom an athlete and providing these parameters. I don't have any NIT method. So how does this work? What's happening? A student athlete is calling the innit method off my shooting class. So if I were to have some additional code for a student athlete, let's an additional attributes like sport, which I don't want my student class to have. Then I can add that here. So to do that, I will define my own innit method for the student athlete class so defined in that, and it will take in all off the parameters from my student class. I'll taste it all here. And in addition to this, I'm going to add in sport equals none as well. So I'll initialize for with the default value if no and instead off typing out this code from here. What you can do is you can call the innit method from the super class and student. Being the parent of student athlete is known as the Super Class, so we can accomplish this by typing in super open close parentheses dot double underscore in it double underscore and then provide whatever you want to provide the innit method off our parent class. So here are parent class takes in First, last and courses. So I'm going to pass in first, last and courses okay and parent class does not have capability off handling sports so that we're gonna have to define here for ourselves. So I'll say self, not sport equals sport. And now if I add in a sport here, let's say hockey. And instead of printing out courses, I'll print out sport. This should work. It's right out there. You hockey now something I should mention here in terms of constructors. If you have cold like this in your constructor, for example, have set sports default value to non and courses Default value to none. If you have cold like this, where one or more off your parameters can default to none, meaning if they don't have to be provided, you can't have a parameter after that that is required. For example, you can't have code like this if I run this now you see Pathan is going to complain, say non default argument follows default argument. In this case, you would want to think about how you want to design this. Maybe you want to change the order and put sport before courses or something like that and then initialize it in that way. All right, so that's up to you. I'm going to leave this as none. OK, now there's one concluding function that I want you to be aware off before we complete this video, and that is a way for testing. If an object, let's say Jane is an instance off a specific class, and the function I'm going to scroll down here is called his instance. So let's try it out. Print is instance. It takes in two arguments. The 1st 1 is the object you want to test. So in our case, that's Jane. And then the 2nd 1 is the class name. So we want to test if Jane is a student athlete, okay? And you don't put the parentheses at the end. I don't know why I defaulted to that. Okay, So this is going to tell me if our Jane object is off class. Student athlete. If I run this, there you go. It says True. What if I remove athlete over here? So now it's testing. If Jane is off type student, that also returns. True. That is because our student athlete class inherits from student. So if I actually put in the base object that all objects in python are based off of and clear this up, let's run it. See, that's also true. However, if I put in list, which is a totally different object or data type and run this again, you'll see it's as false. Okay, so this function we're actually gonna use later on in the algorithm section when we test for data structures after we've built certain structures to see if our object that were creating or passing in our off that type all right, great. And that completes our look at python objects and building our own custom objects as we need. And if we look at our syllabus, the last item is now checked off. So congratulations on having completed this in depth. Look at the python programming language. I hope you enjoyed it. You are now fully equipped to deal with the upcoming challenges that we're gonna take on in the next part of the course as we dive mawr into the computer science aspect of things with algorithms, performance analysis and then on to data structures. Hope you're excited. I'll see you in the next section. 30. Thank you: Congratulations, you've made it. At this point. I'd like to thank you for taking the course. I hope you enjoyed learning about the Python programming language and building programs with it. The topics we've covered, like strings, numbers, lists, which you'll encounter as arrays in most other languages, then dictionary or hash structures, loops for loops while loops functions, Object Oriented Programming and methods. These are all very important topics when it comes to working with programming languages. And you're likely to get exposed to them all over again and again in the real world. At this point, you are definitely ready to take the next step and decide which direction you want to go using programming or using Python in general, whether you want to pursue further knowledge of programming with algorithms and data structures, or you wanted to start applying your skills right away by building web applications or regular apps, or one to pursue machine-learning and learn about Python's abundant resources in libraries for it, the possibilities are endless. And with that, we'll end this video. Thanks again for taking the course and happy coding.