Learn Python - Full Boot.dev Course with Commentary

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
Welcome To Learn Python the instruction says press the gray run button in the bottom right of your screen to see the code's output let's do that this text is printed continuing on with the instructions let's build fantasy Quest a text-based game we need to prompt the players of fantasy quest to create a name for their characters edit the code so that it prints enter a character name then press the blue submit button to check your work I'm going to take a moment to point out that python has nice simple syntax so we just type print and then a parenthesis then a quote to denote what's going to be printed an end quote after what we want to be printed an end parenthesis and that's all we can submit that hooray next one fix your first bug I like this I like this approach where they're giving you a bug to fix that's that seems like a good pedagogy thing says um XP boost okay that's what that's telling me combat in fantasy Quest isn't working as intended it appears that players are gaining Health when attacked instead of losing it so this is this is good this is very to the point and it's making you fit read and think about the code can I bring this over here yes I can I don't want to decrease the font size really anymore so sword damage equals 10 player Health equals 100 Health after attack equals player Health less sword damage that looks like an error but let's run it and we can see the output says a lot of Fred's health is 10 is 100 malafort is hit by a sword for 10 damage latherford South is now 110. so just from the output we can see that that's wrong and we can also reason that sword damage should subtract health let's run it again see if it makes more sense yes it does and let's submit reach level 30. cool the console so this is talking about the console in the context of this Pro of this programming course I think since the console is a panel that displays important messages like errors or the text output of a program if we want to see what's happening in our code we need to print it to the console using the print function we'll learn more about functions later but for now just know that the print function will print anything you put inside parenthesis so print quote anything you put inside can run that and sure enough it prints it out very good assignment we need to tell our new players how to move their character print the following text to the console use the error keys to use the arrow keys to move huh not error so I'm telling it use the arrow keys to move let's submit this I'm enjoying all the shiny bits that they've added recently okay what is python thousands of students start their coding Journey right here with python I actually started with python when I decided I was going to go professionally into programming I had seen a little bit of labview and Matlab and c and Mathematica before then which actually sounds like a lot now that I say it all in one go but when I really decided to get serious about programming it was python that I decided to learn and boot.dev says we think it's the best programming language to get started with python is famous for being a simple language that's easy to read and write however just because it's simple doesn't mean it's not useful python is an extremely popular language in the industry and is well known for back-end web servers devops Cloud engineering devops and Cloud engineering machine learning scripting and automation ad set Etc on the other hand it's not particularly well known for front-end work while it's possible to do so python isn't typically used to build visual user interfaces yeah I haven't seen a lot of that myself and there we have a quiz for reading comprehension python is not often used in front-end apps correct I earned XP fun python is known for being simple to read and write very good what is code code is just a series of instructions that computers can follow computers obey each instruction one after another programs can be comprised of many instructions oh I forgot my timer like many like Millions of here foreign instructions in coding is the addition instruction printing numbers print can print text using quotes so here's our example of that print text not submit I just want to run this but I can also print numbers without quotes well I'm going to be churlish and show that it can print numbers with quotes as well but now we show that it can print numbers number one number two number three and so on unlikely it can't print the number e without parentheses let's without um quotes what's the error name e is not defined I guess we could probably I'm I'm getting I'm going a little far afield here but this might be fun import map print map dot e see if that works yeah 2.1 2.718 and so on sorry for that sorry for that jump off off of the main course of things let's get this looking a little better and you can do math directly inside the parentheses we have three plus five could be eight got it assignment it's common in video games to do basic Edition for example we may need to calculate the additional damage of Sword deals when it is Enchanted with a spell our hero sword does 250 normally but does an additional 75 damage when it's Enchanted calculate and print the result of 250 Plus 75. I'm adding spaces in between the numbers even though I don't strictly have to let's prove that I don't have to yeah it still gives a good result and it gives the same result regardless of the spaces or not but it looks better with the spaces so I will include them now submit that's good multiple instructions code runs an order starting at the top of the program for example print this runs first print this runs second prints this runs last I'm going to be silly and rearrange this just to prove that python doesn't care whether what it's doing makes any sense if I run this we have this prints second this prints first this prints last we can do that because python is just going to do what we tell it to assignment the dialogue in our game needs to be printed in the correct order in the first level our hero encounters a talking owl names Jax let's display their conversation to the user through text rearrange the code so that it prints in the following order let's reset the code yes I want to reset the code we put Jax Baka first hero dot dot dot Jax says something and then here says something okay we have Jack says something here says something Jack says something hero says something we can submit this very good so codes code in this running order top to bottom syntax errors syntax is jargon for valid code that the computer can understand for example current hello world is it is invalid syntax because prnt is not a valid function Prince is spelled incorrectly as a result an error will be thrown in the code won't execute let's run it with print and see what happens python error Trace back most amazing call last file this is interesting eval code code Runner co-routine eval anyway the important thing is at the bottom name error prnt is not defined I wonder if I can do something ridiculous here foreign T equals print can I run that and now print is defined oh that's fun and ridiculous okay reset the code okay there's a bug in our game our players are getting mad because they pay us 20 a month I have access to fancy Quest fantasy Quest find the syntax error in the code and correct it let's run the code and it says print is not defined and rather than correct the error directly I'm going to try and walk around it and see if this allows me to pass I'm sure it's not the solution they're looking for but let's see oh I did pass with that that's excellent um I'm going to screen cap this and share that in the Discord to show that I got away with something silly syntax errors so we have a little bit of discussion of syntax here a coding language of syntax makes up the rules that Define what properly structured expressions and statements look like in that language for example in Python the following would be considered correct syntax print hello world while in a different programming language like go the correct syntax would be fmt.println hello world there's an example of python being simpler to write than something like go code can have many different problems that prevent it from working as intended some examples include a bug in the logic for example a program that should add numbers multiplies them instead a problem with speed a program that calculates how to play the perfect game of chess might never be able to finish because it requires too many calculations it used to be that was a problem for chess computers and it was a big deal when computers were able to do enough calculations to win a chess game these days chess is pretty well solved so we do with the with the computers that we have easy access to or it could be a problem with syntax this is the most common problem for new developers luckily the python interpreter will try to give you a descriptive error message in the console to help you find the problem syntax definition I'm looking over these options and I think the result the answer is valid code in a programming language notice that code that produces the correct output would be incorrect because you it's possible to have correct syntax but incorrect logic we actually saw that on a few pages back when I printed this print second before this prints first the syntax was fine but the logic of the program didn't make any sense okay valid code in the programming language got it uh syntax there goes what happens if you try to run code with invalid syntax what are what are our options here I think these might be fun to read through we have the computer will freeze you will provide it it will be provided a syntax error message in the code won't execute or the network will disconnect it'd be a problem if the computer would freeze and that would make programming kind of scary to learn but fortunately you'll just be provided with a syntax error message and the code won't execute okay that was chapter one take a quick breather and get back into it with variables in chapter two so from the course variables are how we store data in our program so far we've been directly printing data by passing it directly into the print function now we're going to learn to save data in variables so we can use and change it before we need to print it a variable is name is a name that we Define that will point to some data I already did this before with saying print equals print for example I could Define a new variable called my height and set its value to 100. I could also Define a variable called my name and set it equal to Lane to create and creating variables to create a new variable in Python we use the following syntax I'm going to print type this out to practice it I do variable to equals 2. also this can be called anything equals three assignment we need to keep track of our players health of Our Hero's health on the first line of code create a new variable named player health and set it equal to one thousand so we have here I'm going to run this just to check 1000 looks good so let's submit Quest complete get 12 exercises correct in a row cool continue okay chapter two section two variables vary variables are called variables because they can hold any value and that value can change it varies for example the following will put 20. we say acceleration equals 10. then acceleration equal 20 print acceleration and it's going to print out 20. the explanation goes the line acceleration equals 20 reassigns the value of acceleration to 20. it overwrites whatever was being held in the acceleration variable before it's worth mentioning that the equal sign doesn't mean equality in Python it means assignment like assigning a value to a variable which is different from assignment as in this course is telling me to do something so the assignment is we need to reduce Our Hero's Health as they take damage in the game before each print function in the provided code change the value of player Health to be 100 less than it was before um I'm going to I'm going to stick to only things that I've learned so far in this course so so let's test that one sure enough it goes down to 900. and let's just paste that line but before we print player health and here and here how many times is this going to happen that many times 900 800 700 600. so that's good let's submit that yay XP let's do some math now that we know how to store and change the value of variables let's do some math here are some common examples of mathematical operators in Python syntax we have sum equals a plus b oh this is an interesting tidbit some type of sum let's see what it says about type of sum oh I should print that I'm going to take a screen shot here because I might mention this um it's a little weird that some is highlighted but it's because some is a built-in function or method whereas if we try to do this with difference we find that name error difference is not defined that's interesting so that's why we have this sum being highlighted in Orange here anyway moving forward difference equals a minus B we can write product equal a times B or for the next one we can write quotient equals a divided by B now on to the assignment create a new variable called armor Health on line four line four oh I better reset the code create a variable armored Health Online 4 and set it to player Health times armor multiplier so armored l equals player L times armor multiplier let's run that it should give us 2 000 yep submit let's do some more math that's a that's a fun title I think it's a fun title I don't know if you agree creating negative numbers in Python works the way you expected just add a minus sign in front of a number so for that my negative num let's call it let's call it minus ten let's print my negative num it shows it below is -10 reset the code assignment when our hero walks through poison their health should be reduced change the poison damage variable to be negative fun fact computers can do math on really big numbers very quickly another fun fact python doesn't have a long integer type it just has an integer type um is it it's called predictor right it's print type of layer help yeah Class end okay I was I was doubting myself for a second there change the poison damage value to be negative getting back to the assignment run it it runs I'll submit it yay comments comments don't run like code they're ignored by the computer comments are useful for adding reminders or explaining what a piece of code does in plain English so a single line comment example is a hashtag symbol telling us that speed is a variable describing how fast your player moves speed equal to so this is a comment multi-line comments AKA doc strings you can use triple quotes simple quotes like this oh it surrounded it for me that's nice uh multi-line comments AKA doc strings you can use triple quotes to start and end multi-aligned comments as well code found below will print hello world to the console I would argue that's not a very useful doc string but we're just doing basic examples here so that's okay assignment the lion wanting the code I need to reset the code line number one in the code was meant to be a comment but the developer forgot to use the right syntax hashtag fix the bug by making the first line in the code a comment here is where I like that we have the Run button because I can click run and let's see what the error is syntax valid syntax error invalid syntax that's interesting surprised it's not a name error and why is it right there that's an odd place for it to unless it's unless it's complaining about it oh it's probably complaining about it right there let me yeah best sword is is what it's complaining about that makes a lot more sense okay go back to resetting the code fix the bug by putting in the hashtag and run okay best sortable Scimitar print best sword submit very good variable names variable names can't have spaces they're continuous strings of characters in Python you should use snake case after all python is a snake when creating variable names it's become the rule of thumb for The Language by way of comparison camel case is where the beginning of each word except the first is that is capitalized so case in the example no casing some variable here equal ten camel case some variable here equal 10. snake case some variable here equal 10. which is valid camel case I almost clicked on hero Health here but it's this one nice variable names variable names can't have spaces they're continuous strings of characters in Python you should oh wait which is valid snake case I don't want to repeat myself on that whole spiel which is valid snake case that's this one okay basic variable types in Python there are several basic data types and I wonder which types they're going to start out with strings are raw text encoding speak they are called strings because they are a list of characters strung together strings are declared in Python by using single quotes or double quotes that said for consistency's sake we prefer double quotes I've seen single quotes use sort of a lot in a lot of places but I will take their word for it that here at boot.dev we prefer double quotes so name with single quotes and name with double quotes numeric types numbers aren't surrounded by quotes when created but they can have decimals and negative signs so so x equals five that creates an integer y equal minus five that creates also an integer we can print type of X and it'll tell us ends then we can go forward and say x equals 5.2 y equals minus 5.2 let's print type of X comma New line and we should see pretend print class int and class float a float is a number with a decimal and this is something worth mentioning about python as a python programmer you don't declare what the type is you give python data and python decides what the type should be what if you had something that was equal to five but you wanted it to be a float well you would have to say x equal 5.0 and now we can see that from this first print oops we get class float Boolean type a Boolean or Bool is a type that can only have one of two values true or false as you may have heard computers really only use ones and zeros these ones and zeros are just Boolean values um so we have well I won't type the code for that but with zero equals false and one equals true although I've heard that in some places like for operating system stuff they use zero as true because zero is the non-error code so it's like true that your thing to narrow it's it's potentially confusing but we have is tall equal true we can print type of is tall and an interesting note about the design of the language is that the the true and false are both capitalized and I'm not sure why that is because it seems like you could just as easily have used lowercase true as the keyword for that type but uppercase true it is okay assignment fix the code the bugs in the code to move on so we need to reset the code their health should be an integer ah yes Better Health should be an integer player has magic should be a Boolean so we just have to take away those things yo doomja hey thanks for stopping by okay player Health has a class int pair player magic is a Bool submit none type variable not all variables have a value we can declare an empty variable by setting it to none Mt equals none the value of empty in this instance is none until we use the assignment operator equal to give it a value not is not a specified string note that the num type is not the same as a string with a value equal none my none equal none my not none equals quote and what if we print my none equals double equals we haven't learned that yet but I'm going to use it anyway this is going to be false okay Moving On Assignment declare a variable named enemy and set it to none don't change the print function what if I do change below that line anyway enemy and then the people and snug run submit enemy is none yo what if I huh it didn't print that's interesting it just printed yo anyway submit we got this non-type like we mentioned the last exercise the num keyword is used to define a null variable or object in Python the non-keyword is an object which we'll cover later and it is a data type of the class none type why might you use a none value to create bugs how about as the default value that will be replaced later I've seen that in code at work for sure hey cool it didn't count me as incorrect for at for accidentally on purpose missing that last one claim the XP continue Dynamic typing python is dynamically typed all this means is that a variable can store any type and that type can change so not only the value can change we saw that before but now we're saying that the type of the variable can change which by the way you can't do in some other languages for example if I make a number variable I can later change that variable to be a string this is valid speed equal 5 speed equal qualified but just because you can doesn't mean you should in almost all instances it's a bad idea to change the type of a variable the proper thing to do is just to create a new one is to just create a new one although interestingly I was seeing the exact opposite pattern in the learn Rust book the other day if I remember maybe I'll link to that but I probably won't remember anyway speed equal five speed description equals quote five what if it weren't dynamically typed strongly typed languages like go which you'll learn in a later course are strongly typed instead of dynamically typed in a strongly typed language if you try to assign a value to a variable of the wrong type an error would crash the program if python were strongly typed the first example from before would crash on the second line speed equals quote 5. the computer would give an error along the lines of you can't decide a string value five to a number variable speed is changing the type of a variable generally a good idea I want to say on Tuesdays but I'm going to protect this streak of correct answers and say no it's generally not a good idea okay moving on Dynamic typing more about Dynamic typing what kind of typing does find out as python employ reading comprehension check here it's dynamic math with strings most of the math operators we went over don't work with strings with the exception of the plus addition operator when working with strings the plus operator performs a concatenation fancy word concatenation is a fancy word that means the joining of two strings first name is Lane last name is Wagner full name is first name plus last name whole name now holds the value Lane Wagner notice the extra space at the end of Lane in the first name variable this extra space is there to separate the words in the final result Elaine Whitener with a space I want to know so first without equals 1 plus 2. for a result that should be easy enough to anticipate what it's going to be equals three plus space plus four and second Oops I messed up here second result now third result equals one plus two red third result I wonder if it'll be an error and finally what results equals one plus two let's see what all of these do type error unsupported operand types for plus and string just out of curiosity is this one is this one going to be okay uh oops I erased the wrong things no I already blindfolded up but oh that's an interesting result that's actually kind of interesting let's let's look back at um let's look at this will be this one when we do one plus two it says type air unsupported operand types for plus int and string however when we try it with fourth result can only concatenate string not into the string I should screen cap these because that's interesting how when it started with a string it tries to concatenate but I comment those out and move back to these it says unsupported operand types for plus int and string it's a different error even though it's the same kind of problem that's interesting okay go back to reset the code assignment we have a second player in our game we need to tell each of our players how much health they have left edit line 9 to print player one's Health you have 1200 health using string concatenation and the variables provided don't edit Above This slide okay sentence start plus player one L plus sentence and and we have edit line 10 different players to health sentence start plus player two l a sentence and let's see if those look right you have 1200 Health you have 1100 Health looks good after all this time I still like the fireworks or the I don't know what those are but I like them multivariable declaration oh I forgot about this feature we can save space when creating many new variables by declaring them on the same line sword name comma sword damage comma sort length equals quote Excalibur comma 10 comma 200. which is the same as sword length equal Excalibur sword damage equal 10 sword length equal 200. any number of variables can be declared on the same line of variables declared on the same line should be related to one another in some way so that the code remains easy to understand we call code that's easy to understand clean code I don't think I like this multivar multi variable Declaration on one line I think it's better to have one thought on each line and not squeeze a bunch of thoughts into one line but to answer this question there's no limits what is clean code I like the answer code that is easy for developers to read and understand okay we're into chapter three computing with section one python numbers python numbers in Python numbers without a decimal part are called integers just like they are in mathematics integers are simply whole numbers positive or negative for example 3 and -3 are both examples of integers arithmetic can be performed as you'd expect so addition two plus one is three subtraction two minus one is one multiplication two times two is four division three divided by two is one point five well that's different and the course says this one is actually a bit different division on two integers will actually produce a float a float is as you may have guessed the number type that allows for decimal values well I want to see something here what about 4 divided by two is that going to be a float I need to print it 2.0 it is a float interesting actually hadn't realized that I kind of assumed that if it can result in an integer it will pay assignment on line nine create a total damage variable that contains the sum of the different weapons damage values total damage um attempted to make a list out of these but we'll just do it this way sword damage Plus based Arrow damage plus paste spear damage Plus paste dagger damage plus paste fire damage and average damage is just going to be actually I can use total damage divided by how many are there there are five what does this do don't touch below this line average damage is 3.0 total damage is 15. okay submit yay that's fun numbers review in Python numbers without a decimal are called integers contrast this to JavaScript where all numbers are just a number type that's interesting integers are simply whole numbers positive or negative for example three and minus three are both examples of integers floats a float is as you may have guessed the number type that allows for decimal values my integral five my float equal 5.5 blank and blank are numerical types in Python we have integer and float or division python has great out of the box support for mathematical operations this among other reasons is why it has had success in artificial intelligence machine learning and data science applications our division is like normal division except the result is floored afterwards which means the remainder is removed as you would expect this means the result is an integer instead of a float seven double divide by 2. and interestingly we have a video here which I'm not going to jump into at the moment but if you go through the course feel free of course to watch that um 11 divided by 2 should be 5. yep exponents python has built-in support for exponents something most languages require a math library for three to the power of 2 is 9. what would be the power of what would be 2 to the power of 3 that should be eight and again we'll skip past the video changing in place it's fairly common to want to change the value of a variable based on its current value we could have player score equals four then player score equals player score plus one play Square now equals five or letter square equals four next player score equals player score minus one so it now equals three don't let the fact that the expression player score equal player score minus one is not a valid mathematical expression be confusing it doesn't matter it is valid code it's valid because the way the expression should be read in English is assigned to player score the old value of player score minus one that's what I was saying before about this equals sign is an assignment operator not an equality statement assignment on line 5 add 234340 to the current value of player score player score multiplayer score plus two three four three four zero clear score is that cool plus equals python makes reassignment easy while doing math in JavaScript or go you might be familiar with the plus plus Syntax for incrementing a number variable in Python we use the plus equal operator instead so starving equals four star reading plus equals one already now equals five I'm going to take a moment to pause and point out that that's the same as writing star rating equals star rating plus one that's the same as star rating plus equals one back to this on line five use the plus equals operator to add 10 to the player's health we'll say player Health Plus equal to 10. yep so that's how plus equals works oh scientific notation as we covered earlier a float is a positive or negative number with a fractional part you can add the letter e or E followed by a positive or negative integer to specify that you're using scientific notation um it's interesting that it's a float print 16 E3 prints 1600.0 or print 7.1 e minus 2 prints 0.071 if you're not familiar with scientific notation it's a way of expressing numbers that are too large or too small to conveniently write normally in a nutshell the number following the E specifies how many places to move the decimal to the right for a positive number or to the left by for a negative number yeah that's right underscores for readability python also allows you to represent large numbers in the decimal format using underscores instead of commas to make it easier to read uh that's that's useful because you know um we had print 16 18 well what if we wanted it to be um an integer we could we we might especially if this was like print a five now we have five zeros that's going to be a lot of zeros so I could put them like that to make the source code easier to read even though the result um is going to be the same right if I print 1 6 with all the zeros without those underscores same result reset the code this time I do the constraints for our app server we have a maximum number of players we can have on a single fantasy Quest server declare a variable on line one called max number of players set it equal to 1024 a bunch of zeros using scientific notation okay Max number max number of players equals 1.024 e 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18. that's a lot of players and it displays it that way that's interesting okay we'll submit that got it good logical operators you're probably familiar with the logical operators and an or logical operators deal with Boolean values true and false The Logical and operator requires that both inputs are true in order to return true I wish I had the coding um window here but I don't the logical or operator only requires that at least one input is true in order to return true well here we have examples true and true equals true and false equals false you could also have false and false ah okay so true and false we can also have false and true equals false and the other example here is false and false equals false but with the or true or true is true because at least one of them is true or false is true we could also have false or true is true and finally false or false is false python syntax print true and true print true or false nesting with parenthesis as you would expect you can Nest logical expressions using parenthesis like any other code but we haven't learned about parenthesis and other code yet but that just means that true or false will execute first which will be true but then when we try true and false we get false what does the following statement evaluate to true and true that much is true or why because of short circuit evaluation I already know it's going to be true as the final result but let's keep looking at this true and false is false but true or false is true so it's true Sharpshooter Platinum cool okay we're going to talk about binary numbers now binary numbers are just base two numbers they work in the same way as normal base 10 numbers but with two symbols instead of 10. each one in a binary number represents a greater multiple of two in a four digit number in a four digit binary number that means you have the eighths place the four is placed the twos placed in the ones place similar to how in decimal you would have the thousandth place the hundredth place the tens place in the ones place we have a video about binary numbers I'm gonna Breeze past that what does one one zero zero represent in decimal we have one two four eight so that should be 12. okay this is the same same thing here but we have what does 1 101 represent in binary well it's one more than the last so it'll be 13. or what is a represented decimal yeah binary numbers oh what's the largest number you can store in five digits of binary so in um why did you take away that example darn it um five so five digits count with me ones twos fours Eights 16s six digits would be 32 so one less than that is 31. bitwise and operator um yeah okay I guess we'll do this too bitwise operators are similar to logical operators but instead of operating on Boolean values they apply the same logic to all the bits in in a value for example say you have numbers five and seven represented in binary you could perform a bit wise and operation that would result in five oh 101 a11101 a wanted binary is the same as true while zero is false so really a bit wise operation is just a bunch of logical operations that are completed in tandem and is the bitwise and operator in Python so five and seven is five well five and two is zero so for that example 01010 it doesn't seem very meaningful to be doing bit wise and on decimal numbers but okay binary notation when writing a number in binary the prefix zero B is used to indicate that what vowels is a binary number we have examples of that in the code here Guild permissions it's commonplace in backend development to store user positions permissions as binary values think about it if I have four different permissions a user can have then I can store it as a four digit binary number and if a certain bit is present I know the permission is enabled well you could really get by with a two digit binary number zero one one zero one one but can create Guild is first bit can review Guild a second bit can't delete Guild is third bit oh can can edit kill this fourth bit oh I see where this is going which are represented by zero B zero zero zero zero for example if a user only has the can't create Guild permission their binary permissions would be zero B one zero zero zero a guild which can review Guild and can edit Guild would be 0b0101 in order to check for say the can review Guild operation we can perform a bit wise and operation on the user's permissions and the enabled can review Guild bit 0b0100 if the result is zero B one zero zero again we know they have that specific permission oh hello Sammy are you a good kitty are you gonna walk in front of the camera now and step on the mic table that's great sorry about that noise we have here so what's going on in the in the code here assignment assign a binary value to the user's permission so that the user will have the can review Guild permission and the can delete Guild permission uh well let's just let's just do what it says and then we'll think about it can review Guild is the second bit can delete Guild is the third bit so 0b 0 1 1 0. and the outputs just tell us user can create Guild as false user can review Guild equal true user can delete kill it is true and user can edit Guild is false uh so that looks good but I want to understand the code that they're using to evaluate this oh I see user permissions bitwise and can create Guild that's the zero B one zero zero zero that's equal to the binary number can't create Guild then we're good but if the user permission doesn't have that then it's going to be 0 and 0 it's not going to be equal to one zero zero zero zero okay I see what's happening there I feel like this could use extra explaining maybe for some of my viewers so I'm going to take a screenshot of it and maybe give it maybe work through an example but let's just some let's just run again to make sure it looks good these are going to have the Ken review Guild and can delete Guild can review Guild can delete Guild good this I'll look at that later not we skipped a very important logical operator not the not operator reverses the result it returns false if the input was true and vice versa print not true prints false print not false prints true The Operators and or and not are logical operators okay on to chapter 4 with just comparisons comparison operators when Kona is necessary to be able to compare two values Boolean logic is the name for these kinds of comparison operations that always dissolved in true or false so it looks like all of these are going to be either true or false The Operators we have less than operator greater than less than or equal to greater than or equal to actually equal to and not equal to assignment change the operators in code okay confirm so that each statement evaluates to true if it doesn't already change the operators not change the numbers so 5 less than six that'll be true five not equal 6. that's good I need to change this one to five and we change this one so five equals 5 will be true 6 greater than or equals six also will be true let's just submit this comparison operator evaluations when a comparison happens the result of the comparison is just a Boolean value it's either true or false take the following two examples is bigger equal 5 greater than four is big or equal true in both cases we're creating a Boolean value called is bigger with a value of true since 5 greater than 4 is bigger is always assigned to the value of true why would I use comparison if I can just set it to true okay that's a fair that's a fair question you wouldn't in this case however let's imagine that instead of hard coding the numbers five and four we want some Dynamic variables that we don't know the values of perhaps you're making a video game I need to keep track of player scores in order to calculate who wins you would need to write something like this Player 1 wins equals player one point greater than player two points and we print Player 1 wins let's see what this comment is about player one point to player two points are defined elsewhere and change somewhere else in the game's code Prince true one player one is winning otherwise prints false okay that all makes sense assignment use comparison operators to assign the correct Boolean values to the missing variables Elon height 5 Sarah height 10 Jill Heights 7 Bob Heights 6 donated above this line Bob taller than Elon I don't have to think about it I just have to write Bob height greater than their autocomplete here no Sarah taller than Elon is going to be true but we're gonna write it out Sarah hype greater than Elon height and Jill taller than Sarah is going to be jail height greater than Sarah height which is going to be false we have in here oh print it's going to print the type of each one print type of that print that print type of Sarah taller than Elon Prince Sarah taller than Elon print type of geother and Sarah and print genital and Sarah okay let's submit that very good comparison practice car size equal four truck size equals five is smaller equal color size less than truck size is smaller is true so again we have this comparison operator We compare two numbers and we get a result that's a Boolean value okay on line six create a variable called enough armor and use a comparison operator decided to true or false actually enough armor or equals something comparison something is there the true or false depending on hero armor is greater than or equal to M enemy damage so the first something is hero armor your armor is greater than or equal to I feel like it shouldn't be equal to maybe it's okay and your armor can withstand the enemies its blows is false okay so again the shape of that was enough armor equals variable comparison variable comparison variable okay on to the next increment decrement if we're changing a number and simply want to increment add to our decrements that prevent from these there are special operators for those what are the special operators oh well we've seen the increment and decrement operators plus like the plus equals one or the minus equals one or the plus equals two minus equals two notice that Shield armor plus equals one is just shorthand for shield armor equals Shield Armor Plus One okay decrement Shield armor by three on line seven Fields armor minus equals three down to two got it if statements so this is this is a good one because this is when we get into the value of a Boolean tells you whether or not some other code will execute so let's see that in this course it's often useful to only execute code if a certain condition is met if condition do some stuff here for example if Bob scored greater than Bill score print Bob wins take a look at the code edit player Health on line 1 so that the code prints dead don't edit below this line if it equals zero Prince dead okay good so again let's look at the pattern here we have if addition do stuff but if condition is false then we don't do that stuff but I can write maybe do stuff okay on to the next if practice if Bob's grow greater than build score print Bob wins complete line six it should only log the warning message if number of Swords is less than number of soldiers so again we're putting a condition here and the condition is going to be variable comparison variable we want to know if number of swords is less than number of soldiers and we print we do not have enough swords for the Army very good if else also LF an if statement can be followed by zero or more LF which stands for else if statements which can be followed by zero or one else statement which can be followed by zero or one else statement I guess that should be not plural for example if score greater to high score print high score beads alif score greater than second highest score print you got second place elif score less than third highest score print you got third place else print better luck next time so it's so the pattern is if condition maybe do this alif condition maybe do this I'll call this condition one and conditions condition two alif condition three maybe do this then finally else do this and the interesting thing here is that else doesn't contain a condition because if these conditions haven't been met this one's going to happen no matter what so now talking about this code example first the if statement is evaluated if it is true then the if statement's body is executed and all the other else's are ignored that's what the if else part means if the first if is false and then the next alif is evaluated likewise if it is true then its body is executed and the rest are ignored if none of the if statements evaluate to true then the final else statement will be the only body executed this just reminds me of python or else I'm not going to go into that right now but I'm going to take a screenshot and talk about it later okay assignment complete the code it's missing some conditions let's reset the code it's report dead if player health is zero otherwise it should print injured if player health is less than five if neither of these are the case it should print alive okay so print Dad if player Health equals zero so remember it's variable [Applause] comparison variable if player help double equals zero print dead else if a variable player help is less than five it should print injured else it should print alive run that and we get injured note for now the player Health in the test code is always four so your output will always be injured we'll learn how to write more Dynamic programs in future assignments good to know did I remember to submit that one I think I didn't okay now we can go to the next one if else practice here's some basic rules with if else blocks you can't have an else alif or an else without an if so you always have to have an if you can have an else without an alif okay that's that remember to check if two values are the same use the equal equal operator same equal five to equal equals six same as false same equals six equal equals six notice the order of things happening here is that six equal equal six operates to true and then true gets stored the same assignment there's a bug in our code on line six so the bug is we left out our Boolean con statement or condition edit the code so that if current player name is the same as high scoring player name it logs you are the highest scores player if so variable comparison variable current player name is the same as equal equals high scoring player name print you are the highest scoring player I'll Sprint you are not the highest scoring player as it happens you are the highest scoring players so let's submit that go on to the next one if us practice same rules seven and nine are missing their conditions so we're gonna fill it in with the same pattern variable comparison comparison variable we'll do the same thing on line nine we want if current player name is the same equals equals as high scoring player name so if you're the highest scoring variable player otherwise if current player name is the same as so the comparison is equal equals lowest scoring player name you are the lowest scoring player and that's the one that it evaluates to okay very good let's now move on from that and head to a BRB screen oops Loops for a programmer's best friend Loops allow us to do the same operation multiple times without having to write it explicitly each time for example let's pretend I want to print the numbers 0 to 9. I could do this print zero print one so on and so forth and nine even so it would save me a a lot of time typing to use a loop especially if I want to do the same thing one thousand or one million times a for Loop in Python is written like this are I in range 0 10 print I in English the code says in excruciating detail I might add oh hello Sammy anyway in English the code says start with i equals zero I in range zero if I is not less than 10 if I is not less than 10 exit the loop we haven't seen a knot less than well we've seen less than so we evaluate I less than 10 and then we flip it okay now print I to the console step four add one to I range defaults incrementing by one go back to step two the result is that the number zero to nine are logged to the console in order white space matters in Python the body of a for Loop must be indented otherwise you'll get a syntax error assignment complete the missing sections of the for Loop so that it prints the numbers 0 to 99 to the console so the we start with an i the variable is going to be I and it's going to be in a Range object from 0 to 100 and I know it's 100. because when it's not less than 100 we will exit the loop but 99 we will print but at 100 we will exit the loop and not print you can see here 97 98 99 submit complete 240 exercises wow TV Josh says 10 million XP thank you TV Josh I appreciate that we've got some trouble with the diabetes stuff I'm okay Loops as a reminder a for Loop in Python is written like this where I in range 0 to 10 print I in English the code says start with i equals zero I in range zero if I is not less than 10 X is the loop but if I is less than 10 enter the loop print I to the console add one to I and go back to step two actually could rearrange these instructions a little bit like I think of it as if one start with i is zero two deck if I is less than 10. proceed into the loop let's exit the loop anyway let's move on the result is that the number zero nine are logged okay white space matters in Python we've already gone through this write a for loop from scratch the logs the numbers zero to 199 to the console we have four I in range i n range we start with zero we write 200 because we wanted to go to 199. we wanted to print I let's check that that runs 199 yes submit Loops practice as a reminder a for Loop is written like this edit the for Loop to print the numbers 5 to 15. I'm going to do what might be tempting and do range 5 to 15 and I'll run that and oh no it only printed up to 14. I guess I'd better type 16. so that it makes it to 15. okay let's submit that that's good I'll open the feedback survey in a new in a new tab and maybe do it later Loop review or review the loop for I and range 0 to 10 colon print I prints the number zero nine to the console why should you want to use a loop because the computer understands Loops better than repetitive code well it understands both equally well which is to say it understands nothing so I won't answer that one let's get the timer back because Loops speed up your app or because to do the same thing over and over again without writing the same code that's the one I like okay Loop review for Iron Range zero to a thousand prints the numbers I it's a number is 0 to 999 to the console why does the code on the left put 0 to 99 and 0 to not 100. um the choices include because printout only happens while I is greater than not equal to a thousand that's not it because printout only happens well I is less than not equal to a thousand that sounds right while I is greater than or equal to that's not right it only happens with Y is less than or equal to that's not right it's print I only happens while I is less than a thousand okay moving forward Loop review white space matters in Python the body before Loop must be indented otherwise you'll get a syntax error and by the way a lot of programming languages don't rely on white space to get the syntax right okay not only that but every line in the body of the loop must be indented in the same way we use the four spaces convention pressing the tab key should automatically insert four spaces okay it is blank to end it the body of a traditional for Loop in Python it is required what is this fire thing one day is a study in a row huh range continued the range structure we've been using in our for Loops actually has a second as an optional third parameter the step for Iron Range 0 to 10 comma two print I print zero two four six eight the step parameter determines how much to increment I by each iteration of the loop you can even go backwards go by minus one in this case it's smart enough to know that the number is greater than zero for us for us to continue assignment fix the code so that it prints the numbers 10 to 1 in order 10 to 0 comma minus 1. that should do it yeah 10 to 1 in order submit a another million XP no I don't want to open Twitter right now I'm glad that password was obfuscated uh okay we did that move on to the next one with the bouncy blue arrow F strength in Python oh I like f strings you can create a string with Dynamic values by using F strings in Python it's a really beautiful syntax that I wish more programming language is adopted number of bananas equals 10 F quote you have race numb bananas ripe brace bananas the opening quotes need to be preceded by an F then any variables within curly braces have their values interpolated into the string at the hometown Tavern in fantasy Quest The Innkeeper offers free meals and retirement plans based on the age of his patrons I wrote a loop for you that increments the ah variable from 0 to 76. in the body of the for Loop if age is less than eight your coach should print oh we're gonna we're gonna have to use things we learned in a previous lesson if age less than eight print f-spring quotes I'm used to sing single quotes with an F string but I'll I'll follow their their preference and use double quotes with the F string you qualify for free meals you are blank and will replace blank by age years old LF H greater than 65. interestingly not of age that's equal to 65. you qualify for retirement and F quote we qualify your retirement you are blank you're so old age years old so again we put the braces and we put the variable name in here and the syntax highlighting is nice because it suggests that this age is going to mean something different than if I typed age over here underscore should be the current value of the age variable and we don't do anything so I um I don't make an else statement I could write an else statement but the quantum doesn't require it so you qualify your retirement you are 74 years old looks good sprinklers not sprinklers I don't know what to call those things but I like them some game remember that the increment and decrement operators can increment and decorate a variable by any amount number of enemies equals 10 number of enemies plus equal two so it'll be 12 or number Venom is minus equal to so it'll be eight fix the bug in the program instead of adding one to Total at each iteration of the loop it should add I for example instead of one plus one plus one plus one plus one plus one plus one plus one plus one plus one okay that's enough we want zero plus one plus two plus three plus four plus dot dot dot TB Josh says confetti yes confetti is the right word okay thank you I needed some help with that one um we just want Total plus equals I and this should be some big number 49.50 that looks right congrats you earned 189 XP some game two assignment writer program that skips that sums all the numbers from 0 to 99 but skips even numbers so I'm starting thinking 0 comma 100 we could go by two this is going to be wrong let me just print I if I'm not 8. print I and don't submit it yet but run it and notes that it's not skipping even numbers instead it's doing only even numbers how can we fix that well we could start at one instead and it'll continue while the number is less than a hundred and now we get a different result I don't want to print I for my submission and submit hey clean 500 XP continue okay on to the next one and I need to step aside because my dinner is about to come out of the oven thank you know I don't know why I'm wearing these I don't need to be there's no sound right now okay getting back into it except the headphone cable is now in my way okay oh we're on to another chapter we are now going to study lists a natural way to organize and store data is in the form of a list some languages call them arrays but in Python we just call them lists think of all the apps you use and how many of the items in the app are organized in lists for example a Twitter feed is a list of posts an online store is a list of products the state of a chess game is a list of moods the list this list is a list of things that are lists well that got meta listen python or declared using square brackets with comets comma with commas separating each item inventory equals iron breastplate healing potion leather scraps arrays can contain items of any data type in our example above we have a list of strings interestingly this is kind of a we can also if we wanted to have different data types I feel weird without the headphones on I don't know why probably because I'm expecting to hear um I guess I guess I want to hear the follow noises so I guess I do want to hear if the head something happens in the headphones sorry I'm I'm losing focus here let's focus in assignment let's work on fantasy Quest inventory take the one away we can store items the player is carrying in a list add a short sort to the end of the list so comma and then quote for a new string and short sword and submit very good this continued sometimes when we're manually creating lists it can be hard to read if all the items are the same line of code we can declare the array using multiple lines if we want to keep in mind that this is just a styling change the code will run correctly either way now you might be saying but wait Eric I thought that indentation matters in Python well the python knows that when we're inside of for example um are these what are these called These are called brackets I'm afraid I'm going to mess it up now square brackets yeah that's right so once we're within brackets and it's the same thing for parentheses if we're within parentheses it ignores the leading white space okay keep in mind this is just a styling change when would you declare an array on multiple lines when the array contains string instead of numbers well not necessarily when there are only a few items that doesn't make sense when there are two are many items it's hard to read them all in one line that's the one lists continued sometimes when we're manually creating this it can be hard oh wait uh which types of items can be stored on a list is it numbers is it strings is it booleans it is all of them counting and programming in the world of programming counting is a bit strange we don't start counting at one we start at zero instead indexes each item in the array has an index that refers its to its spot in the array take the following array as an example names is Bob Lane Alice Brianna index 0 equal Bob index one is Lane index two is Alice index three is piano which index refers to the second item in a list so first second um goes 0 1 or 0 1. so the answer here is one I like to sometimes talk about let's go to the next page so I can have something to work with indexing and lists so good we're still talking about that um first second third but or we could talk about the zero of the one if and the three up to it let's justify these so they look better oh I'm mixing this up terribly but it'll be worth it for the point I'm making foreign this is more difficult than it needs to be so zero one two first second third zeroeth one it to it and that could go on I like this way of counting when you're talking you're talking about zero indexed things okay getting back to the course indexing with lists now that we know how to create new lists we need to know how to access specified items in the list we access items in a list directly by using their index indexes start at zero the first item and increment by one with each successive item the syntaxes that follows so so the syntax is to create a list I'm going to do taper list one two three and then access of value and let's say excess the two value which is actually the third value and so it'll print three yeah three is the two at the one reset the code okay indexing into this that's what we said best language is one print go because index was red well that's very opinionated assignment we need to allow our players to access items within their inventory change the value of item index to the index and inventory that holds the value of leather scraps item index so item equals inventory at item index we want leather scraps zero wanted to a three fourth where's leather scraps oh leather scraps is here it's the one if one so we item in x equals one item leather scraps inventory index one item by the scraps run all right the length of a list can be calculated using the length function Len again we'll cover functions in more detail later but this is the syntax length equals Len of fruits like this list is equal to the number rather than the list the number that is present don't be fooled by the fact the length is equal to not equal to the index of the last element in fact it will always be greater by one why is that the case well we have we have t equals zero one two and we are counting one two three from length of t is going to be three it's because we index from zero so the last index is one less than the length and that's always going to be the case in a python list assignment some of our players inventories are huge so looking through the entire list is cumbersome let's make an easy way for them to see the last item in their list it's at the last index variable equal to the length of inventory minus one you will need to use the Len syntax last item iron bar let's see it that's right oh my there are so many items in the in there but iron bar is in fact the last one okay submit list updates we can also change the item that exists at a given index for example we can change leather to leather armor in the inventory array in the following way inventory equals leather healing potion iron ore inventory 0 equals leather armor now inventory equals leather armor healing potion iron ore so we have this my list at index equals new value and it's like we're assigning the new value to my list at this index the assignment is we need to update the items in our player's inventory when they smelt iron ore into an iron bar on line six reset the code update the iron ore element in the array to be an iron bar iron ore is at index one the the zero with one if so inventory at one equals quote iron bar run this code we have healing potion iron bar Bread Short sword looks good I really don't want to get one of these wrong I've I've got such a streak going that I'm almost afraid to mess up it's common to create an empty list then fill it with values using a loop we can add values to the end of a list using the dot append method cards equals empty list this is a common pattern for them but actually I see here that we are using the for Loop over there so that's good cardstock append Nvidia card setup and AMD the list of cards is now Nvidia and AMD assignment we need to generate a unique user ID for each player in the game an ID is just a unique number use a loop to add the IDS of 0 through 99 to the player IDs list I will say yes integers are unique and they're easy to come up with but they're not always the best IDs for that you can use there are other ways to generate IDs that are more cool but this is going to work for now player IDs Dot and we just append I use a loop to add the you can use of 0 through 99 to the player IDs list print player IDs and sure enough we have let's check that it starts at 0 0 through 99 okay submit pop values dot pop is the opposite of dottapent Pop removes the last element from the array and returns it for use for example so b equals one two three that's an example last and equal to pop and now last inch equals three but what is t equal p equals un comma two assignment our player is selling items in their inventory to the shopkeep up all right let's reset the code pop the last item from inventory Don't Touch Above This line don't touch below this slide Brian range zero to length inventory pop the last item for the inventory list until there is nothing left pop the items into an item variable so that it prints each time on line 17. okay item equals inventory dot prop interestingly we're not using we don't seem to be using I at all which some some Ides an IDE is an integrated development environment some Ides would complain about that but for now we're okay um okay so we come down we sell the healing potion because that's the it was the first thing so it's the last thing to get popped and then the inventory is empty and we're good to go counting the items in a list remember that we can iterate count over all the items in an array using a loop for example the following code will print each item in the sports array for Iron Range 0 comma length of sports print Sports I assignment our players need a way to see how many copies of a specific item they have in their inventory within the loop count how many times potion bread and short sword appear in using the potion count bread count and short sort count variables respectively so I'm going to do this solve this using what we've learned already which is if statements so if remember variable comparison variable then we'll do something so if items at I and the comparison is equals potion but I'll do a double quotes because that's what they have been saying to do potion count plus equals one alif we can say we can use an L we can use an alif statement here we could also just write if but let's use l if if items I equals red then bread count plus equals one L if items I equals short sword then short s short sword sword count plus equals one and now let's run this and see what the counts all are says you have four potions six pieces of bread three short swords I don't feel like counting them so let's just say that this is good and it is excellent moving onwards no index syntax in my opinion python has the most elegant Syntax for iterating directly over the items in a list without worrying about index numbers if you don't need the index number you can use the following syntax I was actually gonna maybe think about mentioning that but it looks like the course has done it for us so trees equal Oak Pine Maple for tree in trees print tree and it prints Oak Pine maple tree the variable designed using the in keyword directly accesses the value in the array rather than the index of the value if we don't need to update the item and only need to access its value then this is a more clean way to write the code when should we use the no index syntax when we don't need to know the index just the value that's a good time we need our code to be faster I don't think it really changes how fast the code goes because this is it's all C under the hood right and C is going to be doing indexes or when we want to write code that is harder to read and that's not a good reason okay 12 no indent syntax um more on this which method of writing for Loops is considered more clean assuming both options will work definitely four item and items is more Clint to write and read find an item in the list example of a no index or no range syntax or fruit and fruits print fruit assignment is we need to check if a player has a specific item in their inventory use the no index syntax so we'll say four item in in then re iterate over each item in the player's inventory if you find an item called leather scripts set the found variable to true if um if you find an item so if item equals leather scraps with double quotes because that's the way they said they like it um and are we gonna find it other scraps yes we are found the leather scraps very good next 14 find the difference assignment we keep track of a character's level in an array when someone's level changes we want to know about it so we can congratulate them find any differences between old character levels and new character levels and when you find them print the index where the levels are different Don't Touch Above the slides so now we have iterate Loop over both arrays at the same time using the range syntax and print the indexes where the items in the arrays different for example if the arrays were 2 and 2 5 and 5 3 and 19 that's a big level up seven and seven five and eight your code should print two and four because zero with one two it is different three fourth is different okay hey five viewers how about that thanks for stopping by um if old let's copy paste it if old copy character levels is not equal to oops we needed that I not equal to new character levels at I will do something and they just wanted us to print the index print I oh we've got lots of indices to potentially print 14 some other ones got it modulus operator in Python the modulus operator can be used to find a remainder for example for example 7 modulo 2 would be one because two can be multiplied evenly into seven at most three times two times three equals six then there is one remaining to get from six to seven the modulus operator is the percent sign percent it's important to recognize modula is not a percentage though it's just the symbol we're using bajlo 8 3 twice three gets you to six and there are two more left so the remainder is two an odd number is a number then when divided by two the remainder is not zero so assignment create an array of the odd numbers between 0 and 299 inclusive well we already have um we already have an I I'm deciding which way to do this I could start at one and go by 2. but I'm gonna not do it that way I'm instead going to use what we just learned and say if I modulo to not equal zero and for clarity maybe I'll add a parenthesis here then odd numbers oops I wrote a three where I should have written the two numbers Dot and all right and let's see if that looks right up to 299 starting from 1. okay let's submit that and see if we got it yes we did yay confetti thank you TV Josh for shouting out the TV is for shouting out that it's confetti that it's flying at me slicing lists python makes it easy to slice and dice this to work only with the section you care about one way to do this is to use a simple slicing operating which is just a colon with this up right you can specify where to start and end the slice and how to step through the original list slicing return to the original list slicing returns a new list from the existing list the syntax is as follows LST initial and index jump that you might recognize from range where it was the initial and jump the like one comma 100 by 2. this gives you all the odd numbers reset code the above reads give me a slice of scores list from index 1 up to but not including five skipping every second value all of the sections are optional if they're optional how does it know which one you mean if you only put in two so one through five gives you 70 30 20 90. and 1 through all gives you 70 30 20 90 10 50. okay first assignment first print a slice of champions list that starts with the third item in the list one two three so that's the two width item first print champions sliced starting from the third which is index two and take all the rest then print them B ambians starting at uh print a slice of the champions list that ends with the third item from the end of the list I know I happen to know that I could use a minus but I'm not going to do that I'm going to just count zero one two three four five six it would be the seven if we wanted them all but one two three seven six five four I think that's the way to do it and thirdly print champions that skips every odd number index all of them by two so how does it know the difference between what I'm asking for I think I need double colons here so Champions two through all zero one two to the rest of them I think I got this right yes oh it paused for a second and I thought maybe I missed it that's funny list operations concatenate concatenating two lists pushing them together smoosh is really easy in Python just use the plus operator print all so all is one two three plus four five six print one two three four five six assignment fantasy Quest allows users to keep lists of their favorite items we need to add them all to one giant list so we can keep track of the totals John's favorite Jack's favorites Brianna's favorites Don't Touch Above This line create a new list that has John's favorites followed by Jax followed by Brianna's so new unspot new equals and I'm going to copy paste that's John's favorites followed by Jack's favorites followed by Brianna's favorites yeah print length of new and print the actual list containing all the other items print new so we've got a total of six that makes sense and we've got all the items so let's submit list of operations contains checking whether a value exists in a list is also really easy in Python just use the in keyword so fruits equals apples orange and banana print banana and fruits the result is true tip quotes within quotes in order to use quotes within quotes your user needs to be escaped or you need to use the other kind of quotes because we usually use double quotes we can Nest strings within single quotes f double quote banana is in fruits lists brace single quote banana in fruits that's interesting assignment our players have requested an in-game feature that will allow them to type in a weapon to a weapon name to check if it's in the list of top weapons of the realm so we have a list of the top weapons Don't Touch Above This line take a look at the top three of the three print statements replace the static Boolean values in the curly brace with an in statement that checks if the weapon in the text is in the top weapons list so we're checking if let's give ourselves some more space here we're checking if Sword of Justice sort of Justice in what's the list called top weapons next we check if great Acts and top weapons and then your bow in top weapons how come I can't I want to I think I messed up the I'm trying to scroll the thing back up so we can see things might have to refresh the page is this gonna oh it remembered my stuff that's nice and now we can sort of adjust this is the top we've been true grade X is the top we've been true Killer Bow is the top weapon false run oh we already ran it let's submit it yeah this solution python has a built-in Dell keyword keyword dial that deletes items from objects in the case of a list you can delete specific indexes or entire slices so nums equals one two three uh this is tricky down dumps three deletes the fourth item or if you will the 3th index item so the output is one two three five six seven eight delete items from the second to the third or or from the one if to the three of exclusive so we're left with one four five six delete all elements Del nums colon output is none or is empty list which is different from num important not importantly assignments in fantasy quests there are lists of strongholds on the map that players can visit to defeat powerful bosses uh first delete the first stronghold for the list Del strong oops Dell strong holds at the zero with position which is the first and the release of strongholds Prince strong holds delete the last two strong holds from the list as a slice Bell they didn't tell us this but I know that we can do minus to all like that I'm just I don't feel like counting how many there are uh print the list of strongholds that leaves us with the morgoth mountains The Lonely Island mordia and oh that's that's wrong okay fine I'll do the counting um or is it wrong I'm getting hungry for goth mountains The Lonely Island gondolin we're left with minus so leave the last two strong ones from the list as a slight so get rid of mourdain and Gondola that's not right I want from minus two to the end we have more Dia okay that's good oh I was getting a little scared there that's it for lists chapter 7 functions functions allow us to reuse and organize code for example let's pretend we need to calculate the area of a circle we can use the area the formula area equals pi times r squared or in code r equal five area equals 3.14 times R times r this works great the problem arises when there are multiple places in our code that need to get the area of a circle so this example is going to show repeating code R equals 5 area equals the formula R2 equals seven area two equals the formula times R2 R3 equals 11 Area 3 equals the formula with R3 R3 times R3 because it's squared we want to use the same code why repeat the work let's declare a new function area of circle notice that the def keyword is written before the function name and tells the computer that we're declaring or defining a new function the area of circle function takes one input which can also be called a parameter or argument that returns a single output we give our function the radius of a circle we get back the area of our Circle to use oh there's a looks like a typo in here let me take a screen cap of that to use or call the function we can pass in any numbers the input and call and capture the output in a new variable radius equals five at area of circle equals area equals area of circle parens radius let's talk through The Code by step and I'm going to write an example over here for further discussion oh meow Sammy meow hello okay so the radius variable is created with a value of five if you are here I created the length with five let's make it six so it's different the area of circle of function is called with a single argument radius or here I take area of rectangle with a argument of length the area of circle function is executed with r being equal to five and then we have to scroll up to see what what's in that function and I have to Define area of rectangle of l l maybe it's a great variable to use because sometimes L looks like one but we'll go with it there is the result of 3.14 times R times R is returned from area of circle which happens to be 78.75 or here it would be 36 I'm going to print it so to approve that I have the right idea there okay area of circle radians radius resolves to the return value of 78.75 or in this case 36. and the area variable is created with a value of 78.75 or in our case 36. let's print let's run this to oh what did I do area of rectangle typo see it says name error name area of rectangle is not defined 36. so there we have that assignment let's reset the code confirm we need to calculate the area around a player that they're able to attack with in attack within with a one meter sword for example they should only be able to attack enemies within the area of a circle of one meter radius on line 8 add a second function call to area of circle that passes 0.5 in as the radius capture the result in a new variable called player 2 area okay so we have we're gonna have player two area let's equal the area of circle with 0.5 and we'll submit that very good so to review on that we had area of circle which is a function and to call that function we write it with parentheses around whatever the input or argument to the function will be oh hello Sammy are you here to interrupt me do you want some attention I know you can't see him but he's here just being a kitty all right Sam you get to be on camera now there he is there he goes oh oh Sammy that's what you get when you come up on my desk you get thrown off to the internet let's move forward multiple parameters functions can have multiple parameters or inputs we can have defined subtract of A and B return a minus B assignment we need to calculate the total damage from an attack involving three different enemies complete the calculate damage function that takes three numbers in and as its parameters and Returns the result I'm going to screencap because that's missing a word had complete the calculate damage function that takes it that takes three numbers as its parameters and Returns the result of adding them all together so return the inputs are enemy one damage plus well we have negative damage down there that's interesting plus enemy 2 damage well what did I do I guess I can have multiple I can write on multiple lines that's what I did that's interesting okay uh what did I do wrong though oh we don't need a plus sign here that's not right you doubt seven you belch six not points nine points six points nine points seven points okay looks good so what did we do there let's review that we have a function definition which they gave us these inputs and we said that the result of the function will be to return the sum of those inputs where to declare functions you probably noticed that a variable needs to be declared before it's used let's Show an example of that a equals 5 print a this is going to work just fine but if we reverse that and try to print a before we Define it what oh that's interesting so let's let's let me um review what happened here I said a equals five print a and let's run it it does fine that's not surprising so let me screencap that for later but now let's say a equals 7 but we try to print it before we set it and it gets a is five what if we run it again then it gets a is seven um uh let me take a screen cap of this this feels like a bug to me take a screen cap of this run it again it gets eight so the environment remembers what the previous value of a was that's an interesting Behavior um let's refresh the page so that we start with a fresh thing let's print B and say b equals seven the first time we run this we get name error B is not defined that's as expected but if we run it again wait now it works oh we never oh we never defined B but now if we run b equals seven okay that's fine and then print B it's going to say seven because it remembers how we defined B before that is so weird okay let's get back let's reset the code and get back to where we were to declare protons you probably noticed that a variable needs to be declared before it's used that was what that whole playing was about for example the following doesn't work print my name my name equals Lane Wagner it needs to be my name equals Lane Wagner print my name lines of code execute an order from top to bottom so a variable needs to be created before it can be used that means that if you define a function you can't call that function until after the definition the main function is a convention used in many programming languages to specify the entry point of an application by defining a single main function and only calling main at the end of our entire program we ensure that our function that our function are defined before they're called I should take a screenshot of the whole thing there's a bug in a program Fix It yeah the bug is that main has to be called after it was defined fantasy Quest is booting up okay there we have that although interestingly now if I screencap this I'm going kind of wild with the screen caps but that's okay and if I put it back to that way then it's succeeds where it probably shouldn't I report an issue now I don't want to figure out how to do that I'll do it I'll do that later um let's go back to the correct way so I can submit this okay got through that one took me a while because I went on some detours but that's okay order of functions all functions must be defined before they're used you might think this would make structuring python code difficult because the order in which the functions are declared quickly become so dependent on each other that writing any almost anything becomes impossible as it turns out most python developers solve this problem by simply defining all the functions first then finally calling the entry point function last if you do that the order of all the functions are declared and doesn't matter the entry point function is usually called Main um let's play around with this example on the previous page this is kind of an interesting example so clearly this works let's actually refresh the page just to prove that it's not remembering something from before so we execute we say we Define function Main and we say that main contains function two that's okay because we're not we're not trying to run function two yet we're not trying to execute function two we can Define function two later and we and the and python will know that function two is going to call function three but it doesn't care yet what function three is because it hasn't been executed then we Define function three and to print I am function three and only once we run main does the Cascade of main cause function 2 and function 2 cause function 3 and function 2 cause function three or something like that I think I overstated one of those that's the point of that example okay functions must be defined before they can be called yes however they can be they can be defined in another function before they've been defined them so they can be used in another function before they're defined themselves provided that they get defined before we try to run them does that make sense I mean I don't know it's here this I don't I know no one's answering in the chat right now but just rhetorically does that make sense true functions must be defined before they can be called the next question is function says python functions must be defined in the order they call one another that one is false we saw it down here um like if that were true I'm not sure I love the wording on this one let me take a screenshot to remind myself of that I mean that's false they can be defined in any order as long as they've all been defined by the time we need to run them that's what matters I think I'll make a separate video about that detail that's a that's a good detail scope refers to where a variable or function is available to be used for example when we create variables in a function by giving names to our parameters for example that data is not available outside of that function for example Define subtract of X and Y return x minus y result equals subtract five comma 3 print X error X is not defined let's prove to ourselves that that's actually what happens I mean I know it is but let's prove it invalid syntax it's missing a colon that's hilarious now what name X is not defined okay hold on let me um run this code foreign take this one okay when the subtract function is called we assign the variable X to 5 but X only exists within the subtract function in other words it's a local variable if we try to print X outside of that function then we won't get a result in fact we'll get a big fat error assignment find the bug in the code we're using variable names from the wrong scope fix it I need to reset the code Don't Touch Above This line wait what's going on here oh okay see it's calling get Max Health as a function of modifier but modifier is not defined in the main scope in fact if we run this we should get an air name error name modifier it's not defined so we have to give it my modifier and my level and now it should run nicely Max health is 50. okay good that works type error failed to fetch that's weird okay got it right I don't know what happened just a quick just a just a um I don't know what happened Global scope so far we've been working in the global scope that means when we Define a variable or a function that name is accessible in every other place in our program even within other functions so for example if pi equals 3.14 and to find get area of circle radius return pi times radius times radius Pi is available from the global scope while radius is available in the local scope because Pi was declared in the parent Global scope it is usable within the get area of circle function assignment let's change how we are calculating our players stats the only thing we should need to Define globally is the character level and then let our functions do the rest I'm not sure I love declaring character variable globally but I I'd have to think about like the implementation details before I would be sure of that okay declare player level at the top Global scope and set it to four let's see what this is doing character has 15 primary stats character has 40 max health so we're using player level along with other along with the local variables which are the arguments to calculate things scope quiz can functions access variables declared outside in the global scope yes they can scope quiz can code outside the scope of a function axis variables that are inside of that function no they cannot functions practice degrees conversion formula Celsius equals 5 9 times Fahrenheit minus 32. okay assignment let's take a break from working on fantasy Quest For a Moment instead we will use what we've learned to build a function we could use in the real world write a function called 2 Celsius that converts the temperature in Fahrenheit to Celsius okay we're just practicing writing up so we're practicing writing function um I'll go ahead and say that Celsius equals make it simple by copying um I can't type Fahrenheit because they gave us F so just f minus 32. foreign consistency let's call this C 112 degrees is 44.45 degrees Celsius that sounds about right notice something that is here I made a variable C and then returned C but we can actually save some writing by just directly returning the result of that calculation and that's going to give the same answer 44.44 degrees Celsius looks good another functions practice exercise let's get back to working on fantasy Quest we need to make a way to easily check if an item exists within our inventory complete the string exist function that checks if a given string can be found within an array this is a pretty basic function to have to write but okay is this Sally and Bob Joe and Bill it's false training says Sally and Bob Sally Bill returns true so we just have to write string return to check in Spring array I think that's what they called it yeah that's right healing potion does not exist in this list iron helmet does not exist in this list iron ore exists in this list short sword exists in this list that all looks right Boolean logic I think we talked about Boolean logic before Boolean logic refers to dealing with Boolean true or false values for example dogs must have four legs and we're less than 100 kilograms both conditions must be true cats are cool if they go faster than 200 mile per hour or if they are electric oh cars huh I'm thinking about cats obviously at least condition one at least one condition must be true and syntax the and operator maybe we haven't seen the and operator before the and operator takes a Boolean value on each side and returns true if both billion values are true let's go over how this function would evaluate given the parameters 4 and 99. return true and true return true let's see what happens with what happened with 3 and 98 instead return 3 equals four is false 98 less than 100 is true return false the and operator will only return true if both conditions are true or syntax the or operator returns true if at least one of the conditions are true def is cool car of speed and is electric returns speed greater than 200 or is electric let's use a non-electric car that can do 250 return 250 greater than 200 or false I'm gonna this is this is odd to me I'm gonna take a screen cap I don't know why we're suddenly back on Boolean logic in the middle of functions return to assignment we need a way for our game to track whether our character's attack hits or misses complete the does attack hit function the following should return to true if either of the conditions are met the attack rule is not a one so condition or condition first condition is attack roll not equal one oh it's if either of the following conditions are met so uh so either condition and condition or condition that's the shape of it so the attack rule is not a one that's the first condition and the attack rule is greater than or equal to Armor class foreign or the second condition is attack roll equal 20. what did I do wrong here invalid syntax oh single equal that's an assignment operator that's a mistake I should have written double equals for the equality comparison operator with the rule of 17 and an armor class of I don't feel like going through all of these let's just submit it good and let's let's review what we what I put in here we have a condition and a condition compare combined with an and that becomes one condition and then we have condition or condition Boolean quiz refer to the following Boolean statement what is the value of result is tall equal true is fat equal true is skinny equals false is short equals false result equals is tall and is fat or is skinny and is short true and true is true so we have true or something but with an or if either one is true then the result is true so the answer is true that's an example of short circuit evaluation I don't need to care about the result of the second half because I already have a true and that makes the or that satisfies The Ore regardless of what the second half is going to be hours to seconds assignment we need to display the current in-game time in seconds to our players write the convert hours to seconds function it should convert hours to seconds so how do we convert hours to seconds we take hours we take it times 60 we get minutes we take that 60 again we get seconds and we need to remember to return the result of that calculation 33 hours is eleven eight eight zero zero seconds I'll take that on faith it says it's correct so we'll go with it first element from array assignment let's add another function to our inventory system write a function that Returns the first element from an array if the array is empty then return the string error instead um we haven't learned to try catch yet so I'll use if statements if length of items equals zero return error else return items zero so remember the way to access an item from a from a list or an element from a list is to use the square bracket and then give the number of the index first item in blank is error first item and there's this iron ore first item in one two is one okay those not look good should serve drinks assignments in fantasy quests players can go to a Town's local pub drinking virtual beer refills their stamina complete the function that determines if a bartender should serve drinks to a customer the function should return true only if all of the following conditions are met so we have three conditions I'm going to write condition and condition and addition just to organize it return and I'll put parentheses around these conditions because it'll help me keep track of things so the first condition is the time is between 5 and 10 inclusive what is where's the time here's the time variable so five less than or equal to time and I'm less than or equal to 10. the bartender is not on break we have an on-break variable so oops and not oops on break and condition uh what is this variable called and customer age greater than or equal to 21. Let's test this Pages 22 on break is false times as H should serve equals true when time is one should serve as false when on break is true should serve as false when ages 18 should serve as false and in the last last cases everything's okay so it should serve as true time is 11 should serve as false that all looks good hey scholar cool find Max Infinity the built-in float function can be used to create numeric floating point value that represents a negative Infinity value I've added it for you as a starting point negative Infinity equals float minus then positive Infinity equals float amp assignment our players want to see a way want to find a way to see if their strongest attack from their last combat let's add another function to analyze data from our combat log complete the find Max function so that it looks at each number in the list and Returns the maximum value if no maximum found is just for it just returns negative Infinity how can it not how can it not manage to find a maximum oh if it's an empty list then it won't find a maximum so for Num and nums if num is greater than the maximum oops if Now is better than the max so far X so bar equals number see if these check out Max of one two three four five is five Max of these is 300. Max of these is 20 Max of these is five next this is 21 Max of these is minus infinity maybe it's worth me talking a little bit about why we need to use Infinity here we want we need something to compare the first number to and we want it to be the smallest possible number because then num will always be greater than that if we just for example if we started with Max so far equals zero when we run that well we get the right answer for all of these but if we had something that was all negative numbers then the Mac this program as it's currently written would return zero which is not correct that's why we need the float minus infinity value although I will point out there's another way to do this which is to write Max so far equals them zero and that also um oh that doesn't work because there's an empty list here okay forget about that example that was a bad example here if I was gonna do it that way I would have to write a check to see that the numbers list is not empty okay let's submit this reverse array assignment some of our players would like to view their inventories in reverse order let's write a function that takes an input array and returns a new array except all the items are in reverse order goes like that I'm going to give two ways to do this the first and simplest to write is just to return items with slice notation all all minus one and we have learned about slice notation in this course so I think that's fair now order reverse in is array this that's cute uh the other way I could potentially do this would be or uh in range length of items or let's do length of items common zero comma minus one output equals empty list output dot append items I return output let's check that that looks good too it does not look good oh that's interesting what did I do wrong oh it's um it's inclusive at length of I we need length of minus one and we need minus one so it'll go down to zero that's a little tricky but it works I'm going to go back to the simpler approach got it and I like the confetti functions quiz which keyword is used to create functions in Python that is Def none return When no value is specified for a function for example maybe it's a function that prints some text to the console but doesn't explicitly return a value it will return none the following code Snippets all return exactly the same thing so return none return without saying anything or not even including a return keyword what happens if there is no return line in a function the program crashes no it's not that it just returns none parameters versus arguments parameters are the name used for inputs when defining a function arguments are the names of the inputs supplied when a function is called to reiterate arguments are the actual values that go into the function say 42.0 The Dark Knight or true parameters are the names we use in the function definition to refer to those values which at the time of writing could be at the time of writing the function could be anything that said it is important to understand that this is all semantics and frankly developers are lazy with these definitions you'll often hear the words arguments and parameters used interchangeably but to be pedantic A and B are parameters five and six are arguments and blank are values that are passed into the function by the collar we have arguments blank are inputs specified by the function definition parameters all right one more in this section multiple return values in Python we can return multiple return values from a function all we need to do is separate each value by a comma return get user return dameidomain.com 21 active email comma age comma status equals get user print email print age print status there's kind of a lot going on within this code but let's see what what else the course says first oh this is weird email underscore underscore equals get user it says this works and by convention you should not use the underscore variable later I don't know why they're showing an example where they use the underscore variable then and it's interesting that 21 gets thrown out so this the last time we I mean I guess that makes sense because that's essentially saying like email equals get user the zero with one underscore equals get user the one at one and underscore equals get either the two width one assignment we need to filter the profanity out of our game's live chat feature complete the filter message function it takes a list of chat messages as input and returns two new lists the first list contains the same message but with all the instances of the word shoot and dang removed the second list contains the number of shoot and downwards that were removed from the message at that particular instance it looks like we have some helpful some helpful instructions for this clean messages equals empty list and create two empty lists that you'll return at the end of the function clean messages is that number of it's pretty numbered dirty word counts caught that sometimes naming things is the hardest thing in programming for each message so that I'm thinking for Loop for message and messages split the message on white space using the split method to get a list of words so my list equals I'm not going to say list because that's a that's a special word in Python so my list otherwise I could just say p or I could call it words equals message dot split on the on the space character I don't know why I tried to write a colon there good words is empty lists create a new list that will contain all the non-bad words for this message three create a counter variable and set it to zero we'll increment this when we remove words from the message for each word in the message for word and words if word is in the list dang or oops isn't always there shoot counter plus equals in with the counter plus equals one else if it isn't a bad word instead add the word to the non-bad word list you created else good words dot append word five join join the list of bad words into a single string I'll just write a comment for that now trying good words into a string six append the new clean message to the final list of filtered messages clean messages dot append my string append the counter of bad words um am I getting my indentation correct here I might I might not be for message and messages so we're still in the for message and messages Loop is where we want to be clean messages that attend my string dirty word counts dot append counter return the messages first now we should be at this indentation the the invitation that's within the function and we return clean messages comma dirty word counts let's try running that oh made a mistake my string is not defined that's right that's because I haven't done that yet the join and split tips joining and splitting strings in Python I already did the split but join method the syntax here is we choose the string for joining and then we give it dot join and the list hello there Sam so I guess I'm calling it my string let's call it s no it's called clean image equals space dot join good words clean messages dot append removed one words censor text well it that doesn't make a lot of sense remove two words censored text and pane the and Pane and the whole thing what does that come from shoot and pain in the whole dang thing fun all right I'll review the code that I wrote we start a clean messages list what are we going to do with that we're going to take clean messages and append clean message clean message came from joining the good words and the good words came from checking whether word is in the bad list meanwhile dirty word counts we take dirty words count so we append counter where did counter come from counter came from here if word was in the bad list and this code looked all right I mean this results looked all right so let's submit very good okay we're almost done with the chapter 7 functions adapter chapter chapter default values for arguments in python python has a way to specify a default value for function arguments this can be convenient if a function has arguments that are essentially optional and you as the function Creator want to use a specific default value in case the caller doesn't provide one fault value is created by using the assignment operator in the function signature so Define greeting email to find get greeting of email common name equals there that's clever so it says hello name it would say hello there or else it would say hello lane or whatever so message equals MSG equals cake reading lane example.com lane hello Lane welcome you've registered your email latest example.com message greeting hello there message get greeting of landed example.com hello there welcome you've registered your email Lane at example.com if the second parameter is omitted the default value there value will be used in its place as you may have guessed in order for this structure to work optional arguments that have default specified come after all the required arguments assignments we need to write a calculate damage function that accepts a weapon name and an Arbon value armor value as inputs and Returns the correct amount of damage to be inflicted as an attack the thing is a weapon is actually optional if no weapon is specified by the collar of the calculate damage function we'll just assume the attacker is using the fist weapon I get it weapon equals fist return the attack damage minus armor value see the attack values of the various weapons anything else just returns zero as the total damage I'm tempted to write a dictionary but we haven't learned dictionaries yet so I'll just write this with if statements um so we have we have attack uh we don't have to Define attack damage yet um if weapon equals fist attack damage equals five alif weapon equals this logic is going to be a little bit twisted but it'll work alif weapon equals dagger an attack damage equals 10. alif weapon equals sword attack damage equals 15. else attack else just return zero but if we have any one of those then we return attack damage minus armor first just check that it runs hit by a spell hit by a fist three damage with two armor hit by a dagger with three armor seven damage that looks right hit by a dagger with two armor eight damage hit by a sword with 5 armor 10 damage those all look correct yay confetti and now we and now we learn about dictionaries that's funny that I wanted it in the previous one dictionaries in Python are used to store data values in key value pairs dictionaries are a great way to store groups of information car brand is Tesla Model is three year is 2019. assignment complete the get character record function it takes a character's name server level and the rank it should return a dictionary with five values so return we have this dictionary name is named from the function server and server from the function level oops some words because that's what they like us to use here there's a level from the function rank it's rank from the function and ID is ID from the function oh interesting is there are they going to use a different variable here or ID oh okay is the name and the server concatenated with the hashtag in the middle for uniqueness we can't have two Blood Warrior one two threes on the server for example Blood Warrior one two three and server one would make the ID Blood Warrior one two three hashtag server one okay name Plus hashtag plus server hmm invalid syntax did I skip a comma oh I have a semicolon it's in place of a colon that won't help okay that looks good so to summarize the Syntax for creating a dictionary and also summarizing that I did return and then entered the value that I wanted to return which in this case is a dictionary so we have an opening curly brace some some value it could be a string it could be a number it could be something else but there but it can't be anything it has to be an immutable value and then that's that's called the key and that's followed by a value which in this case comes from the function definition duplicate keys because dictionaries rely on unique Keys you can't have two of the same key in the same dictionary if you try to use the same key twice the associated value will simply be overwritten assignment assume the same assignment we had before but now another developer has introduced some bugs with multiple keys in the dictionary level equals one rank equals two remember the get character record function takes a character's name server level and rank it should return dictionary with five fields um I think we just have to take away this thing where it said level is one hey an F string that's clever okay yeah that was all we needed to do there accessing dictionary values dictionary elements must be accessible somehow in code otherwise they wouldn't be very useful a value is retrieved from a dictionary by specifying its corresponding key and square brackets the syntax looks similar to indexing into a list so there's the syntax we have car we have square brackets and we close the square brackets and we have the key inside um I'm gonna take a screen cap here because I quibble with something here what kind of brackets are used to index in a into a dictionary it's square brackets but I think curly should be curly braces not curly brackets maybe anyway Square setting dictionary values you don't need to create a dictionary with values already inside it's common to create a blank dictionary then populate it later with using Dynamic values the syntax is the same as getting data out of a key just use the assignment operator equal to get that key a value so names are Jack Bronson Jill McCarty and John Denver namesicked equals braces curly braces her name and names dot split returns a list of strings where each string is a single word from the original names array equals name dot split what if we gave it at someone who only has a single name anyway here we update the dictionary names the rate at named zero equals names one okay so it's a dictionary from first names to last names what is the correct syntax to create a new key value pair in an existing dictionary it's we see it here dict square bracket key equals value this is the same example what happens if you assign a new value to an existing key the value updates so we overwrite the old value what happens if you try to delete a key that doesn't exist in the dictionary deleting all dictionary values you can delete Keys using the Dell keyword so Dell names sticked Joe he's into this notice that if you try to delete a key that doesn't exist you'll get an error I had to read that part because I didn't actually know that okay what happens if you try to Dell a key that doesn't exist in a dictionary you get an error counting practice checking for existence if you're unsure whether or not a key exists in a dictionary use the incurred keyword so if cards is Ford F-150 and test the three print forward in cars that's true print GMC in cars that's false assignment we need to be able to report to our players how many enemies are in their immediate vicinity but they want the count of each Enemy by its kind complete the count enemy's function it takes a list of enemy names it takes a list of names as input it should return a dictionary where the keys are all the enemy names from the list and the values or the counts of how many how many time each enemy appeared in the list how many times foreign this one is a little bit trickier I feel like they oops what did I just do or name in enemy names we we start with counterdict is empty value and we'd might you might think that we could start by saying counteredict at name equals one well that works the first time we see name but it doesn't work the second time we see name you might also think that we could say plus equals one but that won't work the first time we see name because there will be no entry for dictionary name in there so we have to check if name in counter predict something else something else so if name is not encounteredict then we create the key with a value of 1 otherwise we counter decked at name plus equals one let's run this and see if it looks reasonable it does not look reasonable foreign I think because I have to return counterdict so Jackal 6 Cobalt 3 Soldier 3 Gremlin one that looks right so to let's let's submit it in check okay good confetti we start with an empty dictionary then we Loop over the name in enemy names then if the name is in counterdict then we can take the value at counterdict and increment it by one which remember is the same as saying counterdict at name equals counter dictate name plus one otherwise we create a new entry at counterdict at name and set it to equal to one finally we return the counter dictionary iterating over a dictionary in Python okay we have an example with fruit sizes apple is small banana is large grape is Tiny for name and fruit sizes size equals fruit sizes of name printf name name size size Apple size small banana size large grape size tiny assignment we need to display on our player's screens what the most common enemy in a given area of the game map is complete the get most common enemy function it should iterate over all the enemies in the dictionary and return the name of the one with the highest count it notice addiction it it's a dictionary of enemy name to count tip negative Infinity when you're trying to find a max value it helps to keep track of the max so far variable and to start that variable at the lowest possible number negative Infinity Max so far equals float negative Infinity you also want to keep track of the enemy value associated with the maximum count I would set the value for default for that variable to none so given that hint or tip and Max name equals none so for enemy what is it it's enemy name in enemies sticks um enemy account equals enemies at the Key of enemy name there is another way to do this but I think I'll just stick to the way they've shown for the course enemy count equals enemy stick of enemy name if enemy pounds greater than Max so far then Max so far equals enemy count and Max name equals enemy name what do they want us to return return the name try this one we have an error what did I do wrong predict object is not callable oh I didn't need to call that using Jackal 2 gram and seven most common Gremlin most common Gremlin most common soldier Okay submit that confetti ordered or unordered as of python version 3.7 dictionaries are ordered in Python 3.6 an earlier python dictionaries were on ordered because dictionaries are ordered the items have a defined order and that order will not change unordered means that the items used to not have a defined order so you can't refer to an item by using an index the takeaway is that if you're using if you're on python 3.7 or later you'll be able to iterate over dictionaries in the same order every time this seems to be implying that you can okay that in later versions of python I don't know what version of python we're dealing with here but let's just say d equals one a two B oops and what if we try to see we can't we can't I guess if we could say for key and D print D at Key so we can we can access them in order but my point is we can't we can't access them by index anyway python dictionaries before 3.7 were unordered okay take a drink of water before we get into sets okay sets are like lists but they are unordered and they guarantee uniqueness there can be no two of the group in it of the same value in a set fruits equal apple banana grape print type of fruits class set print fruits banana grape apple notice that it's in a different order because the order is not guaranteed adding values fruits.add pair empty set because the empty because the curly braces syntax creates an empty dictionary to create an empty set just use the set function for its equals set fruits.add pair print fruits it's pear iterate over values in a set order is not guaranteed fruits equals apples banana grape or fruit and fruits print fruit Prince banana grape apple assignment complete the remove duplicates function it should take a list of spells that the player has learned and returned a new list where they're the most one of each title you can accomplish this by creating a set s equals set notice I don't want to write set equals set because set is a special word that refers to the set data type and we don't want to overwrite that with our variable name getting a set adding um adding all the movies to it oh there's a there's a typo you can kind of see the history of this course that it used to be a list of movies you can accomplish this by creating a set adding all the movies to it then iterating over the set and adding all the movies back to a list and returning the list it makes no sense to learn a spell twice once it's learned it's learned forever what if it's forgotten though then you might want to relearn it anyway I go along and say for spell in spells and I add the spell to my set s then or spell in s and here we can use spell in two different places because it's only it's only valid within the for Loop but that's okay I have an output list T equals empty list and the function is append and we return the list of unduplicated things Eldritch blast Fireball Sunburst water gun water gun okay submit sets quit sets are like lists okay this is the same information from before how do I remove an item from a set um oh it's down here fruit star remove my set dot remove five item sets quiz what is the type of my vowel in the following statement vival equals curly braces that's a dictionary sets quiz which would be a good use of a set to store all the enemies in a game by difficulty to store all the possible spells in a game to store ID user pairs well not to store uid user pairs because this sets just contain individual values it's not great for storing all the enemies in the game by difficulty because again you have the you would need the enemy name and its difficulty but all the possible spells in a game that's a good one for it okay we're on to errors good errors and exceptions in Python probably encountered some errors in your code from time to time and if you've gotten this far in the course in Python there are two main kinds of distinguishable errors syntax errors and exceptions syntax errors you probably know what these are by now a syntax error is just The Interpreter telling you that your code isn't adhering to proper syntax this is not valid code so it will error if I try to get to run that sentence as if it were valid code I'd get a syntax error this is not valid code is syntax error invalid syntax exceptions even if your code has the right syntax however it may still cause an error when an attempt is made to execute it errors detected during execution are called exceptions and can be handled gracefully by your code you can even raise your own exceptions when bad things happen in your code back before when I had the um I had not defined that string I was thinking in the back of my head I could raise a not implemented error but I didn't it didn't need to do that at the time python uses a try except pattern for handling errors so the classic example dividing by zero try 10 divide by zero except exception as e print f exception except except exception accepted zero dot e for exception the try block is executed until an exception is raised or the tripod completes whichever happens first in this case a divide by zero error is raised because division by zero is impossible the accept block is only executed if an exception is raised in the try block [Music] it then exposes the exception as data e in our case uh one second it then exposes the acceptance data e in our case so that the program can handle the exception gracefully without crashing assignment one of the calls to get Player record is throwing a player ID not found exception change the code to safely make each call with a try accept block if an exception is raised just print it I don't think we need a separate try catch block for each call so let's just make it all inside one block and we're using the basic tip in here which maybe isn't the best practice but we'll do it for now oh maybe maybe I am supposed to do each one in a maybe I am supposed to do each one in its own try accept block let's let's do it that way okay so again we try to do something in code something that might cause an error and then we tell python that in try to do that but if there's an exception then call that exception variable e and then do something else in which case this is just going to print the error try again oh no what are they supposed to do it the other way no that didn't help oh just print it as it is darn it lost my winning streak oh well okay now we're gonna review a try except the try block is executed until an exception is raised or it completes whichever happens first in this case the divide by zero error is raised because division by zero is impossible the accept block is only executed if an exception is raised in the try block it then exposes the exception as data enrk so that the program can handle the exceptions gratefully without crashing if no exceptions are raised on the try block then the accept block won't execute if an exception is raised outside of a try block the program crashes and prints the exception rates your own exceptions errors are not something to be scared of every program that runs the production is expected to manage errors on a constant basis our job as developers is to handle the errors gracefully and in a way that aligns with our users expectations we'll skip the video for now when something in our code happens that we don't expect we should raise our own exceptions for example if someone passes some bad inputs to a function we write we should not be afraid to raise an exception to let them know they did something wrong an error or exception is raised when something bad happens but as long as our code handles it as the user is expected to it's not a bug a bug is when code behaves in ways our users don't expect it to for example if a player tries to forge an iron sword out of bronze medal we might raise an exception we might raise an exception and display an error message to the player however that's the expected behavior of the game so it's not a bug if a player is able to forge the Iron Throne out of the bronze that may be considered a bug because that's against the rules of the game Syntax for raising exceptions raise exception something bad happened assignment if a player ID is passed in the get Player record function we need to raise our own error to alert the caller the function that the player they're looking for doesn't exist the exception should say player ID not found I guess this is else except that we haven't done in alif syndex so I guess it's just the return the return statements will take care of program flow so it'll never get here if any of those works so if it gets here then we say player ID not found okay that makes sense raising exceptions preview software applications aren't perfect and user input and network connectivity are far from predictable despite intensive debugging and unit testing applications will still have failure cases lots of network connectivity missing database rows out of memory issues and unexpected user inputs can all prevent an application from performing normally it is your job to catch and handle any and all exceptions gracefully so that your app keeps working when you are able to detect that something is amiss you should be raising the errors yourself in addition to the default exceptions that python interpretable rates so raise exception something bad happened which keyword creates a new instance of an error to be caught in Python that is from here it's raised good code doesn't need to handle errors it should be error-free that is false there are going to be errors because the world is unpredictable different types of exceptions we haven't covered classes and objects yet which is what an exception really is at its core we'll go more into that in the object oriented colors that we have lined up for you next for now what is important to understand is that there are different types of exceptions and that we can differentiate between them and our code try 10 divided by zero except zero divisibility error print zero division accept exception print on known exception try nums 0 1 print nums two except zero division error print zero division accept exception print on known exception which will print zero Division Unknown exception basically zero division error is a more specific type of exception and we check for it first but if we don't find it and we won't find it in this case then we go to the general exception assignment the get Player record function can now raise two different types of exceptions one is an index error where the other is a custom exception message of the base exception class complete the handle get Player record function it should return the result of get Player record but if an index error is raised it should print index is too high otherwise if any other exception is raised it will just print the exception itself oh I see it says handle get Player record of player ID we try get Player record of player ID except if it's an index error is e then we will print index too high but we don't need Fe except deception print e run this none none index too high negative IDs are not allowed that's the okay that's our index too high what's the index error negative IDs are not allowed was the exception that we didn't know anything about try again oh we need to return get play a record of ID okay in this code sample what will happen racing acceptance review as you notice there are many kind of exceptions many specific exceptions are built into the language like index error and zero division errors and all exceptions count as the parent exception type if you're interested in the official documentation on all the built-in extra step acceptance you can find a list here we'll look at that later maybe refer to the following code for the question try a raise exception zero division except zero division error as e print zero in this whole example what will happen well we're first going to raise the exception then we're going to catch that that same exception as e but we're not going to print zero division we're just going to print zero because that's what the code tells it to do oh I got fooled I got fooled it's nothing the program will crash with an uncut exception because it raises an exception with the tech zero division but zero division error is a different kind of exception so we don't catch the exception that was raised and yeah okay the program will crash with an odd exception oops okay we have a new example try raise exception zero division except zero division error as e print zero except exception as a print other it will print other this time good refer to the calling call for the question try 10 divided by zero that will raise a zero division exception except exception as e print author it will print other good okay time for the BRB screen okay we're on to section R to chapter 11 which is challenges does in this chapter we are going to practice applying the skills and Concepts we learned while building fantasy Quest number sum write a function called number sum that adds up all the numbers from 1 to n for example number sum of five is one two three four five it's fifteen the number sum of three is one plus two plus three is six um I could do a list comprehension but I'll stick to things we've learned so far in this course so for I in range of One n plus one result equals zero because we we start when we're taking it some we start at zero result plus equals I return result let's check that wait sum of one to three is three that's not right oh huh that's a bug plus equals I one to three is six one to five is fifteen okay check minimum number in Python write a number to find min that finds the smallest number in an array find Min 1 3 minus 1 2 plus to minus one vitamin eighteen three seven two goes to two and they're going to tell us now about positive Infinity since you're trying to keep track of the smallest number start with a really big number python has a built-in constant that represents positive Infinity let's say minimum because Min is already defined as a function we start with float is we start with minimum as a float of INF and then we say for Num in nums if number is less than minimum minimum equals number then we return minimum that's all there is to it except I did something wrong name number oh minimum equals num okay that looks good to review this one we start with a really big number so that any actual number is going to be less than that so that the original value for minimum won't mess up our final result remove numbers write a function called remove non-ints that removes all non-integer types from an array you can check the type of a variable using type function now the way I'm going to do this is iterate or possible numb and numbs I don't want to be removing things from an array while I'm iterating over that array so instead I'll make a new output array so if type of possible num little int output dot append possible num and finally we return output let's check that these look right 302 sep yeah that looks right next up factorial complete the factorial function it should calculate the factorial of a number a factorial of a number is the product of all positive integers less than or equal to that number for example 4 factorial is 4 times 3 times 2 times 1 equals 24. the exclamation symbol denotes a factorial tip a special case for zero the value of zero factorial is actually one this keeps Factor as consistent with the invention for an empty product not sure exactly what that means but I'll start with if num equals zero you turn one else actually we don't even need an else because control flow says that if number is one return one but if number is not one then we'll end up on this line and we can just we can just proceed so for num in or X and range of one comma num plus one because we want it to be inclusive when it gives out the numbers let's start with results equals one oh interesting we don't actually need to check if num equals zero but it's probably a good thing to do result times equals X term result the factorial of 14 it says is this big number Factor audio five is 120 that sounds right okay got that one area some complete the area sum function it accepts an array of rectangles where each rectangle is a dictionary that has the following structure the height five width 6. the function will calculate the area of each rectangle then sum them all up in the result so let's do a area rect e direct of a pound b def area rect of a by B return a times B I'm not sure that's really necessary but that's probably a good idea or rectangle in rectangles re um result we'll keep track of results in a variable that starts at zero results plus equals area wrecked of rectangle and we have to access height comma rectangle width now if you're quick you'll notice that I made an error rectangas is not defined I made multiple errors correct for rectangle okay copy paste means I get things spelled right some is none because I forgot to return anything okay those are numbers we'll say that's good got it Fizz Buzz fizzbuzz is a commonly overused little toy program that comes up in entry-level interviews write a program from scratch that Loops over all the numbers from 1 to 99 inclusive and prints them so we'll start with for Num and range one comma 100 remember range function is exclusive at the second number so that's why I'm going to 100 there if the number is a multiple of three instead of printing a number print Fizz if a number is a multiple of five print buzz if it is a num multiple of three and five then instead print fizzbuzz let's see which which way did I know do I want to do this um let's start by checking if num mod 3 equals zero so that's if it's that's means it's a multiple of three and num mod five equals zero print this Buzz so we'll cover the that case first alif num mod 3. equals zero branch is LF num Mod Five equals zero print Buzz else print no so this may not be the most efficient way to do it but I think it's the way that's easily explainable we start by checking if it's both divisible by three and five or it's a multiple of both three and five then that's fizzbuzz and we have an elsif here so if in this case we know that it's not divisible by five well we know it's not divisible by three and five and once we find that it is divisible by 3 or that's a multiple of three then we can print fit then we know we can only print we can fit only fizz and similarly if we know that at least one of these is true but only one anyway this should work yep cool array division right if I can call it divide array that takes an array and has and a number as an input the function creates a new array that contains all the elements of the original array except they have been divided by the second input well it's tempting to write nums you know returned nums divided by divisor but just for interesting let's see what that returns unsupported operand types for for divide list and int you can't take a list and divide it by an ant so instead we have to make a let me see we can do this in place in the nums array go for I in range of the length of numbers at I equals nums at I divide by divisor um do we want to integer divide make sure you're petting the raw float values don't don't round or cast the numbers integers okay I need to return nums notice that I can't just say for Num in nums because I need I need access to the position of the array to save the number back into there try again now what did I do wrong given nums one five and divisor five one five below was returned what hmm am I missing something obvious oh shoot I think this is a bug in the chorus I'm still wrong now what's wrong or numb and numbs my nums something is weird what am I missing here let's just reset the code there it goes there's definitely something wrong with what I'm doing here oh return dumbs that's the problem there okay uh I must be getting tired but I still have a problem with I don't understand what was wrong with for I in range oops four four I am range of length of nums divide by divisor what if I say just put in the dummy number here foreign foreign hahaha I see the problem Oh my I wasn't supposed to I wasn't supposed to change the values and nums foreign nums equals three four five it was actually given nums equals 6 8 10. because lists are mutable okay so the problem here is that it printed the wrong output because the given nums number was wrong okay I've I'm done with that one now join strings write a function called Joint strength that concatenates all the strings it passes as its inputs end on an order and adds a comma between well this is a simple join comma dot drawn experience return Commodore joint strings okay shout out to SC2 Starker F2 okay the Zen of python nice that they're putting that in here Tim Peters a long time pythonista describes the guiding python principles of python in his famous shortbread the Zen of python beautiful is better than ugly explicit is better than implicit simple is better than complex complex is better than complicated flat is better than nested sparse is better than dense readability counts special cases aren't special enough to break the rules although practicality beats purity errors should never pass silently unless explicitly silenced in the face of ambiguity refuse the temptation to guess there should be one and preferably only one obvious way to do it although that way may not be obvious at first unless you're Dutch Now is better than never although never is often better than right now if the implementation is hard to explain it's a bad idea if the implementation is easy to explain it may be a good idea namespaces are one honking great idea let's do more of those um quiz simple is better blank is better than blank simple is better than complex taking it directly from the from the text it's okay for special cases to break the rules well this is a this is a tricky one special cases aren't special enough to break the rules although practicality beats Purity but uh practicality says that it's simpler to go with the first statement so I'll say false an implementation an implementation that's easy to explain is a good idea maybe there should be one obvious way to accomplish a task which language why python here are some reasons we think python is a future proof choice for Developers easy to read and write python reads like plain English due to its simple syntax it's a grade four choice for advancing advanced concepts like AI this is arguably Python's best feature popular according to stack Overflow developer survey python is the fourth most popular coding language in 2020. part 3 python like many languages nowadays is developed under an open source license it's free to install use and distribute portable python written for one problem platform will work on any other platform interpreted code can be executed as soon as it's written because it doesn't need to take a long time to compile like Java C plus or rust releasing code to production is typically faster why not python python might not be the best choice for a project if the code needs to run fast python code executes very slowly which is why performance critical applications like PC games aren't written in Python if the code base will become large and complex due to its Dynamic type system python code can be harder to keep clean of bugs or if the application needs to be distributed directly to non-technical users they would have to install python in order to run your code which would be a huge inconvenience which language typically allows for code to be released most quickly released most quickly is python the best reason to use Python is because its code runs fast that is false python 2 versus python 3. one thing that's important to keep in mind as you continue your python journey is that python ecosystem suffers from split personality syndrome Python 3 was released on December 3rd 2008 but over a decade later this web is still full of python 2 dependencies scripts and tutorials in this course we used python3 just like any good citizen should these days one of the most important breaking chain one of the most obvious breaking changes between Python 2 and Python 3 is the Syntax for printing text to the console python 2 prints space hello world Python 3 print paren hello world assignment update the code from python 2 to Python 3 syntax what happens if I run it just like this oh my oh did you mean print python 2 really needs to die already I thought that was actually part of the error message but it's just foreign text did you mean print arbitrary text okay it's not actually part of the error message that's disappointing not disappointing but it's kind of less fun than it could be okay fix the bug run python really needs to die already got it should you use Python 2 or python3 as you've probably guessed you should always use Python 3 going forward python 2 and Python 3 are similar but pyth 3 contains significant changes that are not backwards compatible with the two point x versions Python 3 code is always backwards compatible with python 2 that is false okay that's it for that course
Info
Channel: Erik Kristofer Anderson
Views: 3,292
Rating: undefined out of 5
Keywords:
Id: wMCs2Py-Ldk
Channel Id: undefined
Length: 237min 29sec (14249 seconds)
Published: Mon Oct 31 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.