Python Part 12b - Advanced Functions Office

Python Part 12b - Advanced Functions Office Welcome to this wisel tutorial on advanced functions in python it's the second in a two-part tutorial on writing functions in this wonderful programming language so here's what you'll learn in this second part of the series in the mini-series we'll learn how you can distinguish between keyword and positional arguments and how you can force users your function to use one or the other we'll look at how you can specify arguments which are optional that you don't have to pass in but you can if you want and then we're going to look at how you.

Can pass an array of arguments to a function and how you can pass a dictionary of arguments and i'll explain what these things mean and finally we'll look at lambda functions which have been promising for some time which are another technique that you can use at any time you'll be able to click on the link at the top right of the screen if it's visible otherwise you'll be able to use the link on the wizard website or indeed on the youtube site and that will allow you to get files to do with the tutorial or any exercises.

But i think i'm about to disappear now and as always i'll let sven carry on with the rest of this tutorial to guide you through the topics let's get started so as an example of using named versus positional arguments we're going to create a function called bmi which will calculate anyone's body mass index which is a measure of how overweight somebody is it's not completely reliable and i put a link to a bbc webpage proving this but as an example of writing a function in python it's invaluable.

So to create a function you type def and i'll call it bmi open brackets and then i'll put my two arguments the first one will be the height which will be a float because you don't have to be a whole number of meters and the second argument will be the weight which is also a float because you don't have to be a whole number of kilos either and your bmi itself doesn't have to be an integer so this will return a float too and that completes the definition of my.

Function so now i'm going to create a variable which i'll call body mass index and i'll set it to be somebody's height divided by their weight squared sorry the weight divided by the height squared so i'll take the weight and divided by the height raised to the power of two and then we can just return that i didn't really need my variable at this stage and that should give us somebody's bmi.

What i can now do is test this out and you're welcome to substitute your figures figures of your friend or relative if you like at this stage so i'm going to create a variable which i will call uh my stats and i'll set it equal to bmi open brackets so uh here's a terrible truth i'm about 1.8 meters tall but i'm a slightly overweight 82 kilos and so when i print this out i think i'm going to see people recommend that your bmi should be less than.

Python Part 12b - Advanced Functions

25 and mine isn't it's 25.3 but it teeters on the edge so that's probably okay so that's a basic bmi function now when i called this i used positional arguments i relied on the fact as we have done throughout this tutorial series so far that the first argument would correspond to the first argument specified in the brackets there and the second one 82 would map onto the second argument in the brackets now you don't have to do that what you can.

Do instead is use named arguments so i'm just going to rewrite this and instead of using positional arguments i'm going to actually name them so i'm going to say where my height is 1.8 and where my weight is 82 and if i run that i'll get exactly the same answer because it's doing the same thing this is two benefits one of the benefits is that it's much easier to read you don't have to think.

Is that the height is that the weight you can immediately see it but the second benefit is i could of course put the arguments in any order i like so i could put the weight first so i'll set my weight to be 82 and my height second it would still work so it's undoubtedly true that named arguments are better to write so why haven't i taught them yet i guess the answer to that is even though they're better very few people.

Bother using them and i must admit i don't usually it's just so much quicker to miss out the names of the arguments and just put the values in instead now there's just one more thing to say about named arguments which is that you can actually mix and match so to prove this let's create another variable i think what we're going to do is show winston churchill's bmi their estimated figures so churchill bmi.

And what we'll do to prove that i can mix and match i'll start with a weight and set that to be my notes say 95 which seems a bit much and then the height is 1.68 now i don't think this is going to work it's underlined it and the reason is a positional argument can't appear after keyword arguments so you can mix and match but only if you do it in the right order now if you think about it this actually does make sense otherwise having eliminated all the named.

