Learn 8 Python Important Concepts Simplified [ Intermediate Python ]

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video you will learn eight important concepts and language features that i think you and me should be very familiar with nowadays i think a lot of us are just caught up with learning these new technologies these frameworks like django fast api flask and so on so learn the core principles and the syntax but do not memorize it never memorize the code but just learn the logic and then you can move on to learn frameworks alright so thank you very much guys and i hope you enjoyed the video in this short video i'm going to talk about a very important concept in python and in programming in general references let's have a variable we'll call it price and this will be equal to 5000 simple integer and let's assign price to another variable we'll call it car so car will be equal to price variable now let's try to alter this price variable and change the value so we will have 7000 for instance so if we will print car car is logically equal to price which is equal to seven thousand so let's see what car has five thousand but when we will print price we have 7 000. let me explain when you assign 5000 to the price variable you're actually creating the 5 000 value in the computer's memory and storing a reference to it in the price variable and when you copy the value in price and assign it to the variable car you're actually copying the reference so both car and price 0.2 or refer to 5000 in the computer's memory when you later change the value in price to 7000 you're creating a new 7000 value and storing it in a second price variable this doesn't affect the value in car actually as integers are immutable values which don't change and changing the price variable is actually making it refer to a completely different value in memory and this doesn't work on lists for instance because lists are mutable data type so if we'll have a value called numbers and we'll have simple integers 0 1 2 3 4 and 5. and let's have any variable for instance jordan is equal to numbers so if we want to alter any value inside numbers list so if we want to change the number 1 to be a string so let's have jordan with the first index to be equal to greetings now if we'll print numbers and if we will print jordan we will get the same result because both numbers and jordan are referring to the same reference in the computer's memory and this was references explained briefly in immutable and mutable data types in this video i'm going to talk about lambda expressions in python to define a normal function you will need the def keyword let's create a function that will return a square number so we'll use the def keyword followed by the name of the function which is square for instance then the input or the parameter that we will need to pass when we will call this function we will close the parenthesis and column then return which is the return statement that returns the result of this multiplication x it by x enter enter if we'll invoke this function square and we will pass any number let's say three we will have nine as a result not all functions need a name though these nameless functions are called anonymous functions or lambda expressions these functions can have any number of arguments but only one expression which is evaluated and returned lambda expression and anonymous function mean the same thing to create a lambda expression just type the keyword lambda followed by your parameter or input which is the x then column then we will need finally to write the expression that returns the x square which is x multiplied by x enter this is useless as the result of this expression will return a memory location on your computer as a matter of fact you cannot use lambda expressions just like that because it doesn't have a name be careful lambda is not the name of the function but it's a keyword that describes what follows is an anonymous function in order to use it you have to give it a name and let's call this lambda expression a so a will be equal to lambda x colon and the expression which is x multiplied by x now you can use this like any other function so you will invoke that a and you will pass inside three and it shall give you the same result which is nine let me give you another example with multiple inputs if i want to create a function that combines the origin and destination of flights for some survey for instance and let's call this lambda expression path will be equal to and we'll use the lambda expression or anonymous function lambda and instead of giving it one input we will give it two inputs here because we will need an origin and destination we will call the first input o and the second d colon then i want a string telling me that the origin then space so what i did here is i called a lambda expression path and this will be equal to lambda taking two inputs o and d and i want to return a string giving me the name of the origin plus the name of the destination enter and let's invoke that path function so path and let's say cairo as the origin and london as the destination enter and there you go origen cairo destination london and let me adjust that so it will be consistent and let's invoke that one more time but we'll change the name of the origin to be tokyo for instance and the name of the destination to be paris so this was a brief explanation of lambda expressions or anonymous functions in python this video is about iterators in python iterator in python is an object that is used to iterate over iterable objects like lists tuples dicts and sets an iterator object is initialized using the etcher method and it uses the next method for the iteration process so it returns the next value in that iterable object when you use a for loop for example to go through an iterable object internally it uses the iter method to get an iterator object which further uses next method to iterate over it's good to know though that this method raises a stop iteration exception to signal the end of the iteration let's have an example on how iter and next methods work let's declare a variable called i underscore value which stands for iterable value and we will give it a value of a string let's say apples let's declare a second variable called i underscore object which stands for iterable object and here we will use the etcher method and we will pass inside our iterable value now let's have a while loop we'll say while true as i want to show you the stop iteration exception we will wrap our code inside a try except code block so we'll say try and we will iterate by calling the next method and so we will declare a variable called item and this will be equal to next method and inside the next method we will pass the i object then let's go ahead and print that item and then accept the stop iteration class and let's go ahead and print a statement telling us that there are no more items to iterate over and we will break out of that loop all right our code is done let's go ahead and try it let's have a second example on lists so let's create another value we'll call it i underscore value two and this actually will be equal to a list with numbers from one through five and we will create a second i object we will call it i object two we'll use the iter method and we will pass inside the i value 2. and let's go down here and change the i object to be i object 2. now if we'll go ahead and try that we get the numbers from one to five all right so this was iterators briefly explained in python this video is about yield keyword let me talk about a very common pattern in programming where you have a function that takes an input or a collection of data does some processing on it and returns a new collection of data where each element has been changed fundamentally let's take this example shown on the screen where we have a function which called foo takes an input then we have an empty list stored in a variable called res what we do next is we iterate over that input which might be a collection of data like a list or dictionary or any iterable data type and then on line 4 we do some processing on that input and then we append it to that empty list and finally on line 5 and by the end of that function we return res so it's a long process which goes through and taking a list during some process and returns a changed one the problem with this is that it's a long operation we don't get back any of the values till it's finished and if this data collection is big we will have a second copy of it in the memory before we can start doing any work on it really but what we want to do is we want to take each element and do some processing on it right away and then immediately give it over to the color of that function and here the yield keyword comes for a situation like this where we don't want a temporary collection which is the rest list right here and where we don't want to iterate many times before we return the value so in order to use the yield keyword we will just delete this list right here on line 2 so let me copy this code block and paste it here then let's go ahead and delete that list because we don't need that anymore we also cannot return the rest now because we don't have it and on line 10 instead of res dot append we will just substitute it by the yield keyword so yield basically means when you get to this line line 10 you want to take this value and send it out of the function as the next element in the sequence and you might think where do the calling for these values come well if they just iterate over each value then each value is being handed over immediately while suspending the function for a second so the process of iterating stops briefly till you ask for the next item and i know this is an abstract example so let me give you a practical example so you will get better understanding of the yield keyword so let's have a function called cube and cube takes an input of num then we will have an empty list then we want to iterate over that num so we'll say for i in num then we will do the processing on the input and we will append it to the res list i multiplied three times and finally we want to return the address list now let's go ahead and create an object we will call it bar and here we will invoke our cube function then we'll take a list of numbers from one to five and let's go ahead and print bar python main.pi and there you go we have a new list with our new cubed numbers now let's go ahead and use the yield keyword and we'll use the same example define cube takes num for i in num and instead of line 16 and 17 we will just use yield and then i multiply three times and let's create our object bar cube one two three four and five and we will print bar exactly like the previous example if we run the file one more time we will have a different outcome notice that i'm not getting the previous result 1 8 27 64 and 125 instead i'm getting a generator object at this memory address and this is simply because generators don't hold the entire result in the memory instead it yields one result at a time as explained previously so it's waiting for you to ask for the next result of that cube operation so actually here we didn't compute any numbers yet so what we need to do is we need to use the next method so we will use the next method inside the print we'll run the file one more time and then we'll get one as we said yield hands over one item at a time waiting for you to ask for the next item so if we'll copy this line four more times and we will execute the file we will get the numbers from 1 through 125 as expected all right so this was the yield keyword briefly explained in python this video is about generators the prerequisites to understand today's topic is to know yield statement and iterators you can check out the latest two videos in the series when we talk about generators there are two terms involved generator function which is like a normal function the only difference is whenever it needs to generate a value it uses the yield statement instead of return statement therefore whenever a function contains yield this function becomes a generator function okay let's define a function and we will call it gen fun open close parenthesis with no inputs involved colon and we will use yield statement or keyword and we want to yield just the number 10 and 20 and 30. all right this is simply our function now let's have our driver code to check out the generator function so we will have a for loop for i in this function gen fun we want to print the i so it will loop over each element inside the function and it will yield it all right let's open our terminal and let's check it out python main.py we get 10 20 and 30. so gen fun is a generator function because it uses the yield statement instead of the return statement now what about the generator object generator functions return a generator object so generator objects are used either by calling the next method on the generator object or using the generator object in a for loop let me give you an example for that so here let me put a comment generator function then here we have generator object so we will have another generator function we will call it gen fun 2 without any inputs or any parameters and we will not yield only numbers but we will try different data types so the first yield is 100 which is an integer yield true which is a boolean value and the third yield let's say hello world which is a string all right this is our gen fund 2. now if i will declare a variable i will call it for instance crap and scrap will be equal to gen fun to function if you will hover over scrap you will find that scrap is a generator in other words scrap is a generator object and let's try to print scrap okay let's open the terminal and let's run the file and we will find that generator object genfont2 at and this memory location okay so this is not useful as we have seen in the last video so what we need to do we need to use the next method so let's involve the next method in our code now if we will run again we will get 100 which is the first yield and as we said the biggest advantage of using generators is that it doesn't use the memory extensively and if we want to do for true as well for the second yield so what we will need to do is just copy that line and now we have 100 and true so in order to yield the third value we'll just do the same and we get 100 true and hello world but what if we run it again we will get an error if you remember stop iteration exception so in order to avoid that let's wrap our code in a try except block so we will take this we will indent it inside accept stop iteration and let's print a statement that this is the last item in the code so let's try that one more time so we get 100 true hello world and our message this is the last item in the code now let me show you a final example that shows generator function creating add generator object so let's create a function we will call it add num which adds two numbers and it takes num as input for i in num just a for loop we want to yield i plus i add num is a generator function now let's declare a variable called foo and through will be equal to add num function and we want to pass inside our arguments so we will have a list of two numbers five and two for instance then we want to print foo and let's check that out so python run dot py and we will get again a memory a different memory address let's use next and let's run that one more time and we get ten because five plus five equal to ten let's copy that line one more time in order to add two plus two now we get ten and four but what if we will do it for the third time now we can expect a stop iteration error so let's wrap that again in a try accept code block so here we will say accept stop iteration and we will print no more values to add all right and we get 10 4 and our message no more values to add so this is our way to handle any errors or exceptions in our code so to recap add num is a generator function foo is a generator object we don't save any values in the memory and wait until we use it instead we yield every value that we really need in order to do some processing on it okay so this was generators briefly explained in python this video is about doc strings in python python documentation string or docstrings provide a convenient way of associating documentation and the documentation could be for modules functions methods classes and anything else it's specified in source code that is used like a comment to document a specific segment of code unlike conventional source code comments the docs string should describe what the function does and not how it does it now let's see what does a doc string look like well the docs string should begin with a capital letter and end with a period also the first line should be a short description and if there are more lines in the documentation string the second line should be blank visually separating the summary from the rest of the description how to declare doc string while the duct strings are declared using triple single quotes or triple double quotes just below the clasp method or anything that we want to describe and in my opinion all functions should have a duct string now the question on how to access a dock string can be answered in two ways one way is using the dunder method doc and the second way we can use the help function let me give you an example let's define a function we will call it func one doesn't take any input and it doesn't do anything really so let's create now a doc string so i will use triple single quotes and i will say this function does not do anything and i will close the triple single quotes and i can say pass and pass in python means skip this line this doesn't do anything now let's access the docstring so we will take our function1 and we will access the dunder method called dog enter and now we get access to the docstring this function does not do anything so this is the documentation of the function describing what the function is actually doing so the under method doc is the first way to access a dog string and the second way we said we have help function so let's take help function and we'll pass inside our func one so we get help on function func one in module underscore underscore main underscore underscore then we get the name of the function and the next line we have the description this function doesn't do anything and we can do the exact same thing with the triple double quotes i know it sounds weird triple double quotes all right let's take a look let's have another function called func two and now we have our triple double quotes let's describe this function which basically doesn't do anything and let's change from past to return none basically it will do the same thing and let's take func 2 dot the dunder method dock and we get the same thing and let's have help function working on funct2 and we get the same thing so it's best practice in python to write doc strings in functions and this was dog string briefly explained in python this video is about closures in python in order to understand closures you should be familiar with nested functions and first class functions you might want to check out a series of videos i've made on functional programming so if you didn't watch it go ahead and watch that first otherwise you won't find a problem understanding closures so let's start by creating a function we will call it outer fung and it doesn't take any parameters or input and let's create a variable and we will assign it to a string and inside the string we'll say hello from outer func function okay next let's create a nested function we will call it inner funk this inner func function is nested inside the outer func function and again it doesn't take any parameters and what it does it prints whatever text is declared above in this case hello from outer func function and by the end of the outer func function we will invoke the inner func now let's go ahead and call or invoke the outer func function and let's check out what will happen we get a message hello from outer fung function ok so let me walk you through this when we have invoked the outer func function this actually has triggered the third line of code which is a definition of that function then declaring a variable called text and assigning it to a string called hello from outer func function then defining a second function called inner func and this prints whatever text is declared above and at the end we invoke the inner func so by invoking the inner func we have printed actually the text which is in the scope of the outer func and the text variable is also called a free variable because even though it was not declared inside the inner func function we still had access to it inside the outer fung scope so text was declared in the outer fung function body but the inner fung function which is a nested function inside the outer function had access to it and can print it all right so by invoking the outer func function you actually have invoked the inner func function okay now let's try to return the inner func function instead of invoking it so the first step to do that is to delete both parentheses and add the word return here and this will change everything completely so if you will try to run the file again it doesn't look like anything happened here and actually if you will assign the outer funk to a variable let's say i don't know batman and you will hover over batman you will find that it's indicating the inner funk function okay so to show you what i mean let's print batman and you'll find that this is a function and the name is inner func so if you will print batman dot name you'll find that it's called inner fung so basically batman is equal to inner fung and this is fascinating because even though we are done with the execution of the outer function the inner function that we have returned still has access to the text variable so to put it simply a closure is an inner function that remembers and has access to variables in the local scope in which it was created even if the outer function is invoked already and has finished executing okay so this is a closure batman actually in this case is a closure and let me show you actually if we will add some parameters here to the outer func function so we will say name for instance as an input and in this case we don't need that variable but we will assign text to whatever name will be passed okay and let's actually create let's say batman outer funk and as a name we will say bruce wayne and let's add a second variable let's say spider-man and let's say here peter parker has a name all right so we have here spider-man and batman and both are referring to the inner fung function so let me clear the terminal and let's invoke both functions because batman now is a closure or is a function that is referring to the inner funk or this nested function and similarly we'll do the same thing with spider-man and let's run the file and indeed we get bruce wayne and peter parker returned okay so this was closures briefly explained in python a sync io or a synchronous io is a library to write concurrent code using the async await syntax async io is often perfect fit for io bound not cpu bound and also a perfect fit for high level structured network code and here we'll touch on the concept of co routines but before i show you how a co-routine looks like i would like to show you what a subroutine looks like you can open your bash or your terminal let's go to python and a subroutine seems to be a very scary word but actually it's a simple function it's also called a procedure and it's declared by the dev keyword so if i will create a function that prints hello just hello and after it prints world on separate line and let's also print the end okay and if you will call the function you will get hello world the end all immediately this is a sequential process hello gets executed then world then the end with no waiting time the subroutine or the procedure gets executed all in one go now let's type the same code but differently we will use the concurrency principle and this means executing a line then giving some time for the other line to be executed then receiving a callback telling us that this line is done for example then the other one is done the last one is done and we finished execution of the whole code this is the whole idea of um the co-routine so for that we will use a sync await so let's first of all import the ascencio module or a sync io and we use a sync keyword main and will print hello okay now i want to give some time to sleep or to block any other code from being executed so we say hey guys wait until this line print hello is finished executing and we can block any task from running by using the async io module dot sleep method just to give some time to sleep and let's give it two seconds for example during these two seconds everything will be frozen until the print hello gets executed even if it's done in less than two seconds still everything will be blocked until the two seconds are done let's print world now let's give it some time to sleep or to block let's say for three seconds just for the example to be very clear to you and at last we'll say the end all right and that's it now if you will try to call the main function directly you'll get here a coroutine object main and saved on this memory address on your machine it doesn't get executed when you just type main but in order to call the main co routine we need to do essentio or async io dot run main hello then two seconds blog world three seconds blog then the end and that's it so this is the main difference between a co routine and subroutine and i will probably create a crash course on a sync io in python because it became very very important nowadays something that you will need to know very well if you would like to be a python developer
Info
Channel: Bek Brace
Views: 17,563
Rating: undefined out of 5
Keywords:
Id: qeOcZiSp3tE
Channel Id: undefined
Length: 36min 25sec (2185 seconds)
Published: Fri Jun 03 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.