Transcript for:
Python Syntax Overview

I'm about to teach you almost all of python syntax you'll learn about the things that python can do we'll be going quick so it may be helpful if you have at least some programming experience in this tutorial if I show code that starts with three angle brackets that means it is the python shell the lines of code are run individually and the result of running the code is displayed right below if there are no angle brackets that means it's a section of code that's meant to run all at once in a program okay let's get started basic math works just like you would expect in Python you can just do addition multiplication division basic order of operations you can use parentheses you can concatenate strings just by putting two strings right next to each other you can use a plus sign to concatenate them to put them together but you don't have to you can just use a space and you can also multiply strings L times five equals Alice five times this is how you create a variable spam is the variable name and it's set to equal the string hello and this is a comment and then a multi-line comment and this is how you initialize a variable we're initializing the a to one you can print a message to the console just like this print hello world and in the print statement you can put a comma and we have a string and then the variable and it just puts a space in between now here this is how you get input from the user just this input here we can set it to this variable and we can print what was typed in and this is a special way this dot format it's a special way to put a variable in a string there's a few other ways that we'll talk about later the length function we can get the length of a string hello is five characters and the Str will convert an integer into a string and then end we can convert a float into an integer these are the different equality operators it's pretty much the same in every programming language just keep in mind that equal to is two equal signs a single equal sign is the assignment operator so we can check to see if hello equals hello well no because there's a capital letter and one in a lowercase h on the other an INT and a float do equal each other an end is is a number without a decimal and then a float is a number with a decimal point here and we can also see if something is not equal dog does not equal can't that's true but you should never use the equal equals or not equal operator to evaluate Boolean operations use the is or is not operators or use implicit Boolean evaluation we can use and to evaluate two things so the first one and the second one has to be true for this to evaluate for as true and we can use or so either this part or this part can evaluate as true for it to be true and you can combine multiple ands and Knots together and this has how you do an if statement so if the name equals Alice then we'll print hi Alice and in Python spacing or tab is very important after the colon the next line has to be indented or tabbed over and each line that's indented the same amount will be inside the if statement so here's how you do if else so if the name is Alice hi Alice else if any other condition if name equals anything else print hello stranger we can also do an LF or an else if so if this is true then we do this but else if we're gonna we're now going to check if this is true if age is less than 12 then we're going to print this and if neither is true we're not going to do anything now we have the if the L if and the else we've combined everything so if the first two are not true we'll do this last line here and this is a loop this is a while loop so while spam is less than five it's going to keep running this these lines of code over and over until spam is not less than five and then the code will stop running now if you do while true that means it's going to continue doing this forever but if it hits a break statement then it's going to break out of the loop and then go to the line underneath the loop the indentation shows which lines of code are within the loop so these three lines are all indented so they're all in the while loop and then this line is indented even more so it's in the if statement so here's another while loop if we get to continue that means we'll just go to the next iteration of the loop and you and it's not going to run any of the code after the continue statement so if name does not equal Joe it's just going to now get another input from the user and then when it gets to break that's when it will break out of the loop and go to this next line of access granted here's another type of loop a for Loop for for I in range 5. so range 5 is going to go through the loop five times and I is going to be each number in the range from 0 1 2 3 4. so you can see it prints 0 1 2 3 4 it gets used a format to add this variable right into here into the string another way you can create a loop is with this so range 0 10 2. so 0 is the first number in the range 10 is the last number in the range and 2 is the increment so it's not just going to count zero one two three four five six and eight nine ten it's going to do zero two four six eight which you can see down in the print statement and you can also count backwards so now we're going we're incrementing by negative one each time so here is a 4L statement the L statement will only run if a break has been reached in the loop and here's how to import a module we're importing the random module and then we're using the random module to get a random integer between 1 and 10. and this is how you would import everything from the random module if you want to end a program early you can use sys.exit this is how you create a function def hello and then you can pass in a name to the function and then this is what is the body of the function so we can call this function many times so here we're calling the function hello and passing in Alice and you can see it prints hello Alice that's right here hello Alice it's getting the Alice from this name variable here and we can also call the function again hello Bob so you can call the function multiple times with different things that we're passing into it and here's a function with return values so when this function is run this get answer function is run it's going to return something different see return it a certain return it is decidedly so so depending on what number what's answer number it is it's going to return a different text so we're going to get a random integer here and then we're going to get the answer of the random integer and it's going to print the fortune which is going to be one of these strings normally a print statement will have a new line at the end but if you specify end to be just an empty string here there will not be a new line at the end so then both print statements will happen on the same line like that and this is just an example of printing a bunch of strings and if there's comma in between them it's just going to put a space in between them when it prints out and you can also specify what the separator is normally it's a space but you can specify it to be a comma or anything else usually if you define a variable within a function you cannot use that function outside of the variable but if you put the global keyword here Global X and we're setting this variable X to be a global variable so now when the function runs here it's actually going to change the value of the X variable people when it prints princess eggs it's spam this is basic exception handling you used a try accept keywords we're going to try something that could cause an error now if you don't have in this try block here an air will make the program end but if you have this try accept instead of making the pro instead of an error making them program end it will do whatever happens here except if there's a zero division error then it's going to print error invalid argument and you can see in this example when we print the spam 0 it's not going to make the program stop it's going to print this error here's another example with a finally statement a finely section code inside the finally section is always executed no matter if an exception has been raised or not and even if an exception is not caught here is how you create a list a list in Python is similar to an array in some other programming languages and a list is just a series of values they could be strings ins or some other variable type and here's how you access an element in a list you count from the beginning and you always count starting at zero so when we do spam 0 that's going to be cat if we said one that would be that two would be rat and we can do a negative number to start counting from the end of the list so negative 1 is going to be elephant here's how we get a sub list with slices so we Define the list here and then spam 0 colon four is going to be a section of the list starting at the zero index and ending at the fourth index in this case is actually the whole list again but here one three we're going to start at bat and then rant or 0 negative one we start at cat and we're going to end at rat because negative one would be elephant here so you're going to go up until but not two the final number after the colon sign if you slice the complete list like this it's going to create a copy so now we have the original list spam and spam two if we use dot append to add an element to the original list the original list now has dog but the copy does not have dog at the end and we can use the the length function to get the length of the list there's three items in that list you can change values in a list with indexes so spam index one we're now going to set that to equal aardvark and if we look at the list again now Aardvark instead of bat is in index one and we can also set index two to be whatever's in index one and we can see it's cat Aardvark Aardvark elephant you can just use the plus operator to add two lists together to become one list you can also multiply a list to multiply the list three times and here's another example of using the plus operator to combine the list and you can delete an element of the list with delete or d e l and then we're deleting the element at the index two which is rant you can use for loops with lists so for I Supply and enumerate supplies using enumerate is going to make I the index and Supply is going to be each item in the list so we print index and supplies is and the format so this is going to go into the first curly braces and the supply is going to go in the second curly braces you can see how that works and you can Loop through multiple lists with zip so we have zip here so now we're going through the name and the age list into n and a and you can see what that prints out you can use the in and not in operator to see if something is in a list so howdy in this list well true is Cat in spam false howdy not in spam false this is the multiple assignment trick where you have this list that equals cat now a size color disposition equals can't it's going to assign each element of the list to each of these variables the multiple assignment trick can also be used to swap the values in two variables you can use the plus equals operator to add something to a variable spam equals hello this line right here spam plus equals world is the same as bam equals spam plus world and you can see what equals here you can also use it with the times equals operator and we can use dot index to find out the index of a certain item in a list and we already talked about this but dot append can add an item to the end of the list and insert can add an item at a specific index in a list and Dot remove will remove the first item in the list that has that value and you can use dot sort to sort a list you can sort number lists you can sort string lists which will store in alphabetical order and you can also reverse the store with reverse equals true you can also use the built-in function sorted to return a new sorted list sorted spam now we'll talk about the Tuple data type the main way that tuples are different from lists is that tuples like strings are immutable so you cannot change them so here is a tuple which is kind of just like a list and you can still access the items in the Tuple similar to the list so at index 0 is hello and we can get the items from index one to three we can get the length and this is showing that we can convert the types with the list and Tuple functions so we have this Tuple function and we pass in a list and it returns a tuple we have this list function we pass in a tuple and it returns a list this is an example of a dictionary a dictionary is similar to what is called an object in some other programming languages and a dictionary is made up of key value pairs so the key is size the value is fat the key is color the value is gray the key is disposition the value is loud you can use the dot values to get each value so in this for Loop We're looping through all the values and we're printing the values red 42. you can do the same thing with the keys so dot keys and now we're printing the keys and then with DOT items we can print each item in the list that has the key and the value and here we're storing the key and the value into these variables as we iterate over the dictionary we can check whether a key or value exists in the dictionary with the N so if name in spam.key is true zafi in spam.values true and you don't even have to do spam.keys you can just do color in spam false this get method has two parameters the key and the default value if the key does not exist so here it's trying to get the value of Cups which does happen to be 2 but if there is no cups then it's going to return zero here in the second one there is no egg so it does return zero if we look up at this top section first we're checking if color is not already in the dictionary and if so we'll set it to Black well there's an easier way to do it which with set default so if you do spam dot set default color black it will only add the color as black if color is not already in the dictionary this is a way to merge two dictionaries so we have the two dictionaries X and Y and if we see what Z is with the asterisk X asterisk X or Squad and now we've merged those two dictionaries into one here are two ways to create sets a set is an unordered collection with no duplicate elements you can use sets to test for membership and to eliminate duplicate entries and they support mathematical operations like Union intersection difference and symmetric difference so you see we're creating this set that does have two twos and two threes but then when we check to see what s equals there's only one two and one three because stats cannot have duplicate entries and since they're unordered you cannot access an index number because they're not stored in any particular order you can add an element to a set with DOT add and Dot update will add multiple elements to a set at once and you can use dot remove to remove an element if you do dot remove and remove an element that's not already in the set you will get an error dot discard is just like remove except when you try to discard something that's not in the set there will not be an error the dot Union method will create a new set that contains all the elements from the sets provided the dot intersections method will return a set containing only the elements that are common to all of them the difference method will return only the elements that are unique to the first set and the symmetric difference method will return all the elements that are not common between them this is an example of a list comprehension so we have this list and then we're going to create a new list but it's going to do something to each element in the original list I minus 1 for I and a so each element in the list we're going to subtract 1 from and here's an example of set comprehension so we have the set and we're doing s Dot Upper for S and B so we're actually changing each of these elements in the set to uppercase and then this is a dict or dictionary comprehension where we're going to do something for each element in the dictionary to create a new dictionary these are examples of some common Escape characters if you want a string to contain a single quote that some quote tab new lines or backslash you're going to instead have to put this in there with these Escape characters so here's an example if you put a slash in in a string when that prints out it's going to put a new line Siri says I'm doing fine you can do slash in single quote to make it appear as a single quote if you put the letter r at the beginning of a string it becomes a raw string a raw string completely ignores all Escape characters and prints any backslash that appears in the string you can use triple quotes to do multi-line strings so the string starts with these three quotes and it ends with these three quotes down here but with triple quotes you can see everything starting at the very beginning of the line so you can't indent it at all but you can indent if you import the ddent function from the text wrap standard package and then you can use the triple quotes and you can indent everything and this code is going to generate the same string as as before this year the dear Alice letter here let's talk about indexing and slicing strings just like getting an element of a list you can get a letter and a string so you just count from zero and you can get the letter zero the letter is index 0 of the string is H you can also get sections of a string you can slice a string zero to five of the string or if you just put blank colon 5 it's going to assume zero or if you put a blank at the end it's going to assume the last character in the string and here's another example you can use the in and not in operators with strings so hello is in hello world hello capital letters It's not in hello world and then chaots is not in cats and dogs well that's false because it actually is you can also use the in and not in operators with lists so five is an a false and we already touched on this a bit but you can use Dot Upper to change the string to uppercase or dot lower to change the string to lowercase and you can use dot is lower to find out if a string is all lowercase in this case it's false because it has this uppercase letter we can use is upper to find out if it's all uppercase was false but here hello is upper true that is all uppercase and you can do that starts with to see if a string starts with certain letters or dot ends with to see if the string ends with certain letters you can use dot join you take a string and do dot join and then you pass in a list and now we'll change that list to a string joining the elements with with whatever string it starts with here so here we use the comma you can also use a a space here and you can split a string with that split splits into a list and normally it's just going to split with at the spaces but you can split at anything like you could split at abc dot R just will right adjust and the full string is now going to be 10 characters and the hello is going to be right adjusted to the end of the 10 characters or it can do with 20 characters so this are just right justifies you can use l just to left to justify in the same way and you don't even have to have it spaces you can have asterisks or dashes or anything you like and Dot Center will Center a string within a certain number of characters you can remove white spaces with DOT strip and it's going to strip off all the spaces at the beginning and the end our strip will just remove the space at the beginning l-strip we'll remove the spaces at the end we've already talked about dot format it's just a way to get variables into a string at where the curly braces are F strings are in some ways an even better way of putting variables into a string you start the string with the letter F and then you use curly braces and you can put the variable right in here so we're using the variable inside the string in an F string you can also do a rhythmic tick or put any code you like within the curly braces so you can see with a plus b 2 times a plus b and it's right within those curly braces you can raise your own exceptions or errors within a code so raise exception and then this is going to be the message that's going to print out so you can see an example of what happens when the exception is raised you'll commonly see a raise statement inside a function and then the try and accept statements in the code calling the function so this box print it's going to raise these exceptions and when we call the Box print function it's in a try and accept block so it's going to try box print and it may raise any of these exceptions and if it does it's going to print an exception happened and then put the string of the error assertions are sanity checks to make sure your code isn't doing something obviously wrong these standing checks are performed by assert statements if the sanity check fails then an assertion error exception is raised so here are some examples we have this pod bay door status equals open and we're going to assert that pop-based door status equals open if this was false this error would be displayed so we're going to set pod bay door status to not be open to something different and we're going to assert that it's equal to open but it's not equal to open so you can see down here the exception will happen so this goes a little smaller but it's an example of logging to enable the logging module to display log messages on your screen as your program runs we'll import logging and then configure logging and then you can add this code within this function that's going to log certain things to the console now let's talk about Lambda functions if we look at this top part of code this is a normal function this function is called add it takes two arguments and it's going to return adding those things together so add 5 3 is going to return 8. well this function down here is a Lambda function and it's equivalent to the function above it's creating this function on a single line so the ad is now at the beginning add equals Lambda x y and you can see the colon is going to add X and Y together you can even create a Lambda function without a name so before it was called add but this isn't even called add we just create the function and then we pass in the the numbers right at the end like regular nested functions lambdas also work as lexical closures so basically you can use a function to create another function so now we're making a plus 3 function that's going to add three to numbers and a plus 5 function that's going to add five to numbers so plus 34 is going to add 3 plus 5 4 is going to add 5. this is how you do ternary operation within python so this is basically a one line code so this is basically an if else statement in a single line so we're going to print kid if age is less than 18 else print adult now let's talk about args and KW args so you can see args here the actual word args is arbitrary the important thing is the asterisk or if there's two asterisks so the asterisk basically means pack all the remaining positional arguments into a tuple while two asterisks is the same for keyword arguments so basically what that means is that we can pass in as many arguments as we like so fruits this can be one argument two arguments three arguments in this example we're passing in three arguments and then it's just going to print each one but you could have had four five six so that's what the asterisk does the KW args it means keyword arguments and you can have an indefinite number of them which is just key value pairs so we can pass in an unlimited number of key value Pairs and here's just going to print them this here is a special way to only run code if it's run as a script so this underscore underscore main underscore underscore is the name of the scope in which top level code executes a module's name is set equal to main when read from the standard input a script or from an interactive prompt so we're checking if name equals Main and if so it will run that code which is just if it's run as a script so let me show you how that would be used so we have this program here that defines the add function here and then now we're testing the add function but now if we want to use this module this code here we would have to comment out this test here so instead in the program we'll say if name equals Main so now if we import this file it's not going to add this but if we run this file just as a program it will run this ad35. we've reached the end you can learn about python classes and objects in this other video leave a comment explaining how to use the parts of python I missed and they'll pin the most helpful comment