Arguments how would it know what positions to put all the other arguments in there'd be ambiguity so yes you can mix and match but you have to do it in the right order so let's try again i'll start this time with a height which in churchill's case was 1.68 and now i've eliminated all the position arguments i can carry on and specify named arguments so i'll put his weight with 95. i've only got two arguments there but the principle works however many you've got you can list out all the positional ones first and then all the others can.

    Be named if you like check this works because before i give

    My thoughts on that i'll just run that and you can see churchill's bmi was a fairly overweight 33.65 unless he was an elite athlete i think it's possible he was overweight is this a good idea i don't think so i think it makes more sense to use either all named arguments or positional ones i can't see the point in mixing and matching having said which the next topic we're going to do will show how you can force.

    People to specify some arguments as positional and others as named you're specifying arguments in a function you can force your user to use them either positionally or by keyword and here's how this works if you specify a forward slash as an argument then any arguments specified before that and the list must be passed impositionally and if you specify a star or an asterisk then anything arguments after that must be passed in by keyword so here's what this might look like for.

    A complicated example admittedly so in this case anything before the first forward slash so anything to the left of this if you like must be passed impositionally so the first two arguments you can't specify the argument name you just have to put in the by contrast the star means that anything following that in the argument list can only be passed in by keyword anything between those two can be passed in by position or keyword.

    So the syntax is reasonably clear whether you'd actually want to do this i'm not so sure why not just give your user the freedom but having said that let's have a look at an example which actually uses these two symbols so to illustrate this i've created a new file called forcing named or positional arguments dot py i've added in the comments from the slide we just saw just as a little backup a bit of information and i've added in stalin's bmi using.

    Estimates i got from wikipedia which don't seem entirely accurate now the difference between the way i'm calling churchill's bmi and stalin's bmi is for churchill's i'm using keyword arguments or named arguments that i was calling them earlier and for stalin i've used positional arguments only and all of this will work perfectly so if i now try running that and you can see churchill was considerably more obese than stalin which is no great surprise although it did surprise me how short stalin was i.

    Never knew that so now let's add in some twists the first thing i'm going to do is type in a forward slash comma and what that will mean is any argument before that which in this case is the height has to be passed in positionally so my prediction is this line of code line 17 will crash because i'm not using a positional argument for that let's see if that's what happens so if i run that you can see it doesn't d crash line 17 and the reason is.

    It's got some positional only arguments passed as keyword arguments the height so what i would need to do is either remove the named argument but i'm actually going to cheat i'm going to comment that out and then if i run this again you should see that the second time it runs and gives stalin's uh bmi because for starlings i'm passing them both in positionally so let's now reinstate that so that's um what position like forcing positional arguments does now let's.

    Twist it and force keyword arguments so what this will do is say any argument after that specifically the wait has to be passed in as a keyword so this time churchill will work fine because i've done that but this stalin will trip up over and line 21 will crash so again let's see if that's actually true and it crashes on line 21 it's always nice to be proved right it takes one positional argument but i gave two so to get this to work what i would have to do is comment out stalin's this time.

    Um and then if i run my code you should see that i get churchill's bmi so that is uh how you can force a user to use keyword or use positional arguments but i think to be honest one of the main benefits is understanding uh functions that other people have written for you to use just to take one example suppose you have a list of three numbers it's a list because it's got square brackets and you want to sort it you may have wondered why you always have to specify the.

    Reverse keyword and the reason is this star there by putting that in the people who wrote

    This function ensured that any arguments you use have to be specified as keywords and not as positional presumably to make it um easier to understand what you're actually doing so that's probably the main benefit of learning about keyword and positional arguments in contrast to the previous section on forcing named and positional keyword arguments.

    This is i think much more useful i'm a big fan of optional arguments i use them all the time as an example here's my bmi i've copied in the function to a new file called optionalarguments.py and just added a line to print it out and if i run that you can see it says my bmi is what it was before but is it i'm not so sure i guessed my height in meters and i guessed my weight in kilos because to be honest i still work in imperial units now international viewers may be a bit baffled by these but the uk still works.

    To some extent in feet and inches and stones and pounds so what i'd like to be able to do is to specify the same thing so i'll just copy that line and repeat it but this time i would like to put my height in inches which is 70 ish and my weight in kilos sorry my weight in pounds which is 178 and that will give me a more accurate view but obviously if i run that it gives me my pmi 0.04 and i feel it's more than that.

    What i need to do is change this calculation but in doing so i don't want to mess up all the previous people who have been using my function successfully without problems so i want to add an argument which is sometimes specified and sometimes isn't and which will default to a given value and that's very easy to do you just go into the list of arguments and add one at the end of your list or more than that if you want i'm going to call mine ifmetric and you specify a type for it which in my case is going to be a billion.

    And you set it equal to true so what will happen now is by default this argument will be set to true but i've got the opportunity to set it to false on my other calls so both of those two lines will work but obviously what i now need to do is i need to go back to my function and add additional syntax in here to cope with the eventuality i'm using imperial units so to do that.

    I'm going to add an additional bit of calculation saying if i'm using imperial units change my calculations so to do this i can say if not if metric so if i'm not using the metric units which i will be by default then what i'll do is i'll take my height set it equal to what it used to be times 2.54 because there's 2.54 centimeters in an inch and divide that by 100 to get my meters.

    Let my weight equal to what it used to be times sorry divided by 2.2 because there's 2.2 pounds in a kilo otherwise i'll leave everything as it was so now if i run this program again you can see a better oh dear i was hoping it would go the other way a better estimate on my bmi is 25.59 because i've given a more accurate uh estimate of my height and weight.

    So that's how you can add optional arguments the most common reason i use them to be absolutely honest is when i've forgotten an argument i've written a function i've included it all over my code and then i want to add the extra argument i forgot and i want to make sure adding it doesn't mess up my existing calls to the function and so i make it optional to make sure that i can specify my call to my argument with or without this extra call to the function with or without this extra argument.

    We've seen that you can pass an optional argument to a function you can actually specify that an argument should have optional size so whether it's just a single item in it or lots of items what this section of the tutorial will do is try to explain an example of when you might want to choose this i must be honest i don't use it myself that often and this is slightly for the sake of completeness so let's say we have a few files listing our films similar to the ones we used in the previous tutorial taking the animation one.

    At random i can open that in notepad and see if it gives me a list of all the animation films and what i'm going to do is import all the lines but the first one for the animation file what i'll then do is extend it so i can import lines for lots of files at the same time so to get this to work what i'm going to do is firstly create two variables the first one i will call file path and i've got this in my clipboard so i'll set it equal to let's paste that in.

    That's where my files are stored and then i'm going to create another variable to create an empty list and this will be populated with all the lines that i want to use to do that i can just put two square brackets one after the other i'm going to do is to find my function which will read in the lines of a file so i'll call it read file i'll pass in a single variable which is.

    The name of the genre because this function is adding lines to my list it doesn't actually need to return anything so to stress that i'll say that it doesn't return anything it's called void in c sharp for anyone who knows that i can read in my file so i can say with open i can put my file path in and then concatenate onto that the genre i passed in but then i also need to add on to the.

    End of that the dot csv to get the full file name and i'll call that genre file without file open what i'm now going to do is to read in the lines and i'm going to store them in a variable which i'll call genre lines do that i can take my genre file read in all the lines from it split the lines so that i've got one item for each line and then pick from that pick out everything from the first line onwards.

    Sorry from the second line onwards so basically i miss out the first titles line from the cs3 file then finally in my function i can add these lines to my array to my list a lines dot extend you can see it's extend because that takes as an argument an iterable set of things which i can add onto my existing list so i'll add in the genre lines i've whoops these genre lines i've just read in.

    That's my function let's now see if this works so i'm going to read in lines from one file so to do this i'll call my read file function and i'll pass in the word animation it's not case sensitive by the way what i can then do is print out the lines to do that i can say for line in lines bear in mind lines is a list which i've accumulated by running my function so for each line i'm just going to print it.

    Out i don't think we've used a function like this before rather than storing the value returned from the function in a variable we're just calling the function without attempting to to output anything from it or to capture any information returned from it so if i now run my program you can see it lists out the lines in the animation file and finally i can get to the point what i'd like to be able to do is to pass in other bits of information so what do we have we had animation we had comedy let's have musicals in as.

    Well so i've missed out the first one and i'd like that to print me a list of all the lines in all the files but it won't because i said it took one argument and i provided three what i can do is magically put a star in front of the name of my argument and what that will mean is it has basically infinite possible length there might be a single item in it there might be lots to make it clear what's going on i'm going to put an s at the end of my argument so i'm going to go genres if.

    Something can be plural i like to have an s on the end of it and then what i need to do is amend my code here so i'm leaping over all the genres there might not be any but they might so i can say for each for genre in genres just need to indent that code and the rest of it will work okay so what will happen now when i run this is it will pass in three string items so the length of this extensible.

    Argument will be three items will have three items in it it'll loop over each item in that collection if you like and open up the file and add the lines to my list and then finally we'll print them all out let's see if it actually works so if i run that you can see i've got my animation i've got my comedy and i've got my musical lines which is all well and good but the thing which always strikes me about this is why didn't i just create this as a list and pass a list into my function instead.

    So i did say i was adding this for the sake of completeness but i feel duty done now and i can move on to the next part of this tutorial so as well as passing in a single optional value as an argument you can actually pass in a dictionary of arguments and what i'll try to do in this example is explain how you do this and when you might use it although again i'm not absolutely convinced this is a an essential part of your python armory.

    Let's suppose you had a list of films as we've had so many times and you want to possibly print out the name of the film when it was released to do this you might contain a set of arguments the first one would be the column number which gives you the common number to pick out in this case it's the third column in our list of films and the link text will be the words it was released in now you could do the same thing to produce different output so if you might want to show how many minutes each film lasted and in that case you could use the same set of arguments but this time you could.

    Pass in the column numbers four and the link test has lasted for this many minutes and you'll get a different output because you've got different inputs going in to get this to work you could create a dictionary of arguments and the dictionary would have two elements the first one would have a key of column number which would be set to four for the second example and the second key would be link text test which would be set to lasted for this many minutes bear with me with this.

    So let's now have a look at this in practice i'm going to use the example of musical.csv file we've seen before and if we open that up in notepad you can see that it contains the title line which will miss out and then it contains for each line of five bits of information the idea of the film the name of it or the title when it was released how long it lasted whoops how long it last how long it lasted and the genre so what we'll do is read that information in and then according to the.

    Value of the arguments we pass in we'll print out one of those columns with some link text before it so to do this i've created a file called argumentdictionaries.py and i'm going to open up my musicals cm csv file and i can do that in the usual way by saying with open i happen to have the path and the file name in my clipboard and i'm going to say as and then i'll call it csv file for each of those what i'm now going to.

    Each file i'm going to print out or leap over all the lines in it so i can say for line in and i can take csv file dot i'm going to read in the entire contents split the lines and then take everything from the second line onwards what that will do is loop over all but the first line of the csv file and then what i want to do is i want to print out the information according to my function which i haven't yet written so i'm going to take a bit of a.

    Digression now and write my function now i could write the function down here but the problem with that is i would be trying to call it before i'd even written it so i need to make sure that my function is at the top of my module so to do this i can define a function i'm going to call it print info and i can pass in two things the first one is the line of text i'm going to print out which will be a string of text and the second thing is the extra arguments i'm going to pass in which will be a dictionary of extra things and the way you specify a dictionary of.

    Extra arguments is by putting a double star in front of it and i promise that's the last extra bit of punctuation i'm going to show you in a function definition line thing isn't going to spit anything back out it's just going to run and stop so i'll just put that it spits out none what i can then do is print out the line to do that i'm going to create a variable i'll call it bits which will take the line i passed in and split it by the commas.

    Will give me a list with five items in it what i can then do is work out which bits i want to pick out and display them so the the link text that i want to display is going to be and this is where you're going to have to take a holistic view it won't make sense till i've done everything in my dictionary called extras there's going to be an argument passed in called link text and once we'll give it the same name.

    That will be the text i want to display between the title of the film and the bit of information i want to display and then i'll have another variable which i'll call column number and i'll set that to be the value of a dictionary key called column number what i can then do is print out the information so i'm going to print out the name of the film which is the first item in the list then i'm going to put a plus in then i can put my link text in.

    DISCLAIMER: In this description contains affiliate links, which means that if you click on one of the product links, I'll receive a small commission. This helps support the channel and allows us to continue to make videos like this. All Content Responsibility lies with the Channel Producer. For Download, see The Author's channel. The content of this Post was transcribed from the Channel: https://www.youtube.com/watch?v=XHXPyatT91c
Previous Post Next Post