Python Lessons - Python For Beg - William Al

You might also like

You are on page 1of 504

in this course i'm going to teach you everything you need to know to get

started programming in python now python is one of the most popular


programming languages out there and it's by far one of the most sought after
for jobs and so if you're trying to get a job or you're trying to you know
automate your life or you're trying to write awesome scripts to do a bunch of
different things then python's for you honestly more and more developers
every day are moving their projects over to python because it's such a
powerful and such an easy to use language a lot of programming languages
out there just aren't very beginner friendly there's a lot of syntax there's a lot
of like little things that if you get wrong the program will yell at you python
is the complete opposite of that you basically just type out what you want to
do and python does it it's that simple there's not a whole lot of syntax to learn
and the learning curve is literally zero you jump in you can start writing your
first program in seconds in this course i'm going to teach you guys everything
you need to know to get started in python i designed this course especially for
python and each lesson has been specially designed with examples that will
help you along the way with so many people starting to learn python the
question isn't why should you learn python the question is why shouldn't you
and i think for a lot of people the reason they might not want to learn python
is because they're intimidated or they're afraid that it's going to be too hard
trust me i'm going to hold your hand through this entire course we're going to
talk about all the core concepts in python we're going to look at everything
you need to know to start programming in python and start being confident
and start writing scripts and start running programs that are awesome and
doing cool things in your life anyway i'm super pumped to be teaching you
guys python i can't wait to get started in this course and i hope you guys stick
around and follow along with the course and learn this amazing programming
language

in this tutorial i'm going to show you guys how to install python onto your
computer and we're also going to install a text editor that we can use to write
our python programs in so the first order of business is to actually install
python on your computer so we want to do is head over to our web browser
and you want to go over here to this page it's just www.python.org forward
slash downloads and on this page there's going to be two buttons down here
and it's just going to say download python 3.6.3 and at least that's the version
that i have right now or download python 2.7.14 so here's the thing about
python there's actually two major versions of python that are in use currently
there's python 2 and there's python 3. so you can see over here this is like
2.7.14 basically any python 2 version we would just refer to as like python 2
and here's like the latest python 3 version and so there's these two versions
that you can download and the first thing we have to decide is which version
do we want to download and here's the basic difference python 2 is a legacy
version of python which basically means that it's like an old version and it's
not being like actively maintained or supported like officially by python
anymore python 3 is like the future of python it's like the newest version it's
the one that's getting actively maintained and supported so there's pros and
cons to picking either one a lot of people will say like python 2 has been
around longer and so there's more like libraries there's basically just more
python code written in python 2. so therefore like there's a few more things
that you can do in python 2 than you can do in python 3. but then again
python 2 is not supported and you know 5 or 10 years from now probably no
one's going to be using it python 3 like i said is like the future of python it's
the newest version it's the one that you know is sort of being maintained
going forward so for the purposes of this tutorial i'm gonna be teaching you
guys python three so we're gonna wanna download python three now here's
the thing like if you learn python 3 or you learn python 2 the differences
aren't very big there are a few differences in like some syntax and just some
you know little things here and there but if you learn python 3 you'll be able
to jump right in and code in python 2 as well don't let anyone you know tell
you that you have to learn one or the other we're going to learn python 3 just
because it's i think probably the best for a beginner to learn and so that's the
one that we want to download so i'm just going to click download python 3
and we're going to go ahead and download this version and when that's done
downloading i'm just gonna head down to my downloads folder and you'll see
here we just have this file i'm just gonna double click and we get this like
python installer so i'm just gonna click through here and we'll be able to
install python 3 on our computer all right when that's done installing we can
just close out of this and we should be good to go so now we have python 3
installed on our computer the next step is we need to choose a text editor so
we're going to be writing a bunch of code so we're going to need some you
know environment or some program that we can write all that code in and
really you can write python in any text editor you could write it in like
notepad or text edit it doesn't really matter but there are special text editors
that are designed just for writing python code and these are called ides and
that stands for integrated development environment it's basically just a
special environment where we can you know run and execute our python
code and it'll you know basically like tell us how we're doing so if we're you
know if we write something that's wrong or we have errors it'll kind of point
us in the right direction of what we need to do to fix that stuff so in this
course we're going to be using an ide and one of my favorites and one of the
most popular ides for python is called pycharm so i'm over here on this
website it's called jetbrains.com forward slash pycharm and this is the ide that
we're going to be using in this course so i'm just going to come over here and
click this big download now button and we'll go ahead and download this
pycharm program all right so i'm getting this page over here you can see
there's two versions of pycharm one is a professional version and that one's
like paid so you have to pay for it but then there's this community version
down here and that's free and open source so i'm just going to download this
one and this should have everything we need to get started using python all
right when that finishes downloading i'm just gonna pull that up in my
downloads folder and again we can just sort of run this guy and i'm on a mac
so i'm gonna have to drag it over to my applications folder all right so we
now have pycharm and we have python 3 installed on our computer so we're
ready to start programming in python

in this tutorial we're going to create our first python program and we're going
to be able to run it and see how everything works the first thing i want to do
is open up pycharm so pycharm was the ide the integrated development
environment that we downloaded in the last tutorial so i'm just going to go
ahead and search for it on my computer and i can just open it up and when we
first open up pycharm we should basically just get a window prompting us to
create a project so you can see that down here actually the first thing i want to
do though is come over here to configure and i'm just going to click on
preferences and i actually want to change the appearance so i'm going to go
ahead and give this a theme so i just went over here to appearance and
behavior appearance and i'm going to change the theme to darcula just
because i think it's a little bit easier to use and look at but you don't have to
do that if you don't want to so down here i'm just going to click create new
project and it's going to give us this little window right here so i can just
name my project and i'm just going to name this draft and then there's this
other option down here where it says interpreter now what we want to select
is python version 3. so if i click down here you'll notice that there's a couple
different options so i'm on a mac computer and by default mac has python
version two installed on it if you're on a windows machine i'm not sure if it
does but in this tutorial we're going to be using python 3. so you want to
make sure that you have python 3 selected as the interpreter otherwise you
might not be able to fully follow along with what we're doing in this video so
now i'm just going to come down here and click create and this is going to go
ahead and create our project for us all right so now we have our python
project up and running and i want to show you guys how we can create our
first python program so over here in this draft folder and this is just that
project that we created i'm just going to right click and i'm going to say new
and i'm going to come down and click python file so we want to create a new
python file this will be our first python program and i can just give this a
name so why don't we just call this app and i'm just going to click ok all right
so now we have our first python file open and we can just start typing in
some python so i want to show you guys just a very basic python program
and this is just going to be a hello world program so we're just going to print
something out onto the screen so when i what i want to do is i want to type
out p r i n t print and i want to type in open and close parentheses now inside
of this parentheses we can make some quotation marks and inside of the
quotation marks i'm just going to type out hello world so this is like a very
basic python program and what this is going to do is it's just going to print
out hello world onto the screen so now what i can do is i can actually run this
file and we're actually getting a little error here it wants us to create a new
line at the end of the file and so now in order to run our python program i'm
just going to come up here to the top and i'm just going to click run and we'll
click this run button right here and i will see what happens so it's asking me
what i want to run i can just click app and down here at the bottom you'll
notice that we have this text that just got printed out hello world so whatever i
print or whatever i put inside of this print statement is going to get printed out
down below in the console so as long as you're getting that print statement to
work then you've actually written your first python program and as we go
through forward in the course we're going to be writing all sorts of awesome
python programs and we're going to be doing all sorts of cool stuff

in this tutorial i want to talk to you about writing a basic python program so
we're going to write just a very simple python program we're going to look at
how we can go ahead and write our programs we're going to talk about how
our programs are getting executed by python and we're also going to draw out
a little shape onto the screen so this is going to be pretty cool i'm excited to
talk to you guys about just the bare basics of python and really just sort of
give you an introduction so over here we have our basic text editor so any of
the python code that i write inside of this file is actually going to get executed
by python so this python file has a bunch of python code inside of it and
basically what we're doing when we're programming in python is we're just
giving the computer a set of instructions right that's really what programming
is it's just like we're specifying a set of instructions and the computer is going
to go off and execute those instructions that we give it and so the more
complex the instructions we give to the computer the more complex the tasks
the computer can carry out so i want to show you guys how we can use some
python instructions or some python code in order to draw out a shape onto
the screen so i'm actually going to draw out a little triangle so over here we
can actually print something out onto the screen in python using something
called a print statement so i can just type out print and inside of these
parentheses i can just type some quotation marks and inside the quotation
marks we can put whatever we want to print out onto the screen so i'm going
to copy this and i'm actually going to make a few of these little print
statements and we're going to actually draw a shape so we're going to draw
like a triangle type shape so down here i'm just going to draw a forward slash
and then up here i'll make a space and we'll do another forward slash here
we'll make two spaces we'll do another forward slash and over here we're
going to make three spaces and a forward slash and now i'm going to draw
like a vertical bars going all the way down

and actually we can do some underscores here as well that'd be kind of cool
all right so now we have our triangle looking shape and you can see it looks
kind of like a right triangle so i can save my file and i can either come up here
to run and click run app or if you're using pycharm you can also just come
over here and click this play button and when i click the play button i want
you to notice what happens down here so down here we have this little
window and this is called the console and basically the console is just a place
where python is going to output some information so when we use this print
statement we're basically telling python like hey can you print something out
onto the console so there's a lot of situations where we're going to want to see
what's going on in our code and we can use that print statement and print
things out to the console and we can basically like have a little window into
what our program's doing in our case we're just going to be printing out this
triangle onto the console so i'm going to come over here and click this play
button and you'll see down here we're actually printing out that triangle so
mission accomplished we were able to print out our shape so i could really
draw any shape i wanted as long as i was able to specify it inside of these
print statements so essentially what python's doing when i click that play
button is it's going into this file and it's looking at all of these instructions in
order so the first thing it does is it goes to this instruction and it says okay
they want me to draw out these like little forward slash and this vertical bar
onto the screen once it does that it goes down to this instruction it says okay
they want me to print something out again when it prints that out it goes
down to this instruction etc so python is actually going to execute the lines of
code that we write in order so the order in which i write the instructions
matters a lot so for example if i was to take this last line here and put it up
here at the top now when i save the file instead of just drawing out that
triangle it's going to draw out this little upside down bottom thing at the top
and then the rest of the triangle down here so the order of the instructions
actually matters a lot so this is basically how your python programs are going
to go as we go through this course we're going to learn more and more of
these little lines so here we're just using this little print function basically it
just prints something out onto the screen there's a bunch of little things like
this that we can learn and as we go through we'll learn more and more
instructions that we can give to the computer but in this lesson i just want to
kind of show you guys the basics right we can essentially just define these
little instructions for the computer and the computer will execute them in
order

in this tutorial i want to talk to you guys about using variables in python now
in python you're going to be dealing with a lot of data and so a lot of times in
our program we're going to be working with all types of information and data
and values and sometimes that data can be difficult to manage so in python
we have this thing called a variable and it's basically just a container where
we can store certain data values and when we use a variable when we put
those data values inside containers it makes it a lot easier for us to work with
and manage all of the different data inside of our programs so variables are
extremely helpful and it's sort of like a core topic in python that you're really
going to want to know and master so in this tutorial i'm going to teach you
guys everything you need to know to get started with variables we're going to
look at what they are why they're useful and we'll look at the different types
of variables and the different types of data that we can store inside of
variables so over here in my python file i just have a very simple program
and it's basically just printing some text out onto the screen and so this is
actually a little story that i wrote it says there once was a man named george
he was 70 years old he really liked the name george but didn't like being 70.
so this is a valid python program i could go ahead and run this program and
you'll see down here in the console everything prints out and it looks great so
we have an awesome little python program here but let's say that inside of our
story i wanted to change the character's name so instead of naming the
character george let's say i wanted to name the character john well i'm gonna
have to go through and i'm gonna have to manually change the name george
to the name john at every place inside of this story where it's mentioned so
i'm gonna have to go over here and i'll say okay john i'm gonna have to
manually change that and then okay down here we're gonna have to again
manually type in john and change it to john so in order to change the
character's name i had to manually go in and change it in both places and now
let's say okay maybe we want to change the character's name age also so in
addition to changing the name we also want to change the age let's make him
a little bit younger so why don't we say john is going to be 35. and so you'll
see here i had to come here and manually change the age and then come
down here and manually change it again right and now that we changed it
like it's going to work it's going to be updated in our program but you'll
notice that in order to make that change like i had to look through the entire
program find it where that value was and change it and this was only with
four lines of the story imagine if i had a story that was like thousands of lines
long and we mentioned the character's name and age like hundreds of times i
mean i'd have to look through each one of those lines and manually change
the character's name and that is not a very good way for us to do this and it's
really not a good way for us to manage the data in our program right the
character's name and the age so we can actually use a variable in order to
store the character's name and the character's age and when we use that
variable it'll make it a lot easier for us to put the character's name and age
inside of our little program here so i'm going to show you guys how we can
create a variable for the character's name and age and i'm just going to go up
here above this print statement and up here i want to create a variable so
when we create a variable in python we actually need to give python a couple
pieces of information the first piece of information we need to give python is
the name of the variable so i need to actually assign a name to this container
where we're going to be storing information and so all i have to do is just type
out the name of the variable that i want to create so i'm going to create a
variable called character name so i'm just going to say character and i'm
going to say underscore name so generally when you're creating a name for a
variable in python you want to separate different words with an underscore so
i have two words here and i'm separating them with an underscore and now
what i need to do is i need to put a value inside of this variable so basically
what i can do is i can just say equals and over here i can type a value so i'm
just going to type out the character's name inside of quotation marks so we're
just going to type out john so now we have a variable for the character's name
and below this character name variable i want to create another variable
called character age so i'm just going to type out character underscore age and
i'm going to set this equal to the character's age which is 35. so we now have
two variables one representing the character's name and one representing the
character's age so what I can do now is I can replace the character's name
inside of the story with this variable and I’m going to show you guys how to
do that so if we want to put a variable inside of this print statement I’m
actually going to have to do a couple of things the first thing I’m going to
have to do is end off this text in here so I’m going to have to put quotation
marks here at the end and you can see I’m basically wrapping this whole
thing into a single like quoted line and now I also have this text over here at
the end so I’m going to have to put a quotation mark here so now I have a
bunch of text here in quotation marks and then I also have text over here in
quotation marks now inside of here instead of saying the character's name I
want to refer to that character name variable so I’m just going to say plus

character underscore name and i want to say another plus sign so i basically
am saying i want to print out all of this text plus the value that's stored inside
of character name plus all of this text and what this will do is it'll actually
print out the character's name when we print this so i'm going to go ahead and
run this program and you'll see down here and actually let me put a space
over here and we'll run it again so you can see down here we still are printing
out there once was a man named john and so what python is doing is when it
executes this line of code it's coming over here and it's seeing okay they want
to print out the value inside of character name so it python's going to go up
here it's going to get the value and it's going to insert it inside of there so i can
basically do this for every instance of the character name in my file so i can
you know i'll just copy this guy right here and i can just paste it down here
where the character's name is so i'll paste this and you can see now we're
doing exactly the same thing that we did up there i can also do this for the
character's age so i'm going to come down here and i'll paste in what we just
pasted in and i'm going to change this instead of character name we'll change
it to character age and i'm going to do this in one more spot so we're going to
do this over here where we're mentioning the age and again i'll just change
this to character age and so now when i run this program it's going to print
out the same story that we were printing out before but now i don't actually
have to type in the character's name and the character's age i can just refer to
this variable and the cool thing about variables is if i wanted to change the
character's name now all i have to do is change it up here so i could change
the character's name to like tom or something and we could also change their
age so i could change the age to be like 50 and now that's gonna
automatically update throughout our entire story so when i click this play
button you'll see now we're using the name tom and he's 50 years old so that's
where variables can come in handy and this can be a really awesome way to
control and manage the data that's inside of our programs with variables you
can also modify their values so for example let's say that halfway through the
story i wanted to change the character's name well i can just make some new
lines over here and down here i can actually assign a new value to one of
these variables so i could say like character underscore name and in order to
give it a different value all i have to do is just say equals and we'll give it a
different value so let's say halfway through the story we want to change the
character's name to mike well now when i run on my program you'll see here
in the first part of the story it says there once was a man named tom and in
the second part of the story it's referring to the name as mike so i actually
updated the variable inside of my program over here and that's a really
awesome way you know a lot of times in these programs you're going to want
to be modifying the values of variables so you can do it just like that so
finally i want to talk to you guys about the different types of data that we can
store inside of these variables so over here i have the character name and the
character age and i'm actually storing what are called strings so a string is
basically just plain text right so the name tom that's just plain text down here
these guys are strings as well so there's a data type in python called a string
and it's just basically going to store plain text so you know any text that you
would have like in a story or you know someone's name you can store inside
of a string there's also another type of data that we can store inside of python
which is numbers so in addition to storing text we can also store numbers so
if i wanted to store a number for example let's say we wanted to store the
character age instead of inside of a string we could store it inside of a number
so i could just type out 50. and when we're storing a number we don't need
these quotation marks you only need that quotation mark when you're storing
a string so if I wanted to store a number I can just write it out like this and in
addition to using whole numbers I could also use decimal numbers so I could
say like 50.5678213

and python's gonna be able to store that number as well so you can store all
different types of numbers and we can also store what's called a boolean
value and a boolean value is essentially a true or a false value and there's a lot
of instances in programming where we're going to want to represent true or
false data for example i could have a variable called like is male and this
would tell me whether or not someone was a male and in my case it would be
true because i'm a guy right so i can actually this needs to be capital so i
could store a value of either true or false and actually if we were naming this
in python we'd want to use an underscore so i would say is underscore male
and this can be either true or false so true or false values is maybe not
something that you're used to dealing with like in the real world but in
programming we're going to be using true or false values all the time they're
super important so like i said there's three basic types of data that we can
work with in python there's strings which is just like plain text numbers
which would be like either decimal numbers or whole numbers like this and
there's true or false values and these are the basic types of data i mean there's
a bunch of other types of data that we can use but i would say 99 of the time
as a new user and a new programmer to python you're just going to be
dealing with these three types of data so those are the basics of the data and
also with variables and you're going to be using variables all the time in
python so you definitely want to practice up and get comfortable using them

in this tutorial i want to talk to you guys about working with strings in python
now one of the most common types of data that we're going to be working
with in python is going to be strings and strings are basically just plain text so
any text that we want to have inside of our program we can store inside of a
string so i want to talk to you guys about all the cool things we can do with
strings and we're basically just going to get a full introduction into why
strings are awesome so over here i'm just going to actually print out a string
so i'm just going to say print and inside of these parentheses i can type out a
string in order to create a string i need to use quotation marks so i can make
an open and close quotation marks just like that now inside of the quotation
mark i can put whatever text i want the string to have so we could say like
draft academy and so now we have a string with the text draft academy inside
of it so if i run my program now down here we're going to print out draft
academy as you can see and when we have these strings there's actually a
bunch of cool things that we can do with them so one thing i could do would
be to create a new line inside of the string so if i wanted i could come over
here and i could say backslash n and you can see it got highlighted in a
different color and what this is going to do is it's actually going to insert a
new line into the string so now it's going to say draft on one line and academy
on another line so i'm going to click play and you'll see down here we just get
draft academy in addition to the backslash n i could also use a backslash
quotation mark so if i wanted to put a quotation mark inside of my string i
can't just put a quotation mark like that because python is going to think that
i'm trying to end this string so if i want to include a quotation mark i can just
use this special backslash character and that's called the escape character and
it basically just tells python that whatever character comes after it we want to
render literally so when i say backslash quotation mark it basically means
like hey python i want to print out a quotation mark and so now we'll be able
to print out a quotation mark right there i can also use this to print out a
backslash so if i need to print out a backslash i could say backslash and it'll
just print out a normal backslash now so you can see just like that so if you
want you can use that backslash to make new lines or print out quotation
marks or you can just use it as a normal backslash in addition to just typing
out a string here i could also create a string variable so i could come down
here up here and we can create a variable and we'll just call it phrase and i'm
going to set it equal to draft academy so i can store this string value inside of
a variable called phrase and then when i want to print out that variable where
i want to access that string variable i can just type the name of the variable
and you'll see that it's going to print out the value that was stored inside of it i
can also use something called concatenation and concatenation is basically
the process of taking a string and appending another string onto it so i could
come over here and i could say phrase and i can say plus and now i can add
in another string so i could say like is cool and now this is going to say draft
academy is cool so i'm basically appending another string onto another one
they call that concatenation and so in addition to doing all that stuff we can
also use special things called functions and a function is basically just a little
block of code that we can run and it will perform a specific operation for us
so we can use functions to modify our strings and we can also use functions
to get information about our strings so i'm going to show you guys a couple
of common functions we can use with these strings and they're actually going
to do awesome stuff so in order to access one of these functions i can just say
phrase and then i can say dot and i'm going to show you guys a function that
we can use to convert this string entirely into lowercase so i could just say
phrase.lower and then i'm going to want to type in open and close parentheses
and this will take this phrase it'll take my string and it'll convert it to
lowercase so you can see now we just have draft academy down here but it's
entirely in lowercase i could also do the same thing for uppercase so i could
say phrase.upper and this will convert the entire string into uppercase you can
see now it's entirely uppercase so in addition to converting the string into
uppercase and lowercase i could also check to see if a string is entirely
uppercase or entirely lowercase so for example i could say phrase.isupper and
this is going to give me back a true or a false value so it's going to be true if
the string is entirely uppercase or false if it's not and you can see here we're
getting a false value because this is an uppercase i can also use these
functions in combination with each other so for example i could say phrase
dot upper and then a parenthesis and then after this i could say dot is upper
and now what it's going to do is it's going to run this upper function it's going
to convert it into uppercase and then it's going to run this is upper function
right after that and you'll see now we're going to get a true value back
because it will have converted the whole thing into uppercase so you can see
now we're getting a true value so you can use these functions one after
another it can be really useful and there's a few other ones that i want to show
you so we can also figure out the length of this string so if i wanted to figure
out how many characters were inside of this string i could just say l e n and
i'm actually going to make an open parenthesis and i'm going to make a close
parentheses so i'm essentially saying len and this is another function it's the
length function and inside of this len function i'm actually passing this phrase
variable i'm basically giving the length function this and it's going to spit out
a number so it'll tell me how many characters are inside of this string and so
you can see here we get 15 because there's 15 characters inside of draft
academy so that's how we can get the length of a string and that's going to be
really useful as we go forward in python we can also get individual characters
inside of a string so imagine if i wanted to just grab one of these characters
like imagine if i wanted to figure out what the first character in this string is i
can actually use an open and closed square bracket just like that and in here i
can specify the index of the character that i want to grab so if i wanted to grab
the first character in this string i can put in a zero so if i say phrase square
bracket zero this is going to give me that capital g and you can see down here
that's what gets printed out now i want to point something out in python when
we're working with strings a string gets indexed starting with zero so you'll
notice that in order to access this g i had to put a zero in here and that's
because in python when we use indexes on a string we start with zero so if
python is counting the characters or it's indexing the characters in a string it's
gonna start with zero so it's gonna say g is zero i is one r is two a is three so
we would say that g is at position zero in the string i is at position one r is at
position two a is at position three etc so we start counting at zero so if i
wanted to access the first k character in the string this g i have to say phrase
zero and that's just a special thing in python and actually most programming
languages do that so they'll start with zero so for example if i wanted to
access this a i'm gonna have to put zero one two three so if i put three inside
of here now we'll be able to access that first a as you can see we get an a right
here so this is actually really useful being able to grab a specific character
inside of a string and you're going to be using that a lot as we go forward in
python there's also another really awesome function that we can use and it's
called the index function and basically what the index function will do is it'll
tell us where a specific character or string is located inside of our string so i
could say phrase dot index and i can actually give this a value so sometimes
when we use these functions in python we can actually give them information
so i can give this a value and we would call this passing a parameter so i
would call a value that i would give to a function a parameter and you'll hear
that word a lot so for example i could say inside of here capital g and now
this is going to return the index of the capital g inside of our string so it
should give us back a zero because g is at the zeroth index and you'll see
down here that we get a zero because that's where g is so for example if i put
an a inside of here like a lowercase a it should give me zero one two three
because that's where the first a is inside of this string so i can click the play
button and you'll see it's giving us a three you can also put actual words in
here so for example i could put like academy in here or i could even just put
like a c a d and this is gonna tell me where this starts inside of my string so
when i click play it's going to give me an 8 because that's where academy
starts right 0 1 2 3 4 5 6 7 8. if i put something in here that wasn't in the string
so for example if i put a z in here that's not in here it's actually going to throw
an error so when i play this you'll see that we get this error down here
because z is not found inside of our program so that index function again can
be really useful and we'll be using that a lot there's also one more that i want
to show you which is called replace so we can say phrase dot replace and in
here i can actually give this two parameters so i can give this replace function
two values that it can use and the first thing i want to use to give it is what i
want to replace so for example i could say draft and then i'm going to put a
comma in here and i want to put in here what i want to replace draft with so i
could just say like elephant and now instead of saying draft academy this is
going to print out elephant academy so you can see down here it just says
elephant academy so this replace function can be really awesome because we
can replace certain words or even certain letters inside of our strings with
other ones so those are just some basic ways that we can work with strings
inside of python and there's a lot of these different functions that we can use
with strings these are some of the most common the ones that i just showed
you right now but if you just do a google search you can find all sorts of
python functions that you can try out and use and you know see what they do
but you definitely want to get comfortable working with strings in python
because you're going to be working with them a lot

in this tutorial i want to talk to you about working with numbers in python
now numbers are one of the most common data types in python and any
python program you write is most likely going to be dealing with numbers at
some point so i want to talk to you guys about just the basics of using
numbers we're going to talk about the different types of numbers that we can
represent in python and i also want to show you guys some awesome
functions that we can use with numbers so we can do certain like
mathematical operations we can do some awesome things with numbers i'm
going to show you guys all of that in this video it's going to be awesome so
first thing we can do is we can actually just like print out a number so if i
want to write a number in python it's really easy i basically just write the
number so i could say like print two and this is just going to print the number
two out onto the screen so i can use a whole number like this i could also use
a decimal number so i could say like 2.0987 and python is going to be just
fine with that we'll be able to print that out onto the screen as well i can also
make numbers negative so i could make this 2.0987 a negative number and
python will be able to handle that just fine too in python we can also use
basic arithmetic so i could do things like addition subtraction multiplication
so i could say like 3 plus four and now this is gonna print this out or why
don't we say like three plus four point five and this will be able to print out
the answer so we get seven point five and we can do addition we could do
subtraction we could do division or we could do like multiplication as well so
you can pretty much do whatever you want inside of python and if you want
to make more complex mathematical equations we can also use things to
specify order of operations so i could use parentheses so for example if i said
3 times 4 plus 5 what python is going to do is it's going to multiply 3 and 4
together so it's going to be 12 and then we'll add 5 to that so we should get
17. but let's say that we wanted to change up the order right i could actually
put a parenthesis around four and five and now it's going to add them first so
it'll add four and five so we'll get nine and we'll multiply that times three so
we should end up with 27. so you can see we can use those parentheses to
specify order of operations so i could make like a very complex little
equation here just by using numbers and parentheses we can also use one
other operation which is called the modulus operator so i could say like 10
and use this percent sign three and this is actually read 10 mod 3 and
basically what this is going to do is it's going to take the first number divide it
by the second number and it's going to spit out the remainder so it's basically
going to say okay 10 divided by 3 that's going to be 3 with a remainder of 1.
so this is going to give us the remainder and you'll see down here we get 1
because that's the remainder of 10 divided by 3. and that modulus operator
can come in handy quite a bit we can also store these numbers inside of
variables so we can store them inside of these variable containers so i could
come over here and i could create a variable called like my underscore num
and we'll just store a value of let's say like five in here and so i could come
down here and i can just print out my underscore num and we'll be able to
print that number out to the screen just fine so in addition to doing things like
a basic arithmetic we can also do some other stuff so one thing i could do is i
could actually convert this number into a string so if i wanted to convert this
number into a string i can just say str and i can put the number that i want to
convert inside of these parentheses and so what's going to happen now is this
number is going to be converted into a string so when i click the run button
you'll see it's just printing out five but now instead of being a number this is
actually a string and this is going to come in handy when you want to print
out numbers alongside strings so i can come over here and i can say like my
favorite number and we'll be able to print this number along with this string
so i can click play and it says five my favorite number if i was to get rid of
this string right here and i wasn't converting the number into a string now
python's going to have a problem with this it's not going to allow us to do that
you can see we get an error so anytime you want to print out a number next to
a string you got to make sure that you use that little string function so there's
a bunch of other stuff that we can do with numbers and a lot of times in
python you're going to want to be using specific like more advanced math
operators so there's a bunch of different math functions that we can use on
our numbers and a function is basically just like a little collection of code that
does something so a function could perform an operation like a mathematical
operation on our number it could also give us information about our number
so i'm going to show you guys some of the most common functions that
you'll be using in python related to numbers the first one is called abs and it
stands for absolute value so we can get the absolute value of a number and so
over here i'm just going to make this variable negative 5 and basically i can
just say abs and i can make an open and close parentheses over here and this
is going to give me the absolute value of this number up here so when i click
the play button you'll see it's just giving us 5 because 5 is the absolute value
of negative 5. i can use a few other functions there's another one which is
called pow and so it's just p-o-w and i'm actually not going to use this
variable we just use a normal number and this function is going to allow us to
pass it two pieces of information so i can give this function two pieces of
information the first is going to be uh like a number and the second is going
to be the power that i want to take that number to so i could say like 3 comma
2 and this is basically just going to be 3 raised to the power of 2. so it's just
gonna be three squared so we should get nine down here you can see that we
do so i could pass in like you know some crazy number like we could pass in
a four and we could raise it to the power of six and so we should get like a
pretty big number here and you can see we get 4096 so this pow function is
really useful for taking numbers to specific powers so in addition to using this
pow function we can also use another function which is called max so i can
say max and what this is going to do is it's basically going to return the larger
of the two numbers that we pass into it so right now i'm giving this a 4 and a
6 and this should tell us which number is higher so over here it's just printing
out six because that's the bigger number i can also use another function called
min and this is gonna do the opposite so now instead of printing out the max
number it's gonna print out the smallest number and it's gonna print out four
down here as you can see another cool function is called the round function
and this is gonna allow us to round a number so it's just gonna follow like
standard rounding rules so if i said like 3.2 inside of here now it's going to
round it down to just normal three but if i said like 3.7 it's going to round it
up to four so that'll allow you to round a number so there's a few other
functions that i want to show you guys but in order to get access to them i'm
actually going to have to do something called importing and in python we can
actually import external code into our files and so if i want to access these
specific math functions i have to import something called python math so i
can just say from up here math import and this star and basically what this is
going to do is it's going to go out and it's going to grab a bunch of different
math functions that we can use so i already showed you guys a few of these
different math functions but there's actually a bunch more and in order to
access them we're going to need to include this line of code inside of our file
so once we have that now i can access a few others so there's another function
which is called the floor method and it's just flor and what this will do is it'll
basically just grab the lowest number so it's essentially just going to chop off
this decimal point and you can see over here now we get a three because
we're using that floor function there's also another one called seal and that's
just gonna do the exact opposite so that's just gonna round the number up no
matter what so no matter what we'll always get four if we have a three point
whatever here and there's another one which is called square root so it's just
sqrt and essentially this is just going to return the square root of a number so i
could say like 36 and now we should get six back so those are all some very
interesting functions and inside of this math module so we would call this a
module and you don't have to worry too much about what that is right now
just know that when we put this line of code into our program it gives us
access to a lot more math functions so it basically allows us to do a lot more
things with math inside of our program and there's a bunch of different math
functions in python and if you want you can basically just go online and
search for different math functions i showed you guys a few here and i would
say the ones that we looked at here are probably the most commonly used but
there's a bunch more and like i said you know there's tons of documentation
on all this stuff so you can just look up you know math functions in python
and there's going to be tons and tons like lists of these things that you can use
inside of your programs to perform different math operations but for now
that's just been a little bit about using numbers a little bit about doing you
know certain math operations and using functions with those numbers

in this tutorial i'm going to show you how to get input from a user so we're
basically going to allow a user to input information into our program and i'm
actually going to take the information that the user inputs i'm going to store it
inside of a variable and then we're going to be able to do something with that
variable so i want to show you guys how we can actually go about getting
input from someone and down here in my python file all i have to do to get
input from someone is i just have to type out input and then an open and
closed parentheses and what this is basically going to do is it's going to tell
python like hey we want to get input from a user and python will allow the
user to type in some information and inside of these parentheses we can
actually type a prompt and so generally when we want the user to enter in
some information we want to tell them what we want them to enter and that's
what we can put inside of here so i'm just going to say enter your name so
we're actually going to create a little python app which is going to allow the
user to enter in their name and then we'll store the name inside of a variable
and then we'll basically just say hi to the user so we'll say like hi and then
whatever the name they entered was so what i want to do is i actually want to
store whatever the user inputted into our program inside of a variable so i can
actually go over here and i can create a variable i could just call it name and i
could set this variable equal to input so what i'm doing now is i'm taking the
value that the user inputs and i'm storing it inside of this variable container
called name and so now i have access to whatever they entered in so what we
can do is we can say print and inside of the parentheses i can just print out
hello and then i'm just going to add on to this name and actually why don't we
put an exclamation point so essentially we're getting a name from the user
we're storing it inside of the name variable and i'm printing it out onto the
screen so i'm going to go ahead and play this and when we run the program
you'll notice down here python is giving us this little prompt so it's saying
enter your name now in here i can actually type in a value so i could type in
mic and then i can just hit enter and python is going to go ahead store this
value inside of that variable and then it's going to print out hello mic and so
this is kind of cool and actually what we could do is we could prompt the
user to enter in more than one piece of information so i could actually copy
this line of code and i'm going to paste it below here and why don't we have
the user enter in another variable so we could have them enter in for example
their age and over here we just want to say enter your age so now we're able
to get two pieces of information from the user and i can say hello name and
then i can say you are and i'll print out their age so i'm just going to print age
so now i'm basically able to get both of these pieces of information from the
user i can get their name and i can get their age so when we run this program
i can type in both of those pieces of information so it'll say enter your name
so we could just make up a name like john and then enter the age let's say
john is 25 and now it's going to say hello john you are 25. so the program is
able to get input from the user and then it's able to use that information in
order to say hi to the user and tell them how old they are so getting input
from the user is a great way to make your programs more interactive and here
we're just scratching the surface right we're just basically getting two you
know piece of information from the user but you can use these inputs to do
awesome things in python and as we go through this course you're going to
see some really cool things that we can do with these inputs

in this tutorial i'm going to show you how to build a very basic calculator in
python we're basically going to build a calculator where we'll get two
numbers from a user and then we'll add those numbers together and print the
answer out onto the screen so this will give us some practice in getting input
from users and we'll also talk about getting numbers from users as opposed to
just strings so i'm really excited to get started on this calculator the first thing
we want to do is create two variables and inside of those variables we want to
store the two numbers that the user wants to add together so down here i'm
just going to say num1 and that's what we'll call our first variable is equal to
and now i need to get input from the user so i'm going to say input and inside
these parentheses i'm going to say enter a number

and now i basically want to do the same exact thing but for the second
number so we'll paste this guy down here and i'm just going to say num2 and
then we'll just say enter another number so now we're able to store the user's
input inside of these two variables so now all i want to do is just print out the
results so i'm actually going to create a variable called result so i'm just going
to say result is equal to and basically we just want to add these two numbers
together so i'm going to say num1 plus num 2. and now all we have to do is
just print out the results so i'm just going to print result so we basically have
our entire program written out here and this will allow us to enter in two
numbers and then we'll add them together and print out the answer so i'm
going to click play and down here we can enter our number so i'm going to
enter the first number we'll say 5 and i'm going to enter my second number so
let's say 8.0 or let's say 8.3 so now it should print out the answer but if you
look over here that's not quite the answer we were looking for right 5 plus 8.3
is definitely not 58.3 and here's what happened when we get input from a user
by default python is just going to convert it into a string so it doesn't matter
what we put down there when we're entering the numbers python's always
just going to be like okay this is a string that's it sounds good right it's just
going to make it a string in order for us to make these num1 and num2
variables numbers we're actually going to have to convert the strings that we
get from the user into numbers and so the way that we can do that is by
basically just coming over here and when we add the two numbers together i
can use a special python function in order to convert those strings into
numbers and there's actually two python functions that we could use for this
the first is called int so i could say i and t i can make an open parenthesis and
i can make a closed parentheses and basically what this is going to do is it's
going to convert whatever is inside of these open and close parentheses into
an integer number and an integer number is basically a whole number so it's
like one two three four five so it's a it's a whole number in other words it can't
have a decimal point um and so what i could do is i could say int and i could
put these inside of parentheses and now what this is going to do is it's going
to convert both of these numbers into integers in other words into whole
numbers that don't have decimals and it's going to add them together and
we'll print out the result so why don't we do that and we'll just see if this
works so i'm gonna click the play button and down here we'll enter our first
number so i'm just gonna enter in a four and then i'll enter in a five and now
you can see it's printing out the correct answer four plus five and so that's
essentially our basic calculator but we do have one problem with this
calculator so i'm going to run it again and i'll show you guys what that
problem is if i wanted to add in a decimal number so we'll add 4.3 and 5.5
you'll see that we're getting this error and that's because i'm using this int
function up here and this int function is looking for a whole number so if i
put decimal numbers inside of there it's going to break the program there's
another function we can use instead of an in we can say float and a float is
basically just a number that has decimals so it's a decimal number so i can
convert both of these guys into floats and now i'll be able to use decimal
numbers so i can click play and i can just enter in some numbers so i could
say like four and i could also say like 5.5 and now it's gonna be able to add
both of those numbers even if one of them's a decimal and that's the beauty of
using that little float function so in certain circumstances you might want the
user to only be able to enter in an integer to a whole number but in a lot of
cases like in this calculator we want them to be able to enter any number that
they want so we're going to use this float function so i'm just going to recap
what we did one more time we created two variables num1 and num2 and we
basically stored the two numbers that the users inputted into those variables
and then we converted them into numbers and we added them together and
we printed out the results so this is a pretty cool calculator i'm happy with it
hopefully you guys learned something and as we go forward in this python
course you're going to learn all sorts of ways that we can make this calculator
more complex

in this tutorial i want to show you guys how to build a mad libs game in
python so a mad libs game is basically just a game where you can enter in a
bunch of random words so like you know verbs nouns names colors and you
basically take all of those words and put them into a story randomly so over
here i my web browser i just have an example of a mad lib so you know
down here we're basically just taking random words like an adjective or a
noun or a plural noun and entering them inside of a story so like you read
through the story and then like some random word pops up and mad libs can
be pretty fun and i'm sure you guys have you know at least heard of mad libs
before but if not that was just a little introduction so i'm going to create a mad
libs in python and this is going to be really cool so down here i have this like
little poem it just says roses are red violets are blue i love you and so you
know this is kind of like a classic poem but i think we should mix it up a little
bit and create a mad lib for this poem and so instead of having this red color
over here i want to have the user enter in their own color instead of having
violets why don't we have them enter in a plural noun and instead of saying i
love you why don't we have them say i love and then some celebrity so
celebrity so this is the basic structure for our little mad lib right i want to
basically have the user enter in a color enter in a plural noun and enter in a
celebrity and then i'll take all of those words and put them inside of our mad
lib and hopefully we end up with something that's pretty funny so how can
we actually go about building this in python well the first thing we're going to
have to do is we're going to have to be able to get these words from the user
right that's pretty obvious so i think what we should do is we should create
three variables called color plural noun and celebrity and we'll store the user's
inputs inside of those variables so up here let's create those variables the first
variable i want to create is going to be called color so say color and i want to
set this equal to the input so i'm going to say input and inside of here i'm just
going to give them a prompt so i'll say enter a color and we can basically just
copy this line of code and i'm going to paste it down below and we'll paste
one more time so now we're going to create our plural noun variable so i'll
say p-l-u-r-a-o plural noun and we'll just say enter a plural noun and actually
over here i want to make a colon as well so then finally we'll create our
celebrity variable and we'll say enter a celebrity and so now basically we're
creating three variables called color plural noun and celebrity and inside of
them we're storing the color that the user enters the plural noun the user
enters and the celebrity the user enters so last thing we have to do is replace
these guys with those variables so i'm basically just going to add in the color
over here and we're going to add in the plural noun so i can just go like this

and finally we'll just add in that celebrity

so now we have a pretty cool madlib and it should be functional everything


should work it looks like it's good to go so let's come over here and we'll run
our program and then down here in the console we can play our little mad
libs game so i say enter a color i'm just going to say magenta enter a plural
noun why don't we say microwave and enter a celebrity let's say tom hanks so
when i click enter what should happen is we should get our mad libs printed
out so i'm going to click enter and now we have our mad lib so it says roses
or magenta microwaves are blue i love tom hanks so it's a pretty good mad lib
and obviously you know the more the more print statements we put over here
you know the better the mad lib could it could be and we could store as many
you know variables up here as we wanted this was just a very simple mad lib
we only took in three inputs but you know you could see how you could take
something like this and create a little mad libs game so your homework for
this lesson is to go off and make your own mad libs game hopefully one that's
a little bit funnier than mine but that's the basics of creating a mad libs game
in python

in this tutorial i want to talk to you guys about working with lists in python a
lot of times when you're programming in python you're going to be dealing
with large amounts of data and when you're dealing with large amounts of
data you want to make sure that you can manage it and organize it properly
and a list is essentially just a structure that we can use inside of python to
store lists of information so we can take a bunch of different data values we
can put them inside a list and it allows us to organize them and keep track of
them a lot easier so generally you would create a python list and you would
put a bunch of related values inside of that list and then you can use it
throughout your program so i'm going to show you guys just the basics of
using lists we're going to look at some of the common use cases and really
just get you up to speed with what lists are and why they're useful so over
here in my program i'm actually going to create a list and we create a list a lot
like we create a python just like a normal python variable so the first thing we
want to do when we're making a list is give it a name so we want to give it a
descriptive name something that's going to basically describe what's inside
the list in my case for this example let's make a list of like friends so we
could say like here's a list of all my friends so i can say friends and i'm going
to set this equal to the list of values that represent my friends and we want to
create a list we can use these open and closed square brackets so whenever
you use these open and close square brackets python basically knows okay
they want to store a bunch of values inside of this list so why don't we go
ahead and start adding some values so we can say like my friends are like
kevin karen and let's say jim so here i have three values inside of my friends
array so when we're creating a normal variable in python generally we just
give it one value right so i would create a variable i would give it one value
maybe a string or a number or a boolean but when we make lists we're able to
store multiple values inside of the same like little item inside of the same
object right and then what i can do is i can access these individual items
inside of my program so inside of this friends list we're basically storing all
of these different values and that can be really useful so now that we've
stored some values let's talk about what you can put inside of a list so you can
really put any piece of information in python we could put things like strings
numbers or booleans so if i wanted instead of just putting strings here i could
change like one of these to a number and i could change one of these to a
boolean and it wouldn't matter python is going to be fine with that but let's
change these back to strings just for the sake of the example so now that
we've created our list how can we access individual elements inside of this
list it's a good question i'm going to go ahead and print something out to the
screen the first thing we can do is we can just print out the actual list so i can
just say print friends and then when i run this program if we look down here
in the console you can see it's just printing out the actual list of friends right
but let's say that i wanted to print out a specific element inside of this list well
i can actually refer to elements by their index so each one of the elements
inside of this list has a particular index and the indexes actually start at zero
so we would say that this first element in the list kevin has an index of zero
we would say that this other element karen has an index of one and this third
element gym would have an index of two so even though jim is technically
the third element inside of the list it has an index of two and that's because we
start indexing at index position one and so that's just kind of how lists work
and that's how list indexes work so if i wanted to access a specific element
inside of my friends list i can just refer to it by its index so over here after we
type out friends i'm just going to type in open and closed square bracket and
inside of this open and close square bracket i want to put the index of the
element inside the list that i want to access so if i wanted to access this guy
right here this element i can just put a zero so i can say friends zero and now
when i run my program it's just gonna print out that value it's just going to
print out kevin if i wanted to access this gym value over here i can put a 2
and that will give us that gym value you can see right there so we can access
elements based off of their index we can also access elements based off of
their index from the back of the list so for example if i said negative one
inside of here this is going to give me access to this value right here for jim
and you can see that's what it does so when we use negatives it starts
indexing from the back of the list so if i said negative two this is going to
give us karen and so you can use the negatives to access items at the back of
the list just keep in mind though and this is kind of um interesting we would
say this first element here is index position zero right but we would say the
first element at the back of the list is index position negative one so just keep
that in mind so there's actually other ways that we can access like just
portions of this list so for example let's say i just wanted to select the last two
elements in this list and i didn't want to select the first one well in here i can
just say one with a colon and this will grab the element at index position 1
and all of the elements after that so now we should just grab jim and karen or
karen and jim in that order i could also specify a range so actually let me add
in a couple other elements just so we can illustrate this better so i'll add in
two more names so if i wanted to i could select like the element at index
position one up to the element at index position three so it's going to grab this
one so that's one two and it's actually not gonna grab the third one so it's it's
gonna grab all the elements up to but not including three so it'll grab karen
and jim so let's go ahead and run this and you can see it grabs karen and jim
so you can either just put like one with a colon after it and it'll grab that index
position and everything after it or you can specify like a range that you want
to grab from so that's how we can access elements inside of this list but we
can also modify elements so for example i could come down here let's say i
want to modify this value right here karen well all i have to do is just access
that element so i could say friends and karen is at index position 1 and i could
change this to whatever i want so i could say friends index position 1 is equal
to mike and now when we print out friends index position 1 that value is
going to be updated so it's just going to say mic instead of saying karen so it
can be really useful to modify values inside of arrays so it can be really useful
to modify values inside of python lists so those are kind of the basics of
working with lists in python and actually in the next tutorial i'm going to
show you guys even more ways that we can use these lists we're going to
learn how to like add elements to a list delete elements from a list copy lists
and a bunch of cool stuff uh with these lists but for now this has just been sort
of like the basics of working with lists

in this tutorial i want to talk to you guys about using functions with lists in
python in python a list is one of the most important structures where we can
store our information a list basically allows you to take a bunch of different
values and organize them and store them inside of their own little list
structure so down here in my program you can see i have two lists i have a
list of lucky numbers and this is just a bunch of different numbers and then i
have a list of friends so this could be like a list of somebody's friends and it's
basically just a bunch of strings with names in them so these two lists are
storing a bunch of different values and what makes lists awesome is not only
could i store like this many values i mean i could store hundreds or thousands
or millions of values and when you're working with a lot of data and a lot of
information in python these lists are invaluable so because lists are so
important there's actually a bunch of different functions that we can use with
lists and those functions allow us to do things like modify the lists and get
information about the list so in this tutorial i just want to show you a bunch of
those functions we're going to talk about some of the most common and the
most popular functions that you would use on lists to make them more
powerful and make them more easy to use so the first thing we can do is
obviously just print out a list so down here i'm printing out this friends list
and when i want and when i run my program you see down here we're just
printing out all the elements in the list so it's always good to be able to print
out all the elements inside of a list but there's a lot of other functions that we
can use so one function is called the extend function and the extend function
will basically allow you to take a list and append another list onto the end of
it so i could say like friends dot extend and inside of these parentheses i can
pass in the list that i want to add on to the friends list so i could say like lucky
numbers and now when i print out this friends list not only is it going to have
all the elements in the friends list it's also gonna have all the elements inside
the lucky numbers list you can see down here we have all of our friends and
then we also have the numbers over here so that's a really easy way to
essentially just like add two lists together we can also just add individual
elements onto a list so i could come down here and i could say friends dot
append and this will actually allow me to append another item onto the end of
this list so over here i could just add another name so we could say creed for
example and now i'm like adding another friend onto the end of this list so
when i run the program in addition to having the original items that were in
the list up here we also have this additional item at the end and that append
function is always going to add the item onto the end of the list but let's say
that you wanted to add an item into the middle of the list so like right here or
right here there's another list function called insert and insert is going to take
two parameters the first parameter is going to be the index where you want to
insert the item so why don't we insert it here at index position one i'm just
going to say one and then i'm going to type in the name of the element that i
want to add so we can just say like kelly and now at index position 1 we're
going to have the value kelly and all of these other values are going to get
pushed up they're going to get pushed to the right one index position so now
when i run the program you can see we have kevin this new element kelly
and then all the other elements have been pushed off to the right we can also
remove elements so for example let's say i wanted to remove this gym value
all i have to do is just say friends dot remove and i can just type in whatever
element i want to remove so i want to remove this gym element so now when
we run the program jim is going to be gone from the list and we just have
these four guys left you can also remove all of the elements from the list so if
i just wanted to completely like reset the list and get rid of everything i could
just say friends.clear and this is going to give us an empty list so it'll get rid
of every single element inside the list there's also another really cool method
which is called pop and you can just type out pop like that and basically what
pop's going gonna do is it's gonna pop an item off of this list so when i click
the play button you'll see here that we're left with kevin karen jim and oscar
so we basically got rid of the last element inside the list and that's what pop
does it pops an element off of the list so it basically removes the last element
in the list so we have our list but let's say that we wanted to figure out if a
certain element was in this list right if a certain value is in here so let's say i
wanted to check to see if my friend kevin was in this list well i could say
friends dot index and in here i can just pass a value so i could say like kevin
and this is gonna tell me the index of kevin so it'll tell me if kevin's in the list
so now when i click play you can see down here it says zero if i was to say
like oscar in here for example now it'll give me the index of oscar so that's it
three but if i put a name that wasn't in here so like if i put mic that's not in the
list and so now we're gonna get back an error because it says mike is not in
the list so that's an easy way to figure out if a specific element is inside of the
list and if it is then you'll know what index it's at you can also count the
number of similar elements in the list so i'm actually going to come down
here copy this gem element and we'll add another gym element into here so i
could come down here and i could say friends dot count and we'll pass in
gym and this will tell me how many times the value gym shows up inside of
this list so it should say two which it does down there because we have two
values with the text gym and so we have all these values we could also sort
this list so i could come over here and i could say friends.sort and what this
will do is it'll sort the list in ascending order so we have a bunch of text here
and you'll see what it does basically what it's going to do is it's going to put it
in alphabetical order so you can see we have j k o and t so the list went from
being just random order like whatever we had up here to now it's in
alphabetical order and that's also going to work for lucky numbers so i could
say like lucky numbers dot sort and then we'll print out lucky numbers and
these should now be in ascending order which i'm realizing they already are
up here but if i was to take this 42 and put it down here now it will figure
everything out and put it in ascending order anyway we can also reverse a list
so if i wanted i could reverse this lucky numbers list i could say lucky
numbers dot reverse and now when we print it out instead of being 42 8 15
16 23 it's going to be 23 16 15 842 so it's basically just reverse the order of
the list and finally there's one more list function i want to show you guys
which is copy so i could actually create another list and i could make it as a
copy so i could say like friends2 and we could set this equal to friends.copy
and now friends two is going to have all the same attributes as friends
because it's basically just like copied it basically took a copy of that friends
list so you can see it's the same exact thing and copying lists can come in
handy in a lot of different situations so those are just some basic list functions
and just to kind of like you know get your feet wet in working with lists
obviously like the more you work with them the more you practice using
these different functions the more comfortable you're going to get but that's
just kind of like a basic overview of what you can do

in this tutorial i want to talk to you guys about tuples in python now a tuple is
a type of data structure which basically means it's a container where we can
store different values now if you're familiar with lists in python a tuple is
actually very similar to a list it's basically a structure where we can store
multiple pieces of information but a tuple has a few key differences from lists
that we're going to talk about in this tutorial first thing i want to do is i want
to show you though how to create a tuple so i can come down here and i can
create a tuple and one of the most common examples of tuples is coordinates
so let's say i had a series of like x y coordinates i could create a variable
called coordinates and i'm just going to set this equal to and open and close
parentheses and whenever we want to create a tuple inside of python we're
going to use these open and closed parentheses and inside of here inside of
these parentheses we're going to put the values that we want to store so i
could for example put a list of numbers so this could be like my coordinates i
could have like 4 and 5. so this would be my tuple with coordinates inside of
it and one of the things about tuples that makes them unique is a tuple is
immutable and you'll hear that word a lot when we're talking about tuples
immutable it basically means that the tuple can't be changed or modified once
we create our tuple up here you cannot modify it you cannot change it you
can't add elements to it you can't erase elements from it you can't change any
of the elements inside the tuple what you see is what you get once you create
the tuple it's it's as it is it can't change so i could come down here and i could
print out some of the attributes inside the tuple and the way i can access them
is just by using an open and closed square bracket and in here i can pass in a
index so tuples are indexed starting at zero so technically we would say that
four is at index position one and or sorry four is at index position zero and
five is at index position one so if i said coordinate zero now it should print
out four and down here we're printing out four so if i wanted to print out that
five we can just put a one inside of those square brackets and now we'll print
out that five so i can access the elements inside of a tuple i can easily access
each each entry but if i was to come over here and try to change one of the
elements so if i said coordinates and coordinates 1 and i tried to set it equal to
something else like 10 python is actually going to give us an error when we
run this program so i'm going to run the program you see we get this error it
says type error tuple object does not support item assignment because it's
immutable because we can't change it so that's basically what tuples are how
we can create them and you know a tuple like i said it's very simple you just
create it and then you have it and now i want to talk to you guys about a
common topic in python which is the difference between tuples and lists so
remember a list is basically doing the same thing a list if we wanted to create
a list we would just use square brackets instead of those parentheses and if i
was using a list i could assign different values to it i could i could basically
mutate any of the elements i could add delete modify change whatever i
wanted with the list but with a tuple we can't do that and that's sort of the
basic difference and really python doesn't say anything more than that it
basically just says like one of them is immutable one of them's not but in
practical use cases generally people will use tuples for data that's never going
to change so you'll you'll store data inside of a tuple when that data doesn't
need to be mutated that's why something like coordinates is such a good
candidate for a tuple because once you have coordinates like we're probably
not going to modify them right we might add other coordinates so for
example if i wanted i could create a list of tuples so i could say like four five
six seven maybe we have some other coordinates like 80 34. so here i have in
a i have a list and inside of it we have these tuples um but remember these
tuples can't be modified the values can't be changed so really it's just a case-
by-case basis i would say by a huge majority you're going to be using lists
most of the time tuples are more of a niche you know they're used in more
special situations but there are plenty of situations where you want to use
tuples so if you're in a situation where you want to store data that can't be
changed or mutated then tuples are the way to go so yeah that's just some
basics about tuples some basics about the difference between lists and tuples
and so a tuple is a great thing to add into your python repertoire

in this tutorial i want to talk to you guys about using functions in python now
a function is basically just a collection of code which performs a specific task
so i can take a bunch of lines of code that are basically doing one thing i can
put them inside of a function and then when i wanted to do that task or do
that one thing that the function was doing i can just call the function and so
functions really help you to organize your code a lot better they allow you to
kind of break up your code into different you know little chunks that are
doing different things and they're really just awesome so functions are like a
very core concept when we're talking about programming in python so i'm
going to show you guys how to create an awesome function today let's say
for the purposes of this tutorial we want to create a function that says hi to the
user so the one task that our function performs is basically just saying hi to
whoever is writing the program so over here if i want to write a function the
first thing i have to use is a keyword in python it's called def so d e f and
basically when python sees this keyword it's going to say okay this person
wants to use a function so after we type out def we need to give this function
a name so just like when we are creating variables we give them descriptive
names we also want to do the same thing with functions so if i'm creating a
function i can just give it a specific name which basically says like what it's
doing so we're going to create a function that says hi so i'm just gonna call
this function say hi just like that and once we type out the name of the
function and so also i could type out say hi with no underscore or i could type
out say hi with an underscore both are considered like good practices in
python a lot of times if you just have a simple like two word function like this
you don't need to put an underscore but we could put an underscore there if
we wanted after we type out the name of the function i'm just going to type in
open and close parentheses and then i'm going to type a colon and basically
what this is doing is it's saying to python like all right all the code that comes
after this line is going to be inside of our function and in order to write code
that's going to end up being inside the function we actually have to indent it
so over here you'll notice that when i clicked enter my text editor
automatically indented the text so it's automatically like using this indent here
and that's kind of like one of the rules in python is like the code that goes
inside of this function needs to be indented so if i was to write some code like
out here this is no longer going to be considered inside the function so you
can see as i type out code and obviously this isn't real code but as i type text
over here that's indented this little like marker over here it's basically saying
like oh yeah that's inside the function but then when i write code over here
that is like not at the same indentation level as this stuff it's no longer
considering it inside the function so that's just a little thing any code inside
this function needs to be indented all right so our function is just going to say
hi to the user so i'm just going to have it print out

some text it's going to say hello user so this is a very simple function
obviously we just have one line of code and inside of a function you could
have you know as many lines of code as you want but for our purposes we
only need one line in order to perform our function so now all we have to do
is call this function so if i want to execute the code inside of this function i
have to do something called calling it so if i was to just run my program as it
is right now i'm just going to run it you'll see that nothing happens over here
right even though this function is printing out hello user when i run the
program it's not doing it and that's because the code inside of a function isn't
going to get executed by default the code inside of a function is only going to
get executed when we specify that we want to execute it and in order to do
that we're going to have to do something called calling the function so in
order to call the function you basically just type out the function's name and
those open and close parentheses so i'm just going to type out say hi and open
and close parentheses and now when we when we run this program again
you'll see that it prints out hello user so we're executing the code inside of the
function and i want to show you guys just one more thing here just talking to
you guys about how these functions actually work so up here i'm going to
print top and then down here i'm going to print bottom so i want to show you
guys the flow of these functions inside the program so when i run this
program you'll see we print out top hello user and then bottom so essentially
what's happening is when python goes through and executes this program it
goes over here to this first line it says okay we want to print out the word top
and then it goes down here and it says okay we want to execute the say hi
function so python actually jumps up and it goes over to this say hi function
and it's going to execute all of the code inside of this function so it's going to
go through execute all this code and then once it's done executing all the code
in the function it's going to jump back down here and it's going to move on to
the next line which is bottom so that's kind of like the flow of functions again
with functions generally when we're naming these functions um you want
them to be named in all lower case and usually when we're naming stuff in
python if there's two or more words we're going to use an underspace or an
underscore in between them so i could write this out as say underscore high
but in a lot of situations though if i have a function like this where the name
is really short it might just be easier to leave it without an underscore but why
don't we just put an underscore in there just to be uh super python official all
right so now we can actually make these functions a little bit more powerful
and what we can do is we can give them information so a lot of times when
we write a function we're going to want to have additional information that
gets passed in and these are called parameters so a parameter is a piece of
information that we give to the function so over here i can actually specify
that this function needs to receive some parameters so i can basically say like
hey if you're going to call this function you need to give us some information
you need to give us some parameters and all i have to do to do that is just
type out the name of the parameter that i want to receive so why don't we
allow the code calling this function to tell it what name to say hi to up here i
can just say name and basically what this means is it means whenever i call
this say hi function we have to give it a name so down here if i was to call
this i have to include a name in here so i can say like mike and what we can
do now is we can actually access this parameter or this variable inside of our
function so i could come over here and instead of saying hello user i could
say hello name and basically what this is going to do is it's just going to say
hello to whatever name got passed in here so i'm actually going to copy this
and we will do this twice so i'll say hello mike hello steve and now when i
run this program you'll see that instead of just saying hello user it's saying
hello to whichever name i passed in to the function so that's why this can be
really useful right we can give the function information and depending on the
information we give it it'll perform its task a little bit differently i can also
include more than one parameter so you can i mean technically you could
have like as many parameters as you want so i can put another one in here we
could say age and now i'm going to have to pass in an age along with these so
i'm just going to pass in age and pass in an age for down here and i'm just
going to pass in strings so we can say hello name

you are age so i'm passing in two pieces of information and now when we run
this program it's going to call the function and it's going to use both of those
pieces of information so say hello mike you are 35 hello steve you are 70. so
essentially we're writing out this one line of code which just prints out like
hello to someone and we're allowing this function to receive two parameters
so the name and the age and depending on the name and the age the
function's gonna print out hello a little bit differently and that's kind of the
beauty of using functions so you could pass anything you want into a
function so for example i could pass in a integer instead of a string for the age
so like i could pass in a number the only difference is over here we're gonna
have to convert this into a string but it's gonna work just the same so you can
pass in um strings numbers booleans arrays you can really pass uh any type
of data into a function and it's gonna work so you can see here we get the
same result so that's the basics of functions and as you go through um with
python you're gonna you know be using functions more and more and
generally it's a good idea to break your code up into different functions so
whenever you have like a grouping of code that's designed to perform a
specific task that's usually a good candidate to be put inside of a function

in this tutorial i want to talk to you guys about using the return statement in
python functions now a python function is basically just a collection of
python code that performs a specific task and when we want to perform that
task in our python programs we can call a python function and a lot of times
when we're calling a python function we just kind of call it and it does its
thing and then we move on with the program but sometimes when we call a
function we're actually going to want to get information back from that
function so when i call the function i want it to basically execute its task i
wanted to execute all the code and then i wanted to like give me some
information back so that could be like a particular value it could be
something like telling me how the task went basically the function can just
communicate back to us like hey here's some information and that's what the
return keyword can allow us to do the return keyword can basically allow
python to return information from a function so i'm going to show you guys
how we can do this i want to create a very simple function and it's just going
to cube a number so when we cube a number we take it to the power of 3. so
if i was going to cube like 2 it'd be like 2 raised to the power of 3. right it's
just pretty basic math so we're going to make a function that will cube a
number and i'll show you guys how we can use that return statement so first
thing we want to do is make a function i'm just going to say def cube we'll
call it the function cube and over here we can specify any parameters that this
function will take so basically any values that we want to give this function
so we're going to give it one function which is just going to be a number so
i'm just going to call it num and then over here i'm going to type out a colon
and then down here we can put any of the code that we want to be included in
this function so basically this function is just gonna cube this number so we
could just type out num times num times num right that's gonna give us num
cubed so that's all well and good and if i come down here i can execute this
function so i can basically just call it i'll say cube and why don't we pass it a
3. so i'm going to go ahead and pass it to 3 and i'm going to save this and now
let's go ahead and run this code so we're on the code and you'll see down here
nothing happened right so nothing got printed out in our program in fact
when we called this cube function it didn't really do anything so let me try to
print this out so maybe if we print this function out it'll give us back the
information that we want so type out print and we'll print out the value of the
function i'm just going to click play we look down here it says none so when i
printed out the value of this function it told me none but really this function is
supposed to be cubing the number and here's how we can use the return
statement in python i can come over here and i can just say return and now
python is going to return whatever value we put over here to the right so
when i call this cube function and i give it a 3 python's going to go off it's
going to execute this function when it sees this return statement it's going to
say okay i want to give a value back to whatever called this function and it's
going to return this value now when i print out cube 3 it should print out the
answer because we get an answer back so when i play this you'll see down
here it says 27 so we got the correct answer so i could do this with anything
why don't we cube like four or something so now i'll run this and you can see
we're constantly getting the correct answer back so that's the basics of using
this return statement it allows us to return a value back to the caller in other
words back to whatever's calling the function so i just want to illustrate this
point a little bit further i'm going to come up here i'm actually going to create
a variable so i'm going to create a variable called result and i'm just going to
set it equal to cube 4. this variable result is going to store the value that gets
returned from the cube function so it's it's not going to store like cube4 it's
going to store the value that gets returned from executing that function so
now if i came down here and printed out result it's actually just going to print
out 64 again because that's the value that it's storing so this return statement
can be really useful for like getting information back from a function we can
use something like a parameter like this 4 as a parameter and we can give
information to a function and then we can use the return statement to get
information back from a function and i do just want to point out one more
thing i'm actually not able to put any code after this return statement so if i
came down here and tried to put like a print statement this actually isn't
gonna work so this is never gonna get printed out so if i just typed out like
code right here when we run this program it's not going to type out code that's
because when i use this return keyword it breaks us out of the function so
python is going to go through it's going to execute the code in the function
whenever it sees this return keyword it's just going to break back out and
we're going to be done so we'll never be able to reach this line of code so
that's the basics of using return statements and you can return any data type
you want we could easily return like a string or a boolean or an array it
doesn't really matter you can return whatever you want and a lot of times in a
lot of situations you're going to want to get a value back from a function

in this tutorial i want to talk to you guys about using if statements in python
now if statements are a special structure in python where we can actually help
our programs to make decisions so by using an if statement i could execute
certain code when certain conditions are true and i can execute other code
when other conditions are true so basically if statements allow our programs
to respond to the input that they're given so depending on the data that we're
using in the program our programs will be able to respond so when certain
data is certain values we can do certain things and when other data is other
values we can do other things so you know your programs are essentially
becoming a lot smarter and actually if statements are things that we as human
beings deal with every day so you know as you go throughout your day
generally you're dealing with if statements all the time so i want to kind of
give you guys a brief introduction into if statements and we'll talk about some
of the common if statements that you'd see in everyday life and then we'll go
ahead and do a really awesome example to kind of like show you guys what
if statements can do for us so over here in my text editor i just have this little
text file and in here i wrote out a bunch of if statements that a lot of people
will encounter on a daily basis so here's the first one it says i wake up if i'm
hungry i eat breakfast so let's break this down a little bit up here it says if i'm
hungry and this is a condition right this is either going to be true or it's going
to be false right if it's true i'm gonna go ahead and eat breakfast right if it's
false i'm just gonna skip whatever was in here and move on right so that's the
basics of an if statement right we have a condition in this case if i'm hungry if
the condition's true then we do the action so we eat breakfast otherwise we
just skip it so down here we have another one it says i leave my house if it's
cloudy i bring an umbrella otherwise i bring sunglasses and so this one is a
little bit more complex than the one we just looked at you'll see we have our
condition right it says if it's cloudy if that condition's true we're gonna bring
the umbrella but in this case if the condition's false there's something else that
we want to do so in the case up here if this condition was false we just moved
on but now if this condition's false then we're going to go ahead and bring
sunglasses so that's another example of an if statement it's a little bit more
complex finally i have one more down here and this one's even more complex
it says i'm at a restaurant if i want meat i order a steak so if this condition is
true we order the steak but if this condition is false then we're going to move
on and we're actually going to check another condition so i'm going to say
otherwise if i want pasta i order spaghetti and meatballs this is another
condition if this condition is true we get the spaghetti if it's not true then
finally we're going to move on down here and we'll just default to ordering
the salad so all three of these if statements are valid if statements it's just they
get more and more complex as we go down the list so hopefully that's you
know can kind of wrap your head around what if statements are we're
basically specifying conditions if those conditions are true we're going to do
certain things and if those conditions are false we can do other things or we
can check other conditions all right so let's head over to our python file and
we'll start writing some actual python so in here in my app.python file i want
to create an if statement and i'm going to show you guys a very basic if
statement in this tutorial and then in the next tutorial we're going to look at
some more advanced if statements and so what i want to do is create a
boolean variable so i'm going to create a boolean variable that's going to store
whether or not the user is a male so it's just going to be called is underscore
male and i'm going to set this equal to true because i'm a male so we have this
boolean variable right and right now we have it set equal to true i can actually
use an if statement to check to see what the value of this variable is and if it's
true i can do something so if i want to use an if statement all i have to do is
just type out if and then i just need to type out a condition so basically i
would have to type out like uh something that's going to be true or false like
for example in the other page we were specifying like if i'm hungry or if it's
cloudy here we're just gonna check to see if is male so in other words if the
person is male and so remember this has to be a like it has to be able to be
reducible to a true or a false value so in our case we're just using a boolean
because that's like the easiest thing we can do so i said if i specified my true
or false condition now i want to just type a colon and what i want to do now
is make a new line and so anything that i put below this with an indentation is
actually going to be executed when that condition's true so i could put print
and down here i could just put you are a male and now you'll see what
happens when i run this program it's going to go down here and it's going to
say you are a male but if i changed is male to false so instead of this being
true i just change it to false now all of a sudden it's not going to print
anything so it's just going to be blank down here that's because this condition
wasn't true so anything that i put below this if declaration and that has an
indentation like that is going to be executed when the if statement is true we
can also use another keyword in python which is called else and else is
basically going to be like otherwise so you remember before we said if it's
cloudy i'll bring an umbrella otherwise i'll bring sunglasses well this is going
to be like our otherwise so i can say down here else and now anything that i
put below else is going to get printed out when that condition isn't true so
why don't we just put you are not a male so now we're able to cover both of
the situations for this variable if it's false we can cover that situation so it says
you are not a male if it's true we can cover that situation as well so it'll say
you are a male so that's pretty cool but we can also make these more complex
and actually before i talk about that you can put as much code as you want
inside of an if statement so i could have like you know dozens of lines of
code if i wanted um i'm just giving you guys a very simple example so why
don't we make this more complex and i'm going to add another variable into
the mix so i'm going to add another you know boolean attribute into this mix
i'm going to make another variable called is tall and we're going to set this
equal to true as well so now i have two variables in the mix let's say i wanted
to write an if statement that will check both of those variables so i could write
an if statement that's like if they're male and they're tall or if they're male and
they're not tall or if they're not male and they're tall like i could write out a
bunch of if statements to check the combination of these variables so the way
i can do that is by using one of two keywords so the first keyword i want to
show you guys is the or keyword so i can come over here and i can say if is
male or is underscore tall and what this is basically going to do is it's going to
say if the person is either male or if they're tall then we want to do something
so this is only going to be true when one of these values is true when one or
both of those values is true so down here we could actually put instead of you
are a male we could put you are a male or tall or both that's going to be more
appropriate and then down here we would say you are

neither male nor tall and that's because if we execute the code inside of this
else that means that both of these guys are false right so i'm saying if they're
male or they're tall we're going to execute whatever is in here otherwise that
means they're neither male nor tall we're just going to execute this down here
so let me show you guys how this works i'll click play and these are both true
so it's going to say you are a male or tall or both if i was to set one of these to
false so let's set is male equal to false now it's still going to say you are a
male or tall or both but if i set them both equal to false now it's going to say
you're neither male nor tall so that's kind of the basics of using the or operator
and there's another operator we can use which is called and and basically it's
similar to or except both of these conditions have to be true so this is
basically saying if the person is male and they're also tall then we're going to
execute whatever's in here so we could actually change this text to say you
are a tall male because we know for a fact that if this is getting executed
they're both male and tall we can also change this print statement down here
this could say you are either not male or not tall or both so you can see it's
basically just saying that you're either not one of them or you're not both of
them so we click the play button and you'll see because they're both false it's
gonna say you are either not male or not tall or both but if i make them both
true now it's gonna say you are a tall male if i was gonna make one of these
false though so let's make is tall false now it's not going to execute this first
print statement it's going to execute the one inside of the else so to say you
are either not male or not taller both so that's the basics of and and or and
you'll you'll be using those a lot as you use your if statements but there's
actually one more uh thing we can do we can add in some more conditions so
up here i'm checking if they're male and they're tall but what if i wanted to
check if they're male and they're not tall so if they're like a short male i can
use another keyword in python called elsif or really it's just typed out e-l-i-f
and it stands for else if and after this we can put another condition so over
here i'm going to check to see if they're male and they're not tall so i'm going
to say else if male is male and now i can type in not tall and the way i can do
that is by saying not and open and close parentheses and saying is tall and
basically when i use this not function it's going to negate whatever is inside
of here so if this was true it's going to make it false and if this was false it's
going to make it true so basically that'll tell us whether or not they're tall and
then i'm going to use a colon and now down here inside of here we're
basically just going to type out any of the code that we want to happen when
this condition's true so down here we can just print out you are a short male
and there's actually one more condition that we want to check for which
would be if they're not male and they're tall so we can make one more else if
and i'm actually just going to copy this guy and we'll paste it down here and
so i want to say if not is male and is tall so now we're checking to see if
they're male and or if they're not male and they're tall so here we could say
you are a you are not a male but are tall so essentially here we have an if
statement that's going to cover every single condition for these two variables
so in every single situation of the two values of these variables we're going to
be able to print something out for it so if i made both of these true it's
basically going to tell us you are a tall male if i make is male false it's going
to tell us you are not a male but are tall if i made ismail true and is tall false
then it's going to tell us you are a short male and if i made both of these false
it's going to tell us you are either not male or not taller both and actually we
need to change this so this should say you are not a male and not tall so that
would be a better printout for that situation so you can basically see how we
can use ifs else if and else in order to help our program to make decisions and
really to respond to the different data in our programs so i'm able to respond
to every combination of the values for these two variables and that's really
cool so in this example we were just using simple boolean variables but in the
next tutorial i'm going to show you guys how you can actually use something
called comparison operators so we could compare like two numbers or two
strings and we could use those as our conditions but for now i think this is a
good introduction into if statements so i'll see you guys in the next tutorial

in this tutorial i want to talk to you some more about if statements in python
more specifically we're going to be looking at using comparisons inside of
our if statements so if you're following along with the course in the last
tutorial i talked to you guys about just the basics of if statements and we used
a couple different boolean variables and depending on the values of those
booleans we were able to do certain things in this tutorial we're going to look
at another way to use if statements which is with comparisons so instead of
just using boolean values we can actually compare different values so like i
could compare a couple numbers or i could compare a couple strings and
depending on the results of those comparisons we can do certain things so
this is going to be pretty cool and this is really going to give you guys a full
understanding of what you can do with if statements so for this tutorial i
actually want to create a python function and this function is going to give us
the maximum number that we pass into it so this function is going to take
three parameters as input and it's going to print out the biggest number that
we give it so let's create this function i'm just going to say def and i'm just
going to call it max num and inside of these parentheses i'm going to specify
that i want three parameters as input so i'm going to say num1 num2 and
num3 so basically we're passing it three numbers and this function will return
the largest of the three so in order to figure out which of these numbers is the
largest we're going to have to use an if statement so i can say if and over here
i need to specify a condition right so i need to put like a true or a false value
and so what we can actually do is we can compare these different numbers so
i could say if num1 is greater than or equal to num2 and num1 is greater than
or equal to num3 so basically what i'm doing here is i'm comparing these
different numbers so i'm saying if the first number is greater than or equal to
the second number and this is a comparison so when you think about it when
we compare these two numbers we're going to end up with a true or a false
value right num1 is either greater than or equal to num2 or it's not it's actually
a boolean value right it's either true or it's false same thing over here the
result of this comparison is either true or it's false so technically i'm putting a
true or false value in there i'm just getting that true or false value by using a
comparison and you'll notice over here we're using something called a
comparison operator and basically this is just like how we want to compare
them so we're saying like greater than or equal to in this case so down here if
this whole condition is true in other words if the results of these two
comparisons end up being true then we know that num1 is the biggest so i
can just return num1 i can say return num1 but we also want to check some
other conditions so i can say alif and now i want to do some other
comparisons so i'm going to say else if num2 is greater than or equal to num1
and num2 is greater than or equal to num 3. so i'm doing essentially what i
did up here except for num2 so again i'm comparing these different numbers
and this is going to end up being a true or a false value depending on the
result of the comparison so down here again we can just return num2 because
if all this is true that means we're going to end up returning num2 and then
finally we can just say else so if num1 isn't the biggest and num2 isn't the
biggest then we can pretty much assume that num3 is the biggest so now we
have our function so down here i'm actually just going to call this function so
i'm just going to say actually i'll print out the result so i'll say max num and
we'll pass in like three four five so we're basically calling that new function
that we just made and i'm gonna go ahead and run this program so you can
see down here in the output we printed out five because that was the biggest
if i was to change this middle one to the biggest so we make the middle one
40 now it'll be able to take on that situation and finally i can make this like
300 and it'll be able to handle that so no matter which number num1 num2 or
num3 ends up being the biggest it's able to tell us without a problem so these
comparisons are a really really really common way to make if statements and
a lot of times you're going to want to be comparing different values inside of
python so over here we're comparing numbers but we could also compare
strings so i could easily make these both like you know i could make this like
a dog and i can make this dog and i could say a different operator so i could
say like this double equal sign would mean equal so i could basically say like
if this string is equal to that string so you can basically like compare all
different data types you know i could compare numbers strings you could
also compare booleans so once again these are comparison operators and this
one is greater than or equal to but there's a bunch of other comparison
operators we can use so the most basic is just going to be a double equal sign
and that basically checks to see if the two values are equal so it'll say like if
number one is equal to number two we can also say not equals and this
exclamation point will basically mean not equal so it's if num1 is not equal to
num2 we also have greater than less than greater than or equal to less than or
equal to and those are kind of all of the operators or all the you know the
basic comparison operators that you're going to be using in python so using
comparisons is really awesome and there's going to be tons and tons of
situations inside of python where you're going to want to compare different
values so these can be extremely useful

in this tutorial i'm going to talk to you guys about building a calculator in
python now if you've been following along with this course you'll know that
in the beginning of the course we actually created a very basic calculator
basically the user could just enter in two numbers and our calculator would
add the numbers together and spit out the answer in this tutorial i want to
show you guys how to build a more advanced calculator so this calculator is
going to be able to perform all of the basic arithmetic operations so we can
add subtract multiply and divide and we'll actually allow the user to specify
which one of those they want to do so the user will enter in a number they'll
enter in whatever operator they want to use so plus minus divide multiply and
then they'll enter in the second number and we'll perform the operation for
them so this can be pretty cool and it's going to show you how we can use if
statements in like a practical application so let's get started the first thing we
want to do is get input from the user so i'm going to create three variables one
for the first number one for the second number and one for the operator and
we'll basically store the values that the user inputs into those variables so the
first one will just be num1 and i'm going to set this equal to input and we're
going to give this a prompt so i'll say enter first number and here's actually
the thing is whatever the user enters we're going to want to convert it into a
number so generally in python when we get input from the user no matter
what they put in it just gets converted into a string but we don't want a string
because we're going to have to be adding or subtracting or multiplying these
numbers together so whenever they enter in the number i just want to
immediately convert it to an actual like number data type instead of a string
so what i can do is i can actually say float and i can surround this entire input
tag with parentheses and now what this is going to do is it's going to
immediately convert whatever the user inputs into a float now that's going to
mean that they're going to have to insert a number otherwise we'll get an error
but for the most part this should work out for us so i'm actually just going to
copy this guy and we'll go ahead and paste it over here and we'll paste it one
more time so we're basically just trying to get three pieces of input from the
user so the second thing we want to get is the operator so i'm just going to say
op for operator and i'll actually get rid of this float because we want to keep
this as a string and i'll just say enter operator so that's going to be like plus
minus multiplication whatever and then finally down here we'll get num2 and
again we're going to want to convert this to a float so i'll say enter second
number so now basically what we're doing is we're getting the first number
we're getting the operator and we're getting the second number from the user
so what we need to do now is we need to figure out what is inside of this op
in other words we need to figure out what operator the user was trying to do
so are they trying to do addition are they trying to do subtraction like we want
to figure that out so we can use an if statement in order to figure that out so
i'm going to come down here and i'm basically just going to create an if
statement so i'm going to say if and we want to check a condition so i'm
basically going to check to see if this operator is equal to a plus sign so i can
say if op equals plus sign and now if the operator is equal to plus sign i'm just
going to print out num1 plus num2 but let's say that instead of a plus sign
they entered in something else so we can say l if op is equal to and now we'll
check if it's a minus sign and so here we'll just print num1 minus num2 and
actually forgot to put a colon here so we can just do these for everything so
now we can say l if op is equal to division and here we'll just divide the two
numbers so i can print out num1 divided by num2 and finally we'll do the
same thing for multiplication so i'll say l if op is equal to asterisks and we'll
just print out num1 times num2 alright so basically over here we have every
you know condition but i also want to put in an else statement so in the case
that the user enters in an operation that's not like one of the four that we
specified up here i just want to throw an error so i'm just going to say op or
actually we just say else and here we'll just print out like invalid operator all
right so this if statement should give us everything we want basically i'm just
checking to see if it's equal to a plus sign a minus sign a division sign or a
multiplication sign depending on which one it's equal to we'll do a different
operation so let's go ahead and run this and see how we do so i'm going to run
this program and it says enter first number let's enter five enter an operator so
why don't we just do addition and enter a second number let's do 23. so now
it prints out the answer 28 so our calculator actually works let's try another
operator just to make sure so we'll do six and why don't we multiply it by i
don't know 5.23 so now we go off and we do the multiplication and looks like
we got our answer so our calculator seems to be working and so basically all
we did was we got the input from the user and then we used if statements to
figure out what they wanted to do right so we could check to see if they
wanted addition we could check to see if they wanted subtraction or division
or multiplication and we could also check to see if they entered in an invalid
operator so actually why don't we try that too so i'll enter in like five and now
we'll just enter in like an open and close parenthesis and a four so you can see
here it's able to tell like the program's smart enough to know that that's not a
valid operator so these if statements can be really powerful and we can use
them in combination with getting the user input to create a little calculator

in this tutorial i want to talk to you guys about using dictionaries in python
now a dictionary is a special structure in python which allows us to store
information in what are called key value pairs so essentially i can just create a
bunch of these different key value pairs and then when i want to access a
specific piece of information inside of the dictionary i can just refer to it by
its key so the word dictionary is actually pretty appropriate here if you guys
are familiar with a normal dictionary you know in a normal dictionary you'd
have a word and then you'd have a definition associated to that word so in
this situation the word would be the key in other words the word is what like
uniquely identifies it inside of the dictionary and then the value would be the
actual definition so this is going to make more sense once we start working
with this but i just wanted to give you guys a quick introduction so in this
tutorial i want to create a little program that will allow us to convert a three
digit month name into the full month name so i could convert for example
like j a n to january or i could convert m a r into march like i want to be able
to have a program that can do that for us and that's actually a pretty good use
case for a dictionary so we're actually going to create a dictionary and i'm
going to show you guys how we can do that so the first thing we need to do
in creating a dictionary is just give it a name so i want to give this a specific
name so i'm just going to call this month conversions and now i just want to
set this equal to an open and closed curly bracket so whenever we create a
dictionary in python we're always going to want to create it inside of these
open and closed curly brackets so inside of the dictionary now we can just
start defining what are called key value pairs so i can define a key and then i
can give it a corresponding value and the way that we can do that is just by
typing out the key and then typing out the value so in our case we're
converting three digit month names into the full month names so i would
want to type out for example j a n and then i can type a colon and i want to
type out the value i want to associate with it so we could say january i could
basically do this for every combination so i could say like feb and this would
be february and actually after each one of these we're going to need to put a
comma so i could do the same for march we'd say mar

so essentially what i can do is i can specify an entry inside of this dictionary


for each one of these so this over here would be the key and this over here
would be the value and here's one thing is all of these keys have to be unique
so if i was to come down here and change this to j a n this is actually going to
give us a little warning so you can see down here it says dictionary contains
duplicate keys that's a no no when we're creating dictionaries so you always
want to make sure that the keys are unique all right so i'm going to go ahead
and create one of these for each one of the months and then we'll come back
and we'll talk about it all right so i've gone ahead and created an entry for all
12 of the months so now we have a bunch of unique keys and each one of
those keys is associated with a different value so this is the basics of creating
a dictionary we have a bunch of these different key value pairs and now what
we can actually do is we can access them from inside of this dictionary so if i
wanted to access a specific key or a specific value all i have to do is come
over here and i'm actually just going to print it out onto the screen so we can
see it all i have to do is refer to the dictionary by name so it's just called
month conversions and there's actually a bunch of different ways that i can
access these month names so i could access different entries inside of this
dictionary the first way is just by making a open enclosed square bracket and
inside here i can just type in one of the keys so for example inside here i
could type in nov and what this should do is it should give us back the full
name for november so when i print this out you'll see that we get back down
here november so i could do the same thing for you know any of these we
could say like m a r and now we should get march back so i'm able to refer to
the key and it's going to go into the dictionary and it's going to give me the
value that's associated to that key there's actually another way we could do
this too so i could say month conversions dot get and inside of here i could
also pass in the name of a key so i could pass in like dec and now we'll be
printing out december and what's cool about using this get function is i can
actually specify a default value that i want to use if this key is not found so
there's going to be certain cases when we're dealing with dictionaries where
you're going to put in a key that might not necessarily map to a value inside
of the dictionary so you put in an invalid key so let's just try to do that so i'll
just put like luv that's not a month abbreviation so when i try to run this you'll
see we get this none down here and in a lot of cases you're going to want to
create some sort of a default value so if i'm in this situation where i have a
key that's not mappable to any values inside of this dictionary i can actually
pass it a default value so inside this dot get function i can make a comma and
now i can pass in like a default value to get printed out so i can say like not a
valid key and now when i put in the invalid key instead of saying none it's
going to go ahead and say not a valid key so this is going to give us like a
default value that we can fall back on so these dictionaries are really
awesome and the keys over here don't have to be string so you could also use
numbers so for example i could say like 0 1 10 like i can put any numbers i
want over here as keys as long as they're unique and then i can access those
keys just like i normally would down here with this get function or with those
open and close square brackets so that's sort of the basics of using
dictionaries it can be really useful to store key value pairs and honestly you're
going to be using them a lot in python to store different types of data

in this tutorial i want to talk to you guys about while loops in python now a
while loop is basically a structure in python which allows us to loop through
and execute a block of code multiple times so i could specify like a few
different lines of code and then i could put that code inside of a while loop
and it would basically loop through that code executing it repeatedly until a
certain condition was false so while loops can be awesome and there's a lot of
situations in python where we're going to want to loop through specific lines
of code so in this tutorial i just want to show you guys the like bare basics of
how while loops work and then in future tutorials we're going to use while
loops to create little games and stuff like that so let's talk about while loops
when i create my while loop the first thing i want to do actually is create an
integer i'm basically creating a variable that's a number and you don't have to
do this for a while loop but just for our demonstration i'm going to so i'm just
going to call this i and i'm going to set it equal to 1. now what i want to do is i
want to create a while loop so i'm basically just going to say while and over
here i want to specify a condition and this is what's called our loop condition
or you can also refer to it as a loop guard and basically we are going to keep
looping through the code inside of the while loop as long as this condition is
true so whatever condition i put in here as long as it's true we're going to keep
looping through the code inside the while loop so i'm just going to say while i
is less than or equal to 10. and now i'm going to put a colon and i'm going to
make a new line and so anything that's below this while loop declaration and
that's indented like this is going to be considered code that's inside the while
loop and so that code is going to get repeatedly executed while this condition
up here is true so i'm just going to put a very simple line of code here we're
just going to print out the value of i and then down here i'm going to actually
increment i so i'm going to add 1 to i so i'm going to say i is equal to i plus 1.
so basically i'm taking this i value and i'm adding 1 to it there's actually a
shorthand that we can use in python to do something like this though i could
just say i plus equals one and that's automatically going to add one to i so this
is like a little shorthand and you'll see people in python using that a lot so
over here we basically have our while loop so i have the outline for a while
loop so we're defining this variable up here and we're going to keep looping
through the code inside the while loop as long as this condition up here is true
so if this condition is false for example if i is equal to 11 then we're not going
to loop through this code anymore and we're just going to move on so down
here i'm actually just going to print done with loop so this will kind of
illustrate this for us all right so let's go ahead and run this program i'm just
going to run it and you'll see down here we get some output so we're actually
going to get numbers printed out 1 all the way down through 10 and then
we're printing out done with loop so basically what's happening is we're
printing out every time we go through this loop so initially i is equal to 1
right the first thing that python's gonna do when it gets to this while loop is
it's gonna check this condition so before it does anything else it's gonna check
this condition and it's gonna say okay is one less than or equal to ten and
that's true so as long as this guy is true we're going to go through and loop
through all the code inside of here so we're going to print out i which has the
value of 1 and then we're going to add 1 to i so now i is going to go from 1 to
2. now what we're going to do is we're going to go all the way back up here
to this while loop declaration and we're going to check the condition again so
remember i checked the condition the first time and then i loop through all
the code then i go back up to the top and i check it again so i'm going to say
okay is i less than or equal to 10 at this point i is equal to 2 so i is less than or
equal to 10. so now we're going to go through and we'll execute all this code
again so i'm going to print out i so it's going to be 2 and i'm going to add 1 to
i so now we have 3. then python is going to go all the way back up to the top
and it's going to check the condition again so on every iteration through the
loop before python does what's inside of this loop it's going to check that
condition and as long as the condition remains true we're going to keep
executing the code inside the loop eventually though in this program i is
going to end up being 11 right so on the last iteration it's going to end up
being 11. we're going to come back up here and we're going to say hmm is 11
less than or equal to 10 nope and so since it's nope we're going to come down
here and we'll print out this done with loop lines so that's the basics of how
these while loops work we're specifying a loop condition as long as that
condition's true we'll keep executing the code inside of the loop and after
every execution of the loop we're going to come back up and check the
condition again so that's how we end up with this printing out down here so
that's the basics of a while loop and we can use these while loops to do all
sorts of things like while loops are very very powerful

in this tutorial i'm going to show you guys how to build a basic guessing
game in python and in this guessing game we're actually going to be using all
sorts of cool programming structures that we've learned up to this point in the
course so we're going to be using things like if statements and while loops
and variables and all these cool things in order to build this game so the basic
idea is we will specify like a secret word so we'll have a secret word that we
store inside of our program and then the user can interact with the program
and try to guess the secret word and so what we want to be able to happen is
we want the user to be able to keep guessing what the secret word is and keep
typing in different responses until they get the secret word right so that's the
basics of what this game is going to be and now let's go ahead and create it so
the first thing we want to do is create a variable to store our secret word so i
could say secret word and we're just going to set this equal to a secret word
so why don't we make it draft that's a pretty good secret word and now what
we want to do is we want to create a variable that will store the user's
response so i want a variable that will store like all the guesses that the user
makes so i'm just going to call this guess and i'm just going to set it equal to
an empty string right now so now we have the secret word and we have a
variable to store the user's guess and what we need to do is we need to be able
to prompt the user to input the secret word but here's the catch what we want
to happen is we want them to enter the secret word and if they don't guess it
correctly we want to prompt them to enter it again so we can't just use a
single input statement we actually have to use something called a while loop
and we can use a while loop in order to continually ask the person to guess
the word until they guess it correctly so let's go ahead and create our while
loop so i'm going to say while and after i say while i need to specify a looping
condition or a looping guard basically this is something that as long as it's
true we're going to keep looping through this loop so basically i want to say i
want to keep looping as long as the user's guess is not equal to the secret
word so as long as they haven't guessed the secret word i'm going to keep
going through this loop and inside of this loop what we're going to do is we're
going to ask them to input the secret word so i can take this guess variable
and i can set it equal to input and i'm just going to say enter guess and so over
here we're basically telling the user to enter in their guess i'm storing
whatever they enter inside of this guess variable and then what's going to
happen is we're going to come back up here we're going to check to see if the
guess is equal to the secret word if the guess isn't equal to the secret word
then we're gonna do it again but if the guess is equal to the secret word then
we're just gonna break out of this loop and so we can come down here and we
can just print out a success message so i could say you win because they got
the secret word this is a very very simple program but this is essentially all of
the code that we need to be able to build a game like this so let's go ahead and
play our game we can run it and see how we did so i'm gonna click play and
down here you can see it's prompting us to enter a guess so i'm just gonna
type in some you know random text we can type in whatever we want and as
long as we're not entering that secret word it's going to keep prompting us to
enter different information but if i enter in the secret word so if i enter in draft
now all of a sudden the program's going to terminate and it's going to say hey
you win because we were able to guess the secret word so that's like a really
cool way for us to be able to do this and we actually have a fully functional
guessing game but i think this guessing game could actually be improved
quite a bit a lot of times when we're making a guessing game we want to set a
limit so in other words i want to set a limit for the number of times that the
user can try to guess the word so let's say that the user has three tries right
they have three guesses in order to guess the word and if they can't guess the
word after three tries then they're gonna lose the game but if they can guess
the word inside of three tries then they'll win the game right i think that
would be a little bit more of a fun game so why don't we try to program that
game basically we're going to set a limit on the number of guesses that the
user can have in order to do this we're going to have to create a couple more
variables down here in other words we're going to have to store a couple
more pieces of information the first piece of information i want to keep track
of is how many times the user has guessed right so we can just make a
variable called guess count and we'll just set this equal to zero because
initially the user won't have guest down in this while loop every time we go
through the loop i want to increment that guess count right so every time
we've gone through this while loop i want to increment that count because
that means the user will have guessed so down here i'm going to say guess
count plus equals 1. and this is just going to add one to the guest count
actually whoops all right so after each iteration of this loop we're gonna go
ahead and add one to the guest count all right so that's the first variable that
we're gonna need we're also gonna wanna store another variable and this is
going to be called guess limit and basically this is going to tell us how many
times the user can guess the word so i'm going to it's going to be guess limit
and we'll basically just say 3. so let's say that the user has three tries to guess
the word three strikes and you're out so the user if they can't get it in three
tries then we're gonna basically say that they lose the game and i'm also
gonna need one more variable here which we're going to call out of guesses
and i'm just going to set this equal to false initially so this out of guesses
variable is going to be a boolean and it's going to tell us whether or not the
user is out of guesses so if out of guesses is true that means they have no
more guesses right they basically lost the game and if out of guesses is false
that means that they still have some guesses left so they can keep playing all
right so let's use these different variables in order to make our program more
functional so the first thing i want to do is when i go through this loop i want
to check to make sure that the user has more guesses right in other words
before i let the user enter a guess i want to check to see that they haven't
already used up all their guesses so down here i can make an if statement i
can say if and inside of the condition i want to check to see that guess count
is less than guess limit if guest count is less than guest limit that means that
they haven't guessed the total number of guesses that they have so they have
some guesses left and if that's the case and if that's true then i'm going to go
ahead and give them a guess and then we'll increment the guess count if this
isn't true in other words if they have reached their guess limit then i'm going
to want to set out of guesses equal to true because they're out of guesses right
they have no more guesses because the guess count wasn't less than the guest
limit and so that means that they're out of guesses so they have no more
guesses so there's actually one more thing we need to do inside of this while
loop we need to add another condition onto this loop guard so right now
we're going to keep looping as long as the guess is not equal to the secret
word but remember if the user's out of guesses in other words if they've
reached their guess limit we don't want them to guess anymore right so if
they ran out of guesses then we want to basically break out of this loop and
not give them any more guesses so i'm going to go ahead and add another
condition onto here and i'm going to say while they haven't guessed the secret
word and they're not out of guesses so it's going to be not out of guesses then
we're going to keep looping so as long as they haven't guessed the word and
as long as they still have some guesses left we're going to keep looping but
otherwise we're going to break out of the loop and so down here we're
printing out you win but actually when we break out of this loop there's going
to be two possible scenarios so again there's two possible ways that this loop
could end right either the guess is equal to the secret word so either the user
guessed the word correctly or the user ran out of guesses and so there's two
situations down here that we need to account for and so i'm going to use an if
statement to figure out which is which so i'm going to say if and we're just
going to type out of guesses and if the user is out of guesses then i want to
print out of you lose so we're basically gonna be like you lost the game
otherwise though if they're not out of guesses that means that they guess the
word correctly so we're just gonna print out you win all right so now we have
all the logic for this little guessing game setup and let's see if we can run it
and play through it so i'm just going to run this program and now it's going to
tell us to enter a guess so why don't we enter more guesses than we have so
we're gonna try to lose the game so i'm just gonna enter one guess two
guesses and now i'm on my final guess so if i don't get it here we should
actually lose the game and you can see it says out of guesses you lose so we
weren't able to guess it in the number of tries that we had let's run the
program again and we'll try to win the game so we'll get a couple wrong let's
say we're on our last guess and i'm like okay i can do this so i type in the
word and bam we won the game so that's how we can basically create a game
where we have a guess limit so this is a lot of code let me walk you guys
through this one more time so you can just get a full understanding of what
we're doing up here i created a few different variables we created this secret
word variable and we created this guess variable then we also created some
more variables so we created this guess count variable and this just keeps
track of how many times the user has guessed the word and you can see down
here every time we give them a guess we're incrementing the guess count we
also have guess limit and guest limit is telling the program how many times
the user can guess so before i go through this while loop the first thing i'm
doing is i'm checking to see that the guess count is less than the guess limit in
other words do they still have some guesses left if they do then we're going to
get the input from the user otherwise we have this other variable up here
called out of guesses and out of guesses is going to tell us whether or not they
have some guesses left so if this is equal to false that means they have some
guesses if it's equal to true however it means no more dice no more guesses
they are done so they lost the game the last thing we needed to do was
specify an additional condition up here so we are going to keep looping
through the code inside of this loop as long as the conditions up here are true
so as long as they haven't guessed the word and as long as they're not out of
guesses we are going to keep looping through and so when eventually the
user does break out of this loop there's going to be two possible situations the
first situation is that they ran out of guesses and so we want to check to see if
that's the situation i want to check to see if they're out of guesses if they are
we'll print out a lose message if they're not then they must have guessed it
correctly so they win and so that is how we can use while loops and if
statements and also variables in combination with each other to build a pretty
awesome guessing game

in this tutorial i want to talk to you guys about using for loops in python now
a for loop is a special type of loop in python which allows us to loop over
different collections of items so a lot of times we'll use for loops in python to
like loop through different arrays or we could loop over like the letters inside
of a string or we could just loop through like a series of numbers so for loops
provide a very specific purpose and the easiest way to kind of wrap your head
around why for loops are useful it's just for me to show you guys a bunch of
different examples so that's exactly what i'm going to do we're going to look
at why for loops are awesome so down here in my text file in my python file
i'm going to write out a couple different for loops so the way that we create a
for loop is just by saying for and now what i want to do is specify a variable
and this variable is going to essentially represent a different value every time
we go through this for loop and you guys will see how that works in a second
but just know that this variable is going to be used on every iteration of our
for loop and each time it will most likely have a different value so in our case
i'm just going to call this letter and i'm going to say for letter in and now what
i want to do is i want to specify a collection that i want to loop over one
example of this would be like a string so i could put a string in here i could
just put like draft academy and now i can just put a colon and so basically
what this is going to say is it's going to say for every letter inside of draft
academy i want to do something and so down here inside of this for loop and
again we need to indent this we can put what we want to do with each letter
so let me just show you guys like basically what this is gonna do so i can
print out a letter so i can print out this letter variable and it's actually gonna
print out a different letter inside of this draft academy string on every single
iteration of this loop so i'm going to run this program and down here inside of
my console you'll see that i'm basically printing out draft academy so on the
first iteration of the loop i printed out the first letter in draft academy which
was g on the second iteration of the loop i printed out i third was r fourth was
a so i'm essentially just looping through all of the letters inside of draft
academy so i'm saying for each letter in draft academy i want to print out that
letter so this is kind of like how for loops can be used we can define a
variable and that variable will change on each iteration of the loop right so on
the first iteration of the loop this letter variable represented a g on the second
iteration of the loop the letter variable stored at the value i etc right so we
went through this entire string we were able to print out each letter so in
addition to using this with strings we can also use this with other collections
for example like an array so if i created an array up here let's just call it
friends i'm going to set this equal to a bunch of different values so we can put
like a list of our friends in here we can say like jim karen and kevin instead of
saying letter why don't we call this friend and i could say for friend in friends
and now we'll print out the friend so over here i'm saying for each friend
inside of this friends array i want to print out the friend so now we'll actually
be able to print out each element inside of that array so down here you'll see
we're printing out jim and then on the second iteration we're printing out
karen and on the third we're putting out kevin so i'm able to loop through all
the values inside of the array and just so you guys know like you can name
this variable whatever you want so i could name i could give this like any
random name and if i want to access it though i have to access it using that
same name so we can loop through uh something like an array we could also
just loop through a series of numbers so i could say index over here and again
this can be anything i'm just going to call it index so we could say for index
in range and then in here i can pass in a number so i could pass in like 10 for
example and down here i'm just going to print out the index when i run this
program you guys will see that it's basically going to print out every number
in the range from 0 to 10 not including 10. so starting with 0 it's going to
print out 0 1 2 3 4 5 6 7 8 9 but notice that it didn't print out 10. so it's
essentially just printing out all the numbers between 0 and 10 not including
10. you can also specify a a range of numbers so i could say for example like
3 and 10 and now this will print out all the numbers between 3 and 10 not
including 10. so we'll run this program and you can see we print out 3 4 5 6 7
8 9 and not 10. so whatever value that you put um here in this second position
is not gonna get included in the range and ranges can be uh really useful so
for example i could use a range to loop through an array just like we did
before so if i wanted i could say something like for index in range and now
inside of this range i can pass in the length of the array so just so you guys
know if i wanted to get the length of this array in other words if i wanted to
figure out how many elements were inside of it i could just type out l e n and
then inside parentheses the name of the array and so this is gonna spit out
three because there's three elements inside of here right kind of makes sense
so what i can do is i can say down here inside of this range function i can just
type in len and then friends so what this is going to do is it's going to
essentially give me a range between zero and the number of friends inside of
this list so down here i could actually type out friends index and this will
allow me to access each individual friend inside of this list just like we did
before but now i'm doing it with a range so you can see i'm typing out jim
karen and kevin so actually for each iteration through this loop it's basically
going to be printing out friends zero friends one and then friends two because
in here we're passing in a three and remember whenever i pass in there it's
gonna range from zero all the way up to that number but not including that
number so that's another way that we could print out all the elements in the
array and looping through something like an array is actually a very very
common use case for for loops but like i said we can use for loops to loop
through essentially any collection that we have so we could loop through like
a string we could also loop through um you know something like an array so
this can be really useful and that's one of the basics of for loops in python and
i also want to show you guys one more example just while we're here so why
don't we go ahead and print out a range up to five right so this will just be a
simple program you can use all sorts of logic inside of these for loops so let's
say that i wanted to do something special on the first iteration of the loop so i
could say if index is equal to zero and if the index is zero then we know it's
the first iteration of the loop so i could do something special i could like print
out first iteration and then otherwise we could just print like

not first so this would be an example of like maybe you want to do something
on the first iteration of the loop and do something else on subsequent
iterations so if i play this you'll see only on the first iteration is it printing this
out and otherwise it's printing out other stuff so you know don't be afraid to
put some complex logic inside of these for loops because it can really make
your programs more powerful

in this tutorial i'm going to show you guys how to build an exponent function
now an exponent function is basically going to allow us to take a certain
number and raise it to a specific power so in python there's actually a really
easy way to do this i can come down here and i can print we can say like 2
and we can just do two multiplication signs and i could say three and this is
basically just going to be two raised to the third power so you can see here i
can just print this out and we get eight because that's two cubed so it's really
easy to do exponents in python but i want to show you guys how we can use
something like a for loop in order to create a function like this of our own so
we'll actually create an exponent function that will basically do this and we'll
use for loops to do it so let's create a function so i'm just going to say def and
now we need to give this function a name so why don't we call it raise to
power and inside of here i'm going to accept two parameters the first
parameter is going to be the base number and then the second parameter is
going to be the power number so we're going to take the base number and
raise it to the power number so over here we can just make a colon now
inside of this function we need to start writing some code here's the thing
inside the function we don't necessarily know the value of this pow num right
for example if we knew that we were just trying to like square this number or
cube this number i could just return like base num times base num right that
would square the number or i could cube the number base num so right so
this would be like the number cubed the problem is though we don't know
like right off the bat what this value is going to be right this could change like
the user can decide that so in order to write this function we're actually going
to need to use a for loop and i'm going to show you guys how we can use a
for loop to basically figure this out so the first thing i want to do is create a
variable and i'm just going to call it result and we're just going to set result
equal to 1. so we're going to start this off at 1. now i want to create a for loop
so i'm basically just going to say 4 and over here i basically want to specify
like a index so i'm going to say index in and now i want to specify a range
and a range will basically range us through a collection of numbers so
basically i want to multiply the base num by itself as many times as the
pound num specifies right so over here i can just make this a range of pow
num right and so we'll basically loop through this for loop as many times as
poundnum so if poundnum is two we'll loop through it twice if number is
four we'll loop through it four times and every time through the loop we'll
multiply base num by itself or actually you'll see we're going to multiply it by
this result and so down here inside of this for loop i can basically say result is
equal to result times base num this should actually give us everything we
need to take this number to the specific power so the actual like result you
know of doing the math is going to get stored inside of this result variable so
the first time through the loop we're just multiplying base number one right
and so now result is going to become the same value as base num the second
time through the loop so this would be if we were squaring the number we're
basically multiplying result by base num again so it's essentially just base
num times base num the third time through the loop we're multiplying result
times base num so we're essentially just like cubing the number so that's
essentially what this for loop is doing for us so the last thing i want to do is
right here below this for loop i'm just going to return the result so we'll be
able to return whatever the result of raising the number to the power was all
right so let's come down after this function and we're just gonna call it so i'm
just gonna say actually we'll print out the answer so i'm gonna say raise to
power and inside of these parentheses remember we can pass two numbers so
let's raise three to the second power so we're just going to square three and
we'll see how this works so let's run the program and you can see down here
in the console we're getting nine let's try something a little bit uh crazier let's
try three to the fourth power and we'll run this and we get 81 so that's three to
the fourth power let's try two to the third power and we're getting eight yeah
so that makes sense so our raise the power function is working just as
expected and i'll just walk you guys through it one more time so inside of this
function we're taking in two pieces of input we're taking in a base number
and we're taking in a pow number so that's like the base number is going to
be taken to the power number i'm defining a variable here called result and
result is where we're going to store the actual result of doing the math now
we specify this for loop and i'm basically saying that i want to loop through
this range of numbers when i put pow-num here it's basically going to range
from zero all the way up to but not including the power number so we'll
basically loop through power number of times if that makes sense and then
every time through the loop we're just multiplying result by base num and
then we're just returning results so that's the basics of building a power
function and obviously like if you're just trying to take a number to a power
in python it's really easy but this kind of shows you like the internal workings
right for a function like that to work we would have to actually type
something out just like this

in this tutorial i want to talk to you guys about two different concepts in
python it's going to be a pretty cool lesson first thing i want to show you guys
though are two dimensional lists so down here in our python file i just want
to create a basic list so i'm just going to call this number grid and i'm just
going to set this equal to a normal list right just like this now normally if we
were creating a list i could just put in a bunch of attributes and a bunch of
elements right and now all these elements are inside of this number grid list
everybody's happy but another thing i can do is i can make all of the elements
inside of this number grid list lists so the first item in the number grid list is
going to be a list the second item in the number grid list is going to be a list
etc so i'm going to show you guys how to do that i can basically just come
down here and where i would normally put the first element in the list i can
just create another array so i'm just going to make an open and closed square
bracket and now i'm just going to say one two three and i can create the next
item in my list i can say four five six and let's make another item in this list i
can say seven eight nine and finally we're gonna put one more list inside of
the number grid list and it's just gonna have zero in it so inside of this number
grid list right this high level overall list we have four elements and all of
those elements are themselves lists so essentially what we're doing is we're
creating a grid right this grid has one two three four rows and one two three
columns right four rows three columns and that's kind of like why these can
be useful is we can create a grid like structure inside of python using two-
dimensional lists so this is a pretty cool list structure and i want to show you
guys how i can access individual elements inside of this list structure so for
example let's say i wanted to print out one of these values let's say i wanted to
print out this one right here the way i can access it is by saying number grid
and the first thing i want to do is make an open and close square brackets and
in here i want to put the index of the row that i want to access so this would
be like row zero because that's the zeroth element in the array this would be
row one it's at index position one this would be row two row three etc so i
could put row 0 and now right next to this i'm going to make another square
bracket and i want to put the index of the column so this would be like
column 1 column 2 column 3. so i'm going to put another zero because this is
at the zeroth index of this first array so i just put zero zero here now we can
print this guy out to the screen and you'll see down here that we get that one
so i could also do this for like for this eight for example so this is going to be
zero one two it's gonna be row two and column one and now we should be
able to print out that eight so that's basically how we can access elements
inside of this 2d list the next thing i want to show you guys is a nested for
loop a nested for loop is a situation like i said where we have a for loop inside
of a for loop and i'll show you how we can use this nested for loop in order to
print out all the elements inside of this array so i'll basically show you guys
how to parse through a two-dimensional list or a two-dimensional array
alright so basically we're just going to create a normal for loop so i'm going
to say 4 and i'm just going to say row in number grid and i'm using the word
row here because i'm kind of seeing these guys as rows right these are sort of
horizontal rows in our little grid so for each of those rows for each of the
elements inside of number grid i want to loop through so i could actually just
print out each row right now and it's just going to print out all the rows inside
of this list you can see down here we basically just get exactly what we have
up there but i want to be able to access each of these individual attributes
inside of each of these array elements so we can actually create another for
loop and i'm going to put that for loop inside of here so now i'm going to say
for column in row and basically what this is going to give us is each
individual column or each individual element inside of these arrays so for
example inside of the arrays that are the elements of the number grid uh
hopefully that makes sense so down here now i can just print out column and
this should actually print out every single value inside of this two-
dimensional array so let's go ahead and run this program and down here
you'll see that we're basically printing out one all the way down to zero so
we're printing out all of the elements inside of all of the arrays inside of the
number grid so that's how we can use two-dimensional lists and nested for
loops together and both of those things are actually pretty handy in python

in this tutorial i'm going to show you how to build a basic translator in python
so essentially we can take in a string so we can take in like a phrase or a word
and we'll be able to translate it into a different language so over here i have
this little file and it basically specifies this language that i made up so i'm
calling it the draft language and in the draft language all vowels become g so
if i was going to translate an english word into a draft word for example the
word dog i would look through the word dog in any instances where there
was a vowel so in our case let's just say a e i o or u i would convert that
vowel into a g so dog would map to d g g cat would get mapped into c gt so
those are the basic translation rules obviously this is a pretty simple language
but you get the point any vowel is going to become a g and then we'll get the
draft language so we're going to build a draft translator over here in our
python file let's start making this translator the first thing i'm going to do is
just define a translate function so i'm going to make a function here and i'm
just going to call it translate and inside of these parentheses we want this to
take one piece of information which is going to be the phrase that we want to
translate so i'm just going to say phrase and now inside of this function we
need to figure out like okay how can we translate english into our draft
language well remember the rules is basically just any vowels become g's so
the first thing i want to do is create a variable and this variable is going to be
the translation so this will be like the final result that we're going to return to
the user so i can say translation for now i'm just going to set it equal to the
empty string so this is just going to be like a completely empty string it's not
going to be doing anything and now what we want to do is we basically want
to loop through every letter inside of this phrase and if it's a vowel we want to
change it to g and if it's not a vowel we want to leave it alone and we're
essentially going to be looping through phrase and we're going to be adding
the letters onto this translation one by one so let me show you guys how we
can do this i'm gonna make a for loop so i'm gonna say four and i'm just
gonna say letter in phrase and so now when i loop through here i can access
each individual letter inside of the phrase that they passed in so what i want
to do is i want to check to see if the letter is a vowel or not right if it's a vowel
then we can add a g onto translation if it's not a vowel then we can just add
on whatever letter it was onto translation anyway so i'm going to use this if
statement i'm going to say if and there's actually this special thing we can do
in python we can check to see if something is in something else so i can say if
letter in and over here i'm just going to type out all the vowels so we'll say a e
i o u and a e i o u so i'm basically checking to see if the letter is inside of this
string and if the letter is inside of here then we know that it's a vowel so down
here we can handle that case so i can say translation is equal to translation
plus g because if this letter is a vowel we just want to convert it into a g
otherwise though i can basically just say translation is equal to translation
plus letter so in the case where we have a vowel i'm adding a g onto
translation in the case where we don't have a vowel i'm just adding on
whatever letter it was onto translation so finally down below this for loop we
just want to return the translation so i'm just going to say return translation
and now we have a awesome translate function and it should probably work
so let's come down here and we'll test it out so why don't we allow a user to
input some information so i'm basically going to call this function actually
we're going to print it out so we'll print this out and i'm going to call this
function translate and inside of here i'm actually just going to pass whatever
the user inputs so i can just say input and inside of these parentheses i can say
the prompt so enter a phrase and so now i'm basically combining all these
statements together i'm saying i want to print out the translation of whatever
the user enters in so let's go ahead and run this program and we'll see how we
do so i'm going to run the program it says enter a phrase actually let me
format this a little bit better okay

all right so it says enter a phrase so let's go ahead and do that so let's just type
in the example we used before i'm going to say dog and so now out pops the
answer which is d g g so that's kind of cool and we can just keep running this
as many times as we want so i could type in like to be or not to be so this is
like a little bit longer of a string and you can see it translates it into our draft
language so that's basically how we can create our little translator app and
that's pretty cool and so you can see we're using a for loop in combination
with an if loop and that's a really powerful structure and actually there's one
place over here where we can make this a little bit more efficient so instead
of saying if letter in this string you'll notice here i'm checking to see if it's in
all the lowercase and the uppercase i could actually just say if letter.lower in
and now i only have to type out the lowercase letters and it's still going to do
the same exact thing so that's a little like hack or whatever that we could use
and there's also one more problem with this program so you'll notice down
here we're setting the translation equal to the translation plus g but the
problem is if i was to start my word inside of the phrase with a capital vowel
so in other words if i said like on you'll notice that when this gets printed out
it gets printed out as lowercase gn so it's not keeping our uppercase syntax
and that's kind of a problem so we could actually use another if statement in
here and we could check to see if letter dot is upper and if the letter is
uppercase then we can just set the translation equal to the translation plus a
capital g

otherwise we can just set it equal to the lowercase g so now we're able to
control both of those situations so let's just test this and see if it works enter a
phrase say on and now we're keeping that capital letter so those are just a
couple different ways that we could make this program a little bit better but
the basic concept is we have a for loop and then we have some if loops inside
of it and we're calling this awesome function that can translate a word for us

in this tutorial i want to talk to you guys about comments in python this is
going to be a pretty short tutorial i just want to give you guys an overview of
what comments are and how we can use them in our python programs so over
here in my python program i just have this line here it says print comments
are fun so if i run my program down here inside of the console it's going to
print out comments are fun right so any code that i put over here is going to
get executed by python but there's actually a special line of code that we can
write and it's called a comment and a comment is basically a line inside of
our python file that's just not going to get rendered by python so when python
sees it it's just going to ignore it it's not going to execute it it's not going to
print anything out it's just going to kind of ignore it and comments are
basically just used for us humans so a comment is used for like me or another
developer to write a little comment a little like plain text you know comment
inside of a file so in order to create a comment i could use this hashtag
symbol so i can click hashtag and now i am writing a comment so i can write
whatever i wanted in here i could say like this program is cool and you'll
notice when i run the program that doesn't show up anywhere right it doesn't
matter what i put after this hashtag this is just like ignored by python it's just
for me or another developer to come in here and use so a lot of times if you
want to write like a little note inside of your python files or maybe you can
write yourself a little reminder or if you want to write a line to like explain a
line of code so for example i could write a comment that would explain this
print statement so i could say like this prints out a string right now anybody
looking at my file would be able to read this and they'd be like oh that's what
this does okay cool so comments are useful for leaving little comments in a
python file if you want to make comments on multiple lines you can just
create a new line and use another hashtag and so then i could type out
whatever my next comment was and generally if you're going to put
comments on multiple lines you want to just use multiple hashtags but there's
actually another way that you can write out comments so you can use a triple
quotation mark so i'm typing out the single quote and i'm typing it out three
times so you can see here up here we have this three times we have this three
times so in here i can you know write any comment that i wanted so i could
put you know as much text up here as i would want and same thing when i
run this program it's just not going to get rendered so this is another way to
make multiple line comments but the like official python like style guides or
whatever just recommends that if you're going to put comments on multiple
lines you use these hashtags so you know you can really do whatever you
want but if you want to be like super python official then use these hashtags
comments can also be useful for doing something called commenting out a
line of code a lot of times when you're writing a program you might have a
line of code in there that is maybe like potentially messing stuff up and so
what you can do is you can actually comment out that line of code so i could
put a comment in front of this line of code and now when i run my program
the program is going to run but it's not going to use this line so sometimes if
you're trying to see if like a line of code is causing you trouble or if you want
to see what your program would be like without a line of code or even like a
block of code you can just comment it out and that way you're not actually
deleting the code from your file you're just commenting it out so python's
gonna ignore it and those are really the two uses for comments it's to write
little notes write little comments about different things or to comment out
code and as you go forward in python i'm sure you'll find uses for comments

in this tutorial i want to talk to you guys about catching errors in python now
a lot of times when we're writing python programs um you'll encounter
different errors so different situations could come up and your program might
throw an error or it might throw an exception and a lot of times when these
situations happen they'll completely stop your program from running and
what we can actually do is we can watch out for you know certain specific
errors that are gonna pop up in our program and we can actually handle them
so instead of our program just breaking and stop executing we can actually
handle those errors and do things when they occur so i want to show you
guys an example of using this down here i'm saying number is equal to int
input enter a number basically what's happening is i'm prompting the user to
enter in a number using this input command and then i'm converting
whatever they entered into an integer so as long as they enter in like a valid
integer i can convert it into an integer so i can convert it into like a whole
number and i can store it inside of this number variable then i'm just printing
it out so let's try to execute this program i'm going to run the program and
you'll see down here it says enter a number so we can enter in like four for
example and when i answer in four everything's gonna work and it's just
gonna print out four and everything is right in the world and actually i'm
gonna modify this up here so it's a little easier to see but let's say we run the
program again so it says okay enter your number let's say that i break the
rules and i don't enter a number so i just ignore what the prompt says and i
put you know some random text in here now when i enter this the program is
going to throw an error you can see down here it says value error invalid
literal for int base with base 10. basically hey you didn't enter in an integer
like you said you would right we told them to enter in a number they entered
in text so it broke the program and this is a situation that happens a lot so
there's a lot of different situations where something can just go wrong in our
program and up until now we've just kind of accepted it as a reality but if
you're writing a real live python program you don't want something like this
to trip up your program you don't want the entire program to break when
somebody just forgets to enter in a number right you want to be able to
handle all these different situations and in order to handle them we can use
something called a try accept block and a try accept block will basically
allow your program to try out um a piece of code and if everything goes well
then we're great like we could try out entering in the number and if the user
enters in the correct number great but if they don't enter in the correct number
then we can basically like account for that so they entered in something like a
string when they're supposed to enter in a number we could tell them like hey
you entered in the wrong thing so i'm going to show you guys how we can
use these try accept blocks i'm going to come up here and i'm just going to
say try i'm going to make a colon and now i want to indent both of these
things so both of these things are going to be inside of this try block now i'm
going to make a new line i'm going to come down here and i'm just going to
type out accept and i'm also going to put a colon here and down here i'm just
going to print something out so i'll just say like invalid input so now since i
put this code inside of this try block if the user enters in something wrong it's
going to be able to catch it so it'll be able to catch what the user does wrong
and print out invalid input onto the screen so let's go ahead and run our
program and it's just going to say enter a number so we're going to ignore that
we'll enter this in and now instead of yelling at us and breaking the program it
just says hey invalid input so it was able to handle the error they got called it
was able to handle the invalid input error basically just told us hey no more
input so this is a really powerful thing that we can do in our python programs
basically just to protect our programs right if i want to have my program
running for long periods of time i can't have something as simple as an
invalid input trip it up so i can catch that invalid input using these try except
blocks but here's the thing you'll notice that this little guy down here is
getting highlighted and let's just see what it has to say so it's basically saying
too broad exception clause and this is a message that we're getting because
when i just say accept this will catch any error under the sun so anything that
can go wrong in my program for the most part this is going to accept it so let
me give you guys an example let's say i had in my program i was creating a
variable right so i wanted to create a variable called value and i set it equal to
10 divided by zero now if you know anything about math you'll know that
you can't divide a number by zero it's not possible so the program isn't gonna
be able to handle this and you'll see that this is gonna throw an error for us so
when i run the program it basically says zero division error division by zero
we're not allowed to do that right if i took this and i put this down inside of
this try block and i just pasted it in here it's gonna get caught by this
exception that we wrote down here so it's gonna get caught by that except so
when i run the program you'll see it says invalid input but the problem is that
we didn't input something that was invalid right we just divided by zero but it
wasn't able to handle that right so it could not divide by zero it threw an error
so even though we didn't get an invalid input even though it was because we
divided by zero it still printed this out and this brings me up to another point
is we can actually catch or we can accept specific types of errors so for
example in this case we got a division by zero error in this case we got an
invalid input error right we put something in that was wrong it couldn't
convert the value so i can create two different accept blocks to catch two
different types of errors so down here i can just make a space and i can
specify the type of error that i want to catch so when we divided by zero it
was zero division error so if i just put zero division error in here now it's
going to catch that zero division error so i can say divided by zero i could
also make another accept so i could say accept and we can catch the other
exception that we got so i think it was a value error right it was we put in the
wrong type of value inside of that input so now we can print out invalid input
so with these two except blocks we're basically able to handle both of these
situations so for example if this ends up breaking the program this division by
zero then it'll be able to catch that so down here it'll tell us hey you divided
by zero but if i was to get rid of this line of code and i just entered in the
number wrong so i came down here and i entered in a string instead of a
number now it's going to tell us invalid input so we're going to be able to
specify what happens when certain things break so when we get a valid when
we get a value error we can say invalid input when we get a zero division
error we can say divided by zero so depending on what breaks depending on
what happens we can actually do different things and i want to show you
guys one more thing we can do which is we can actually store this error as a
variable so i can say accept i can say as and i can type in a name here so a lot
of times people will just say like e-r-r and down here i can print out the actual
error so i could just print e r r and so if we end up dividing by zero so if i say
answer is equal to 10 divided by zero we're gonna throw this error and it's
gonna print out what went wrong so now i can run this program and it just
says division by zero so it just printed out the error that we got so that's
another useful thing you can do is you can actually like print out the specific
error that got thrown now a best practice in python is to use these specific
errors so you always want to accept and accept for a specific error what you
don't want to do is just say accept and then just accept anything under the sun
it's just too broad and it's not a good practice in python so you always want to
be catching specific errors like this

in this tutorial i want to talk to you guys about reading from external files in
python now a lot of times in python you're going to want to read from files
that are outside of your python file so you might want to read information
from like a text file or a csv file or like an html file and you can actually use
something called the python read command and it will allow you to read a
file that is stored outside of your python file so you can use these files to get
information or you can parse through different files and do different things so
i'm going to show you guys the basics of reading files opening files closing
files doing all that stuff over here i have this file called employees.txt and it
basically just lists out a bunch of different employees like these could be
employees in an office or whatever so it's just listing out all of this
information so let's say that inside of my app.python file i wanted to read the
employees inside of that file the first thing i have to do is actually open that
file from inside python so i can use a special command called open so i can
say open and then in here i can type in the name of the file that i want to open
so this is either going to be a relative path to the file an absolute path to the
file or just the file's name if both files are in the same directory so in my case
app.python and employees.txt are in the same folder like they're in the same
directory so i can just type out the name of the file i can just say
employees.txt and now i want to put one more thing inside of this open
function and it's going to be the mode that i want to open the file in so you
can actually open files in a couple different modes and the first mode is called
read so i can just put an r here and that's going to stand for read and this
basically means that i only want to read the information inside the file i don't
want to modify it i don't want to change it i just want to read it i just want to
see what's in the file and do some stuff with that information another mode is
called write so i can type in this w and writing basically means that you can
change the file right you can write new information you can change existing
information there's another one called a and a stands for append and this
basically means that you can append information onto the end of the file so
you can't modify any of the information in the file you can't change any of
the information but you can add new information and there's one more which
is r plus and this basically means read and write so this will give you all the
power of reading and writing so in our case we're just going to be working
with regular r so we're going to be reading from the file now this open
function will essentially just open the file so it's going to like go over to that
file inside of our file system open it up and it'll allow us to read through it but
generally we're going to want to store this opened file inside of a variable so i
can create a variable and we can just call it employee file and i'm just going
to set it equal to this open function so now the open employees.txt file and all
the content inside of it is stored inside of this employee file variable now
whenever you open a file you always want to make sure that you close the
file as well so just like we have this open command we also have an close
function so i can come down here and say employee file dot close and this is
essentially just going to close the file so we're no longer going to be able to
access it and generally it's a good idea whenever you're opening up a file you
want to also make sure that you're closing the file at some point so generally
once you're done reading it you can just close it so that's kind of like how we
can open and close a file now let's talk about how we can get information
from the file right there's no point in having the file there if we can't figure
out what's in it so there's actually a few different functions that we can use on
this employee file to figure out what's inside of it and i'm going to show you
guys some of those so i'm just going to make a print statement and inside this
print statement we'll basically just print out some information about the
employee file so the most basic thing we can print out is just the entire
contents of the file but before i do that i want to show you guys how you can
check to make sure that a file is readable so before we do anything else
generally it's a good idea to make sure that it's possible to read this file and
there's a function inside of python we can use called readable so i'm just
going to type out employee file dot readable and this is going to return a
boolean value and it's going to tell us whether or not we can read from this
file so i'm going to run my program and you'll see down here we get a value
of true and that's because we set the file with a read mode so it's in read mode
we can read from it if i was to put a w here so if i put like right now readable
is going to be false because we can no longer read the file we can only write
to the file so i'm going to change this back to r so we can just read it so once
you figure out whether or not the file can be read from let's actually read it so
there's another function called employee file dot read and this is basically just
gonna spit out all the information in the files so when i run the program it's
just gonna spit out all of this information right all the information that was in
that file i can also come down here and we could read an individual line
inside this file so i can say employee file dot read line and what this is going
to do is it's going to read an individual line inside of this file so now when i
run this program you'll see it's just reading that first line in the file and this
readline function is actually just reading the first line and then it's basically
like moving a little cursor onto the next line so if i was to copy this line of
code and then print it again down here i'm saying employee file.readline so
it's going to read the first line and then when i say it again it's going to read
the line after that so this is actually going to end up printing out the first two
lines in the file so when i run this program you'll see we print out gym
salesman and dwight salesman so if i was to do this multiple times like i
could technically print out every line inside of this file and you can see we
can do that and so that can be pretty useful for reading multiple lines in a file
but there's actually another function that is better at doing that and we can say
instead of employee file.readline we can say dot read lines and what this is
going to do is it's going to take all of the lines inside of our file and put them
inside of an array and so now when i print this out you'll see we have this
array down here it says gym salesman that's the first item in the array dwight
salesman's the second item in the array it's basically taking each line and
putting it inside of an array so if i wanted to access a specific line i can just
refer to it by its index in the array so if i said one now this is going to give us
that dwight salesman line because that is at index position one inside of the
array you can also use this read lines function with a for loop so i could come
up here and create a for loop i'm just going to say four and we'll say
employee in employee file and then for each employee we just want to print
them out so and actually sorry we have to put employee file dot read lines up
here and so now this will loop through all of the employees in this employee
file.readlines array so we can actually just print out the individual employee
and now this will print out all the employees inside of that file so it's basically
printing out each line in the file and that can be pretty useful so you can use
all of these different functions like read read line read lines readable you
know there's a bunch of these different things that we can do to get
information from a file and so there's a lot of cases where you're going to
want to be able to parse through information in a file and this is a awesome
way to do it so just to recap whenever you want to open a file and read from
it you can just use this open function type in the name of the file and then the
mode which in our case is going to be r then you can do all sorts of stuff with
it and you always want to make sure that you close it when you're done that's
just good practice so that's the basics of reading from files and hopefully you
guys can use this in some way shape or form in the future

in this tutorial i want to talk to you about writing and appending to files in
python so one of the cool things about python is it allows you to work with
external files so i could have like an external text file and i could actually like
completely read all the information in it i could parse through it use that
information to do certain things but in addition to reading a file i could also
write a file and that's what i want to talk to you guys about today is writing
new files and appending onto existing files over here i basically just have
some code written out and this essentially just reads information from this
employees.txt file so you can see over here i'm specifying the mode which is
r and that stands for read and then down here i'm just reading all the contents
of the file and spitting it out on the screen so i'm going to click the play
button over here and you'll see that if this executes so it's printing out all of
the lines of code in our text file so over here i'm in this employees.txt file and
it just has all this information like employees in an office but let's say that i
wanted to add another employee onto here right let's say that a new employee
joined our company so we wanted to add them on to this list well i can come
over here to my app.python file and instead of reading from the file i want to
append to the file so i want to say a and appending to the file basically
basically means that you're adding some text at the end of the file so
wherever the file ends you're just going to add some text onto there so what
we can do is we can actually add another employee into the file so instead of
printing something out i'm actually just going to say employee file dot write
and when i say employee file dot right i'm going to be able to write
something to the end of the file so i can basically just write whatever i want
so why don't we add in another employee into our employees.txt file so we
can add in another employee why don't we say like toby and he's going to be
in human resources so now when i run this program it's going to add tobii
human resources onto the end of the file so i'm going to run my program and
you'll see that nothing shows up down here in the console but if i go over to
my employees.txt file all of a sudden we have a new entry over here it's toby
from human resources right so i was able to append a line onto the end of this
file but here's the thing you need to be careful when you're writing to files
because you can actually mess up a file very easily for example i already
added toby here into my file but if i was to run this program again you'll see
that over here in this employees.txt file it went ahead and added tobii again
right so it added this employee here again and also you'll notice that in this
case this employee didn't go on to the next line i accidentally ran my file
again and all of a sudden it messed up this file over here and so appending
you really need to be careful because if you actually run your file again or if
you you know append something on something wrong to the file it's
permanent like it's getting saved inside of the file so i want to talk to you
guys a little bit more about you know appending another thing we could do
let's say we wanted to add another employee and you'll notice over here in
this employees.txt file when i appended it on again it got appended to the end
of the existing line right so the first time i had a new line there but if you
don't have a new line at the end of your file and you all and you want to add a
new line you're going to have to add some special characters so let's add
another employee and we'll call her kelly and let's just say kelly is in

customer service so kelly is going to be in customer service and if i want to


add this employee onto the end of the file in a new line i'm going to have to
put a new line character in front of it so i can say backslash n and this will
append this entry into the file with a new line so on a new line so now when i
run this you'll see we get kelly from customer service on her own line so you
want to make sure that you're aware of like these special characters that you
can use they call them escape characters and you know anytime you're adding
onto a file you want to make sure that you're adding on exactly where you
want to add on so in addition to appending to a file i could also just like
overwrite a file or i could write an entirely new file so since we already have
this open instead of appending to the file why don't we just write a file so i'm
going to use this w and now if i say employee file dot right because i'm using
w and i'm not using a it's actually going to override the entire file and it's only
going to put this inside the file so when i run this and we go over to this
employees.txt file you'll see we only have one line inside of this file now it's
just kelly customer service that's because i was using w not a when you use w
it's just overwriting everything that's in that existing file you can also use w to
create a new file so over here i could say employee file is equal to employees
one dot text and now what's gonna happen is when i run this it's gonna create
another file for me so i'm gonna run this and you'll see over here in my file
browser we have this new file employees1.txt so if i open this up it has
exactly the same stuff as in this employees file but it basically created a new
file for us and so a lot of times you're going to want to create a new file and
you can use different extensions too so if i wanted to create like a web page i
could say

index.html and i could also add in some html code in here so if you don't
understand html don't worry about it but if you do i could put like a paragraph
in here another paragraph like this is html basically html is like a web page
and the point i'm trying to make is that you could write out a web page inside
of python by doing something like this so now when i play this we get this
index.html file and it has some html inside of it so that's one way that writing
to files can be really useful you can overwrite an existing file you can write a
new file and create it or you can append on to the end of a file and there's
tons of applications for writing to files and python's a great language for
working with reading writing and doing all that stuff with files

in this tutorial i want to talk to you guys about using modules in python now
a module is essentially just a python file that we can import into our current
python file so for example if i wrote a python file that had a bunch of like
useful functions or useful variables or you know other things like that i could
take that file i could import it into the file i'm currently working on and i
could actually access all of those functions all of those variables all the stuff
from that external file inside the file that i'm currently working on so i'm
going to show you guys how we can use modules and we'll talk about like
you know where you can find awesome modules and and really why modules
make python an awesome language so over here in my text editor i actually
created this file and it's called useful tools dot python and basically this file
just has a bunch of sort of like useful tools that i might want to use in one of
my programs so you'll see over here i have some variables this one is telling
me how many feet are in a mile this one's telling me how many meters are in
a kilometer and then we have this list here which lists out all of the members
of the beatles i also have a couple different functions down here so i have this
get file extension function and this uh basically just will you know you give it
a file name it'll tell you what the extension is and then we have this other
function down here which simulates rolling a dice so you pass it a number if i
pass it like a six it would roll a six sided dice if i pass it a nine it roll a nine-
sided dice et cetera so this is like a python file that i wrote and it has some
useful stuff in it and honestly there's a lot of stuff in here that i might want to
use in the other python files that i work with so let's say i'm over here at this
app app.python file and i'm thinking to myself huh i think i could use one of
those functions that was inside of that useful tools file actually yeah i need to
simulate rolling a dice in my program well instead of having to go over here
copy this function and then paste it over here into my program i can actually
just import this useful tools file and i'll be able to import all of these functions
and all of these variables and attributes so the way i can do that is just by
coming up here and i'm just going to go right at the top of my file and i'm just
going to say import and then i want to type in the name of the file that i want
to import so i'm just going to say useful underscore tools and python is going
to be smart enough to know that it should go off and grab all the stuff from
this useful tools dot pi file so once i've used that import statement i can
actually use all of the functions inside of that useful tools file so for example i
could simulate rolling a dice i could say useful tools dot and now i'm actually
able to access all of the attributes from inside that file so when i say useful
tools dot you'll see down here in my little suggestions menu it's telling me
like beetles feet and miles get file extension meters and kilometers roll dice
so it's giving me access to all of the stuff that was in that file so over here i
could just say like roll dice and we could pass this like a 10 we'll roll a 10-
sided dice and now this should actually be able to run that function so we'll
simulate rolling a 10-sided dice you can see we got four and this is a really
core concept in python which is importing functionality from external python
files and this is like huge in python and this is seriously going to change the
way that you create your python files so you'll notice like i didn't have to
copy any functions or any variables or anything over into this file and yet i
was able to use all the stuff that was inside this useful tools file so that is
huge and honestly it's going to save you a lot of time because you can write
something once and then you can import it into your other files so that's
really the basics of using modules i mean modules are very simple a module
is just any external python file that you want to use some stuff inside of it i
want to show you guys a place where you can go to find a huge list of
modules so i'm going to go over here to my web browser and i'm on this
website it's actually like the official python docs and basically all i did to get
here was just type in list of python modules in google and depending on the
version of python you're using you're going to want to make sure that you
click the right one i clicked on the version three one and over here on this
page you can see there's just a huge list of python modules and these are
basically modules inside of python that you can just access so essentially
there's like all of this awesome code that's already been written for you and so
if there's some sort of functionality that you want to have inside of your
python program chances are there's a module in here that has that
functionality so there's all sorts of stuff you can do i mean if you just look
through this list like you'll see a huge collection of basically just you know a
bunch of either python variables or python functions just you know things
that you can use to make your programs better so here's what i would
recommend like head over to this page and just sort of look through a lot of
these different modules you know see what you can see and honestly like if
you click on one of them it'll bring you to a page that talks about like how to
use it it'll tell you like how to import it and just you know some basics about
it and this is sort of like the list that's on the official python docs but here's
the other thing the python community is huge there's tons of developers who
use python and you can actually find a lot of third-party modules so if you
just go online and you know look up like python module for doing x or
python module for doing y chances are somebody out there has already
written a python module to do what you're trying to do so if you get good at
using modules and you get good at you know looking for them and finding
them you can actually save yourself a bunch of time because chances are that
somebody's already written a module to do you know what you're trying to
do or like part of what you're trying to do so now that we've taken a look at
all these different python modules i want to just kind of dive in a little bit
deeper into how we can actually use these things so you'll notice here there's
a lot of files right there's a lot of different modules that we apparently have
access to in python but the question is where are all these files stored right
when i was over here in my program for example i was using this useful tools
dot pi file like i knew where that was i created that file i was directly involved
in making it and i just imported it over here it was pretty easy right but what
about all of these files right what about all these modules over here like
where are all of these stored and there's basically two types of modules here
there's built-in modules which means they're just built into the python
language so we can't just automatically have access to them and there's
external modules and a lot of these external modules are just stored in
basically the same folder that we installed python on our computer so for
example let's look at a couple of these right we have um like base64 bdb bin
ascii like if i come over here and you'll see i'm over here in my little file
explorer i have my python project which is draft there's also this other folder
over here called external libraries if i was to click down on this and i come
down here you can see it's just the version of python that i'm i'm using there's
a folder here called lib and this is a very important folder this is basically
storing all of those external modules so you can see if i scroll down here we
have all of these different like modules right so here's that base64 here's bdb
right a lot of these external modules are stored inside of this lib folder and
like i said there's external modules there's also a few modules that are just
like built-in modules they're not going to be stored inside of here and you can
actually tell so for example if i was to come over here and click on base64 it
tells me where the source code is so the source code's in lib forward slash
base64. we were able to see that right i was i saw that inside of my lib folder
uh this bin ascii though for example if i click on this you'll notice that this
isn't giving me a folder because this is basically just like built into python so
we don't have to worry about uh you know locating that file it's just kind of
like it just kind of works so some of these are external some of them are built
in and i want to show you guys uh in addition to using these modules right so
there's a lot of good stuff here and honestly you could spend you know years
and years just learning about all these different modules but a lot of times
you're going to want to use modules that other people have written um and
you know there's a lot of developers who work on python and who write
different modules so there's a lot of useful modules out there that aren't
included in this list right they're not going to be inside of this lib folder by
default and what we can actually do is we can install those external modules
those third-party modules that don't just come pre-installed with python and
i'm going to show you guys how to do that really quick so the first thing you
need to do obviously is find a python module that you want to install that you
want to download and i have actually used one in the past python docs it's a
external module that you can use to basically use python to create word
documents which is pretty cool so you can like format word documents
inside of it so i'm just going to look that up here in google i'm just going to
type in python docs and look here's the thing there's tons of these external
modules you don't have to use python docs i'm just giving you guys an
example but really if you just look up like useful third-party python modules
there's going to be lists of hundreds of these things online in my case though
python docs has a website and it basically just has like some installation
instructions so i'm going to come over here and it tells me that i can install
python docs using the command pip install python docs so this brings us to
something i want to talk to you guys about which is pip and pip is essentially
a program and actually if you have a newer version of python 3 it comes pre-
installed with python 3 and you can use pip to install python modules it's
referred to as a package manager and a package manager basically just allows
you to like install manage update and uninstall like different python modules
so pip is extremely useful and in order for us to install python docs we're
going to have to use pip so i'm going to show you guys how we can do that
what i want to do is open up the command prompt or the terminal on my
computer if you're on a mac you want to open up your terminal if you're on a
windows computer you want to open up your command prompt i'm using a
windows right now so i'm just going to come down to the search bar and type
in cmd and this command prompt should come up so i'm going to click this
inside of the command prompt we can actually use pip the first thing you
want to do is just check to make sure that pips installed and like i said if you
have a newer version of python 3 pip should come just pre-installed and it
should just work in here if you don't have a newer version of python 3 though
you might have to install pip separately and there's tons of instructions online
on how to install pip so i'm just going to check to make sure that i have it i'm
going to type in pip hyphen hyphen version and this should spit out the
version of pip that i currently have so as long as we have pip then we're ready
to install an external or a third-party python module all i have to do is just say
pip install and now i just want to type in the name of the python module so in
the case of python docs it was just python docs like that now again you don't
have to install python docs i'm just doing this for this tutorial just to kind of
show you guys how this is going to work but you know what you want to do
is go online and look up some third-party external python modules and
generally like i'd say 90 to 95 percent of the time you're going to be able to
just install them using pip in the off case that you can't install them using pip
chances are they'll be like some detailed installation instructions but i would
say for the most part any like legitimate python module is going to be able to
installed using pip so over here i'm just going to say pip install and then the
module name so python hyphen docs and when i click enter this is going to
go off and install python docs for us so i'm just going to click enter and it's
going to go off and install everything we need for python docs so you can see
we successfully installed python docs 0.8.6 so i'm going to show you guys
where exactly this got placed so normally when we install a external third-
party module it's going to get put inside of this lib folder but it's going to get
put inside of a special folder in here called site packages so site packages is a
special folder and if i open this folder you'll see now we have this docs folder
and we also have this python docs 0.8.6 pi 3.6 dot egg info folder so these
two folders um are basically included in that module installation so you can
see this docs folder has a bunch of different python files and has a bunch of
stuff in here that we can use so if i wanted to use this inside of one of my
programs i'm just going to refer to the name of the module so in our case it's
just going to be docs so i used python docs in order to install it but we're
going to use docs if we want to import it so i could come up here and i could
say import docx and now i can actually use it so i can just say like docs dot
whatever and you can see there's a bunch of different stuff down here there's
like a document document part image part there's a bunch of stuff that we can
use with this and obviously depending on the python module you install
there's going to be different instructions but you can see it got stored down
here in this site packages folder if i wanted to remove this i could use pip to
do it so i could just say pip

uninstall and we could just again say the module name so python docs and
pip will now uninstall this on our computer so if i was to go back over to this
folder you'll see that those two that docs folder and then that other folder
disappeared so they're no longer here and i'm actually not going to be able to
use this anymore so that's sort of the ins and outs of using modules now again
there's tons of these modules and i can make dozens and dozens of python
courses covering each one of these modules you know the built-in modules
the the modules that are included by default and external modules there's tons
of these things out there and really as a python programmer now what you
can do is you can go out and play around with these different modules i
showed you the ins and outs of installing them and you can use pip to install
all these different modules and you know you can make sure that you have
them by checking the site packages folder or the libs folder but really now it's
on you to just kind of go out and use these modules and don't shy away from
this because modules are a huge part of python and you're definitely going to
want to include them in your python stack

in this tutorial i want to talk to you guys about classes and objects in python
now classes and objects are extremely useful in python programming and
they can help you to make your programs more organized and more powerful
so when we're in python we're dealing with all types of data right and a lot of
times when we're writing programs we're going to have to work with
different types of data and there's essentially like a few basic types of data we
can deal with usually things like strings so like plain text numbers and
boolean values those three are kind of like the main types of data that you're
going to be working with in python and we have all sorts of structures we can
use to store that data you know things like lists or dictionaries but here's the
problem is that not all information not all data not all things can be
represented using strings numbers or booleans right there's a lot of things in
the real world that we can't represent in something like a string or or just a
number right in other words something like think of like something like a
phone or a computer or a person right you can't really represent those things
in like a string or a number you know in other words like the data types that
we have available to us in python can't cover that and so what we can do with
classes and objects is we can essentially create our own data types so i can
create my own data type for anything i want in python so i could create like a
phone data type and it could represent a phone so i could store all the
information i would ever want to know about my phone inside of that data
type and in python we could create a class for it and essentially what a class
is is it's just saying hey here's another data type that we want to use in python
so with a class you can essentially define your own data type and it's super
awesome classes are extremely useful classes are used in almost every single
major programming language out there so in this tutorial i just want to give
you guys a basic introduction of classes and using them inside of python so
let's say that i'm writing a program and i want to represent a student inside of
this program so maybe i'm writing a program for like a college or a university
let's say that in this program i want to model a student like i want to model a
real world object and i want it to be a student right we don't have a student
data type and i can't really represent a student in just a single string or a
number so what i can actually do is i can create a class for a student and i'm
basically creating like a student data type so i'm going to show you guys how
we can do that and create our student class so over here i'm just going to
make a new file we'll just make it a new python file so i'm just going to call it
student.pi and inside of this student.pi file i want to create a student class so
the way that i can do that is just by typing class and now i want to type the
name of the class that i want to create so in our case we're going to create a
class called student so i'm just going to say student and now we're going to
make a colon now everything that goes inside of here is going to be inside of
our student class so everything that's indented like this will be considered a
part of our student class and basically what we can do inside of this student
class is we can define a bunch of attributes about a student so essentially
what i'm doing is i'm like modeling a student i'm creating our student data
type and i can use things like strings integers and booleans in order to map
out what a student should be and what a student should have so i want to
create something called an initialize function and the way i do that is just by
typing out def and i'm just going to type two underscores and then the word i-
n-i-t and then two more underscores and you also want to type out open and
close parentheses and inside of those parentheses we want to type out self and
then we want to colon after that what i can do inside of this initialize function
is i can basically map out what attributes a student should have so we can
essentially define like hey here's the student data type in python so what i
want to do is add in certain attributes after this self so i'm just going to say
self a comma and now we can start thinking about you know what values will
represent a student inside of our python program so if i'm thinking like i'm
thinking something like name right so every student in our program should
have a name they also might want to have a major because they're in college
they probably also will have a gpa so their grade point average like how
they're doing in school and let's define one more thing let me think why don't
we make a boolean and it's going to be called is on probation and this will
basically tell whether or not the student is on probation so essentially what
i'm doing inside of this initialize method inside of this init function is i'm
defining what a student is in our program and so in this program a student has
a name it has a major it has a gpa and it has a value that determines whether
or not it's on probation this right here is the student data type so if i'm
representing a student inside of my program now it has all of these attributes
associated to it and that's basically what i'm doing up here now inside of this
initialize function we actually have to do something and basically what i want
to do is assign some values so i'm going to be writing out some stuff and this
might not make total sense right now but this is going to make sense in a
second after we create our first student object so just stick with me right now
and just basically know that we have to do what i'm doing over here so i'm
just going to say self.name is equal to name and then i'm going to say
self.major is equal to major self.gpa is equal to gpa and i'm going to say self
dot is on probation is equal to is on probation so again this might not make a
whole lot of sense right now but in a little bit this is gonna make total sense
so now that i have this student class defined i can actually use this class
inside of my other files so i'm gonna come over here into this app.python file
and this is just my main file so i actually want to create a student right so in
that student class we defined the student data type and we basically said like
hey a student has a name a major a gpa and it says whether or not they're on
probation that's like the template for what a student is but we can actually
create a student so we can create an actual student and give it some
information and that's called an object so this student class over here is
basically defining what a student is so a class is just like an overview of what
the student data type is an object is an actual student so it's an actual student
with a name a major and a gpa it's not just this template anymore it's actually
like a student that we're representing inside of our program so in order to use
that student class and create a student object i actually need to import that so
all i have to do over here is just say from student and this is referring to this
student file i can say import student and basically what this is saying is from
the student file i want to import the student class so even though these are
both student they're referring to different things so this is referring to the file
and this is referring to the actual student class so now that we did this we can
create a student so so you can create an object of a class a lot like you would
a normal variable so i can just give it a name i'm going to call this student1
and i'm just going to set it equal to student and i'm going to make an open and
close parentheses and now inside of this parentheses i want to give this
student a name a major a gpa and an is on probation value so i'm going to say
we'll just create a fake student so i'll just say his name's jim and he's studying
business and we want to give him a gpa so maybe he has like a 3.1 and
finally we want to say whether or not this student is on probation so why
don't we say false so basically what i'm doing is i'm saying that i want to
create a student so i want to actually create a student object and remember an
object is just an instance of a class so the class is like an overall template it
defines what a student is but an object is an actual student with actual
information so we could call student1 now this is a student object so i just
want to show you guys what this student object actually is and what we can
do with it and then i'm going to talk some more about that init function from
before so over here i'm just going to make a print statement and inside of here
i just want to print out student and what's cool about this student1 object is i
can actually access each of the attributes from inside of this object so if i
wanted to get the name of the student i could say student1.name and now this
is actually going to print out the student's name so over here you'll see it
prints out gym if i wanted i could print out the student's gpa and it's going to
print out the student's gpa 3.1 so now that i created this student object i can
actually access the information about the student so essentially i've just
created a student data type so i could create as many of these students as i
wanted if i wanted i could create another student we could call it student two
and essentially we do the same thing we just give it different information so
we could say like pam and her major is art and she has like a 2.5 and let's say
that she is on probation so now i have another student student too so if i
wanted i could access information about that student we could say like
student two dot gpa and now this has given me the gpa of student two so
basically what i did was i created a student data type and i created student
objects and now i'm able to represent a student inside of my program so let's
talk real quick about all this stuff over here because i didn't really explain it
basically what's happening is when i come over here and i say student and i'm
passing in all of these different values those are getting passed into this init
function so remember i passed in a name i passed in a major i passed in a gpa
when we create that student we're actually calling this function and when i
pass in the name the major and the gpa those values are actually getting
stored over here in this name this major this gpa etc right so i'm giving this
student object all of that information and down here what i'm doing is i'm
saying self.name is equal to name and basically what this means is the actual
object's name is going to be equal to the name that they passed in so
self.name is an attribute of student right so the student is storing a name the
student is storing a major the student is storing a gpa but that's different from
this name this major and this gpa remember these are all just values that i
passed in they're just parameters and so i need to take the values that i passed
in and i need to assign them to the actual attributes of the object so i need to
say okay the name of the student is going to be equal to the name that we
passed in one more time the name of the student object is going to be equal to
the name that we passed in the name of the student's major is going to be
equal to the major that we passed in the student's gpa is going to be equal to
the gpa that we passed in that's basically what's happening here so when i say
self it's referring to the actual object so over here when i'm creating this
student object i'm giving it all of this information it's taking that information
and storing it as attributes for the object so hopefully that makes sense i think
that's about as clear as i can make it but the point is that now we have a
student data type so now i can represent a student inside of my python
program and that's like super powerful and what's cool about classes and
objects is you can do this with anything so in this example we created a
student class and then we created student objects off of that but i could model
any real world entity into this program i could model something like a phone
or i could model like a water bottle or i could model you know a keyboard
right i could model anything that i wanted inside of my program i could just
give it certain attributes right and so that's what's cool about classes is we can
model real world objects and we can create our own data types

in this tutorial i'm going to show you guys how to build a multiple choice
quiz in python so basically we're going to set up a little multiple choice quiz
and we'll have the user take the quiz and as they take the quiz we'll keep track
of their score and then at the end we'll tell them how they did so this is gonna
be a pretty cool video i'm excited to show you guys how to do this and we'll
get to use things like classes and if statements and loops in order to build this
program so we're going to use a lot of cool stuff in python the first thing i
want to show you guys i actually did this before i started the video it's this
little array it's called question prompts and i basically just wrote out all the
questions that are going to be or i shouldn't say the questions i wrote out all
the question prompts that are going to be inside of my multiple choice quiz so
the first one just says what color are apples and the answers are red purple or
orange the next one is what color bananas the options are teal magenta and
yellow and the third question is what color are strawberries and the options
are yellow red and blue so this is obviously a very very easy multiple choice
quiz but i just kind of wrote out the questions beforehand so i didn't have to
spend time doing that so let's talk about how we can build a multiple choice
test well the first thing i want to think about is how can i represent the
questions in the test right over here we have the question prompts but there's
actually two parts to a question when you think about it there's the prompt in
other words like the actual question itself and then there's the answer to the
question and both of those attributes need to be kept track of right i need to
keep track of what we want to ask and i need to keep track of what the
answer is so what i'm actually going to do is create a question class so i'm
going to create a little data type for questions and inside of that question class
we'll be able to store the question prompt and we'll also be able to store the
questions answer so i'm just going to come over here to my folder and i'm
going to make a new python file and we're just going to call this question.py
so we'll call it question.pi and inside of this question.pi file i'm going to make
a class so i'm just going to say class question and i'm going to put a colon
here so inside of this question class we want to define it and initialize
function so i'm going to say def two underscores in it two underscores and
then we're going to type out an open and close parentheses self and then a
colon so after this self we want to define the different attributes that will
describe or that will be included in a question so we're going to include a
prompt and we're going to include an answer so every question will have a
question prompt and a question answer and now down here i want to take
those values and assign them to the actual class object so i'm going to say self
dot prompt is equal to prompt and i'm going to say self dot answer is equal to
answer so now we have a question class set up and we can store all the
information we need about a question so what i want to do now is go back
over to my app.python file and we're actually going to create an array of
questions so i have over here these three prompts and i'm actually just going
to create another array so we'll just call it questions and i'm just going to set it
equal to two open and close square brackets and we're gonna start creating
question objects so i can just say the first element in this questions array will
be a question and we want to pass question prompts zero and the answer to
the first question was a red green that's the color of apple so i'm going to pass
that first question and i'm also going to pass the answer which is a and you'll
see down here i'm getting an error so saying unresolved reference question so
actually what we need to do before we can create these questions is we need
to import this question class so i'm going to come up in here come up here
and say from question import question so now down here in this questions
array we're not getting that error anymore so we created one question object
and i'm just gonna create a couple more for these other ones so i'm just gonna
copy this one and we will paste this down here

all right so now we're creating two other questions and these ones are gonna
be one and two and the answer to the second question is c and the answer to
the third question i think it's b let me look yeah so it's c and b all right so
essentially what we're doing is we're creating three questions each one is
getting a different question prompt and they're each getting different answers
so now we have an array of questions that we want to ask on our test so the
next step is to actually write a function that will run the test right it has to ask
the user the questions and it has to check to see if they got the answer right so
down here lower in the file let's create a function so i'm just going to say def
and we'll call this run test and inside of this parentheses we're going to take
one parameter into this function we're going to take a list of questions so i'm
just going to say questions so this is basically going to be a list of question
objects that we want to ask the user so once i'm in here all i want to do is loop
through all the questions so i want to loop through each question i want to ask
it to the user i want to get the user's answer and i want to check to see if it's
right and we need to be able to keep track of how the user does through the
test so i want to create a variable called score and i'm just going to set it equal
to zero so every time the user answers a question right we'll increment this
score variable all right so what i want to do is like i said loop through all the
questions in that questions array so i'm going to create a for loop i'm going to
say for question in questions so in other words for each question object inside
of this questions array i want to do something and basically the first thing i
want to do is ask the user the question and i want to store their response
inside of a variable so i'm going to say i'm going to make a variable down
here called answer and this is going to represent the user's answer to the
question and i'm going to set it equal to input and i need to give this a prompt
so i'm actually going to give this the prompt for the question so i can just say
question dot prompt so now i have the answer that the user entered in which
is stored inside this variable so we want to check to see if they got the
question right and i can do that using an if statement so i can say if answer
and this refers to the student's answer is equal to question dot answer so i'm
checking to see if the answer that the student gave is equal to the answer of
the current question that we're asking and if this is true then i just want to
increment score so i'm going to say score plus equals 1. and this basically just
means we're adding 1 to the score so the last thing i want to do inside of this
function is just print out the result so i want to print out how the user did so
down here i'm just going to say print and i'm basically just going to print out
like hey you got like two out of three questions or you got five out of six
questions right or you got 0 out of 10 questions right we'll just print out how
they did so i'll just say you got and now i want to print out how many
questions they got right so this is just going to be the score and in order to
print a number alongside of a string like this i'm going to have to say str and
then type in the number so we'll say str score so we'll basically say you got
however many they got right out of so we'll use this little forward slash and
now we'll just say how many questions there were so we can say and again
we're going to have to convert this to a string because it's going to be a
number so we can say string and then we want to figure out how many
questions were in that questions array so i can say l-e-n and inside of here we
can just say questions so this is kind of like this long statement just to print
out how many questions there were so then over here i'll just say correct all
right so now we have this print statement and it's just going to be printing out
how many questions they got right so let's see if this works the last thing i
need to do is just call this run test function so i'll say run test and i'm just
going to pass it that questions array that we created before so we created this
questions array with all of these question objects inside of it i'm basically just
going to pass that into this run test function so now let's run our program and
see how we did hopefully we don't get any errors there's a lot of code there so
it's possible that we might okay so it says what color are apples huh this is a
tough one all right let's put a so we'll get the first question right what color
are bananas let's get the second question wrong so i'm gonna say b bananas
are magenta and we'll get the third question right so it says what color are
strawberries i'll just put b because that's the right answer so now you'll see
that our program prints out you got two out of three correct so not only did it
ask us all the questions and get our input for each question but it also kept
track of our score and it printed it out so why don't we run through the test
one more time and we'll just like get too wrong this time so i'll get this one
wrong i'll get this one wrong and i'll get this one right so now it says you got
one out of three correct so it's able to actually grade our test and what's cool
about the program we just wrote is if i wanted i could add another question
into here and it would automatically be able to ask it so it doesn't matter how
many questions we put in here it's just able to ask it and so really the point i
was trying to make with this whole video was just how we can use something
like a class in order to model a real world entity so for example we created
this question class and we were able to store all the information about a
question that we could ever need so we were able to sort like the prompt and
the answer so we created our own question data type and then we were able
to create a bunch of different questions pass it into this run test method and it
was able to grade the test and just run the test really easily so that's kind of
the point so hopefully this makes sense you know this was a lot of code so if
you don't fully understand what i did go back watch the video you know try it
a couple times on your own and see if you can create your own multiple
choice test

in this tutorial i want to talk to you guys about class functions in python so a
class function is essentially a function that we can use inside of a class and it
can either modify the objects of that class where we can give us specific
information about those objects over here i have this student.pie file and
inside of here i created a student class so i just had a class student and i gave
this student a couple of different attributes i gave it a name a major and a gpa
so i can give this student all of this information so when i create a student
object it'll have all of that information in it now over here on this app.pi file it
actually created two students so student one is oscar who is studying
accounting and he has a gpa of 3.1 student two is phyllis who's studying
business and she has a 3.8 so what we can actually do is we can use functions
inside of these class files so i could actually define a function inside of this
student class and then all of my student objects could access it so for example
i could come down here and create a function and let's say we wanted to
create a function that told us whether or not this particular student had honors
so whether or not they were on the honor roll right basically like are they like
a really good student so i could define a function called on honor roll and
basically what it's going to do it's going to tell me whether or not this
particular student is on the honor roll and let's basically just say the rules for
being on honor roll is you have to have a gpa of 3.5 or above so if your gpa is
3.5 or above that means you're on the honor roll well over here i could
actually write the code for that so i could say if self.gpa and when i say self
over here this is referring to like the actual student's gpa and you'll notice
over here i have to pass that in as a parameter and that always has to be the
first parameter so i could say if self.gpa is greater than or equal to 3.5 then we
can return true because this student is on the honor roll otherwise else we can
just return false because if their gpa isn't above a 3.5 then they're not on the
honor roll so that's essentially our little on honor roll function and you can
see it's a very small function but it provides a service to the objects of this
class right it allows the objects of this class to figure out whether or not that
current student is on the honor roll so over in this app.pi file i could just print
out that value so i could say print and i'm gonna see if student one is on the
honor roll so now when i run this you'll see it should print out false and it's
printing out false down here because student one only has a gpa of 3.1 if i
was to do the same thing on student 2 student 2 has a gpa of 3.8 so we should
return true and that's exactly what happens so essentially a class function is
just a little function that can be used by the objects of the class and i would
say this is a pretty good example of like what a class function should be
doing it should be like giving us information about the class or it could also
be like modifying information about the class so that's the basics of using
functions in classes i mean this is a pretty simple tutorial but i really just
wanted to introduce you guys to the concept of putting me functions inside of
classes this is going to be really useful and if you're making a class you
always want to think about like what functions can i put inside of here that
will you know essentially help the user to either figure out information about
the object or modify different values in the object

in this tutorial i want to talk to you guys about inheritance in python now
inheritance is basically where we can define a bunch of attributes and
functions and things inside of a class and then we can create another class
and we can inherit all of those attributes so i could basically have one class
that has all the functionality of another class without having to physically
write out any of the same methods or attributes so if that's confusing don't
worry i'm going to show you guys exactly what this is in this video so let me
show you about some stuff i have set up over here i created this class called
chef and over here we just have this class chef and inside of this chef class
we have three functions so this chef can do three things the chef can make
chicken the chef can make salad and the chef can make a special dish and
whenever the chef makes a dish he basically just says the chef makes a
chicken or the chef makes a salad or the chef makes bbq ribs for this special
dish it's basically just saying whatever the chef is doing so if i was to come
over here to my app.python file you'll notice that i'm importing the chef so
i'm basically allowed to use this chef class now and i can say my chef is equal
to chef so i'm creating a new chef so now if i came down here and i said my
chef dot make chicken when i run my program now it's gonna say the chef
makes a chicken if i said make

special dish and i run the program now it's going to say the chef makes
barbecue ribs right because that's the chef's special dish so i have this really
awesome chef class and it works really well but let's say that i wanted to
create another class to model another type of chef right so this chef class is
just modeling like some generic chef right we're representing some generic
chef in our program but let's say that i wanted to create a class that modeled a
different type of chef for example let's say we wanted to create a class that
modeled a chinese chef so instead of just a normal chef this is a chinese chef
well i actually created a file over here called chinesechef.python so we could
actually use this chinese chef.python file to create our chinese chef class so
i'm just going to say class and over here i'm just going to say chinese chef and
basically i just can define everything that the chinese chef can do but let's say
that our chinese chef can do everything that our generic chef can do so the
chinese chef is like a special chef right it's very specific type of chef but let's
say that this chinese chef can do everything that the normal chef can do so the
chinese chef can make chicken can make salad and can also make a special
dish well if i wanted to give this chinese chef all of that functionality i could
just come over here and i could copy all of these functions and i could paste
them in here so now the chinese chef can do everything that the other chef
can do but let's say that in addition to all of these things the chinese chef can
also make a special dish called fried rice so i could say def and we could say
make fried rice so the chinese chef has this extra function which allows it to
make fried rice and over here we just say the chef makes fried rice and let's
also say that the chinese chef has a different special dish so instead of making
barbecue ribs the chinese chef makes orange chicken all right so now we
have our chinese chef class set up and you'll notice that it can do everything
that the normal chef could do so let's go back over to our app.python file and
i want to create a chinese chef object so instead of importing from chef we're
going to just import from chinese chef so i'll say chinese chef and we're going
to import chinese chef so let's go ahead and make a chinese chef object so
down here i'm going to make one and i'll just say my and then my chinese
chef we can print out this special dish so remember the chinese chef can do
everything that the normal chef could do so if i say my chinese chef makes
special dish when i run this program you'll see the regular chef is making
barbecue ribs and the chinese chef is making orange chicken so everything
works out and this chinese chef also has an extra method called make fried
rice and you can also make fried rice but here's the problem right when i go
over here to this chinese chef dot pie i when i wanted to use all of the
functionality that was inside this chef class i actually had to copy and
physically paste all of these functions down into this file right and that's kind
of a drag i mean especially like imagine if this chef had like 20 or 30 of these
different functions in it well i'd have to copy and i'd have to paste all of those
inside of this chinese chef and this is where we can use something called
inheritance so instead of having to copy and paste all of these functions i
could just inherit these functions from that chef class and in order to do that i
can actually just get rid of all of these and i can come over here and right next
to where i'm saying class chinese chef inside of parentheses i can say the
name of the class that i want to inherit from so i can just say chef and i'm also
going to have to import this so i'm going to come over here and we'll say
from chef import chef so basically what this is saying is inside of this chinese
chef i want to be able to use all of the functions that are contained inside of
the chef class so i'll say that one more time inside of this chinese chef class i
want to be able to use all of the functions that are inside of this chef class so
by using inheritance here i'm actually able to come over here to this app.pi
file and now i'm still able to execute for example like the make chicken
function even though i didn't specify the make chicken function in here i
didn't write it out i can still run this program and the chinese stuff the chinese
chef will still be able to make chicken so when i run this program you'll see
down here it says the chef makes chicken and that's because i inherited the
make chicken method from the chef class but here's one thing that got messed
up if i come over here and i say make special dish remember the chinese chef
special dish was supposed to be orange chicken but now the chinese chef is
going to be making barbecue ribs because i inherited this make special dish
function from this chef class so what i can actually do is i could come in here
and i could override that make special dish class so i could say deaf make
special dish and down here i can just override it so i could say the chef makes
orange chicken and now when i go over here and i run this make special dish
function now the chef's gonna be back to making orange chicken so the
chinese chef will make his special dish so that's basically what inheritance
does it allows me to inherit functionality from an existing class into the new
class and i can actually just inherit all of it without having to write it out so i
didn't have to write out make chicken and make salad inside the chinese class
but the chinese chef can still make chicken and salad because it inherited that
functionality from the chef class

in this tutorial i want to talk to you guys about the python interpreter the
python interpreter is basically a little environment that we can use to execute
python commands so it's kind of like this little sandbox environment where
we can test out and try out different python commands or different python
functions in a very safe and neutral environment so it's kind of like a quick
and dirty way to write python and try different things out the way we use the
python interpreter is by opening up opening up our command prompt now if
you're on windows there's a program called command prompt if you're on
mac there's a program called terminal basically you need to open that
program in order to use the python interpreter so i'm here on a mac but if
you're on a windows you can essentially do exactly what i'm doing just inside
of the command prompt so on mac here i'm just going to search for my
terminal if you're on windows you can just search for like cmd or command
prompt and it should pop up so the terminal is basically an environment on
our computer where we can interact with the computer and do different things
without a graphical user interface so normally when we interact with a
computer we're using things like buttons or you know windows and you
know where we can move stuff around we can you know basically just like
interact with the computer with graphics but the terminal or the command
prompt is a place where we can interact with the computer using text
commands so you know i'm not going to get too much into what the terminal
and the command prompt are but that's essentially what it is so inside of here
we can use the python interpreter and the python interpreter is basically just a
little program that like i said we can write you know sort of python in so
generally all you have to do is go over to your terminal or your command
prompt and type in python 3. and since we're using python3 i'm going to type
python3 but you can also just type normal python and i'm pretty sure that
gives you python 2. now here's a quick disclaimer um on windows you may
run into a problem where you can't use this python 3 command and it's
possible that if you're running into that problem python like python 3 hasn't
been added to your windows path variable and basically what that means is
your computer doesn't recognize the command python 3. if that's the case all
you have to do is just go and google how to add python 3 to your windows
path variable it's really easy i'm not going to get into it in this video just
because it's kind of outside the scope but if you're running into that problem
that's probably it it's not on your windows path variable so just google around
for that and you should be able to find an answer but i'm going to type
python3 and click enter and it's going to open up this cool little thing down
here so you can see it basically just has like here's the version of python now
i'm just going to enter so we can have some like new lines here um but down
here this is the python interpreter so we can write python code in here and it's
going to work so i could for example i could write like print and inside of
here i could print like hello world and when i click enter you'll see that it
prints out hello world i could create a variable so for example i could say like
num1 is equal to 10 i could say num2 is equal to 90 and then i could print out
num1 plus num2 and it's going to be able to do that for me i could also use
something like a function so i could define a function in here we could make
a function that's called say hi and it'll take a name parameter and you'll see
here when it saw i wanted to create a function it put these three little dots and
i can indent in and we can write the code for our function so i can say like
print hello

plus name and now i have a function called say hi so i can break out of this
by just entering again and i can call the function so i could say say hi and
we'll say hi to me hi mike so now it's going to say hello mike so i can use a
function i could use something like an if statement you know i could say i
could use something like a for loop we could use while loops i mean we can
basically use all of the basic like python commands and you know inside of
this python interpreter and like i said before it's essentially just an
environment where you can test out python code now this is not a place
where you want to write like any serious python scripts so if you're like
designing and writing a python program i would not recommend doing it
inside of this interpreter it is it's not a very intuitive environment it's pretty
much just set up for some quick and dirty tests if you need to test something
out great this is a perfect place for it because you don't have to set up a file
you don't have to use like some ide you don't have to execute a file you just
go in here it's quick it's dirty you get it done but if you're writing like an
actual program you definitely definitely definitely want to use a text editor
the text editor is just going to be way more organized everything is going to
be a lot clearer and you're not going to get confused with like where stuff is
and what you have so that's the basics of the python interpreter you know in
in the course i haven't really been using it at all just because i think it's a lot
easier to teach when we're inside of a file than inside of here but you know
don't count this guy out the python interpreter is awesome a lot of people use
it and it's great if you just need to test you know little bits of code out without
having to set up some huge environment so python interpreter definitely
awesome i would play around with it you know have some fun and take
advantage of it hey thanks for watching if you enjoyed the video please leave
a like and subscribe to draft academy to be the first to know when we release
new content also we're always looking to improve so if you have any
constructive criticism or questions or anything leave a comment below finally
if you're enjoying draft academy and you want to help us grow head over to
draftacademy.com forward slash contribute and invest in our future

welcome to this learn python through game development course in this


course we've compiled five great game programming tutorials all in python to
help you learn python through creating games you will learn how to create
pong snake connect4 tetris and finally a simple multiplayer game this course
is all about learning through doing if you want to learn python syntax directly
check out our other big python course so there's a link up here or down in the
description some people learn best by just jumping right into projects
especially people who may already have a little bit of experience with another
programming language but without whatever your experience is you may
learn best by just jumping into these game development projects a few of the
tutorials use pygame you don't have to know about pygame already but you
can always check out our pygame course the links right up there down in the
description again you should be able to follow along even if you don't really
know that much about pygame so check the description if you want links to
the code or if you just want to learn more information about the people who
created these great tutorials so let's jump right into it

let's take a look at what we're going to be building today classic pong game
so we've got a paddle on the right we've got a paddle on the left and we've got
a ball in the center okay and the ball goes off the screen and

the opposite player gets a point and the ball continues okay so that is what
we're gonna be working on so let's get started um today we're gonna be doing
this by using python of course this is written in python 3 but it should work in
python 2 as well i don't think there's any python 3 specific code in this
particular tutorial so we're going to be building this on top of the turtle
module turtle module it was a nice little module it lets you do some basic
graphics it's great for getting started with games um a lot of a lot of uh
tutorials use pygame which is amazing uh it's got a lot of great features but
for beginners this is a lot simpler and uh it's built in you don't have to install
it like you do with pygame so now that i've got my turtle imported the
module i need to create a window so i'm going to call it wn you call it win w-
i-n or whatever you want to call it and but i use wn and it's turtle dot screen
notice the s is capitalized it's very important and i'm going to give it a title
and i'm going to call that pong by at tokyo edtech that's my twitter handle and
do feel free to uh you know leave comments i do take keep close eye on
things and if you have any trouble let me know and i want to change the
background color of the window to black it's classic pong and i want to
change the size of the window and i want the width to be 800 and i want the
height

to be 600 pixels okay then i do something called wind tracer this one's a little
bit hard to explain but basically what that does is it actually stops the window
from updating and uh so we have to manually update it what this lets us do is
basically speed up our our games quite a bit if we didn't do that things would
run much much slower so every game needs something called a main game
loop and this is where basically all the meat and potatoes of your your game
goes to so we're gonna make a loop while true now i'm going to put four
spaces there you can use tabs but spaces are recommended but whatever you
use make sure that you are consistent you can't mix spaces and tabs and i'm
going to do wind.update and what that does is every time the loop runs it
updates the screen okay just a quick note this this program is written for
beginners so i'm not really using object oriented programming i'm not really
using classes except as it relates to the turtle module this is basically a really
straightforward old school style of programming methodology so let's run
that and see how it goes and what we should have is we have our title black
background it is 800 wide by 600 tall zero zero is at the center so plus 300
minus 300 plus 400 minus 400 remember those numbers because they'll come
in handy in our next few tutorials so that's all for this particular lesson i just
want to get you started we move on to lesson two where we'll add our paddle
on the left paddle on the right and our ball in the center in this part of the
tutorial we're going to add our paddles to the screen and we're going to add
the ball to the screen as well so let's get started with that um so basically what
we we have in pong is we have paddle i'm going to call it paddle a we have
paddle b and we have a ball so those are the three items that we need to add
to the screen now as i mentioned earlier in the previous video we are using
the turtle module to add our graphics and to open our windows and things
like that it's very very convenient it works great for basic games a lot of
people use a pie game which is great but for simple games this is probably an
easier way to get started so everything in our game needs a name so i'm going
to call it paddle a very original and it is actually going to be a turtle what's
known as a turtle object so to do that it's turtle dot capital turtle notice the
capitalization small t because that is our module name capital t because that is
the class name now as this tutorial is aimed at beginners i'm not going to talk
about classes i'm not writing it object oriented style i'm just writing it in you
know functional style although there are some object kind of patterns here
you'll see but for beginners don't worry about that stuff for now so then what
i want to do is paddle a i need to set the speed now this is not the speed that
the paddle moves on the screen this is the speed of animation this is just
something we need to do for the turtle module and what this does is it sets the
speed to the maximum possible speed otherwise things will be really slow we
want to give our paddle a shape and there are a few built-in shapes and we're
going to use square in this case okay there's circle square

let's see a circle square triangle a few others we're going to give our paddle a
color

and we're going to call it white because that's what pong looks like and we're
going to

basically do something called pen up um turtles by definition what they do is


they draw a line as they're moving we don't need to draw lines because that's
not what this program does so we do the pen up and i want my paddle a to
start at minus 350 that's an x coordinate and zero in the vertically centered in
the screen so in our game zero zero is in the middle minus 350 plus 350. so
i'm going to go ahead and run that and see what it looks like so far

okay so this is our left paddle now you know you've played pawn you've seen
the the the demo from the first video clearly it's not the right size so what we
can do

in our program is this now just just for your information uh by default that
shape is 20 pixels by 20 pixels so it's 20 pixels wide by 20 pixels high so
what we're going to do is we're going to stretch the shape so we use the shape
size method you can see i'm using visual studio code it's a very good program
you know on a mac and it tells you you know what you can do stretch width
stretch length etc etc so what i want to do is i want to stretch

the width by five so that's gonna be five times twenty so that'll make it 100
tall and then by 20 wide and stretch length is going to be one we're going to
keep it at the default so let's save that and run it

okay so you can see now we've got a paddle over here 20 pixels wide by 20
pixels high okay now so that's paddle a now i'm kind of a lazy guy so i'm just
gonna copy this so what i always recommend if something's similar similar
styles or similar you know functions you know get it working right once and
copy it paste and just make the necessary changes so now that we've done
that we just need to change that to b so if you keep consistent names it'll
really help your programming in this case we want it to go on the right side
of the screen so that's going to be plus 350. so i'm gonna run that and test it
and testing your program is very very important uh at each stage a lot of
beginners i don't know why they insist on typing the whole program in and
then trying to test it and you'll never be able to figure out where the problems
are especially as a beginner unless you do it step by step like this so we got
our left paddle we got our right paddle so i just called i said paddle a paddle b
and then the last thing we need is going to be our ball so i'm going to just go
ahead and copy this because it's basically the same thing i don't need it
stretched i want to keep it the original size and i want to start in the middle of
the screen and i'm going to call it ball instead of paddle so you see once if
you do it like this method if you get everything working correctly there's no
errors and you tested it you just copy and paste it really speeds up your
programming okay so i'm going to run that one more time okay you can see
we've got our left paddle paddle a our right paddle paddle b and we've got our
ball which is starting in the center so we're off to a good start okay so we've
got our pong window we've got our paddle a on the left paddle b on the right
we've got our ball in the middle so in this lesson we're going to learn how to
move the paddles using the keyboard okay so what we need to do is to
basically we're going to create some functions okay and if you haven't ever
used functions before a function is basically kind of a piece of a program that
does a something that's been defined for it so so in this case we want to move
paddle a up we want to move paddle a down we move paddle b up we move
paddle b down okay so to use functions you first need to define your function
and i'm going to call this first function paddle a up okay if you recall in the
last video i talked about doing one function at a time or one piece at a time
getting that working perfectly and then you can copy and just make the
necessary changes so that's what we're going to do here okay so paddle a up
so to move the paddle what i need to do is i need to know the current y
coordinate so what i'm going to do is i'm going to say y equals paddle a dot y
core okay now this part here paddle a is the name of the object we we created
here we called it paddle a and the dot y core method is from the turtle module
okay what that does is it returns the y coordinate and so we're just assigning
that value to a variable called y which makes sense okay so we've defined the
function using the def keyword you notice we have a i guess it's a tab in this
case well it's a space we'll see i might get an error there and i'll explain that a
second if we do and it's supposed to be set to automatically change the spaces
but i think it's not set that way so i'll leave it the way it is so then what i want
to do if i'm going to go up on the screen it's this way so up so y increases as
we go up it decreases as we go down so what i'm going to do is i'm going to
add 20 to y and this is the way you do that you say y plus equals 20. so that
will add 20 pixels to the y coordinate okay so now notice we've just
calculated the y's then what we actually have to do is paddle a set y to the
new y

so now having a function

doesn't actually do anything until we call the function so the function has just
been defined but we're not using it so what we need to do is we do something
called a keyboard binding

okay so in the turtle module we need to do wn so that was our window and
listen this tells it to listen for keyboard input then we're going to use the on
key press method

okay and watch what i do here paddle a up w okay so let me explain what
that does so this line here it tells the the program to listen for keyboard input
this line here says when the user presses w notice that's a lowercase w so if
you have caps lock on it won't work call the function paddle a up okay here's
our function paddle a up paddle a up says get the y coordinate add 20 to the y
coordinate and then actually set the y of the paddle to the new y coordinate
okay so let's test that and see what happens

okay so i'm going to hit the w key okay so you can see how it is moving up
okay we can actually move it off the screen okay so now that we've gotten
that working okay what i can do is i can copy that

okay and i'm going to change this to paddle a down so instead of adding 20
i'm going to subtract 20. and then i need to do a key binding for that as well
so i'm going to copy and paste that so it's going to be paddle a down and in
this case i'm going to use the s key you can use whatever key you want but i
just chosen those because usually it's wasd on the left and the arrow keys on
the right so again i've done one thing i've changed it now i'm going to test it

okay so w s okay so everything's working exactly as expected okay so then


what i'm going to do is now i've got both of those working i'm going to copy
it and i'm going to do paddle b battle b paddle b so if you keep your naming
consistent it makes it very very easy to do what i'm doing which is to be lazy
and just use copy and paste okay and then here

now for paddle b i'm going to use the arrow keys and then for the up arrow
it's a little bit different use up notice it's capitalized and down is the down
arrow okay so again i made a couple changes i'm going to test my code okay
so w s on the left up and down on the right and voila there you have it
removing the ball this is really kind of the meat and the the central kind of
part of the program this is where we actually get the ball to move so we need
to get to move we need to get it to bounce off the top and the bottom and we
need to get it to bounce off of the paddles and so i'm going to show you how
that's going to work because we have our paddles can move and but the ball
does not yet so let's uh get started with that and so what i want to do uh is
with the ball is i want to separate the ball's movement into two parts um an x
movement and a y movement um so what i'm going to call that i'm going to
say ball dot dx d means delta or change you can you can call it x speed or
whatever you want to but dx works very very well now on my computer i've
found that 2 the number 2 works very very well my computer at home
actually it was like 0.1 it's it's much much faster i don't know quite know why
so you might have to play with the numbers here uh to get it you know to
where you feel the game should be so so dx and d y equals two so what that
means is every time our ball moves it moves by two pixels so since x is
positive it's going to move to the right two and since y is positive it's going to
move up two so it'll be kind of moving up and diagonally okay so to get that
to actually happen we have to go inside the main game loop okay and in here
i'm going to say move the ball so what we need to do is ball dot set x and
what we want is the current x coordinate so i'm just basically kind of
combining what i did up here into one line plus ball dot dx okay so the ball
starts at zero zero so zero x so the first time through this loop it's going to go
two then the next time to the loop it's going to go 2 2 2 2 2. so depending on
your computer speed it could just fly off the screen or it could it could go a
little bit slower so again you'll have to play around with that a little bit so i'm
going to say ball dot set y and basically the same thing i could have copied
and pasted but i should have done and ball dot d y okay so i'm going to say
that and i'm going to test it see what happens you see some red lines here i
think there's gonna be maybe a problem yeah um so i'm gonna run that and
explain why it's not gonna work okay so you can see here i've got an error
and this is something again beginners i don't know why do not want to read
error messages the error messages basically tell you what's wrong so you see
here it says tab error inconsistent use of tabs and spaces okay so i mentioned
this in an earlier video so here i used four spaces but here it's a tab okay you
gotta use the same thing each time so i'm gonna go with four spaces that's
actually the preferred method now i can set my editor up so when i hit a tab it
changes the four spaces automatically but i'll do that another time okay so i'm
to run that and hopefully we'll see the ball move

okay so plus it's going plus and right off the screen all right which is what we
expected okay so that's that's good so now what we need to do is we need to
do some border checking

so what do we want to happen when the ball hits the border okay so since it's
moving up and to the right we'll we'll do the top border first once we get the
top border working then it's easy to get the bottom border working so what
we have to do is we have to compare the ball's y coordinate okay so once it
gets to a certain point we want it to bounce so if you recall earlier in the
program we set the height of the window to be 600 so so that means that the
the top y coordinate is plus 300 the bottom is minus 300 okay but the ball
itself is 20 20 high by 20 wide okay so what we'll do then is we'll kind of split
the difference so we're going to say if the ball dot y core so if the current y
coordinate is greater than 290 okay colon and i got to use spaces it's telling
me

if it's greater than 290 what we do is we we set it back to 290. this avoids
certain types of problems and then what we need to do is we say ball dot d y
times equals negative one okay and what that does

is it reverses the direction okay so if d y is two so d y minus negative one is


negative two okay and that should reverse the direction of the ball so let's run
that

okay so let's watch it and boom very good that's exactly what we wanted to
happen okay now since this is working correct exactly as we want it

i'm going to copy and paste that and just make some changes so on the other
end if it's less than negative 290 we set it to negative 290 and that is that so
let's test that to test that we'll need to start the ball off with a negative dy for
now again notice how i'm making a change testing making a change testing

okay it's working that's about what we wanted it was a little bit off screen
there but we'll let that go so that's the borders that's the top and bottom
borders okay now uh the next thing we need to do is the left and right border

so this is where it gets uh not more tricky or anything but you got to think
about what we want to happen so in this case because we're looking at left
and right okay we're not looking at the y coordinate we're looking at the x
coordinate and now what we want to do is if the x coordinate basically if it
goes off the the right side so if you remember we said the width was 800 so
that means it's plus 400 on the left minus 400 on the right so let's say if it's
greater than we'll say 290 or sorry 390. so that tells us it's basically it's gone
past the paddle and it is off the screen okay

what do i have okay so if that's the case basically we're going to put the ball

back to the center zero and then what i can do is i can maybe ball dot dx may
have it reverse direction

okay so let's take a look at that again i'm testing to make sure it works and if
it does then i can copy and paste and do the other side

okay so we got an error um


ah okay so it says we've got a lot of weird stuff here that was a really long
one and

yeah say here so you say it says line 87. so here's the line where it thinks the
error is and there's a lot of different weird stuff but basically what i forgot to
do was zero comma zero

okay so let's test that again

so it should go off the screen okay now it went back to the center and reverse
direction okay so we know it works so let's copy that

and paste it and again we're just going to reverse it so if it's less than negative
390 and that's all we got to do okay so again let's test it

hopefully it will come back

okay so that's basically that's exactly what we wanted to happen okay

um so in this lesson we're going to learn how to get the ball to collide with
the paddles so let's see what we have so far so we've got our ball it's bouncing
off the top of the screen and it's at the edge of the screen it goes back to the
center which is what we want so what we got to do is we got to make it so
that when it touches the paddles it will reverse and how we're going to do that
is basically what we're going to do is we're going to compare the x and y
coordinates of the paddle and the ball so if we look at our code we put paddle
b at 350. so the x coordinate of the center is 350. and if you recall the center
it's sorry it's 20 pixels wide by 100 pixels tall so we need to basically look at
we need to make sure the ball is basically between here and here and that it's
basically between here and here if it is then we'll call that a bounce okay so
let me uh kind of play the math a little bit on that and give that a shot so let's
let's again as i mentioned before we're just going to try and get the right
paddle working and if we get the right paddle working then it's easy to get the
left paddle working okay so i'm going to say so paddle and ball collisions
okay so if the ball dot x-core so if the ball's x coordinate is greater than uh so
we said 350 it's 10 wide so it's greater than say 340. and the ball well actually
i'll leave it at that i'll leave that and then we'll come back and fix it in a bit uh
so that's one condition and the ball's y coordinate

is less than paddle b dot y core plus 50. here's a lot of stuff in here

and there's a lot of different things here ball dot y core

is greater than paddle

b dot y core

minus 50.

okay so i'm glad that's scrolling over

so let me explain that real quick so if that's the case

okay i'm going to tatter four

if that is the case basically we just want the dx same thing we did at the top
times equals one although this is x not y sorry negative one so if it's going
this way the dx is positive it's gonna balance and go back this way so what
we wanna see is the ball x coordinate greater than 340. that means the edges
are basically touching and is it between the top of the paddle and the bottom
of the paddle actually i think it should be 50 it should probably be 40 because
of the size of the ball let's play around with that let's test it out see what
happens okay so i'm going to run that

oops

okay so did you see what happened there

which is not what we wanted

okay see it bounced there


but watch what happens if i miss it see there's like a little bit of a glitch there
it's because even though it's behind the x coordinate is greater than 340 and
it's between here okay so you see how that's kind of acting weird so we need
to do is i'm going to add this condition

and ball.x core is less than we'll say 350. so

that gives it basically to the middle of the paddle

so we'll say ball dot set x to 340. so that moves it back to the left a little bit
and then it reverses the direction which is what we wanted

okay so let me test that one more time make sure it's working

so it bounces which is good

let's let it get past and see okay so you see how it did not get stuck that time
so that's basically what we wanted to happen so let's just test it one more time
yep so that's that's where we wanted it okay so i'm just going to basically take
this i'm going to copy it

paste it and we should do the same thing on this the other side so minus 340

greater than minus 350 and the top and bottom doesn't matter but in this case
it's going to be paddle a not paddle b that will give you some definitely some
weird glitches

and then same thing we're going to reverse the ball so let's test it again

okay so over here we're using the up and down arrows okay bounced over
here we're going to use the w and s keys and we test it okay so something
went wrong there

okay so i know what i did wrong so i had set x here to 340 it should be
negative 340. so again notice because i'm testing it you know after every little
bit of code i knew that the problem had to be in here somewhere because
that's the only thing i changed i just i can't emphasize that enough because my
students like i said they always want to type the whole thing in and then
debug which is never a good idea

okay so let's test it one more time so you see this process we're iterating we're
testing and just making sure everything is working as expected before we
move on okay so that is that for that section so now we've got colliding with
the paddles it's going off the screen the next thing we need to do is to add
some sort of scoring mechanism so here's what we have so far we've actually
got a functioning palm game the paddle on the right is moving using the up
and down arrows the paddle on the left is moving using w and s the ball's
bouncing it's doing everything it needs to do next we want to add a scoring
system so let's go ahead and take a look at that so basically what we want to
do is we want to draw the score on the screen and here's how we're going to
do that in python using the turtle module so what we're going to do is we're
actually going to create a pen okay i just call it a pen but it's actually just a
turtle uh just like the ball like the paddle but the the turtle module gives these
uh turtles uh objects a lot of different abilities so i'm gonna make a pen and it
like the other is a turtle dot turtle again i always spell that wrong and keep an
eye on the capitalization so small t for the module name capital t for the the
class name which we it's happening in the background uh same thing as
before so pen dot speed and again this is the animation speed not the
movement speed it's not really gonna move but uh we're gonna give it a color
pen dot color the shape doesn't matter because we're not gonna see it if we
want to print in white on the screen like classic pong style and pen dot pen up
this is because we don't want to draw a line when the pen moves every turtle
actually starts out at the dead center of the screen then we move it somewhere
if we don't do pen up you'll see a line moving between those two points and
then here we want to hide the turtle because we don't need to see it now with
the ball and the paddle paddles uh we didn't hide it because we want to see
those on the screen but the pen we don't want to see we just want to see the
text that it's going to write so pen dot go to and 0 comma i think 260. again i
played around with the numbers that's why i know 260 is the number i want
um if you remember again the screen height is 600 so that means it's 0 to 300
here so we want the score to be right around this part of the screen and then it
gets pretty easy at this point is we use the right method so we want to write
and i'm going to write player a and now when the game starts the score of
course is zero two spaces player b zero comma and you want to align equals
center because that will center the text for us around that point and then we
want to choose a font okay now watch here i've got an extra set of
parentheses here okay don't forget that and i want the font courier because
that's kind of old school techie uh i choose a font size of 24 and normal i
think normal i think you can choose bold and italics i'm 100 sure on that one
okay so be very careful again we've got a set of parentheses here and we've
got an extra set of parentheses here for the font so because there's three uh
arguments we got to send there okay so again now test your code make sure
this is working so i'm going to run that okay so that's what we wanted you see
i forgot a little space after player b okay but yeah that's that's basically what
we wanted okay so that's how we get the default score on the screen so what
we got to do is we need to keep track of the score and so what i'm going to do
and i'm going to put this up here

and score so i need to create a couple variables i'm going to call it score a and
we start the game it's always zero and score b is going to be zero now down
down here okay so we get a score when the ball goes off the screen so here's
the right side so if the ball goes off the right side think to yourself who gets a
score of course that is going to be player a so what i can do is score a plus
equals one that adds one to player a's score and by the same token on this on
the other side

if the ball goes off the left side of the screen player b gets that okay so let's
run that

oops okay so nothing we don't see any change can you guess why

okay now if you said well we didn't update uh the score on the screen you'd
be 100 correct okay so what i'm just going to do is i'm going to copy this

line here and i'm going to put that into here

and you'll see what i got to do is instead of the zeros this is just print you
know basic printing you know 101. so i'm not sure how to do that i do a video
on that somewhere i'll try to remember to link that below about how printing
works so we use the format method on our string and we want score a and
score b okay so what that does is it puts score a here and score b there so i'm
going to again make sure i'm using spaces i'm going to copy that because i'm
pretty sure this is correct um

so basically every time i update the score i need to update the actual printed
score on the screen or the shown's displayed score i should say so i'm going
to run that now watch what happens here okay so you can see it did update
okay but clearly something is wrong okay because basically what it's doing is
it's just printing on top of itself okay so what we have to do is before we do
the call the right method we say pen dot clear that will actually clear what's
on the screen now it happens so fast that you don't see it but it it actually it
does so take my word for that one

and again if you're using pygame or some other you know framework or
method you might have to do this type of steps but for the turtle module this
is what you need to do okay so i'm going to run that

and let's watch what happens okay so player a just got a point player b just
got a point and so on and so forth so yeah so basically we've got a pretty well
working game here again the game never ends you just go until you know
until you give up and get bored uh which is pretty easy with pong um so i've
got yeah i've got another tutorial coming up on this in this series i'm going to
show you how to add a little bit of sound uh which is interesting uh especially
depending on the operating system that you are using i'm going to show you
how to add a little bit of sound to your game so just basically you know what
you need to do to get started with that uh is you need to have a sound you
need to have a sound file and what i've done is i have downloaded this file
from uh i forgot the site now but uh it is bounce dot wave and it's like kind of
a classic old school um bouncing sound you'll hear it in a minute now python
is generally pretty cross platform basically everything that we've done so far
it doesn't matter which operating system you're using linux mac or windows
everything works the same sound is one of those things where it doesn't work
the same so right now i'm on a mac and i'm going to show you how to do it
on a mac and then i'll talk about how you would do it then on linux or
windows okay so it's a bit different okay so the first thing i got to point out is
that the sound that i found bounce dot wave uh and wave files generally are
more compatible cross-platform compatibility uh is in the exact same folder
as my python file so right now i'm on pong7 and punk 7's in there so they are
in the same folder that's that's a really important point now that you can you
can work around that if you know what you're doing but for beginners this is
probably the easiest way to do things and so basically it's really simple when
do i want to play a sound and so i'm going to play a sound when i i'm going
to put when i when the ball either touches one of the borders

or bounces off of the paddle okay so in mac okay so i'm going to use
something called the os module and what that lets us do is basically interact
with the operating system uh through text commands and so i've imported os
so i can use that module and then down here so what i can do is i can say os
dot system that will do a system function call for us now on mac it's a play
bounce dot mp bounce dot wav

okay so this is it this will play the sound when it hits the border now there's
there's a problem here and i'm going to show you that in a second but again
let's test it see what happens

oops went the wrong way wait till it's the top i'll turn my volume up

oops sorry my bad uh a play is for linux af play is for mac let's try that again
got that backwards had a 50 50 chance and i blew it okay let's listen

now did you notice that everything stopped while that sound played so watch
it again okay that is not what we want to happen okay so to get around that at
the end of this command we need to add an ampersand that's the and symbol
okay so again let's test it

and now watch it will not delay

okay so a little bit it's a little bit off but that's you know neither here or there i
suppose what to deal with that um okay i think actually what i would
probably have to do is edit this this wave sound there's probably a little bit of
a a blank space at the beginning of it um so that's that's it uh on mac okay so
let me uh copy that and let's say we want to play it when it bounces at the top
bottom and when it touches the paddles so we just need to put oops when i do
that

okay so let's test it so again i got it working once now i just copy and paste so
it should bounce here

oops

i missed that i'm terrible at pawn apparently okay now you can choose
different sounds you have one sound for when it bounces off the walls one
sound for when it bounces off the paddle etc etc okay now if you are a linux
user the system is very very similar instead of af play it's a play and that's all
you have to change okay now for windows it's a little bit different now i can't
test it for you but i can explain how it works and i do have a video that
explains this and i'll try to remember to link that down below and basically in
windows instead of importing os you import winsound which is a little
module that only exists on windows and then when you want to play your
sound instead of this os dot system stuff you would type win sound dot play
sound again pay attention to the capitalization okay small w capital p capital s
then in parentheses so you don't need the ampersand here but you do need a
comma and a wind sound dot snd async so what that does is that same thing
as adding the ampersand uh that'll stop if it's asynchronous it'll play the sound
in the background if it's not asynchronous program will stop again i can't
show this to you because this is mac but uh that should should do it so i'm
going to undo that and get back to my system oops so we wanted to oh yeah
keep going yeah a play and it's af play let's leave that i'm gonna test it one
more time and that is our pong program okay yeah not the most exciting
thing in the world but you know you learn a lot of different concepts you
know how to put objects on the screen how to move them with a keyboard
how to detect collisions um update the score on the screen game main loops
sounds so basically all the basic elements that you need to make a game are
included in pong that's why it's one of the classics and i remember playing
this as a child it brings back some memories
so let's just go ahead and get a look at what this final product is going to look
like so on like an x by x grid so whatever you want it to be you have a little
snake moving around there's a snack is what i want to call it that shows up
and as you collect it it increases the length of the tail and then obviously if
you run into yourself and i just did that by clicking the back key while i was
going forward um it gives you a little error message here says you ran into
your tail um your length was nine dot dot dot whatever um and then you can
continue and play as long as you want um anyways what i'm going to be
doing in here is i'm going to be coding everything object orientated i know
that there's a much faster and easier way to do this but it doesn't really teach
you that much this way you're going to learn a bit about objects about classes
how we can kind of work with them and you'll see like how the flow of my
program goes and you should learn quite a bit especially if you're somewhat a
beginner programmer what we're going to be using to make this is module
called pi game if you don't know about pi game and you want to learn about
it before you do this i would recommend that all right so let's start coding so
pretty much what i've done is i've just set up the flow of the program all the
classes and the function just to remind myself what i need to write um and
while i'm talking here it's probably a good idea if you guys copy this down so
what we're gonna have is we're gonna have two main objects we're gonna
have a cube object and a snake object and our snake object is gonna contain
cube objects if that makes sense so each one of those little red uh i don't
know squares that was moving around is a cube object and the whole thing is
our snake object we're gonna have a few functions here draw grid redraw
window random snack message box and main so let's get started with our
main function here and this is what's gonna be our main loop so essentially
what i need for the main loop to start is we need to make a surface so in high
game to do this we do win equals pi game dot display dot set underscore
mode and then i'm going to set it let's see here what do i want the height to be
let's say width and height like this oops bad spelling and i'm just going to
make a variable here called width equals height equals and we'll just set this
to 500 by what i have 500 like so now we need another variable i'm going to
set this as rows uh i can delete this down here it's going to do something but
i'll do that later and this is how many rows you're going to have or rows or
columns whatever you can set this to whatever you want just make sure it
divides 500 evenly otherwise you're going to have like weird looking rows if
you know what i mean so i'm just going to set mine to 20. that's what i'm
using the other one but if you want to make it harder set it to something like
10 and there won't be as much room for the snake to move around and the
games will go faster pretty well okay next what we need to do is we need to
set up a snake object so i know that uh we haven't even created like anything
in the snake class yet but i'm just gonna do s equals snake and i'm just going
to give it a position so in this case we want to or a color sorry which is going
to be red because red green blue 255 for red and then i'm going to give it a
position we're going to start in the middle so i'm going to start at 10 10. now
let's move into our main loop so i'm just going to say wow flag create my
variable up here flag equals true and then we're just going to start by doing a
pi game tick so pi game dot time dot delay 50 like so and that's just going to
delay us uh i want to say like 0.5 or 50 milliseconds every time so that our
program doesn't run too fast i'm also just to create this clock.tick i'm going to
put that at 10 and what i'm going to do is i'm going to create a clock object up
here um and this is a built-in thing in pi game and what this is going to do is
i'll explain in just one second once i finish typing it pie game dot clock i
believe it is oops dot time dot clock like so so what this clock dot tick is
actually going to do is it's going to make sure that our game doesn't run at
more than 10 frames per second so that would mean essentially that our snake
would be able to move like 10 blocks in one second and again we don't want
it to be that fast so that's why we're also delaying by like a few milliseconds
here if you put this too low then again it's going to move too low you can
play around with the speed this is kind of what i found was the best speed um
and it may vary depending on what machine you're on it shouldn't it might so
you might want to just change these numbers again the lower this goes is the
faster it's going to be and the lower this one goes is the slower it's going to be
so they're kind of inversely proportional like that all right um next what are
we going to do here i'm just going to call redraw window oops and i butcher
that so bad oops redraw window like so i'm just going to give it a surface
which is in this case going to be win that we've created up here and for now
that's all i'm going to put in my main loop here and we'll move more into that
once i start coding some other stuff okay so now that we have our redraw
window being called here i'm going to go and i'm going to start coding our
redraw window so what this is essentially going to do is we first need to
update the display so pie game dot display dot update like so and we also
need to um draw the grid so we're actually going to draw a grid we're going
to pass it that same surface that we were given um and move on from that
we're also going to fill the screen so when dot fill in this case i'm just going to
use black so it's zero zero zero um and there we are that's all we need to do
right now but essentially we're also going to need to draw the snake we're
going to need to draw a few other things on the screen that we'll get to later
okay so draw grid let's move into this one now uh what we need to do here is
a set look draw a grid which is pretty easy to do so what we do is we we're
given rows and surface so it's probably a good idea if i actually passed in the
rows and the surface so i'm just going to global them here so that i can
reference them i think this is going to work we'll do global rows and width
like that and here we also need to make these global just because i don't want
to pass them in every time i draw a grid we're just going to say width oops
and rows and this height variable is actually not necessary because we are
just going to draw a square like a square surface every time so we can just
make this the same we don't need two variables for width and height do it are
going to contain the same number anyway so global width and rows i go here
draw a grid given with rows and surface so now we're going to put in well
first we're going to put our rows or oops width row and surface like that okay
so that should be working now in here what we first need to do when we're
drawing a grid is we want to figure out um how big each square in the grid is
going to be because what we're going to do is we're going to just draw lines
going down and across but we need to figure out where to draw those lines so
we have to figure out kind of like the gap between each of the lines so the
way we do that i'm just going to create a variable here size between is equal
to our width integer divided by our rows um this is just so that we don't get
like large decimal numbers um because that we cannot pass into our uh
drawline method in uh in python okay so now i'm just going to create x
variable and a y variable and i'm going to set these to zero i'm going to say 4l
in range and this is just standing for line pretty well in rows like that now
what i'm going to do is i'm going to increment my x by the size between i'm
going to increment my y by the same so y equals y plus oops size between
and get rid of one of the spaces here oh okay there we are and now we're
simply just going to draw two lines so to draw a line in pie game all we have
to do is pie game dot draw dot line and the arguments that that takes is a
surface we need a color in this case it's going to be white so we do 255 255
255 for white we're going to draw at x 0 comma x w and i'll go through this
in just one second what this does and i'm just going to copy this and draw one
more and then explain how this is going to work pretty well okay so now we
need 0 y and w y like so okay so what this is going to do is this is going to
draw two lines for us every loop of this for loop and these arguments here is
the start position of the line and the end position of the line so the first line
that we want to draw is going horizontal which means we don't want to
change the y value at all so what we need to do is we need to find the x um
and then we're going to put y at zero uh because we're going to be at the top i
think that's right at least oh sorry this this line is being drawn down not being
drawn to the right i was getting confused there okay so we're going to change
the x but we're going to keep the y at zero and then we're going to stay at that
same x and we're going to keep the y at the width of the screen so that we're
going uh far enough down and then same thing here this one is going
horizontal excuse me i messed that up before so our x is always going to stay
at 0 and our y is going to be what's changing as we draw horizontal lines
across the screen i hope that makes sense to everyone how that works
anyways i'm going to move on from that and that's all we need for the draw
grid function so let's just go ahead i probably made a mistake here but we'll
run the program to see if everything's working again our name win is not
defined win.fill ah so i've called this win one really needs to be surface like
that so let's try now and there we go we get a nice little grid um on our screen
like so 20 by 20 grid there we are so now let's move into another uh function
or actually let's start coding one of the classes here so like i was talking about
before we're going to have a snake object which is going to contain a bunch
of cube objects so essentially what we're going to do is we're going to have a
list of cubes and that's going to be known as the snake body so let's go ahead
and write that in now what i want to do for that is just create a list so we're
just going to say body is equal to and then a blank list i'm also just while
we're already up here and creating a class variable i'm going to create turns is
equal to and it's just going to be this set of squiggly brackets here that we'll
uh we'll get into in a bit okay so now that we're already in this snake function
what we need to do is we just need to define our parameters here that we're
passed in so we're just going to say self.color equals color say self dot head
equals cube which i'll get into in a second given the position say self dot body
dot append our head self.head like this so what we're doing here now is we're
saying okay so the head of our snake which is going to be important because
we need to know where that is at all times so we can move accordingly is
equal to a cube at the given position and the given position is what we pass in
here as like the starting position of our snake or we could create a new snake
like we'd have multiple snakes moving around and anyways that's the
position now we're saying we're going to append to the body this head so now
this is in our list here and then we can go through that list and we can draw
things we can move it we can check things we want all of our cubes to be
ordered within this list so that's why i'm putting that in first now i'm just
going to give this one which is called during x is equal to 0 and turn y which
is equal to 1. so what this is going to do is we have a direction for x in a
direction for y for moving our snake so obviously these are going to be a
value like negative 1 1 or 0 and that's going to be the same for y and x if y or
x is equal to one negative one then the other one is going to be equal to zero
because you can only be moving in one direction at the same time and this is
just going to keep track of um what direction we're moving in and we'll use
this in the next function that we're going to code which is our move function
so moving is pretty straightforward at least in terms of just if you have one
object moving around the screen getting it to go left straight right but when
you have the snake object it has to turn at certain points so when i click left
the rest of the snake is still moving forward once it reaches the point where
the head turned left then it has to turn left so that's where things can get a bit
complicated anyways to start what i'm going to do is say for event in pie
game oops what am i doing with my typing here hi game dot events dot gets
like so and then we're just gonna say if event dot type equals equals pi
pygame dot quit like this and this is the first one we always want to code in
because we want to make sure that if they click that little red arrow um it
actually works and we can quit we're gonna do pi game dot quit like that and
i'm just gonna say if actually we don't even need another if because the way
i'm going to do this is uh this other way you might have seen in pi game
before to move things around you said if uh event dot type equals key down
and then you just check which key was pressed and move to the left this is a
similar thing but it works smoother i've used both of them a lot and this is one
i prefer so i'm just going to use this so pygame.key.get underscore press so
what this is going to do is it's going to get a list actually i think it's like a
dictionary or something like that that has all the key values and then if they
were pressed or not so that way if you press more than one key at once when
you're looping through it'll adjust to that whereas the other one you can only
click one at a time and you couldn't move like per se diagonally if you're
moving like a character on the screen it doesn't matter too much for this but
this is the way i like to do it so now i'm going to say four key in keys because
remember this is going to give us all of the keys and then like one or zero
value if they were clicked or not um so we need to loop through all of them
and check we're going to say if keys and then pygame dot key or oops dot k
underscore left i thought it was key there and then we're going to say if keys
high game dot k underscore right like that and we can continue down here
with up and down and then we'll get into exactly what is going to happen
when we click these keys so last one here

all right and there we go okay so now what we're going to do is we're going
to change the direction according to what key we click so if we're going left
that means that our x has to be negative because the way again coordinates
work in pi game is in the top left hand corner of your screen is zero zero um
so if we want to be moving left we should be making our x negative to move
uh more towards zero right if we want to move right then we make our x
positive which would be one in this case because we're just going to move
one cube at a time to go further to the right same thing with the y it's kind of
weird in pi game how the y works because the more y you add the further
down you go um so we'll do that in a second so for x we're going to set
itself.during x equals negative one again because we're moving left and we're
going to set our gen y equal to zero and this is because again we don't want to
be moving in two directions at once and be going diagonally now this is what
i was talking about is we need to remember where we actually turned because
if you just have one cube in the ground that's fine but when we have multiple
cubes we need to be able to turn left right we need to remember where we
turned so that the tail of our cube can turn at that point so that's why we have
that self dot turns list up here or just this turns um i want to say dictionary or
set whatever so we're going to add to that self.turns and we're going to give it
a new key and i'll go through how this works in a second self.pause here is
equal to and then we're going to give just a list of self. during x and self dot
during black okay so you might be kind of confused on what's going on here
so i've created a new dictionary up here that's what i'm going to call it
officially you could think of it as a set as well um and pretty much we're
going to add a key which is the current position of the head of our snake um
and then it's going to be set equal to what direction we turned so we're saying
we have a new turn at this position and our character or our snake moved left
so it's going to say we have self.germ y which is right here is negative one
self.earthsurf.x area and then during y is equal to zero so we know what uh
way we actually turned and i hope that makes sense that's uh yeah that's how
we're gonna do that now i'm just gonna copy and paste these and then change
these values so when we're going right this is going to be one oops same
thing here so we'll put that in this is going to be zero and during y we're going
up is going to be negative one now when we're going down we need to
change this to one and this to zero and i'm just going to get rid of that and
there we go okay so that is pretty much how we go about doing this and i can
also just put alifs here as well because we don't want to be able to move in
more than one direction so we're going to prioritize the left arrow key if
they're not clicking the left arrow key then we'll check if they're doing the
right otherwise up otherwise down because we don't want them to be able to
click more than one key at once okay so next we need to actually move our
cube and this is where it gets a little bit more tricky um in terms of looking
where our cube is and if it's at that turn then we're going to turn it so i'm just
going to start coding and i'm kind of going to go through exactly what i do so
for i see and enumerate oops

and i spoke that wrong didn't i

like that and then we're just going to say self.body because we're going to
look through the list of positions that we have in on the snake we're going to
say p equals c dot position and i'm just going to copy this by the way that's
what this little arrow does here it just makes a copy so that we're not
changing the position of our snake when we do things each just uh just follow
along with it it's not super important okay so we're gonna say if p is in self
dot turns like this because remember what we did is we added the position of
our head two turns so now we're going to say well if this position is in the
turns then we're going to move or we're going to turn right so let's say here so
we're going to say oops equals self.turns p like that so now we've seen that it's
in there uh so now it's in there we can find the index of it and we can grab the
direction value so we know what way we're gonna be moving and now we're
just gonna say c dot move like this and turn zero turn one like so okay now
next i'm gonna say if i equals equals the length of self.body minus one oops
then i'm just gonna do self i don't know why that's capital self.turned dot pop
p okay so i know i just did a lot of coding here and this probably doesn't
make a lot of sense you guys so i'm gonna kind of run through exactly what i
just did um it's it's pretty it's a little bit difficult to explain so anyways what
we start off by doing is we're going to say we're going to get the index and
we're going to get the cube object in our self.buddy because remember our
self.body is made up of cube objects right here um that have these properties
right they're going to have a direction y direction x a start a color so on and
we're going to get we're going to get to coding cube in just a second so they're
cube objects now all of these cube objects have a position so i'm saying for
each object here i'm going to grab their position and i'm going to see if that
position is in our turn list and we create the term list and add to the turn list
um when we turn right when we click left center right so on and then we're
going to say okay so the actual turn so where we're actually going to be
moving is equal to um that are the turns list at that index right so we grab the
turn direction x and direction y which we stored there and now we're just
going to say our cube.move which is another method that we're going to code
and we're giving it that direction x in that direction y so it knows what way it
needs to move pretty well and then i say if i is equal to the length of self.body
minus 1. so that means if we are on the last cube we're going to remove that
turn so once that last cube hits that turn we're going to remove it because if
we were just to leave that turn in the list and that would mean any time you
hit that position on the screen regardless of if the snake was turning there or
not you'd automatically change directions if you don't remove it from the list
um i hope that makes sense okay now also after this if here we're going to say
if the um what do you call it if it's not in the list so if our position is not in the
list we still need to move the snake because it's constantly moving so what do
we do to this will we write an else and i'm just going to copy this in because
it's going to take a second to type because i have another file open and i'll go
through what happened how this works okay now this looks like a lot but
pretty much what this is doing for us is we're checking whether or not we've
reached the edge of the screen so we're saying if we're moving left and the
position so the x position of our cube is less than or equal to zero um then
we're going to change that position so that it goes to the right side of the
screen so the way that we can do that is by saying c dot rows minus one
because again in you start counting at zero in computers um so if our rows is
like 20 then the last cube would be uh 19 in a list right say c dot rows minus
one and we're gonna be at the same y value so we'll leave that there okay and
then we say otherwise uh we're gonna check if we're going right for moving
right and same thing if we're at the edge of the screen move back to the left
side by putting zero here and then next one if we're going down uh what
we're going to be doing is again checking are we less than uh rows minus one
or greater than rows minus one no we're not or if we are then let's move us
back up to the top of the screen uh by changing our y value and then same
thing here if you're moving upwards now if none of that's true so we're not at
the edge of the screen we're not moving up left down to whatever i just said
then we're just simply going to move our cube at the direction x and the
direction y of that cube already so if that cube is moving upwards and it's not
turning and it's not going to the edge of the screen it doesn't need to be
changed just keep moving it in whatever direction it's going and that's why
i'm simply referencing the cube's already existing direction x and direction y
we're not changing anything we're simply just saying okay let's move you
forward one like that i hope that makes sense that was a lot and that's
probably one of the hardest things in this program is figuring out the
movement of the snake so if you guys understand that um then that is the
hard part kind of over with and we're going to get into this cube object so
you're going to understand what all of this means and how our rows and
columns kind of work and stuff like that okay so i'm just going to forget
about reset and add cube for now because we'll worry about those later um
but let's get into the draw method because we want to see if it's actually
working and put this on the screen so simply for i c and numerate why can i
not spell enumerate today like that uh same thing self.body like that we're
gonna say if i equals equals zero c dot draw and you'll see why it is in a
second true else c dot draw surface like that okay so the reason i'm doing this
little check here rather than just drawing every object um is because when we
uh draw the first snake object i'm sure if you remember my other program it
had eyes so what i would simply want to do is make sure that when we draw
that first object we add eyes onto it just so we know where the head of the
snake is uh we don't get confused like what direction it's moving in although
you shouldn't we i want to add the little eyes maybe just for a static as well so
what this true does optional parameter simply says draw eyes if it's the first
one in our list like that if it's the head and then in this draw method you can
see i have eyes equals to false but when you make it equal to true we're going
to do a special thing in here that's going to draw eyes for us okay so now that
we've coded this this whole mess of stuff in the snake class let's just run the
program quickly and see if anything's happening so currently we just have the
grid we don't have any errors or anything but that's because we haven't drawn
the snake object onto the screen yet so what we need to do is we just need to
simply do s dot draw it within our redraw window here so i'm just going to
type all right i'm going to global s here and i'll global it down there as well
you can say s dot draw like that and we need to give a surface so let's give it a
surface and i'm just going to global s so that we can reference it there uh and
is there a reason we aren't being drawn to the screen let's just have a look
quickly s dot draw let's draw oh it's because yes we are indeed drawing s but
we haven't drawn any of the cube objects yet and it is calling the draw
method on all of our cube objects which we haven't yet created hopefully that
makes sense but we'll go ahead and do that now so we have to code a little bit
more before we can see everything so let's just go ahead and get into the cube
object here and let's just say self.start equals start except i'm actually just
going to change this to position because i believe this is what it's supposed to
be

and then we're going to say self. turn x

equals 1 self. during y is equal to 0 and self.color is equal to color and the
reason we have this is because we're going to be drawing later what i want to
call like a snack for the uh for the cube to collect for the snake to collect um
so we want to be able to change the color with that and i've spelt it wrong like
three times during accident y the reason i have during x here set to one
initially is because i uh i want to make sure that we start moving in a
direction if i had this at zero you would have to click a key before the snake
starts moving but i want right when we run the program for the snake to just
start moving so i'm setting it already with a direction x and the reason these
are optional again is so that when we create a new cube object we don't have
to implicitly say direction x is 1 direction y 0 because it's assumed that it's
always going to be like that unless otherwise stated okay let's have a look
what else do we need to do here we need to now code this move function
which is actually really easy all i'm just going to do is we're going to say
since we're changing the direction x in the direction y in our snake class we
need to do that in here so that it stays with the object i'll say during x equals
during x and then the same thing self thought during y equals there and y like
that and then we'll go down here and all we're going to do is we're going to
change our position so self.position is equal to self.pause 0 which is our
already existing position plus self dot during x and they're saying self dot
pause one which is our already existing y value plus equals self dot germ y
like that and just in case i haven't mentioned it here right we're working with
a grid system of 20 rows in this instant so when i say something like uh if our
self deposition is like 1 3 or 10 10 i'm saying we're in the 10th row in the 10th
column i'm not saying the x value is equal to 10 and the y value is equal to 10
because it's not in the case of drawing on the screen because our screen is
actually a width of 500 pixels but just where we are in the grid which is most
important to us right now um is equal to like that value values like one four
three five um so on like that just just to make that clear for anyone who might
have been confused okay so now for drawing um it's a little bit harder just
because of what i mentioned as well is the fact that we need to figure out the
distance between each x value and each y value so when we're drawing
something in pi game it draws in the top left hand corner of the object so if
we draw a cube we're drawing that in the top left so we need to figure out
what that x and y value is going to be for each cube when we're drawing it to
the screen so i'm just going to call this gap here that is going to be our
distance and then the same thing self.w by self.rows and we're going to
change w and rows down in our program later but we can actually just type it
in now like this so 500 and 200 just so we have that set okay so self.w answer
divided by self.rows again that's the same thing we did when we were
drawing the grid to figure out the distance between our x and y values okay
we're going to say i is equal to self.pause zero that's going to save us a bit of
typing in our function here or in our method i'm just going to say
j.self.pause1

so we're just saying i which stands for row j stands for column um like a
classic like convention for it uh so that we don't have to keep typing pause
zero pause one when we move okay so the next one next thing we need to do
is now draw a rectangle we're gonna say pygame.draw.correct like this and
then we need a surface we need a color so self.color and then we need a rect
and here is a little bit of math i'm just going to type it and i'll go through
exactly what what it does j multiplied by this one this minus two this one's
two okay so the reason i have these little plus ones and these minus twos here
is just so you can still see the grid when we draw the rectangle um because if
we were to draw with exactly the dimensions of this distance um then what
would end up happening is we'd cover the white lines of the grid and it just
looks kind of weird if you can't see the white lines um so that's why i have
plus one added here and minus two just so we're drawn inside of the uh the
circle or inside of the square a little bit and you'll see that in a second so what
i'm simply doing is i'm multiplying my i value um which is going to be my
current like row column by the distance that we need to get to the next one
and then same thing for j and then these little add ones minus twos is just to
make sure that we stay inside so a quick quick example if you don't
understand is say we're in a position zero zero so our i is zero and our j zero
we're gonna say i multiplied by distance let's say distance is like 40. okay so
zero multiplied by 40 zero zero multiplied by 40 zero so our position is zero
zero and that's correct because if we're drawing in the top left hand corner
here and we're in position zero zero then that's where we should draw again if
you go something like 0 10 and you or and you move down i guess so 10
you're moving wide down you're going to say 0 minus distance 0 and you're
going to say 10 multiplied by distance let's say it's 40 then we move to that
correct position down the screen so this is rectangle x y with height okay
makes sense now the next thing we need to do is we need to draw the eyes
now you can skip this part if you want i'm just going to copy it in because it's
a little bit of math to make it them like perfectly aligned on the square um but
yeah so we say if eyes and we're saying our center is equal to distance
modulus two uh because that's going to be the center obviously or modulus so
i'm saying divided by two is going to be the middle of r cube and we're
saying the radius that's how big the i radius is going to be and then we go
through a little bit of math here so circle middle is going to be high multiplied
by distance plus center minus radius and then we're finding out the x and this
is just like a random x that i'm setting by just putting it eight pixels up like
every time because i don't want to calculate the x um i don't feel like doing
that and then i'm drawing two circles based on circle middle one circle
middle two and then the radius and a color of black or a color of white
actually sir or no that's black i'm confused alright anyways with all that being
said and done and you guys probably pretty confused right now let's just run
and see if anything's actually happening and you can see we have a cube in
the middle of the screen yay so that's all we've done with all this coding um
so far it's drawn a cube so actually not quite because we still all we have to do
now simply to start having that cube move and seeing our key presses work is
just do a little bit in the main loop so let's move down to the main loop now
and have a look here what we need to do okay so what i'm going to do is i'm
simply just going to call s dot move which is our snake object every time this
main loop runs and what this will allow us to do um is i want to call this
before i read your window is it's going to go up to that method in snake it's
going to check every time that we run the loop if a key has been pressed if it
has we're going to move accordingly and remember that in this move loop
here it moves all of the objects for us so it moves all those cube objects um
and then we're just drawing the grid we're drawing everything in this redraw
function so it'll just display that and update that to the screen so let's see here
and we get an error tuple object is not callable self dot pi zero percent that
they're next um all right one second guys oh it's because i've used

okay so apparently i am an idiot and i forgot to add an equal sign here so the
issue was simply that this looked something like this then i changed it to
square brackets when all i needed to do was put an equal sign like this and
now we should be up and we're working so to reiterate the line here that the
issue is at you guys probably saw this when i coded it to be honest um is in
move in cube it's near the top of the program all you have to do is change this
add an equal sign between this like the bracket and the pause so now that we
run it we can see that we have a moving object and that we can move up
down left right etc so on and so forth like that okay so play around with that
for a second and now we'll get into adding cubes and we're actually almost
done we just need to add the add cube function uh message box a little bit in
the main loop and then we'll be finished okay so what we're gonna do now is
that's all great we're moving around but we need to add stuff to our cube right
like we need to progress the game so to do this we are going to generate what
i want to call a random snack that we're going to place on the screen that our
snake can't eat so the way that we do this i'm just going to say positions
equals item dot body and this item oops shouldn't be item should be item it's
just going to be a snake object i don't know why i'm calling it item but that's
what i'm calling it um and we're simply just going to set like a new list equal
to that list or so on okay so now we're going to say while true

capital t we're going to do x equals random dot rand range if you haven't
imported random yet make sure you do that and y equals random dot range
range rows and rows again should be global so let's make sure that this works
global rows like that and then after this we're going to say if

i don't know how i just typed that but the length of and i'm doing something
fancy here and i'll explain what this does in a second

okay so i know i just typed uh this stuff that probably makes absolutely no
sense to you guys if you haven't been using python for a little bit but pretty
much what this is going to do is we're going to get a list of a filtered list and
we're gonna see if any of the positions are the same as um like the current
position of the snake pretty well so what we're doing is we're saying that we
want to make sure that we're not gonna put a snack on top of the snake
because if we have a really long snake the chance that happens is actually
somewhat high and i didn't do this when i first coded the game so what
happened is when you have your snake moving around the screen all of a
sudden the snack would pop up but it's like on the tail of the snake um which
you don't want so what this is doing and just type it out you don't really have
to understand it is we're saying this this means a function uh z and we're just
checking if the z dot position uh is equal to uh x y so if it's equal to xy which
is the position we just generated here by getting two random numbers so x
and y um then we're gonna have to do this again so we say continue

and else we break like that and then i'm just simply going to return in a tuple
or a tubal whatever you want to call it xy okay so this is confusing but um
you can do this in like a much longer way with the for loop where you pretty
much loop through every position in this list you check it against x and y um
you see if it's the same if it's the same then do this loop again otherwise you
break and you return x y that's all we're doing in there to generate a random
snap any message box gonna leave that and in here now what we're gonna
okay so now that i've created this uh this random snack function what i need
to do is i need to use it so i'm just gonna create a new object i'm gonna call
this snack and it's gonna be equal to another cube right because we want to
have the same functionality we want to be able to draw it uh possibly move it
around right so we're just going to create a new cube object we're going to
give it a position of a random snack which is going to be something like this

random snack and then random snack i believe oh it takes a row and an item
so what we're going to do is we're going to give it row or rows and we'll just
give it our item which is going to be s and then after that what else do we
need for cube i don't think we actually need anything else i think that's all we
need oh i'm going to change the color that's what i want to do i'm going to
change the color equal to green so red green blue 255 for green so that it
shows up it is visible on the screen and now what i'm going to do down here
in this while loop is i'm going to say snack i'm going to check if our the head
of our snake has hit the uh the snack and if it has we're going to add another
part to the body of the snake otherwise we're not going to do that right and
then we're going to generate a new snack and so on so we're just going to say
if s dot body zero dot pause and this is gonna be the head right because we
have it ordered i don't need those brackets is equal to snap dot pause and
remember these are both cube objects so this works fine because they're
going to be tubals then what we're going to do is we're simply going to say s
dot add cube which is a method that we have there that we haven't actually
written yet and we're going to say snack is now equal to well a new cube so
i'm just going to copy this and paste it here so all we're doing is now
generating a new cube for snack i'm sure i could put something in that like
changed it but this is just the way it works okay so now that we've done that
we should be able to move around the screen and get the snack but we need
to code in the add snack method here which i believe i have here or add cube
so the add cube is pretty straightforward we just have to figure out where
we're adding that snack or where we're adding that cube i don't know why i
keep calling it snack to the list so what we're going to do is we're going to
figure out where the tail is and we want to add it after that tail so tail is equal
to self dot body negative 1 the last element in that list i'm going to say dxdy
which again is going to be our direction x direction y i'm just shorting it
shortening it here it's going to be tail dot dern x and tail dot turn y like this
now again you can do this in two lines i'm just doing it like this because it's
faster and now i'm going to copy some again and we'll just go through exactly
what this does

okay so pretty much this looks complicated but all it's going to be doing is
checking what direction that we're currently moving in like the head of the
cube or or the tail actually of the cube is moving in so that we can then make
sure that when we add that um cube we know where to add it so if we're
adding it like to the right of the cube to the left of the cube above it below it
and we can give it the correct direction to be moving in so pretty much um
what we do here is we just say we're going to append a new cube to our body
and its position if we're moving to the right which in here we are because dx
equals one is one less than the x position of that tail so whatever the last cube
is one less than that and that's so that we don't add a cube per se to the right
when we're moving to the right and then we're just going to have overlapping
cubes and you're not going to see them right same thing down here if we're
moving down that means or not down sorry for moving left that means we
need to add the cube to the right side um so one plus that tail the exposition
of the tail of the cube or of the snake sorry so that we can um have it in the
proper position right and the same thing here with x and y uh or with y so that
when we're moving up or we're moving down then we add it above otherwise
we move we put it below so i just stumbled through that um because there's a
lot of different words they're very similar anyways what we need to do now is
simply set the direction uh for that cube so now that we added it in if we just
left it like that it wouldn't be moving anywhere so we just need to change that
to the current direction of that tail so whatever the tail is moving that's where
this new cube is going to be moving in that direction so we're going to say
self.body negative one dot during x equals dx and then same thing down here
except we're just going to change these to y during y equals d y and that again
is just the uh where our tail is moving at that current moment okay so now
that we've got all that done it's time to see what syntax error we get next
name rows is parameter and global one second so i've actually never even ran
into that error oh global rose as okay so let's just make this r and let's change
this to be
one second ah we can just get rid of this and this should work there we go so
now we move around like this the only issue is our snack is not being
generated on the screen and i don't know why that is exactly happening oh it's
because we're not drawing the snack that's why so now i'm just going to
global snack up here i believe that's what i called it and i'm simply just going
to say snack dot draw like that and i got to give it a surface so let's give it a
surface let's run and error name snack is not defined it's because i didn't
global it down here so let's go over that okay so now we have the snack it's
on the screen and you can see that when we collect it we have that cube
added to the end of our snake and that pretty much is almost the game done
so all we need to do now is write that reset method and then we need to just
simply check like when we lose like right now the snake can go through each
other right through itself and you can see we have a huge error when the
snake can go through itself so we need to make sure that when we hit
ourselves um we like end the game and we need to write that message
method as well so to do this um again i'm just going to copy in this for loop
uh and then we'll kind of go go from there so let's move in here okay so for x
and range the length of s dot body we're going to say s dot body x which is
going to be we're just looping through every cube in our snake body we're
checking if the position is in a list of um all the positions after that works um
that's how we're checking the collision if you want to do it your own way um
go ahead but this is the way that i like to do it okay so now what i'm going to
do um is i just want to print the console like their score just so that i know
what it is so say score oops

and then we'll just say plus is the length of s dot body but this is going to
have to be converted to a string unless i put a comma like that so let's just do
it like that and then i am going to simply display a message box will say
message box like this message underscore box uh we have a subject and we
have content and we'll we'll do that in just a second because i haven't yet
actually coded that and then we're going to reset our snake by just doing s dot
reset and this is going to take a position which is going to be our starting
position again 10 10 and then we're going to break out of this for loop
because if we collided once we don't really care if we collide it again and go
back and we continue the game with a snake that has length one now okay so
our reset um this is pretty straightforward all i'm doing in this reset is i'm just
gonna get rid of our turns i'm going to get rid of our body and i'm just going
to change like the direction x and the direction y so maybe it's faster if i just
copy it and you guys can just copy this out so pretty much all i'm doing is i'm
setting a new head which is going to be equal to again like whatever position
we give in because we can move it at a different position if we wanted to i'm
clearing self.body which is again a class variable here and then i'm adding
head i'm setting turns equal to blank direction x is zero direction y is set to
one again so we start moving and you can see it's pretty much exactly what i
have typed out here except i'm just resetting the turns list okay so now that
we've done that all we need to code is message box so this one's pretty easy
um you can see up here just in case you haven't looked yet um i import
tkinter sdk and then from decanter import message box now this is how you
create a message box in a pie game and this is how you create one that
actually shows up on top of the screen and that doesn't like float kind of
below it or doesn't show up right away if you want to say that um so just
watch this is extremely useful to use in other programs too if you if you copy
out this uh function and then you just drag it into other ones so attributes

topmost comma true what this simply does is we're creating a root oops
which is not root.tk it's root equal to tk.tk which is going to be a new tkinter
window we're making sure that this window is going to be on top of anything
so if we have like a bunch of different windows open it just comes up on top
which is what we want i'm just going to simply make this window now
invisible and i'll explain how this works in a second and then from this
message box um what do you call it method class whatever it's going to say
messagebox.show info and then we're going to do subject and content and
this just takes it takes a few more parameters as well if you want but pretty
much this just shows info given whatever subject we type in and whatever
content we have and now i'm going to say try root dot destroy like that accept
oops uh pass and don't ask me what this does because honestly i don't know
but it just works so pretty much it shows this message box and i'm actually
pretty sure the way that this works is it constantly keeps trying to destroy the
message box until eventually you click the x button and then it actually can i
think it's like something like that so anyways that's how you create a message
box and with that we all need to do is add a subject and content so i'm going
to say you lost and our message will be play again

let's run the program for the last time and make sure everything is working so
there we go i just need to get my snake to a length that is uh large enough to
the point where i can actually hit myself

oh okay and there we go so pretty much we ran into an error what is the air i
spelled attributes wrong that is lovely air to run into let's run back up here
attributes attributes attributes where did i even make this function i must have
scrolled path it all right there we go

and i believe that's correct let's try this now

so i'm actually just going to go and see if i can there we go okay so we get a
message says you lost play again and the reason i died there by the way is
because while i was moving right i moved left so technically the head of my
snake actually ran into another part of it so it says you lost play again and you
can make that say exactly what you want and then we can see that our guy
just continues to move so on so anyways if you guys want to see more
content like this go check out my channel it is named tech with tim and i have
a bunch of videos teaching stuff like pie game and doing a bunch of python
tutorials you guys will definitely learn a lot falling through some of my
videos and i would be very grateful if you guys went over there and liked
some of my videos and subscribed

what's up guys in this set of videos i'm going to show you how to program
connect 4 in python by the end of these videos we'll build something that
looks like this

it's a simple two player connect four game with graphics i think this is a
really good exercise for your beginner to intermediate level python
programmers who want to build their skills i'll just finish up a game real
quick just so you can see how this fully works as you can see i have the
diagonal and it says player one wins cool all right so more specifically in this
first video we're going to do something a little bit simpler and then build up
to that graphic based connect 4 game so by the end of this specific video
you'll have something that looks like this it's a command line connect four
game where you actually manually type in numbers to drop your pieces so
you see the one there the two etc alright so let's start building that just quickly
i want to mention that i'll be programming in python 3 and then using
sublime text 2 as my editor i posted a link to a video on how to set up these
things in the description so one of the first questions i asked myself when i
was writing this game is what is the best way to represent the board so if i
drag in a connect four board real quick you can see that it is six rows by
seven columns and to me this looks like the perfect structure to represent as a
matrix in python so that's what we'll do so we'll define a function called
create board and that's not gonna accept any inputs and then we're going to
make a a matrix of all zeros with the dimensions six by seven and to help us
do this we're going to import a package called numpy and if you haven't
already installed this you can open up a terminal window and just type in pip
install numpy and as you can see i already have it so we're going to use this
as follows we're going to say board equals numpy dot zeros and that's going
to make a matrix of all zeros which is good for our initial state and then the
dimensions six rows by seven columns cool and then we just need to return
that board and we can test to make sure that worked by doing the following
create board and then print board and as you can see if i run oh no what
happened as you can see if i run that we we do in fact have this six by seven
matrix of all zeros so that looks good we can begin writing the main game
loop now so we're gonna write a loop that says while not game over and so
our loop is going to be running as long as this game over variable is false and
the only way it becomes true is if someone has a four in a row so we need to
initialize the game over to be false to begin with equals false and the only
way that's going to switch to true is if someone got a four in a row so now
we're going to need to we're also going to want to real quick make our board
initialize before we start the game just so we have something to put pieces
into so we have our board we have our game over variable and now we're
going to want to be able to ask

for player 1 input

and then we're also going to want to eventually be able to ask


ask for player 2 input so this kind of leads us to the problem of oh how do we
differentiate between whether it's player 1 or player 2's turn so we're always
going to define another variable up here called turn that's just going to
initialize to zero so what we're going to say is if turn equals equals zero then
we're going to want to ask for player one input all right so in python there's a
function a built-in function called input as you can see it highlights blue for
me so we're going to say selection equals input and then

we're going to say player 1 make your selection so this is what the player one
is going to say and then the way we're going to initialize this game is we're
going to just say they can type in between 0 and 6. so this is what the player 1
should see so if i build this you see we run into this error so this is because
sublime text doesn't accept this input function so my work around for this
was i installed a package in sublime called sublime repl i'll put a link in the
description on how to install this and i can run the input function through that
so now you can see player one make your selection three and it doesn't do
anything with that input right now but you can see that it's asking me that and
i can type in hit enter all right cool so we also just want to make sure that it
saves our selection properly so we're going to print selection i also just want
to see you know if i type in a number does it actually give me the number or
does it give me a string that represents the number so i'm going to also print
in type of selection i just want to see what we're getting so i'm going to run
that again and as you can see error again but we're going to go to supply rpl
and the link is in the description as i just said run current files so 2 and as you
can see it gets 2 but it says it's a string so we're going to want to make sure
that it's actually a integer so we can just surround this with int input on and
this should work so let's see run that again and you can also run this through
the command line so if you run this in your terminal go to the the directory
that the file is in and type in python and then file name it will also run it just
as i'm running it in this sublime rapl uh player one make your selection three
cool and now he says it says three and it says the class of that is an int so that
looks good to me so now you can save some sort of selection from the user
and you can also edit this so that it requires you to make a specific num type
and a specific number but we'll just leave it as like we'll imagine our players
are following the directions right now all right cool we have that and then
we're also going to want to be able to ask for player 2 as input so that's going
to happen else otherwise so if the turn is not equal to 0

then we want to ask for player 2 input so selection equals and we'll just copy
this from above

and we'll just have to change just to say player two make your selection all
right cool and now at the end of the turn no matter whose turn it is we're
going to want to increase are turned by one so turn plus e or plus equals one
so i'll make it increment it by one and then we're also what we're gonna also
want to do is we're gonna just make this odd even so we're gonna use mod
division so it's going to be turn mod 2 turn equals turn mod 2 and this is just
basically making it go uh take the remainder of whatever our turn is divided
by 2. so this is just going to alternate it between zero and one so it will
alternate between player one's turn and player two's turn so let's just see if
this works properly so we're gonna run this build python current file player
wanna make your selection two player two make your section four player one
make your selection two oh that looks good it's alternating between our
player one and our player two cool okay and now we're going to want to start
building our actual functionality we're going to want to be able to make this
selection right here actually drop a piece into our board so i'm going to find
another function up here called definition drop piece and we might define a
couple functions so maybe have a drop piece and then we'll just do pass for
now and maybe we'll also have like is valid location so that will check
whatever number that the player typed in we'll check to see if that's a valid
location we'll also define a function called get next open row and how all
these functions are going to work together is as follows so it all begins with
the player making a selection the zero to six here represents the column that
they want to drop their piece in so maybe a more appropriate title for this
would be col representing column col next we're going to take this column
and the current board we have and pass it into this is valid location function
so board column and to visualize how we can check to see if the column they
selected is a valid location we will print out the board real quick

so as you can see imagine this is the zeroth row is the first row second row all
the way up to the fifth row here and then this is the zeroth column first
column second column etc we're starting at zero as our first index so if we
wanted to check if the column that the user selected let's just assume that the
user always types in a valid number zero to six if we wanted to check to see if
it's valid all we need to do is make sure that this top row for that specific
column is not been filled so let's imagine that we're putting ones in for player
one going and two's in for player two going so if this top row is still zero for
the specific column we selected then we know that it's okay for us to drop a
piece in that row or in that column it hasn't been filled all the way to the top
so do that so this is the fifth row so all i'm going gonna do is just check to see
whether or not the position at the fifth row and let's say you know whatever
column we select is zero and if it is that means the column is still free if it's
not then that's not a valid location we'll have to have the user try something
else so to do that let's just do board so we're going to return board and then
the row is 5. and the column is whatever the user selected so here so and
we're going to make sure that's equal equals zero so if that's true then we're
good to we're good to let them drop the piece there if that's not true that
means the column has been filled up all the way and one thing i'll note that
will probably change in a future video is that it's kind of getting messy in my
code a little bit with just throwing these random numbers here all the way all
over the place and programming these are called magic numbers you kind of
don't know where they come from so i'll clean those up in some of the future
videos in the series so return board five column equals equals zero and that is
just checking to make sure that that column has an empty slot okay so now
that we've gotten the valid location let's get the next open row in that column
so if we think back to our board that's just checking to see when we drop it in
let's say the zeroth column here on the the left checking to see which row of
these the piece will fall on so to do this we're going to write a quick little loop
so we're gonna do

four and we're gonna also have to pass in the board and the column into this
one so the loop we're gonna write here is for r and range and i'm actually
going to start getting rid of some of these magic numbers so i'm going to
initialize a

global variable called row count and often globals are capitalized just to so
that our static variables that don't change or capitalize just to show that
they're a non-changing variable so the number of rows we have is 6 and the
number of columns we have is seven so i'm going to do for r so for row in
range so the number of rows we have so row count

and we're going to check the board position we're going to see

if board our position or so the column equals equals 0 then we want to return
that row so basically if the row is equal to zero so imagine we're filling this
whole board up with ones and twos if the slot is still zero that means it's
empty still so we're going to return the first instance that it's empty so this r is
going to count from 0 to row count minus 1. and we're going to return that
first case where it equals 0. okay so now we got the next open row and then
finally what we're going to want to do is drop the piece so this is going to
take in the board the row and the column and then we'll also add something
we'll just call it the piece so whether it's player one or two going so all this is
gonna do is go board row column equals equals the piece so we're gonna
make it fill in the board with whatever piece that the player just dropped so
let's put this all together in our loop so first we got the column and now we're
going to check if is valid location of the board in the column and then we can
start getting the next empty row so row equals get next open row and that
takes in the board and column as well so get next input and row board
column and then we're gonna finally drop piece and we're gonna take in the
board the row the column and then for player one the piece is just the one and
we're gonna copy this in to player two as well because player one and player
two the functionality of what they're doing is the same but we'll just have to
change the piece here to two so now and then finally probably after the player
goes we'll probably want to print out the board so we'll print the board here
and let's see what happens now so tools build oh shoot sorry supply maripl
python run current file so player one selection we're gonna drop our piece
right in the middle so that's zero one two three this is the third column so
three uh what happened why did it not fill in let's figure out what exactly
went wrong there so should have updated the board but for some reason it did
not um so let's see

okay i see what i did wrong here so i accidentally put in two equal sign here
and what we're really trying to do is an assignment we're not trying to set see
if the boardrow column position is equal to that so i didn't assign it so now it
should work so we'll rerun this so tools sublime repl

python run current file player one make your selection we'll say go to the
middle three player two make your selection we'll do three as well player one
make your selection and as you can see one issue we're having right now is
that the pieces are starting at the top and going downwards and so the reason
for this is our convention was to say that this was the zero zero index but in
the actual numpy they represent this right here as the zero zero index so i'm
just going to add an additional function real quick called print board and all
that's going to do is change the orientation so that what we're seeing is
actually the the flipped over the way we're expecting to see a connect 4 board
kind of be building from bottom up so print board and we just need to pass in
the board and all we're going to do is there's a command in dumpy so the
command is

let me just remember it it is np dot flip i'm going to do board and then you
have to flip it over you have to specify the axis so the zero is the axis i'm
going to flip the board over the x-axis so that should get it upside the the right
side up again so instead of doing a print board here we're gonna now call our
new print function so print board and then board and we can also do that
down here if we want to print uh it doesn't matter i guess to start but print
board whatever okay now let's run it again tools it's primary pl python run
current file player will make your selection three three three and as you can
see now it's building up from with ones and twos um just how we expect
okay that's all i'm going to do for this video in the next video i'm going to
kind of build in the functionality of actually checking for wins with these
ones and twos and then in the next video probably after that we're gonna
actually add the graphics so make sure you stay tuned for those videos all
right thanks for watching this one guys see you in a bit

what's up guys and welcome to the second video in the programming connect
4 in python series at the end of last video we had something that looked like
this it's just a simple command line based connect four game and the one
problem with this is that if i actually won this game so as you can see i just
went with player one down the bottom the game doesn't let me know at all
that i won so we need to implement that functionality so we're gonna define a
function called winning move and we're gonna have that taken the board and
then the last piece that was dropped

so winning move there's a bunch of different ways to implement this and the
way we're going to do is not the most efficient method but it's probably the
easiest to describe in a video so that's kind of why i'm selecting it but we're
going to manually check all the different possible places you could win in
connect four so all the horizontals all the verticals and all the diagonals and
check to see if there is a winning combination on the board and because we're
doing this after every turn we're going to pick up the first instance of that
winning combination so we'll know who won probably the more practical
way would be to just check around the spaces where the last piece was
dropped but that code got a little bit messier when i was doing it before so i'm
gonna just do it this way so we're gonna first check all the horizontal
locations

and to do that we'll have a loop that iterates over the columns so for c in c
range column count and so we defined a column count up here above and
that's seven and one thing uh i think would be a cool challenge for you guys
to try that i don't think my game is going to be able to do at this point in time
is a very well designed like connect four game you would be able to change
these numbers so like i could change it to say like 12 or something and this to
like eight and the game would still be able to work you still have like a
connect 4 game but just a bigger board and so that's like kind of a cool way to
make sure like you've designed things in a smart way where you don't have
just these random like magic numbers popping up all over the place and i'm
actually going to change this real quick to row count and column count just
because i'm going to try to eliminate the magic numbers where i can and we'll
clean this up to row count minus one so this is the last row the left index of
the last row okay getting back to winning move so we want to check
horizontal locations for the win so we're going to first loop over all the
columns and then we're also going to have a loop over all of the rows and
what this loop is going to be over is not every single position but over all of
the possible starting positions for a horizontal wind so if we think about our
board a horizontal wind can start this spot this spot this spot and this spot it
can't start here because you can't go four over from this location so this is our
last column the third column in terms of indices and then upwards we can go
all the way to the top vertically because it can so this half sorry you can't
really see but we're making a box around that half is where our starting
locations can be for this first um this first check so we're iterating over the
columns so it can only be the number of columns and then we have to
subtract three because three of those columns couldn't actually work so we're
subtracting three off of that one and then all the rows could work so that's
totally fine so now we're going to check all the four in a row location so this
is going to look like something like that so if board

row column so this is just indexing the matrix equals equals piece and board
row c plus one so this is taking the next one to the right so we're checking
horizontally so we're only changing the columns equals equals piece and
board r c plus 2 equals equals piece and then finally and board this is the
fourth piece in a row board c plus three equals equals

peace

then we're gonna return true

so we want to return true the first time this happens we're not going to return
this expression because that would return that would break out of this loop
before we wanted it to okay and so what we're writing right again this is not
the mo the best way probably to write it you know we have these magic
numbers popping up but it's just a very simple way to check for all those
horizontal locations right so let's do the same thing with vertical locations
locations for when and actually before i do that let's just uh check to see if we
can get some functionality on this so if validation and we're gonna also write
a if statement that says if winning move

and so we're gonna say

board and then the piece is one so if it's winning move we're gonna just print
out uh

player one wins congrats yay


okay let's just see if that works with the horizontal real quick and then we're
also going to want to set this game over variable to true because the game is
in fact over if the move is winning so let's just run that real quick python run
current file okay player one make your selection three

yay it says player one wins and we i guess accidentally printed the board out
one extra time but you know we did get that functionality it did check that
horizontal wind so i think that looks good obviously um you'd want to test
these like very thoroughly but for the sake of the time of this video i'm going
to just start going to the horizontal the vertical location so if you think about
where vertical locations can start um you can start we need four up so it can
start it's pretty much the opposite of the ver the horizontal so vertical could
start all of this bottom section because we need four up but it can be in any
column so it's gonna be pretty similar to the last loop but we're gonna have to
change the row um so you'll see in a sec shift tab tab

we're gonna have to change instead of the column count doing uh for c and
column count minus three we're gonna have to do row count minus three
because we can't start at the top row and then we're gonna have to add these
pluses to the rows actually row plus one row plus two

and the last one is row plus three and once again like see if you could figure
out how to manipulate this um these equations to work for any length of a
board and also let's say maybe we wanted to make a game that was like
connect six like it'd be a cool challenge for you guys to try to build these
functions so that they could be any number of columns any number of rows
and any number of pieces for the winning length okay so let's check to see if
the vertical locations now work we're going to run this again real quick so
tools

python current file three

cool it works again so we see you have the four in a row with the ones right
here and it says player one wins congrats so that looks good uh now we have
to get to the little bit of the trickier um things we have to check for the first
we'll check for the positively

sloped diagonals and we're also going to make a separate method to check for
the negatively sloped

and you'll see why we need to do this in a sec diagonals all right so let's think
about it we're going to think about it the same way where are our possible
starting locations that we could have a positively sloped diagonal well we can
start here and go up we start here and go up here and go up so i think the last
piece we can start here and go up so this is going to be the top row and we
can't go any farther than this piece right here so that looks like we're doing
row count minus three and column count minus three so

all right so we're gonna we'll just copy this code see oh no what happened see
and i'll paste that in right here all right so we're gonna have to subtract three
from column count and from row count and then how this is going to
increment is you start with that initial starting location and then we need to
plus one to both things because it's a slope it's not just a horizontal or vertical
now so with a do the addition step for both of these okay cool and as we've
been doing let's just check to see if we can get a diagonal win here so player
one make your selection i'll just start in though

all right we're almost there

uh so close don't screw this up now keith okay and we'll check here cool the
diagonal there worked so that looks like it's working too and then finally we
need to do the negatively sloped diagonals

and so if we think about negatively sloped diagonals they can start at the top
and go downwards but they couldn't start any lower than this right here this is
the the last one they could start at because they have to go down four so that
looks like it would be the top rows and then also the columns minus three so
we're going to start the rows at three and we're going to have to start the
columns in the normal normal location so this is going to start from three to
the row count and so it's three because if you think about it z this is the zeroth
row this is the first row second row third row so even though it's actually the
fourth up it's third index so that's why we're starting at three and that's going
to go all the way to the top and the column counts actually good as it is and
so this is going to have to now go it's going to go positively over in the
column direction but it's going to go down a row so negative 1 here

negative 2 here and this is just a negative slope you you know you have one
direction positive one direction negative and this will be negative three so
let's test to see if this works come on

rpl python current file okay we'll just build up the left side first

okay two

okay

okay okay okay we're almost into the negative diagonal there so player one
you can go three and then player two two and then two cool the negative
diagonals work now too okay so that looks like we have all the possible
winning directions you should more thoroughly test to make sure the all the
edge cases work but to me that looks pretty good so we're also going to
implement the functionality for player two in this main game loop

okay so this is player two player two wins congrats game over true okay and
if you wanted to you could just break out of the the loop if you didn't want to
see this board and the turns changing at the end okay so that's we've now
finished the command line version of the game so we'll start building out
probably in the next video we might clean up the code a little bit and then
we'll build out the graphics okay see you in a bit

what's up guys and welcome to the third video in my programming connect 4


in python series in this video we're actually going to implement the graphics
for our game so at the end of the last video we had something that looked like
this it was a fully functional command line based connect4 game so we're
gonna take this game and we're gonna expand on it to actually make it look
nice so the first thing we're gonna do to do that is import a library called
pygame and just like the numpy library if you don't have pi game installed
just open up a new terminal window and type in pip install pygame as you
can see i already have it cool all right and now what we're going to do is
we're going to have to start out by initializing pot pie game so this you have
to do in any pie game project so before our game loop starts we're going to do
pie game dot init

okay and then what we're gonna have to do is define our screen size how big
do we want our game to be so if i real quick just build the finished version i
have you can see that you know it's pretty you know you can kind of break
this game down into squares i would say you have squares that represent each
column in each row and then i have this one extra row at the top so we're
going to define each one of those squares as 100 pixels so the sizes we're
going to talk about right now are all in pixels so the square size is going to be
100 pixels and then our width for our screen is going to be the number of
columns so the column count times the square size cool and the height is
going to be the row count times the square size and actually if you saw my
the game i just dragged in i'll drag it in one more time i actually added one
additional row because i wanted this spot where i could display this circle
that i'm dropping so we'll actually make this row count plus one times square
size for the height

and that will be packaged together nicely in a variable called size which will
be a tuple of width comma height and then to get pygame to actually read that
we need to type in the following screen equals pie game dot display dot set
mode and then we'll have it read in the size and if you're wondering where
i'm kind of just magically getting these functions from i'm looking at the
documentation on the pi game site so if you go to pygame.org docs you can
find all the kind of functions that i'm using i'll post a link to that in the
description

i'm going to real quick test to see our screen is actually working so you can
just run control b and as you can see the window popped up and then it
disappeared we'll handle why it's disappearing in a second so it looked like
though it is reading in that screen cool so let's now create a function called we
do a couple things so i think first we'll define a function called drawboard and
this will just be like print board that we defined up here but now we're
actually going to draw it with the pie game graphic so draw board is going to
have to take in the board and that's about it and i'll actually pass this for now
because we're going to make some changes to our loop before we do this
draw board so the first major change we're going to do to our loop is pi game
is an event-based game library so pygame kind of works and allows you to
function in the game by just reading all of your movements of your you know
the keys you press the mouse buttons you click the mouse like how you move
your mouse it reads those all in as individual events so that looks like
something like this so for event in pi game dot event dot get and as i just said
events are like mouse motion mouse button down key down etc so we're
gonna read in we're gonna drop a piece by clicking down so that's one of the
important events we'll have to get so we're going to first do just kind of
follow me on this one event type if event type equals equals pie game dot quit
so this is just something you want to handle in all of your games that you
make just allowing your game to properly exit out if you click the button here
in the top right that x out x is out of it so if that happens we have to do a
system exit just so it properly shuts down and to get this sys right here we're
gonna have to import that into our project as well that means system and that
comes default in any python installation

okay system exit now to get to the more interesting stuff the event that we
really are going to care about to start is um mouse button down so if event
dot type equals equals pi game dot mouse button down and all the different
events you can also find on the pie game website under the docs the game is
going to run by us clicking down on a specific spot on the screen where we
want to drop the piece so instead of reading in the column we want to drop it
in as we did previously now this column is going to be populated by where
we click so i'm going to real quick put all of this stuff all this behavior into
this mouse button down event type because now the events of us dropping the
piece always happen when we click the mouse button down so we don't want
it to happen otherwise we don't want it to be asking for this input all right so
column equals and this is going to be where we click on the screen so just for
now i'm going to just kind of comment out this stuff just so it doesn't run on
us while we're testing control and that's just real quick see if this fixed our
error of
the screen disappearing right when it pops up

uh what happened

prince

and as you can see now we have this screen and it's not you know it's staying
here so that's because we actually added in this event loop here it knows to
kind of continue while these events are happening and the exit out will be
handled properly by this the system exit cool all right so we have our screen
looking pretty good but doesn't have any graphics obviously

so we're going to implement the drawboard function now so if we think about


it i'll drag in the finished one i have again we're going to draw some sort of
rectangle for each of these slots and then a black circle inside those rectangles
and then we'll have to draw this afterwards this piece that we drop and then
whenever we do drop a piece the one or two that's in our command line based
game will become like a red circle or a yellow circle based on what we're
doing so let's implement this

so

first we're going to iterate through kind of every spot in our board so for r or
for we'll say c in range column count and then we'll do the same thing for r
and range row count just as we did above here when we're iterating through
all the the spots well we need to initially just draw it as like an open you
know a blue blue rectangle and then in that blue rectangle we want a black
circle so we're going to do a pie game.draw function so first we're going to
draw a blue rectangle

so that looks like kind of our game board and then the black circle inside of
that will be the open slot so we're going to draw that on the screen and i'm
going to drag in again the the light the the library so i can see exactly what
i'm doing so as you can see here pygame.dry out wrecked we need to take in
the surface the color the rectangle we want to draw and then the width so the
screen is the surface we want to draw it on the color is we want a blue color
so i'm going to define blue as a global variable global static variable up above
this is going to be an rgb value so we're going to say it's 0 0 comma 200 and
that means or 255 or so so that's gonna be a very blue um rgb value because
this means red this means green and this means blue and the only color that's
actually has some value is the blue here so the color we're going to say is blue
we just defined that that's the rgb value now we need to define our rectangle
so our rectangle is going to be either you need to have four different things to
define your rectangle you need to have the size of the width and height and
then also the position so the position is going to be this might be take a little
playing around with to get this but it's going to be c times so these are
numbers zero to you know the column count and zero to the row count there's
gonna be c times square size because we want the actual this is the top left
corner of it and that's going to the

and then our position on the y-axis is going to be r times the square size

and our height and width are going to be the other two parameters of this uh
what that make up a rectangle object and that's just going to be it's going to
be a square so it's square size square size height and width are the same and
the width op argument that i showed was in the documentation as you can see
it's defined as zero so that's optional i think that's just the uh outline like uh
the line that surrounds the square so we don't need to implement that all right
let's test to see if just these rectangles draw properly so down here we'll just
do a draw board taking the board as we did here and then what we have to do
whenever we want to update our display is do pi game dot display dot update
and that will make sure that we actually see what we're supposed to see so
we'll build that real quick oh and as you can see we have this just giant
mound of blue and the one problem i see right now is it's not actually opening
up the i wanted the top to be open so we could have a piece that uh swings
around it so it shows us where we're dropping it so i think the problem with
that is because our axis starts at zero zero we actually need to to shift down
by one square size to kind of account for that offset that we left for that space
so we're gonna have to add a square size here now we build this again and as
you can see it looks proper now we'll need to fill in some circles to represent
the the slots so we'll do that by drawing a circle in pi game and that's also in
the documentation so we do pygame dot draw dot circle and that's going to
take in the surface of a screen and now we need a color so i think a good
color would be just black so we'll define black up above too and black in rgb
is just zero everything zero zero zero okay so this is black and then let's drag
in the documentation real quick to see how we're gonna finish off this circle
so circle circle circle okay position and then radius so this is going to be the
position of the center of the circle as you see in the documentation and the
radius will probably want to be a little bit smaller than our square size just so
there's um the circles aren't touching so let's define a radius two so our radius
is going to be and define that under the width and height and whatnot so our
radius is going to be a little bit less than the square size so we'll do i'm going
to make this also they have to be integer values i believe so once we start
getting into division it might get a little bit messy so it's going to be int square
size divided by two because it needs to be the radius is half the diameter and
the diameter would be the full square size then we'll just minus an arbitrary
like integer value off of that

so now we can draw our circle with that radius but we'll have to do the
position first so the position where is it i forget oh it's in dropboard the
position is going to be so if this the top left of the rectangle our position for
the center of the circle is going to have to be that then with some offset so
square size then r times square size plus square size and the offset is going to
have to be like half of it because we're talking about the radius so half of the
rectangle is going to be adding an additional square size divided by two

adding a square size divided by two all right let's see what happens now oh
and then actually we're gonna have to do the actually specify the radius so the
radius is what we defined just a second ago build what happened uh yeah
integer argument expected okay so it looks like this division caused us to
have some floats in our code so we're gonna have to actually make this int
yeah pie game it seems like only accepts integers so make sure that
everything you every position and radius value you make a integer come on
baby let's go

cool yeah we got a board all right i think that's where we're going to end this
video we'll actually animate the dropping of the pieces and then the kind of
the piecing hovering over here and the text saying you won in the next video
alright see in a bit

what's up guys and welcome to the fourth video in my programming connect


4 in python series in the last video we implemented the background graphics
for our game but if i click around on this screen nothing actually happens so
in this video we'll finish implementing this graphics we'll implement the
piece dropping and then a nice little piece follower up here just a few quick
notes before i begin if there was a feature you wanted to know how to
implement but that i didn't actually cover myself in these videos feel free to
leave a comment down below and i'll try my best to get back to you as
quickly as possible also if you enjoyed this series please please please leave
me some suggestions for future programs that i can write make tutorials on
i'm always looking for new content all right let's get started so to start this
video navigate down to the main game loop before when we were selecting
which column we wanted to drop a piece in we mainly typed in a number
between 0 and 6 to specify this now that we have a graphic we want the
column that we dropped the piece in to be dependent on where we click so if
i click on the left side of the screen we want it to drop the piece in the left
column if i click the middle the middle column etc so where we drop the
piece depends on the x position of our mouse pointer so luckily for us
pygame makes using the getting the x position of your mouse super easy so if
you go to the pi game documentations under the events it lists all of these
events and then it lists the properties you can get on these events so for us we
care about mouse button down and we care about the position so position
gives us an x comma y tuple of where we clicked and i can use that as
follows so i can do print event dot position and then i can rerun our game and
so as i click on the screen you'll be able to see in the bottom left the positions
where i'm clicking so if i click in the top left of the screen it's about zero
comma zero that's where our axis starts if i click on the bottom right of the
screen that's the the full dimension of our game and we specify that to be 700
700 so these are the pixel values of where we're clicking

to develop a kind of way to select the column based on where we click we


need to try to find a pattern on clicking in these different columns so i'm
going to do that real quick and if we look at all these clicks i just made we
can see the first click is between zero and a hundred second click is between
100 and 200 200 and 300 etc so the last column is between 600 and 700 so
we can somehow round these numbers down to just give us zero to six we're
back at where we were when we mainly typed in those numbers so we're
going to do that real quick so let's we can go ahead and uncomment all of this
code and actually this is supposed to be a comment so we can uncomment
this code right here and we can just comment this out for now so column so
we want that to be

we'll say that the x position so this is a tuple in the x values first so the
position of x is equal to event dot position and then it's the zeroth element of
that

the column now is going to be so this is between zero and seven hundred so
the column we can get using we're gonna also just to make this our life's
easier we're gonna import a library called math this comes default in any
python installation so we are going to get what we want to drop it by doing

position x then we're going to divide everything by a hundred because this


would give us a range between zero and seven instead of zero and seven
hundred so the first thing we're gonna do is divide it by a hundred and 100
remember is what we define our square sizes so to make our code a little bit
more robust to changes we're going to do position x divided by square size
and then we want this to be a whole number an integer value so we're going
to have to take the floor of this division so that will round it down to the
nearest integer so we're going to do math.floor

and then the final change we're going to have to make is we just need to make
sure that the column is an integer because we don't we can't take the index of
a float value of decimal value so we'll just ensure that it's integer by just
surrounding with the int and now we should be able to see when we click on
the screen we should see our board building up and we can copy the same
thing for player two and we'll uncomment this

comment that uncomment all of this and then we'll make player two be able
to select the piece in the same way so we'll say position x equals event event
opposition zero and then the column now
oh my god messy okay we'll delete this line cool so let's see what happens
when we build the game so now we have this uh where's the actual game
window what happened oh it like didn't pop up for some reason so click
down the middle if you can see over here in the bottom right our game did
pick up that click so i click on the middle again keep clicking on the middle
and it keeps reading that i'm dropping the pieces in so that looks really good
now we actually have to just represent that on the screen so to do this we'll
just make a small change to our drawboard function that draws the graphics
so navigate to drawboard and we'll just do a if statement here just say so the
rectangle is always drawn the blue rectangles that make up the the board the
black circle represents the empty square so if board i mean board row

equals equals zero then we want it to be a black we want it to be empty if

else if board our row column so this is just indexing our matrix equals equals
one so that's what we see here player one dropped it in the middle then we
want to draw a circle so we can just copy this line because we know that this
is in the right position but we're just gonna have to change the color up

so we don't want it to be black we'll just use red and yellow player one will
be red so this is going to be red and this is not a built-in thing we're gonna
have to define red so we'll define red right below black these are rgb values
so r needs to be have a value and the other two can be zeros so this will give
us a nice bright red and then while i'm up here doing this i'm also going to
define yellow yellow is both red and green it's a combination of both red and
green and rgb so 255 235 0. so now we have red and yellow for player 1 and
player 2.

where was that okay yeah it's red and then one last line which will be

the else condition that would be if board r comma or r c is two so that's going
to be pi game well actually i'll just paste this in again pi game and then
instead of black we'll make this one yellow

and then one thing that might not be intuitive is that whenever we make
changes to our game board after this is all done this loop has been iterated
through we're going to want to call pygame.display.update that will re-render
the screen with the new changes so let us let us and also we're going to have
to add the draw board we use the word we're printing board on every turn but
we're going to draw a board here as well

okay moment of truth clicking right here no what happened so it looks like
it's populating it's just populating it in the wrong spot and the reason for this
is because of how our axis is set up so as you recall when i click down on the
top left this is the zero zero and this is the 700 700 space so in our game
though this is the zero zero piece but it just kind of flipped so when we
printed the board we called that np.flip function so we're just going to have to
figure out a way to offset this to actually be on the bottom of the screen as
opposed to the top so to do that we can just use our height smartly so what we
really need to do is we're starting at the bottom so we need to subtract
whatever we're actually trying to build up from the bottom from our height so
height minus this height

minus this let's try running this

what is happening all right so we still are having a issue and the reason we're
now having an issue is because this piece right here is still filling in the old-
fashioned way so they're kind of like filling in black and red and yellow tiles
all on different axes so what we're going to do make our lives easier is we're
going to take out these two lines into another loop so i'm going to delete those
real quick and we're just going to do a whole nother loop of so just try to bear
with me here i'm going to copy this stuff we're going to iterate through
everything again this might not be the smartest way but it's just going to be
very clean for us to deal with because we're always going to build our we're
always going to build our background and then fill in the piece afterwards as
opposed to like try to fill in our pieces as we're building the back round so i'm
thinking this will work well uh this spacing is just messing me up and these
lines are so long there we go okay so if board rc is one we're gonna fill it with
that then we can just delete this line bring us back

okay so now we have two loops running but this will kind of fix our problem
of them building our board out on different axises so let's try running it again
what the heck

if board rc equals one uh we're gonna have to make this an elsif otherwise it's
gonna fill out the board

for all the empty spaces at the start of the game equals two all right cool let's
see what happens now it looks like it's working properly but it's just offset by
one square size and that's because of this right here we are initially
accounting when we're building downwards we're initially accounting for this
but now that we're building upwards we can delete that from it from the
height so we're going to delete this square size here we're going to delete this
square size here and we should now fully have it working build

yay it looks pretty good huh all right cool so now that we've pretty much fully
implemented a game with graphics we're going to add a couple additional
features so the first feature we're going to add is add this little scroll wheel so
that before we drop a piece we can see what color the piece is and where
we're going to drop it so to do that we're going to add a new event we're
going to track a new event and that's going to be the event type equal to pi
game dot mouse motion and once again all the different events you can use
are listed in the pi game documentation and just like mouse button down the
mouse motion also has a position property so i can do position

x equals event dot position zero so this is going to get me a lot more events
though because it's always tracking whenever i'm making any motion so this
is going to be constantly updating so now we're going to use this position and
draw some circles based on where that position is so if the turn equals equals
zero that's a player one's going then we're going to do pygame dot draw dot
circle screen to the surface color is red because it's player one um the next
thing we need to put in the circle is the position so the x position this is the
center of the circle it's going to be at position x wherever our mouse is then
we just want it to be offset enough so that the full circle can draw so we'll just
make this square size divided by two and then finally we need to specify the
height of or the the radius of the circle and that's just the radius we've been
using for all the tiles else this means it's turn equals equals one it's player
two's turn and we'll just copy this and draw it and now it's going to be
actually yellow so let's look what that looks like if we build that

all right build

okay i forgot to get the display update just like we did in the draw function so
pigram.display.update

build oh it looks good but it's just not ever deleting the circles so what we're
going to do to fix this is right before we actually draw the circle we'll just
draw a rectangle that's black that will black out any previous circles that we
have drawn so pygame.draw.rectangle surfaces of the screen color is black

position is going to start at the top left so that's zero zero it's gonna have with
the whole width of the screen and then the height will be a square size
because that's how big that buffer bar kind of at the top is and that should be
good i think i might have one extra no oh yeah i have one extra parentheses
there yay it looks good so now we have this game over drop drop drop drop
drop that looks good cool and so one thing that you also might want to
change is that if i win the game so i'll win the game real quick with uh red it
automatically closes right away so one thing we can do is we can add a
weight pi game has a built-in weight function so what we can do is if the
game over condition is true so if game over we'll call

pygame.time.weight and this is the milliseconds you want to wait so 3000


would equal 3 seconds so if i run this again

one two three and i'll shut down automatically cool and then right before it
shuts down we wanted some notification that the player actually won so
initially we were printing it but now we'll actually render the print function
on our screen so that will look something like as follows so we're gonna
delete the line that says player one wins and we're gonna initialize a font up
top so that will look like we'll do it right below the the first update so we'll do
my font equals pygame dot font dot system font this is all in the
documentation i'm just copying some previous code i wrote and the last time i
wrote this i'd use a font called monospace but there's other options you can
look at the documentation for all the details and we'll do font size 75 that's
just an arbitrary number that i found worked and then if we go down below to
actually render that on the screen horizontally i can type the following i can
say label equals myfont.render

player1 wins exclamation and then i believe this one right here that i just put
in specifies the axes that it's on i'm not actually sure i might play around with
that to check and then we want the color to be red because uh it's rendering
that text red because player one one and then what we have to do to get that
on the screen to do it quickly we could also use the pygame display.update
function but i'm gonna do something a little different here i'm gonna do a
screen.blit and that just updates that specific part of the screen and i toyed
around with these values before i found that the xy pair where this will start
top left of corner of this deck starting at 40 comma 10 worked pretty well so
let's see what happens when i run that so we're gonna have red win

player one wins

and

huh the one thing is that tile gets in the way um what we could potentially do
we could potentially draw another black rectangle if we wanted to um i don't
know i'm not too bothered by it we'll fix it in one sec we're gonna copy this
for player two

and then we'll say player two wins and the color is gonna be yellow now

build so what happens if yellow wins

i'm making this so hard on myself

player two wins yay

all right and maybe what we'll do is at the start of the mouse button down we
will draw that black rectangle as well so we don't have that annoying
annoying tile getting in our way so right before we click the mouse button
down that will make the thing disappear run it one more time

player one wins it looks good and you can mess around with that as you see
fit okay i mean that's like a pretty good game i'm pretty happy with it

so this is going to be tetris in python with pygame now this is a pretty


advanced tutorial a lot of the stuff i do in here assumes that you already have
a basic knowledge of python you kind of know some of the syntax and you're
not a complete beginner that being said if you are a complete beginner feel
free to watch through see what you might understand you're probably going
to learn something along the way i just might be a little bit confusing because
i'm kind of going to speed through a few things that are i would consider like
trivial right now okay so first step for this tutorial series is you guys have to
download and install pygame because that's the module we're going to be
using okay so let's just give a quick preview of what our game is going to
look like so this is tetris um i didn't go too fancy with the graphics i pretty
much just want to make sure that we get everything functional here and then
you guys can play around and change stuff later on if you want to but yeah
this is a fully functioning game you can see it's just like standard tetris we
have different colors shapes are falling down the screen shows us our next
shape and there we go the road just cleared so that's all i'm going to show you
for right now because i want to get into actually uh coding okay so um pretty
much what we're going to be doing in this first tutorial is we're going to be
working a bit in the main function we're going to be uh creating the grid
we're going to be talking about formatting shapes all the basic stuff just
setting up for the rest of the tutorials so the first step and what i need you
guys to do is you're going to download kind of like a starter file okay and
that's just because if you see here i scroll through my file i got a lot of lists i
got a few things set up here and you know what i could go through and type
them all out but that's just a waste of video because it takes a long time so to
save yourself time and to save me some time what i'm going to do is just put
a link in the description it's a pastebin link click that link and download this
code it's just going to be all this it just has all the functions that we're going to
need for this and then it has these uh shape formats which i'm going to talk
about in just a minute so go do that if for some reason paceman's not working
let me know in the comments and i'll find another way to give it to you but
i'm also going to put it in the pinned comment so that you can just copy and
paste it from there as well i do recommend you check the indentation on it
though because sometimes it messes up on pastebin and uh in the comments
okay so now that you've got that downloaded we're working on that i'm going
to be working in pycharm if you don't know about pycharm don't worry about
it you can just use id idle but this is going to save me a bit of time because it
auto completes variables it does some cool stuff so that's what i'm going to be
working on feel free to work in pycharm feel free to work in whatever text
editor you want just know that that's what i'm using it doesn't make a
difference but some of the stuff i do in here you might not be able to do an
idle or subline text or whatever you guys are going to use okay so we've got
that all the way we've got everything set up and now we're ready to actually
start coding and understanding what's going to be going on so tetris is a fairly
complex game you have shapes moving down the screen they're rotating
around they're moving left and right when they hit the bottom they freeze in
whatever position they're in and then if you have a full row complete like
cubes then that road clears and you keep going and obviously you lose the
game if you stack up too many blocks and it goes up or above the top of the
screen okay so this first variables we need to set up is our screen width and
our screen height so we got 800 700 here the next ones are play width and
play height now this is the actual red box that you guys saw that's what these
are representing so since in tetris we have a 10 by 20 grid we need to make
sure that our play width is exactly half of our play height so that we have
perfect squares right so doing the math here that makes it 30 width and 30
height per block so that's our block size of 30 okay so now this top left and uh
top left x and top left y this represents the top left position of our actual play
area that's so when we start drawing blocks and we start checking for like
collision and stuff like that we just have these already set up and we don't
have to deal with that so the math is pretty straightforward uh you guys can
probably figure that out you don't need me to explain that okay shape formats
so these uh and this is the longest part that's why i got you guys to copy
everything is this is what's going to represent our shapes in tetris now you see
that i have multiple lists inside of lists in most cases this is because each
shape has possibly more than one rotation right so this is the standard rotation
of the s shape and that's actually what they're called in uh tetris like s said i o
whatever and this is the second rotation and these are the only two rotations
or whatever that s can have so that's why we have them in here we have a five
by five grid of periods and then whenever there's a zero that represents where
the block actually exists okay so zed you can scroll through you can kind of
look at them and you can see for some of them for example the square well it
doesn't have any rotation if you flip it it's going to look the same so we only
have one list here for j uh however though we have four right because we can
rotate in different ways l we also have four t we have four as well okay after
this i create a list and it just holds all of my shapes so s said i just so that that
way i can really easily select shapes just by indexing them in the list like zero
through six and shape colors here is the same thing it just corresponds like for
example if i did shape zero and i did shape color zero then that's gonna be the
color of shape zero okay same thing with like six so shape six well color list
or shape color six is the color of that shape um so it just makes it really easy
we don't have to deal with dictionaries or anything like that okay all right so
now we've kind of gone through the like starter file i'd say and you can scroll
down here you can look at the function names i'm not going to explain them
because most of them are pretty straightforward and i'll talk about them when
we start coding them anyways but we do have a class here now this class is
going to be the main kind of data structure if you want to call it for our game
and this is going to represent or this class is going to represent different
pieces so the reason we have the class is because we're going to call this a
bunch of times and it's pretty much just going to hold the information like x y
with height for our piece so let's actually start coding this now so i'm just
going to create my initialization function or method and this is actually the
only method that i'm going to have so i need another underscore just
butchered that um and pretty much what this is going to have is going to have
an x a y and then it's going to have a shape okay and that's the only
information we need for this and i'll show you why so we'll say self.x equals
x self.y is equal to y self.shape is equal to shape and then what we're going to
do here now is we want the color and we want the rotation so self.color well i
was already talking about this self.color is just equal to whatever the index of
this shape is in this color list so what we can do is we can do shape
underscore colors square brackets and then shapes dot index and whatever
shape we were given so if we're given the shape s well let's just find it in the
shape list whatever index that is well that's the color of our shape pretty
straightforward um and then we're going to do a rotation so rotation this is
going to set default to zero and this is so that whenever we click the up arrow
key we can just add one to this rotation and that will represent what shape
we're actually going to be showing because again remember the shape list is a
multi-dimensional list it has you can see here in this case four lists within it
okay all right create grid um i don't know if we want to do this one yet you
know what actually let's go let's go ahead and do this one uh it's not too
complicated so the way that i'm going to represent the grid in tetris so that 10
by 20 grid is just by creating a list full of colors okay so we're going to have a
two-dimensional list and within that second dimension it's going to represent
a bunch of colors okay so i'll show you just by coding and kind of talking
about after say grid is equal to and then another square bracket here for x in
range 20. and don't worry i'll explain this in one second and then we'll say 4x
in range 10 okay except here we're just gonna do zero zero zero okay so what
i've just done here this is pretty this is like the python way to create lists okay
uh list comprehension we're gonna create one list for every row in our grid so
since we have 20 rows we want to create 20 sub lists and each of these like
sub lists or whatever two dimensional lists is going to have a bunch of colors
in it how many colors is going to have well it's going to have 10 colors
because we have 10 squares in each row we have 20 rows so that's the way it
works these x's you could replace with underscores because we don't really
care about the actual variable we just need to do this that many times now
zero zero zero zero or zero zero zero yeah i think that's right anyways uh
that's just black stands for block and the way we're gonna draw the grid is
simply by looping through this grid which we're gonna return and just
drawing each color so it makes it pretty straightforward okay now the only
thing that we have to do here though is we have this locked position uh
argument now locked position well right now we've created a blank grid what
if there's already blocks that have been placed in our grid so like they've
already fallen they're static now they're not moving well we need to also draw
those so to draw those we're going to check if any of the positions in locked
position um are not like or whatever positions are in locked position we're
going to get that color and we're going to change the corresponding value in
the grid i'll show that just by kind of coding it here so for i in range let me do
the length of grid and again this is going to give us 20 because the length of
grid well it's 20 of these right okay so for i and range lineup grid for j in
range and then we'll say the len of grid i because now we're in this list so now
we're going to do whatever the length of that list is okay i'm going to say if
this so if j comma i because j is our x value i is our y value because rows are
represented by i and the columns are represented by j in locked position and
just you know locked pause it stands for locked position it's also a dictionary
so you can see that it's a blank dictionary here and each position so like for
example i had like one one is going to be set equal to a color and the color
could be something like 2550 okay and we're going to talk about that and
create that later but that's just something you need to know for now okay so if
ji in locked position so if that key exists let's figure out what that key is so
that key is going to be equal to well lock position or what the value is sorry
associated with that key ji now we're going to change whatever the current
grid position is here so for grid i j is equal to c okay i know this might seem
kind of complicated but pretty much we're just looking through this grid and
we're gonna find the corresponding position to the locked position and just
change that color in the grid so later when we draw it we get an accurate grid
okay and you guys will see how this all is kind of plays out later if it seems a
bit confusing now okay and then we're going to return that grid um to
wherever we're calling it okay so that that's one part done now we can move
down and we can go into draw window which is the actually let's do get
shape this one's really easy okay so this is literally a one-liner return random
dot um actually what is it called here i gotta have a look i think it's
random.choose random.choice that's what it is random.choice and then we're
going to be given a shape list so say shape actually let's just call it up here
sorry guys shape random.choice shapes all this is going to do is it's going to
pick one of these shapes and it's just going to give it to us so that when we
need to create like a new shape falling down the screen or whatever that that's
all we have to do okay so get shape random.choice that one's really easy okay
next one draw grid all right so what we're going to do is we're going to be
past a surface and the surface is obviously what we're going to be drawing on
so we're going to start by just changing the surface surface not wind surface
dot fill with color this case the color is going to be black okay surface dot fill
zero zero two all right next thing we're gonna do is we're just gonna draw like
a title on the thing so the way we have to do this we first have to start by
initializing the font object so i think we do my pie game dot font dot init okay
this means we're setting up font and we're getting ready to draw to the screen
we're going to create a font it's going to say font is equal to pygame dot font
dot sys capital sys font and then we need the font name i'm the comics fans
guys so i'm gonna use that comic sans uh size of the font i believe yeah size
of the font randy 60 okay so the way you want to set up your own font you
want to change this just change this to any font you can look up fonts on the
pi game website and then just give it a size if you know the name of a font
type it in here it probably exists in in pi game right so now we're going to
need to set up a label so i'm going to say label is equal to font.render and then
in here we need the text that we're going to render in this case i'm going to
call tetris we need our anti-aliasing of one and i believe we need a color in
this case i'm going to make it white okay so text anti-aliasing just set this one
i don't know why you need to set this one but just set it one and then
whatever color you want your label to be okay now that we've got the label
we need to draw this label on the screen so let's blend it not win i'm used to
typing wind surface dot blitz and then in this case we're going to put the label
where do we want to put it well now we want to figure out where the middle
of the screen is so we could just hard code this in but if we ever want to
change the dimensions of our screen we want this just automatically kind of
adapt to that so we're gonna do top left x plus play width over two okay and
that's going to give us the middle of the screen if you don't understand that
um let me know and i can explain it to you in the comments down below
okay now we're going to subtract this sorry this isn't actually done yet by the
width of the label because this is going to matter depending on how long the
label is we it's going to determine where we place it on the screen so we're
going to get the width of the label and we're going to divide that by two okay
so now we need to do the y well the y is pretty easy we can just statically
type this in because it's from the top of the screen so i'm just going to give it i
think like 50 is what i typed in uh 30. okay and that should put it in the
middle of the screen and i can explain that to any of you guys that might not
understand it if you just leave a comment because i don't want to waste too
much time because i think a lot of people might understand that so for i in
range now uh the len of grid because now we're going to start drawing all the
great objects onto the screen so we created a grid we know how that kind of
format works we're going to say 4j in range the line of grid i same as before
and we're going to do pi game dot draw dot rectangle and then this guy's
going to draw on the surface and then we're going to go grid i j okay and then
top underscore left i need to put this in what do you call it brackets here top
underscore left so i just need to scroll over top left underscore x plus j
multiplied by 30 and i'll talk about this one in just a second how this works
and then top left y plus i multiplied by 30. another bracket and there we go
now we just got to deal with this grid thing so that means that we just now
need to pass grid as well into our draw grid okay the way this works we're
going to loop through every color within our grid so this is the color grid i j
alright this is the surface we're drawing it onto and this is the position in
which it's being drawn now we also just need to add two things here that i
realize i forgot because we need the x y we need a width and we need height
so for width and height well that's equal to the block size and block size once
again and you know we can even multiply this instead of by 30 by block size
in case we ever decide to change that so let's do that just to keep this nice and
dynamic and then if we keep going over here the last thing we need is a fill so
we're just going to put comma 0 to make sure that we fill in the shape we
don't just draw like a border for it okay way this works we had our top left x
and we're going to figure out wherever we are so which column we're in
multiply that by block size and that's our x position same thing works for the
y with the starting y position plus whatever row we're in multiplied by the
block size will give us the correct position to draw our cuban okay after
we've done all that we just need to update the screen so game.display.update
and there we go so there's actually one last thing we want to draw and it's that
red rectangle that you guys saw and that kind of represented like the play area
so to draw that we do pygame dot draw dot rect and then surface and then in
this case we're just going to actually let's see here do we want do i want to
dynamically type this in or do i want to just statically draw it so let's give it a
color first of all of red zero zero zero okay and we're actually going to type it
in dynamic just in case we decide to change anything later so top left x and
top left y and then the width oh we actually already have all these variables
so we have the play underscore width and the play underscore height and in
this case we're going to give it a border size of four okay and that's all for
drawing the grid we might come back to this later but for now that's it okay
so this just draws the actual grid ah draw grid and i've added this so okay
we're just gonna copy this part here guys that says draw grid so surface dot
this label and i'm just gonna move this in because i realize i have another
function called draw window so in draw window what i'm going to do is
surface stop fill whatever okay so we're going to take surface and a grid so
i've just copied some of it from there and then instead of updating the screen
here we're going to update the screen over here and we're just going to call
our draw grid uh what do you call it function like this okay so now if we want
to draw the grid and we want to use this same another program we could just
copy and paste this function we wouldn't have to kind of take it out of here
we won't have to like dissect it all right um okay so draw grid again this takes
surface and this takes grid and there we go i believe that's working well okay
now that we've done that we're going to start coding in the main and in main
menu and this is what we're going to finish off with in this tutorial because i
know we're almost at the 20 minute mark right so what we're going to do in
main now is we're going to set up a few variables so the first variable we
need is this locked position locked positions okay and again this is what we're
passing up here into create grid uh it's equal to a blank uh dictionary to set in
case we don't pass it then we don't need it okay so locked positions equals
blank we're going to say grid is now equal to well create grid because we
already created that function with locked positions passed to it we're going to
create a variable called change underscore piece it's going to be equal to false
we're going to make run equal to true this is just for our while loop that we're
going to use we're going to say current piece

is equal to get underscore shape okay we're going to say next piece

is equal to get shape as well we're going to set up a clock object and clock is
equal to tigame dot time dot clock and we're going to set a variable called fall
time equal to zero and those are all the variables that we need in our main
function already coded for us okay so now we're going to set up our while
loop this is our main game loop we're going to say well run first thing we
need to do in our loop sorry for event in in pygame dot event dot get and we
say if event dot type equals equals pi game dot quit well that means we need
to quit the program so the way that we can do that is just simply hitting run
equals false it's going to break us out of our while loop and then we can deal
with that afterwards we're also going to add another event this is a key down
event so if event.type eagles equals pi game dot key down like that then we're
going to check what specific key is actually hit so let's go ahead and do this
now can i get it over with so i'm just gonna type all the different keys and
then we'll go in and code that after so we'll say if what do you call it pi game
dot key equals equals i believe that's what it is event dot key not pi game dot
key my bad guys event dot key equals equals pi game dot k underscore
capital k okay underscore left we say if event dot key equals equals pi game
dot k underscore right like that and then same thing with up and down so
event dot key equals equals pi game dot okay underscore down and last one
okay i'm just going up okay

okay i don't know why that keeps happening okay okay underscore up like
that okay so painfully after typing that left right down up now we can go in
here and we can kind of code what each of these is going to do so if we're
hitting left we want to move our block left if we're coding right we want if
we're hitting right we want to move our block right and we're going down we
want to move down we're going up we want to rotate our shape that's what
the main things are going to do in here so if we want to move our piece left
well we should uh change the watt the x value left twice okay so the way that
we can do that is say current piece dot x minus equals one now i know you
guys are looking at this right now you're saying okay well what what the heck
man so current piece is equal to get shape and that's all it's equal to get shape
well what is get shape and it's just returning random dot choice shapes now
this actually just made me realize the fact that our get shape thing needs to
change a bit that's because we need to actually create a piece in here so we set
up this lovely uh class up here and we weren't even using it so piece
random.choiceshapes is the last argument it takes it also takes an x and a y
value right so for the x and the y well the y is pretty straightforward it's just
going to be 0. the x has to be the middle of the screen so we're gonna give it
five and for y we're gonna give it zero okay and actually for y we'll leave it
zero for now uh but we might wanna make it negative so that it kind of starts
above the screen and then starts falling down okay so we have let's make sure
this works it looks right x y shape yeah okay great okay so that makes sense
now uh how we can change this x value same thing for right i'm going to do
current piece dot y or dot x plus equals one like that and for down we're
actually just going to type this in for now but this is not exactly what's going
to work y plus equals 1 to move downwards and for up well we need to rotate
the shape so to rotate the shape this is actually pretty easy all we're gonna do
is do is currentpiece.rotation plus equals one okay because when we change
that rotation well that changes uh the actual image of the shape okay now this
is all great but the thing is what if we're moving off the screen or what if this
is not a valid position well that's why we have a function called valid space
now valid space we haven't yet coded but i do have it in here somewhere
valid space and what valid space is going to do is it's simply going to return if
the current position that we're in is a valid space so the way that i do this and
this is going to just make life a lot easier if we're moving left let's simply just
change the pieces x move it left one and then check if that's a valid position
and if it's not well then we can just add one and move it back to where it was
so we're gonna say if not and then valid space and valid space is gonna take
two arguments gonna take the current piece it's gonna take the grid okay then
let's just simply subtract or add one to our piece so all this is saying is we're
going to move left but if for some reason moving left results in not a valid
space well let's just add one and pretend like we didn't even move there so
we're not drawing it we're not changing anything so this is perfectly fine and
it's actually a really easy way to check things without having to checking if if
it's below this or above this or whatever okay so now next next one here i'm
going to say if not valid space and same thing current piece with grid well
now in here instead of adding one we're just going to subtract one because we
were trying to move right and there we go same thing with moving down
okay so we're literally just going to type the exact same thing if not

valid space current piece and grid we'll now let instead of adding one we're
just going to subtract one and this is from the y value this time so it's like
current piece dot y minus equals one okay so now for up so when we change
the rotation we are changing the shape okay so it doesn't show this uh yet
right now like how we change the shape but we're gonna do that later so we
can actually just call the exact same thing on rotation because think about it if
we're fully on the right side with like the straight um piece and we try to
rotate well that could result in our piece being moved to the left or to the right
or like there could be positions where it's on the left or it's on the right and it's
not in the grid so we do have to check for rotation if it is a valid space or not
so let's say current piece and then what else are we doing grid here okay and
then in this case again we'll just we'll just subtract one from rotation so minus
equals one and that should all work pretty well okay so after we do that we're
going to make sure that we remember to draw the grid so in this while it will
such say actually draw window i'm going to give it surface and we're going to
give it grid now this reminds me that i haven't yet created a pie game surface
that's great so let's do that so here i'm going to say win equals pie game dot
display dot set underscore mode in this case i'm going to give it what is it
screen width and screen height so s width and s underscore height and that's it
for a display we want to give this a caption though so we'll say pie game dot
display dot set underscore caption yep so let's just call this tetris like that and
now we're gonna just pass when into our main menu we'll put win here and
then in main menu we're going to call main okay and we'll deal with main
menu later i don't feel like coding it right now and it's not really important to
like the main functionality of a game so we can simply just do this okay main
win like this and if i put when here then everything should work out this says
surface change this to say when in lowercases okay so now we've effectively
done draw grid or draw window draw grid get shape create grid we've created
a piece we've gone through what all this stuff in the starter file does and we
are now at 27 minutes hey guys and welcome back to part two of coding
tetris in python with pygame so let's get right into it uh in this video we're
gonna be uh finishing a few other functions we're gonna be doing valid space
convert shape format we're gonna be coding a bit in the main and we're also
going to be fixing a small mistake i made in the last video so this code right
here in draw grid uh yes this does draw our grid but this is not what i
intended this function to do and i kind of just realized this when i was looking
over the video and looking over the code so we're just going to copy this code
from draw grid okay delete it out of there and we're just going to paste it
down here at the bottom of uh draw window okay so now we just have this
after we're uploading the label we have whatever code we had within uh draw
grid okay because draw grid what this actually was supposed to do is draw
the lines for the grid so i kind of got this mixed up while i was uh going
through the tutorial so we're going to finish draw grid now and what this is
going to do is going to draw those gray lines over top of all of our different
colors so we can kind of see where each block is and we can see the actual
grid structure so let's get started with this say sx which stands for start x is
equal to uh what do you call it top left x okay and then sy is equal to top left
y like that all right and this is just so i don't have to keep typing top left x top
left y just makes it a little bit shorter for us okay now i'm just going to say i'm
going to set up a for loop i'm going to say 4i in range and this is going to be
the length of the grid so how many rows we have let's say 4j in range and this
one is now going to be the length of grid i so how many columns in each row
and then here we're going to be drawing lines okay so for every row we're
going to draw a line so pygame dot draw dot line we need a surface let's give
it a surface we need a color in this case it's going to be gray so gray color
code standard is 128 128 128 and then we need two positions okay so the
start position is going to be equal to sx all right and then sy plus um what do
you call it i i believe multiplied by block size and i think that is actually
correct okay now for the end position well it's going to be the same x value
because we're just drawing um or actually it's going to be let me just check
here yeah it's going to be a x value that is just equal to the width so sx plus
whatever the play width is and then the y value is going to be the same here
because if you think about it we're going to be at the same uh y value each
time we're we're doing like we're drawing a horizontal line every horizontal
line is gonna have the same two y values and the x values just gonna be
changed okay so i'm just gonna copy this and paste it in here now okay uh oh
all right i don't know why that did that but we'll just go back like that okay so
now what we're gonna do is we're just gonna do this okay so x sx plus j
multiplied by block size okay s y can actually just stay like this okay and then
for sx same thing means sx plus j multiplied by block size and j is again as
our current column and then this one s y plus play underscore oops we need a
plus sign here plus play underscore height like that okay and that should be
drawing us what do you call it 20 vertical lines and then 10 horizontal lines
down the screen giving us a grid and kind of the way that works is every time
we loop through a new row we're simply changing the y value of uh what line
we're drawing and then these x values are going to stay static just at the left
side and the right side of the screen and then the way that we do it here is we
have the x values that constantly are changing every column and the y values
are staying static being the top of the screen and the bottom of the screen to
draw the vertical lines and that's what i wanted to do within this draw grid
function so now that's all kind of sorted out and we fixed like a small mistake
don't get me wrong you can still have that other code up here like it still
works fine but just in terms of what i actually wanted to do with these
functions that's the way we needed to fix it okay so now that we've done that
what i want to start doing is getting into this convert shape format okay now
this is probably the most complicated function i want to say within our
program and what this is going to take as an argument or a parameter is just
the shape now this is what i was talking about before so when we have a
shape it looks something like this right so we have zeros and we have periods
now this looks nice to us like we can tell what kind of shape this is but the
computer has no idea so how can we get this into a form that the computer
can read and ideally we want to give it we want it to give us positions within
the grid of where blocks exist and then we're not going to give position if the
block doesn't exist so if there's a period like this okay and you'll see what i
mean as we start coding this function and that's what the goal this function is
to do to take that information and put it into something that's actually useful
to us so we want a bunch of positions that's the goal because from these uh
like lists we want to generate a list of positions and then based on those
positions we can do things we can check them we can draw them and so on
so i'm just going to create a list called format don't worry if it's a keyword it'll
just overwrite it we're going to say when we're given a shape we're actually
given a piece object so i don't know why i'm calling it shape but whatever it's
fine so shape.shape and then we can just do is equal to and i'll talk about this
in a second shape dot rotation modulus the length of shape dot shape okay so
what this does is actually gives us the sub list that we need so this needs to be
spelled correctly uh i don't know how i butchered that so bad okay shape dot
shape so if we look again here whenever we're past a shape we're actually
past something like this right so we're past the shape object and its shape
property so right here is looks something like this looks like the variable t
which would have a list full of lists so we want to get the actual sub list so
which one this list right that's the one we want so the way we do that is by
getting the shape rotation modulus the length of the shape so for example if
our current rotation is zero like we haven't rotated yet um then what's gonna
happen is we're gonna have zero modulus the length of shape in this case the
length would be four so we get 0 so we're given this first shape now if we
have 1 we're given this if we have 2 we're given this if we have 3 we're given
this and if we have 4 then we go back and we get this one okay and it just
keeps going and keeps going because modulus simply just gives us the
remainder so that's how we can tell what the actual current shape is within
that main list okay hope that makes sense so now that we've done that what
we want to do is we want to set up a loop and because we want to look
through every row and every column and then based on if there's a zero or a
period we're going to do something so we're going to say 4i comma and
because we want the line as well in enumerate right and then format okay
because format is the list that contains uh like the actual zeros and ones okay
we're just going to say row is equal to list of line this just gives us a nice list
format that we can deal with uh making it easier for us i'm going to say 4j in
or j comma column sorry in enumerate and now row so now every row we're
getting the current line and then we're going to loop through the line and look
for either a 0 or a period so we're going to say if column which is going to be
for example if we have something like this it's going to look like 0 0 okay so
this is what our row is going to look like so when we start looping j will be 0
and column will be a period okay just just in case you're kind of confused
there okay so for if column equals equals and it's gonna be string zero then
we know that we've hit uh like a position like this cube exists here so what
we wanna do is we wanna add the position to our positions list now it's not so
simple as just to add the current i and j value we actually have to add
something else i'll show you right now i'm just going to type it out and then
kind of talk about okay so shape dot x plus j and then shape dot y plus i okay
so this is our x value it's um the current value of the shape because if the
shape is already moving down the screen it's moving left and right well we
need to add that to whatever the j value is whatever column we're in within
this list okay and then same thing for with the y value so whatever the current
y value is of our shape we're going to add whatever column or whatever row
sorry we're now in as for the y value okay and that is the positions that we
need in these positions list okay so now that we've done that we just have to
modify these positions slightly we just have to give them an offset okay and
i'll talk about why this why we have to do this so for i pause in enumerate uh
positions okay then we're going to say positions i is equal to and then it's
going to be the current position okay so we just need to put this in a tuple
because that's what we're going to give it pause 0 minus 2 and pause 1 minus
4. okay so now let's break this down and kind of talk about exactly what's
going on so we start off blank list positions we're just getting the actual shape
within this list so for example we get something like this okay and then we're
looping through it and where am i sorry and we're pretty much just checking
uh if a zero exists in each position of that uh shape okay if that exists then
we're going to add that position into our list and the way we do that is simply
by getting um the x plus whatever the current column is that we're looping
through and whatever the current row is plus y okay now that we've got that
the issue is that if we look here we're going to get something like for a
position list here we'll get something like three one and then we'll get three
two we'll get three three and we'll get three four okay now the issue with that
is we're adding the current x value plus these two periods and the o so we
need to remove these kind of trailing periods right because that's going to
result in our positions being all offseted to the right by too much same thing
with these y values okay because when we're counting this row we're saying
well this is one lower than this row so our current y value say it was zero and
we're adding to it now instead of just adding one we're going to be adding
two so it's going to everything is going to be offset down so the way that we
can kind of fix this is just by offsetting by constant and by offsetting i'm just
going to take every x value that we've added and subtract 2 from it and every
y value that we've added and subtract 4 from it now what this is going to do is
simply just move everything to the left and up so that when we are displaying
it it's just more accurate to the screen okay you guys can see what's going to
happen if you don't offset this and you'll notice that you kind of run into a
few errors so just run with me on this area and just kind of you should see
how this works later on okay okay so now that we've converted the shape
format i want to go and code valid space now okay so valid space is going to
take two parameters shape and grid all right and we're going to check the grid
to see if we're moving into a valid space so what i'm going to do here is i'm
going to create two lists okay i'm gonna say accepted uh how do you spell
accepted accepted underscore pause so these are just gonna be the positions
that are actually valid okay is equal to and just flow with me on this i'll talk
about in a second for j i and then within this list for j in range 10 this is
similarly what we did to did in the last tutorial and then for i in range 20.
okay so this is really similar to the way that we created the grid we're just
getting um every single possible position for a 10 by 20 grid okay and we're
just adding it in a tuple in accepted positions okay that's great but the thing is
i want to convert this into a one-dimensional list so this is the way that we
can do this and make other positions but now how do we flatten this list so
this is actually how you do this okay so accepted pause is going to be equal to
and this is one way there's many j for sub in accepted positions and then one
more for j in sub okay so what this is actually doing now is it's pretty much
taking all the positions in our list and just adding it into a one-dimensional
list and then we're just overriding this list with that so see if you guys can
understand that if not don't worry about it just know that all this does is
simply flatten this list so we go from looking something like this uh we call it
like zero one and then having another list uh embedded just trying to show an
example here two three so we go from that to something that kind of looks
like this and we just have the positions in it now so we don't have those sub
lists and this makes it a lot easier to loop through okay so now we just have
zero one two three rather than having these embedded lists full of other tuples
okay that's that's all we're doing with this line okay so after we do that what
we want to do is we want to get all these positions um and where we're going
to get the shape and we're going to convert it into our positions right because
remember whenever we get a shape it looks something like this it means
nothing to us we need to first convert it into positions before we can compare
it against other positions in our grid so we're going to use this convert shape
format grid our convert shape format we're going to pass it the shape and
we're just going to store this in a variable and i guess we're going to call it
what should we call it formatted okay because i guess that makes sense we
formatted our shape so now we can use this and kind of compare it against
accepted positions so here we're going gonna have a list that looks like
something with a bunch of positions in it and then this one we're gonna have
a list that has a bunch of positions in it so you might see where we're going
here in terms of how to compare these things okay okay so now that we've
done that we've kind of got all our data ready to check this is the really easy
part so we're just going to say four position in formatted and all we're going
to do now is just check if this position exists within accepted positions
because accepted position is every position that we're allowed to have right
so we're going to say if pause not in accepted position and this is an important
part pause 1 is greater than negative 1 false and then otherwise so if we make
it through that loop that means we had all our positions accepted we can
return true okay so let's talk about this really quickly the reason i have this uh
if pause once the y value is greater than negative one is because when we
give this offset of four what ends up happening is we get some uh when we
spawn in our shapes they're going to spawn above the screen now we actually
want this because we don't want our shape to show up on the screen we want
to start falling before it's actually seen so typically this means a y position is
going to start at like negative 1 or negative 2. so the thing is while it's falling
we're checking if it's in a valid position right but the thing is it's not going to
be in a valid position if it's negative so we just want to make sure that we're
only asking if it's in a valid position if the y value is greater than negative one
so greater than or equal to zero okay and this is just a really easy way to tell
us well are we on the grid or not so let's give an example say we're trying to
move left and we're already at the edge of the screen so that means we're
gonna have an x value of negative one well that position of negative one
whatever y value is not going to be in this accepted position great um what he
called list so when we try this we're gonna return false and it's not gonna
allow us to move left and that is the whole point of that and now okay uh
what am i doing here okay so i also just want to modify this part up here so
for j i and range for j in range if i in range 20 i want to just change something
here okay so what i'm going to do actually i'm going to say if grid

i j equals equals and then the color zero zero zero okay so this is an important
part i was kind of waiting i was kind of thinking about this so pretty much
we're only going to add this position into our accepted position if it's empty
which actually makes a lot of sense because think about it if we already have
a color in that position then that's not a valid position we can't move into
where a piece already exists so what this conduct condition does is it says
okay we're only adding this position now if this is true so if i j is true then
we're good we can add the position if it's not 0 0 0 that means something
exists in there so that's why we're not going to add it into our accepted
positions okay so i know this looks kind of confusing because i'm doing like
a bunch of embedded for loops it just saves us a few lines um it's kind of a
cool way to create a list in one liner it's like the pythony way so i figured i'd
do that for most of the stuff in here okay so now that we've done that what
else can we code well you know what while we're here we can code check
lost all right this one's a really easy function this is just simply going to check
if any of the positions are what do you call it above the screen so if we hit y
value of 0 then we know that we're above the screen and we've actually lost
so the way to do this we're going to say for pause in positions because what
this is going to do is we're going to pass a list of positions so we're going to
get every pause now in the position we're going to say x y is equal to pause
which is simply just splitting up the tuple because we know we're going to
get something that looks in the form of like 3 4 okay and we're going to say if
y is less than 1 so equal to 0 or greater then return true else or we don't even
need else let's say return falls down here so if every position is less than or
greater than y or whatever one then we will return false because we haven't
lost yet otherwise we're returning true okay so we're almost getting there now
i want to go down to the main and i want to finish coding up some stuff in
here so last time we kind of just left it at this like moving pieces around
whatever but we have these variables okay so change piece next piece clock
fall time that we're not using so what i'm going to do now is i'm going to
show you guys how we can actually move our shape down our screen at like
a regular time interval so i'm going to create a variable here actually called
false speed and this is how long it's going to take before each shape starts
falling okay so uh we'll talk about how to do this i'm going to start coding it
now so pretty much we're going to say up here and i didn't do this before but
just follow along grid equals create grid based on locked positions the reason
we're doing this i know we already created grid up here is because every time
that we move we have a chance to be adding something to locked positions
we're going to do that later because for example if we hit the bottom of the
screen well now locked position is going to be equal to something else
because it's going to have a new shape in it so we need to constantly update
the grid so that when we're drawing it to the screen we get like an updated
version so that's why i'm doing that up here okay i also need to um actually i
don't think i need to do that here we need to add to fall time okay so the way
we're going to add to fall time because this is going to track um what do you
call it how long since like the last loop ran is by using this clock object that i
set up here okay so before i add to that after here i'm going to do clock dot
tick and then i'm going to add this and i'll talk about this after i do it so dot
get underscore raw time like that okay so the way that this works is this raw
time actually gets the amount of time since this last clock.tick so when i first
add it's going to be zero because we haven't yet ticked the clock and the next
iteration it's going to see how long it took this while loop to run and then it's
going to simply add that amount okay so it's actually going to give us real
time this means this should technically run at the exact same speed on
everyone's computer and everyone's machine because i know when i use fps
fps is dependent on kind of the speed of what you call it um your actual
computer sometimes like the way i did it in other games so this is a better
way to do it so now what i'm going to do is since i've now incremented the
fall time and this is going to be given to us in milliseconds so like one second
would be a thousand uh that's that number and our full speed is in well 0.27
so what i need to do is i have to say if fall time divided by a thousand is
greater than false speed then what we're going to do is we're going to reset
fall time equal to zero and we're going to add one to the current y value so
which means we're scr we're moving down the piece one so this is going to
automatically now move our piece down now the thing is what if our piece
will hit the bottom of the screen or what if it's moving into a position we can't
move into so this is the same thing we've kind of done in here what we're
going to do is we're going to say again if not

valid position or valid space whatever given the current piece and our grid

i believe at least grid okay then and actually we're going to check one other
condition and our current piece dot y is greater than zero so this means that
we're not at like the top of the screen because the same thing with negative
values all right is greater than zero then what we're going to do is we're going
to subtract one from the current piece so y minus equal one because that
means we moved into an invalid position so let's move back up one and
pretend like that never happened and we're just going to say change piece is
equal to true now the reason i'm setting change piece equal to true because
think about it right if we're moving down if we move into a position that's not
valid well we know we didn't move left or right off the screen because we
were moving down that means we must have either hit the bottom of the
screen or hit another piece so in that instance we need to stop moving this
piece and we need to change it and what changing piece is going to do we're
going to do that later is simply going to lock all the positions what they're
currently in and then it's going to make this next piece generate down the
screen and i'll show you that in a second but this is kind of the way to check it
and it's the easier way then you don't have to check like the y values and and
all that stuff okay all right so now that we've done that let's move down here
to the bottom of main and let's start adding a few things okay so what i want
to do down here i want to say shape positions so shape underscore pause is
equal to convert shape format current piece because what we're going to do
now is we're going to check all the positions of the piece moving down to see
if well we've hit the ground or to see if we need to lock it okay so and we're
going to add all that color to the grid so that when we're drawing it we
actually see the piece because right now we have the piece but we don't add
its color into the grid so we're not actually going to see it show up so we first
need to add it to the grid so we can draw it and we can see it moving so to do
that we're going to say 4i in range the blend of shape positions okay we're
going to do here we're going to say x y equals shape positions of i because
that's the current iteration the current one we're looking through we're gonna
say if y is greater than negative one so this means that we're not above the
screen then we say grid y x equals current piece dot color okay because
remember the grid stores a bunch of different colors so all we're doing in the
grid is giving different colors and based on that position in the grid so y x
which is going to be this shape the all the shape positions we're going to draw
that color now the reason i'm going to have this negative 1 is because imagine
that we're at the top of the screen and we try to draw it or we're above the
screen we have a position with a negative y value so if we throw negative
we're not actually going to get an error in grid here but it's going to end up
looking like it's at the bottom of the screen and then moving to the top and it's
just going to look weird if you guys want to see what it looks like without
this just remove this condition and you'll see that why i have it added in okay
so now what we're going to do is we're going to check this uh change piece
variable so i put it up here change piece this means that we've hit the bottom
or we've hit something what we're going to do now is we're going to update
locked positions and this one i'm going to start talking about locked positions
okay so for uh pause actually in shape positions all right we're going to say p
is equal to pause zero pause one all right i don't know why i do this but i
think there's a reason for it so let's just run with it um and we're gonna say
locked positions p is equal to current piece dot color okay so what is this well
locked positions is going to be a dictionary in a form like this all right it's
going to have a tuple in here that's going to have a position it's like 1 2 colon
and then we're going to have a color and the color is going to be another tuple
but rgb values okay so for example 255 0 0. the reason we have this is so that
when we pass locked positions into our grid like this right we can get each of
those positions in the grid and then update the color of grid so every time that
we have like a locked position in a locked position it simply means our piece
is no longer moving it's hit the bottom of the screen and we're on to a new
piece we can get the position and we can get the color and then we can
update the grid based on that and we can keep that in there okay and that's the
way that locked position works so it's a dictionary with the key of a position
and the value of a color all right that's kind of like the data structure for that
now what we're going to do after this after we update our locked positions
and we add positions to it we're going to say current piece equals next piece
okay so we're just going to change that and now since we've said current
pieces now we kill the next piece we need to update next piece so let's get a
new shape because we're just moving forward with the game and now of
course we got to say change piece equals false because we're on to a new
piece that's going to spawn at the top of the screen okay and i think that is
about it what we also want to do actually is we're going gonna check if we
lost the game and i think i do this after draw window i don't think it really
matters but we're just gonna say if check lost based on what you call it locked
positions okay so these are all the positions of the shapes then we're going to
say run is equal to false and that's going to break us out of this wallop and
you know what while we're here let's indent out now let's go pi game dot
what is it i think it's not display.quit or something yeah dot display dot quit so
we're actually just exiting out of our game now up until this point i actually
have not tested my code now i know some of you probably think i'm insane
because we've already written like 300 lines of code we haven't tested any of
it the reason i haven't done this is because i wanted to test this in between
videos figure out what the errors were so that i didn't waste too much time
fixing all of them so i'm going to go through a few errors that we have now
and show you what happens when i run the code so i'm just going to delete
that because that was a fix that i made uh and pretty much you can see that
we crash right away and we actually get a for iron range uh none type has no
length now the reason we get this and this happens down in the main is
because in convert shape formats somehow i managed to forget to return
positions now this is really important because the whole goal of this function
well was to generate this list of positions and we did that fine but we forgot to
return them so uh pretty easy error to fix or return positions now again we run
this we're like okay everything looks good no there's another issue all right so
just watch if i try to go off the screen you can see that we get a uh
unsupported operant for current piece because i forgot to put a y or an x here
so let's go down to main let's fix this what line are we on 262 262
currentpiece.x yeah that would be important okay now i know there's a few
other errors so this one current piece minus equals let's change this to an x
current piece minus equals wow i really messed up on this a lot okay dot
rotation minus equal one okay so this is rotation and let's see anything else
let's run the program see okay we're getting another issue here so if we have
valid spacecraft okay so i just messed up and a bracket here so let's go line
265. ah here we are so we're going to take this quotation mark or what i'm
saying question mark bracket and just put it there and all should be good now
let's see we go down to the bottom of the screen okay we get another and let's
just play this for one sec see if we can run into any errors okay so we're
rotating fine we can't move off the screen and all looks to be doing okay all
right so that's a good sign for now uh let's leave that so it doesn't look like
there's any issues if you find any i probably end up fixing them in future
videos so don't stress about it okay so now that we've done all this what we
need to do next uh is a few things all right so we need to deal with this draw
next shape clear rows draw text middle what other functions i have and i
think that's about it and we're also going to deal with main menu kind of
starting the game finishing the game and all that stuff so what i first want to
do actually is i want to deal with uh draw next shape and then i'm going to do
clear rows just because clear rose is kind of complicated so draw next shape
what this is going to do is it's just going to draw the next shape kind of off the
screen and show us what it is because in tetris typically it shows you like the
next shape the next few shapes um so yeah now this seems pretty
straightforward like just draw the shape it's actually kind of long because we
have to once again get this list turn it into positions that we can use and yeah
it just it gets a bit complicated so what we're going to do is we're also going
to set up a font in here so we're going to say font equals pie game dot font dot
sys font and here we're going to do comic sans again because you guys know
i love comic sans sans size let's do 30 and let's render this font okay so label
equals font dot render text for this is going to be next shape okay feel free to
add a colon or something if you guys want anti-aliasing one text color white
255 235 255 okay basically already been through that okay now we need to
figure out where we're going to draw this this label okay so let's do the same
thing we've done before we say sx is equal to top left x plus the play width
and then we're going to say s y is equal to top left y plus the play underscore
height actually we won't play hundred we're gonna say play height divided by
two okay now what we're gonna do is this is gonna give us um like to the
right maybe i can just run this and show you guys it's going to give us where
my mouse is right here like a position kind of similar to here so what we want
actually here so what we want to do is we want to add a constant to this so we
move to the right of it so this constant we're just going to hard code in and we
can change this and play with it if we want it to be like move more to the
right or more to the left so to move more to the right we're going to add 50
and then to kind of make this look a little bit better we're just going to
actually subtract 100 from this height so we move a bit higher up on the
screen play with these constants if you guys want it to look a bit different
okay so now we've got that what we're going to do is we're going to once
again we're going to format we're going to say format is equal to shape dot
shape and same thing we need the actual shape so not just like that main list
shape dot rotation modulus the length of shape dot shape like that okay so
this is the exact same thing that we did in format whatever okay you guys
know yes know what function i'm talking about and i've lost myself here
okay uh just to get the actual like sub list that we need okay so now um you
might say well what do you what are you doing here we already have like a
function that does this for us don't worry about it just follow along because
this is a bit different the way that i'm going to do things okay so i'm going to
say 4i comma line in enumerate all right and then row or actually format
sorry i'm gonna do the same thing here we're gonna convert row it into list is
really similar to the other function except we're gonna do one major change
and you'll see that for row equals list line we're gonna say four j comma what
do you want to call it column in enumerate row this time and exact same
condition if column equals equals zero what we're going to do here instead of
adding some position to this is we're going to draw something and this is why
i didn't want to use the other function that gives us a list of positions because
i don't care about the position within the grid i just care when we should draw
something or not because this doesn't matter it's not going to be moving we
just want to draw like a constant image on the right side of this or a static
image on the right side of the screen that we can just look at okay so what we
do here is we're going to say pigeon.draw.rect so dot draw dot direct we need
a surface we pass the surface in we need a color that's going to be the shape
color okay and then we need our position to drawn so sx and then in this case
we're going to have to since we're drawing each cube right we're not just
drawing the whole shape plus j multiplied by 30 and then we're gonna do the
same thing with y so s y plus i multiplied by 30. and we can actually just
change this to let's change the block size to be a bit more dynamic okay so
instead of 30 block size just in case we decide to change the dimensions of
our screen later on and then we need a width and a height and that is going to
be block size and block size and we want this filled in so comma zero okay
so what we've done here is really similar to what we've already done uh we're
just going to be drawing these blocks according to where they show up like in
this list based on the initial exposition plus like a changed kind of position or
whatever okay anyways i think that's about it for this oh we need to actually
blit the label now so we created this label we haven't actually drawn on the
screen yet so let's do this so we say surface dot bullet label changes to a
period okay and then we need a position what's our position going to be well
we're actually just going to do sx plus 10 and sy minus 30. okay again play
around with these constants guys if you want your thing to look a bit different
be more centered whatever i again i don't go like too crazy on cosmetics here
i just want everything to work and look decent i assume you guys can mess
around with it all right okay so now we've done that we've drawn the next
shape well we actually need to call this function so within draw window
we're going to call uh draw next shape as well so where should we call this
uh let's see let's call before we draw the grid draw next shape or actually we
can't call it in here where we need to call this is in the main because we only
have next shape within the main so right when we're drawing draw window
we're actually just going to call draw next shape because we need to give it
the next shape so it's going to be next piece and then the grid is that what it
takes or it takes a surface yeah surface okay so let me just go check this to
make sure and our surface is not called surfaces it's called win okay so in
draw next shape yeah we take a shape and a surface okay so that that should
work fine you know what let's actually just test this now and see if it's
working ah and we're not showing up we're not drawing this surface i believe
it is because ah draw a window dronic shape okay so what we need to do
actually is this draw next shape we're going to draw after draw window and
we're just going to update the display in here so pygame.display.update

and then if we go to draw window just remove this display update and this
should work there we go so now we're getting uh next shape on the side the
reason that wasn't working is because we're pretty much drawing over top of
the next shape every time that we drew the window so now that's working
fine we have our next shape showing up and what else do we need to do i'm
really delaying trying to go to this clear rows function because this is really
complicated but i think we're going to have to do this next okay so clear rows
in tetris obviously if we create a full row we need to clear that row and then
so that's the only way the user can win obviously yeah so the way to do this is
probably a lot easier than the way i'm going to do it but try to follow along
because this is the only way i could kind of get to work and this is probably
the hardest part of the actual uh game okay so we're going to take grid and
we're going to take locked positions and what we're going to do is we're
going to set up a few things here just follow along with me i'll try to explain
as i go so i'm going to say ink which is an increment equals zero for i in range
the length of grid negative one negative one okay and we're actually just
going to subtract one from this two what this is going to do is going to loop
through our grid backwards so it's going to start at the 20th row and it's going
to move up to the 19th row okay i'm going to say the current row is equal to
grid i right and we're going to say if the color 0 0 0 is not in our row let's
clear it okay so we're gonna add one to ink don't worry i'm gonna explain this
after guys just follow along okay say i ind equals i i'm gonna say 4j in range
the length of row what we're going to do is we're going to try to

delete locked square brackets current position which can be ji and then if this
doesn't work i'm going to accept and continue okay okay so let's just talk
about what i just did here because i kind of went fast and there's another part
of this function don't worry so the way this is going to work is we're going to
say we're going to loop through the grid backwards we're going to set row
equal to every well row in our grid so whether we're looping through and the
way that we know if the row should be cleared is if zero zero zero does not
exist because if zero zero zero does not exist that means there's no block
squares in our row which means it's completely filled with shapes or
completely filled with cube objects or whatever okay so we know we can
clear it so the way to clear it now and don't worry about these variables i'll
talk about that in a second is to get every position in that row to do that we
need to loop through j in the row and we're already at the current row so we
know that i is just going to stay static change j and try to delete this from
locked positions because now what we're doing is the lock positions need to
be removed so when we tell these since locked position is a dictionary and it's
mutable we can actually just change it within here and that's how we delete
those keys and those colors from the grid okay so after we delete that all what
we need to do is we need to shift every row so what's happening now and i
think i'm actually just going to pull out like a little i have a drawing tablet and
just start using this to kind of explain some things because it's pretty complex
so just give me one second all right so what we need to do is we need to shift
every row so if we delete like a the bottom row and every row above that row
needs to move down by one so if i go to let's see this and delete this okay so
you can see if i have a grid all right and it looks something like this we're just
gonna do like a very basic like three by three grid okay just to save us some
time let's say that we want to clear this row down here so these are full of
colors right so if we clear this row and what happens is we get rid of all these
and then any positions that were above it so let's draw something like this
now this is here well currently this is floating right because if we've cleared
all these positions down here so we got rid of those this is floating so this
needs to move down one so how can we go about doing that and the thing is
every other row needs to shift down by one as well but now let's talk about
like a potential issue we might run into so if i delete all that and let's say we
have a grid that looks like this okay and there's a color here if we delete this
row the grid actually now in our memory only looks like this all right it's only
this top portion because we've deleted an entire row out of the grid so yeah
we can shift everything down by one but now we're left with the grid that's
one less than the other one so what we want to do is we need to add another
row at the top here so that our grid stays the same size because if you delete
an entire row well you're deleting bro right so you need to add back the other
positions at the top because everything's shifting down by one so really the
way it works is you delete this and then this whole thing moves down and
then you add a row at up at top like this okay so that you're back to your
continual grid i hope that makes sense that's kind of the only way i can really
explain it to you guys uh in terms of how we shift things and i'm going to do
it in code all right okay so leave a comment if you guys are confused about
that because i'll try to explain it in a better way but it's just kind of like a
confusing topic in general okay so now what we're going to do i'm going to
say if inc is greater than zero okay we're going to say so this means that we've
shifted and we've removed at least one row and i'll talk about the case in
which we move two rows in one second okay i'm going to say four key in and
just follow what this is uh this is going to be kind of confusing list of locked
positions so locked because we're just we just passed and locked there okay
and then we say key equals lambda i'll explain what this does in a second x
x1 and i think that's about it and we're actually just going to reverse this
negative one okay so for every key in our sorted list of locked positions based
on the y value is what this does so given a list that looks like this so if you
have like zero one zero zero okay given a this is a very basic basic list this
could be a example of uh locked positions list okay what we're going to do is
we're going to sort this list and the way we sort it is based on this number
here this y value and this is what this key equals lambda x x1 does i don't
have to understand that this is just a really kind of complex way to sort a list
what we're going to do is we're going to now make it look like this 0 0

zero one and the way we do that is whether we get all the positions um that
have the same y value in like the correct order okay uh and you'll see why we
need that when we start coding okay so i'm going to say x y equals key
because again remember key is a tuple and we're going to say if y is less than
i and d we're going to say new key is equal to x comma y plus inc and then
locked

new key equals locked dot pop key okay let's uh let's dissect this now all right
because this is i told you guys this was kind of confusing so what we're doing
now is we want to shift every single position in the grid down because when
we delete a row everything above that needs to move down so the first part is
pretty straightforward okay so x y equals key so we're simply getting the x
and y position of each key in locked positions and remember locked positions
has a key and then corresponding with that is a color okay straightforward
now what we're going to do is we're going to say if y is less than i and d and
what that means is if y is if the y value of our key is above the current index
of the row that we removed so if we remove for example row 17 then only
things that are above that are going to move down we don't need to move
anything below row 17 down because we didn't remove anything after row 17
right and i'm going to show this in a drawing in just a second okay so if that
happens what we're going to do is we're going to change a key we're going to
get a new key let's say it's equal to current x value but we're going to
increment this um by a certain value so we're going to add add to the y value
to shift it down and then what we're going to do is we're going to rewrite
we're going to create a new key in locked position which can have the same
color value as the last key again this one this gives us the last current color
value but it's equal to this position right so i'll explain why this works now
kind of with a drawing and why i needed to look at this backwards okay
because when we're looking at from bottom to top um there's there's a reason
for that all right and i might butcher the explanation but just kind of bear with
me here for a second because this is important to understand why this works
and this is the most complex thing and this is actually very useful you might
want to use this a lot like shifting positions in a dictionary or in a list okay so
if i go back to my little drawing thing here and i go like this okay so let's
create a grid um over here let's make it a few more rows this time just for a
better explanation so one two three four okay make it a four by four okay and
you guys can see my fancy drawing skills let's make this a row so let's say we
have a row like this okay so it's green make orange fill orange didn't work
okay so green can stay there orange like this like this and like this and then
we'll add some more colors let's do like blue up here and up here okay so
obviously this is the row that needs to be cleared that my mouse is going over
right now okay so this is the road that needs to be cleared what happens when
we clear this row okay so we've looked from the bottom of the list up and we
found if we're looking at row like four now we're looking at row three and we
say row three needs to be cleared okay so it's cleared so we delete everything
out of row three right this row is now gone so our grid in memory just looks
like this and this so what we need to do now is need to shift these position
positions down but we don't want to shift these positions so that's why we're
getting that ind so we know which position push the positions in our grid to
shift so we delete that row and then what we're doing is we're adding one and
shifting all these positions down okay that's a straightforward example let's
get rid of this and let's do this now okay so let's say when we add our i don't
know shape whatever to our grid we end up getting something that looks like
this okay two rows that need to be shifted down now what we have to do is
we have to delete this row and this row now here's the thing we delete this
row we delete this row how many rows does this now need to move down
well this needs to move down two rows so how do we know how many rows
to move this down how how many rows to move everything else above it
down well that is based on our uh what do you call it increment here and
that's why whenever we delete a row we add one to increment because we
know that we have to now shift it down uh another row okay and that's kind
of the way that this works if that makes sense now the reason that we go
through and we look at things backwards so we don't overwrite existing rows
now this is another complex thing okay uh you probably don't have to really
understand this that much but anyways okay so let's just uh it's not going to
let me undo okay that's fine so we have this right now here's the thing we
started looking at it from the top down to the bottom what would happen is
we would so let's actually have to add another row for this example to make
sense okay so if i add another row and i say well okay boom it's out of color
let's pick yellow right let's say we have a position here and we have a position
here right so that means this position this position and this position all needs
to move down so here's the thing if i move this one down by two all right or
if i move it down by one or whatever it could possibly overwrite this existing
position and we don't want that to happen so why why we have to start
looking at it from the bottom is that when we start moving everything down
we move the lowest most things down first so that way when we then change
this there's no possible way we're going to overwrite this right here okay
because remember if you in a dictionary if you change a key and the key
already exists well you're just going to overwrite that key so that's why we
start looking at it from the bottom if that doesn't make sense don't worry just
that's for any of you that's why okay because i want to make sure i explain
everything and you guys understand at least on some level why i'm doing
what i'm doing okay so that's it for the explanation of clear rows now let's call
it function so when are we going to call clear rows now this is actually an
interesting call we could call this function every loop but we're only going to
call this when our change piece hits the ground now the reason for this is
because you could possibly be moving down the screen and at some point uh
the grid would have a full row before your shape actually hit the ground now
we obviously know the way in tetris when you're moving down the grid um
until you you like land or you stay static we're not clearing anything so that's
why we're only going to call this if we are about to change the piece so clear
rows what does clear rows take again let's say it probably takes grid and
locked positions maybe yeah grid and locked positions okay so pass the grid
we'll pass it lock positions okay so then we're checking whenever we're
changing the piece if we should clear a row and this can clear multiple rows
at once okay i'm going to be showing you guys a few different things so in
the last video i mentioned i was going to be doing more cosmetic stuff so that
is true in this video i'm going to be showing you how to do the main menu
screen how to draw text in the middle of the screen how to make things look
a little bit better and i'm also going to be adding a little bit of functionality to
the game in terms of making the piece fall faster as it moves or as time moves
forward so obviously you want the game to get more difficult as time goes on
so what we're going to do to do that is increase the speed at which the piece
falls down the screen it's pretty easy i'll show you how to do that i'm going to
be adding score and we're going to be displaying that score and that's
probably about it for this game

so the first thing i want to show you is how to add uh the piece falling faster
so to do this we need to create a variable in our main here and i'm just going
to make this equal to uh what do we want to say fall or let's say level
underscore time okay and this is going to just represent how much time has
passed and it's going to be similar to fall time and level is just because as we
increase speed like the level is going up kind of whatever okay so say level
time plus equals clock dot get underscore raw time and we're gonna do
exactly what we did with uh making the piece move down the screen except
we're just gonna change the speed at which it moves down the screen so what
i'm going to do here is i'm going to make another if statement i'm simply
going to say if level underscore time divided by a thousand is greater than
and then you can put in whatever time you want here now i'm going to do
five seconds so every five seconds we increase the speed okay and then we
can decide what we want to increase the speed by so i'm going to say level
underscore time we need to first reset this back to zero so that we continue to
do this and then what i'm going to actually do here is i'm going to say if level
underscore time is greater than and we want to put like a terminal velocity
here so at what speed do we stop increasing the time because we obviously
we can't get to a negative fall speed otherwise you're just going to instantly
fall and we don't want it to get too fast that the game's unplayable so we need
to pick a speed now a good speed that i kind of found was 0.12 because
anything faster than that is like pretty fast but i mean you guys can play with
that and change that around it's really easy number just to fix right and then if
we're greater than that we're just simply going to subtract a value from level
underscore time now this value the magnitude so the size of this value that
you're subtracting is going to determine like how quickly you increase the
speed as well as obviously the time so i put originally 0.01 and i mean
depending on how long it takes you to play a tetris game this is pretty fast
because that means after 50 seconds you're already going to be down to 0.17
which is very quick and almost that terminal velocity so i recommend you do
0.005 that means it'll take about a minute and 40 seconds before you're going
to be close to reaching this terminal velocity which might be good if you're
playing tetris for a decent amount of time okay so you guys can play with
those numbers but that is is going to move it down faster i would show you
but it's going to take like a decent amount of time for it to continue moving
faster so just play with that okay just trust me all right the next thing we want
to do is add score so we need to first create a score variable and say score is
equal to zero like that and incrementing score is pretty simple i'm going to
say and you guys can make this whatever you want whenever we clear a row
i'm going to add 10 to our score because you had 10 pieces or 10 cubes or
whatever that you cleared okay so actually the way that we need to do this is
we're going to return a value from clear rows which is going to be equal to
score now i'm going to go to clear rows and in here i'm simply just going to
return inc okay and inc is the increment so how many rows that we actually
ended up clearing so if we clear more than one row we're going to get a value
of 2 we can multiply that by whatever our score increment is going to be and
then yeah we can just add that to the score so this is pretty straightforward if
we go to clear rows we're going to say score is equal to clear rows multiplied
by 10 right or actually not equal to we're gonna have to say plus equal to
clear rows uh plus ten now what we need to do is we need to display this
score on the screen somewhere where the user can see that we're actually
going to save this score as well when we lose the game okay so the way that
we can display this is we're going to have to do it in draw a window but we're
going to have to pass this score to draw window so after our grid object we're
going to pass score like that and we're going to go to draw window and we're
simply going to add another parameter here score like that now i'm just going
to set it equal to 0 as a default parameter so in case we call it somewhere else
and we forget to add that score that's fine we don't need that so what i'm
going to do now is i'm actually going to go to draw next shape and at draw
next shape you can see if i run the program quickly here uh it shows us like a
little text object okay now i want to uh get this similar text object so i'm just
going to copy this font the label sx sy and i'm just going to bring it down here
into draw window now it doesn't really matter where you draw it i'm just
going to plop it in the middle here and obviously i'm going to change this
from next shape to b score now we need to obviously display what the actual
score is so we can just say plus str score like that and that should be
displaying for us okay so now we have sx and sy which is giving us the play
area i believe or no this is actually the position in which we wanted to draw it
okay so what i'm going to do is i'm going to say now when dot blitz or is it
surface surface dot blitz our text object which is the label and then where do
we want to draw it's going to draw sx sy now i'm just going to have a look up
here to see where i did it here so sx plus 10 sy minus 30. so what i might
want to do is we can add plus 10 to this so it's aligned but then we're out
going to subtract or actually add to the y so it's lower so i'm going to add let's
say like 80 like that so let's test this out and see if it's working uh score so it's
not low enough so we'll add this and do 120 and see where where we're
getting in a score again not low enough let's go 160 and again you guys can
play with these numbers score equals zero perfect and then maybe we'll just
add 10 more pixels here so it's more in the center and you know whatever
that's good enough for me okay good so that is working well so we've got the
score and we're moving down faster now what else do we need to do what we
need to do now is work in main menu and figure out what happens when we
actually lose the game so we have this check lost and all this simply does is
just quit the game for us when that happens but we want to do something else
when we lose and we want to display something to the screen so actually
before i go in main menu i'm going to go up here to a function that i told you
guys i need to get rid of that that i was going to finish which is draw text in
middle now this is going to take a service text and what else do we want let's
say size and color okay so surface text size color this way you can use this in
another function or sorry in another program and you can use it multiple
times with whatever text size and color you want so we're going to set up a
font translate font equals pie game dot font dot sys font by now you probably
know this i'm just going to pick comic sans we're going to make it equal to
size and bold is going to be equal to true now you can make this false if you
want to just omit it completely and then it won't make it bold pretty
straightforward make a label label is equal to again font.render and then we're
gonna say text one for anti-aliasing and color like this okay now we'll just
simply draw this in the middle of the screen so to do this we'll say
surface.blitz label comma and now we're going to do a little bit of math here
so top underscore left underscore x plus play underscore width divided by
two not three minus and we're going to get the label with and the way we do
this i don't believe i've done i've actually done this yet is get underscore width
i think i'm just going to check yeah get width and then the reason i have this
in brackets because i'm going to divide this by two as well and this will
essentially give us the middle position where we should be drawing in terms
of x coordinate okay so now i'm going to give top underscore left y plus play
underscore height divided by two okay and now same thing minus label dot
get underscore height in brackets and divided by two i don't know why i can't
tab over here okay divided by two and that should hopefully be working for
us okay so we can test that out in just a second so we've got this it's blending
now whatever text we want to the screen so this makes it really easy for us to
draw anything to the middle of the screen so the first thing i want to draw to
the middle of the screen is like a you lost message so when it says you lost
what i want to do is draw obviously you lost and tell them that so let's say
draw text middle and then what do we want to draw well let's simply draw
what surface first actually that we need so we'll say win

and then we're going to pass it text and in this case we're going to say u lost
exclamation point size let's go for 80 and color let's go white and you
obviously you guys can play around with that now after i draw that and i
display the screen or update the screen pie game.display.update just because
we haven't called the window yet uh draw window when we do this then
what we're going to do is we're just going to delay so we're going to say
pygame dot time dot delay and i'm just going to delay one and a half seconds
just so once this comes up the user has a second to look at it because then
we're gonna move back into our main menu screen which you'll see okay so
uh i'm just gonna fast forward this until i lose and then you guys can see that
it's working

and there we go so we got you lost and then it delayed and then just quit
because i have this pie game.display.quit here okay so now what we're going
to move to is main menu everything else is working i told you guys it's not
like super difficult all this stuff and in main menu what we're going to do now
is we're just going to make it pop up whenever you start the game and
whenever you lose and it's just going to say hit any key to uh like move
forward to continue okay so i'm just going to set up another game loop in
here um so we're going to say run equals true well run and this is going to be
really similar to the loop we've done above it's just step just a lot shorter
we're and we're going to just draw in here without using a different function
just because we're not drawing very much so it's not important that we what
you call it like update the screen with the defined function so i'm just going to
fill it with blocks so we kind of are getting rid of everything we're going to
draw text middle and what i'm going to do here i'm going to say press any
key to play okay and then we'll give this a size of 60 and a color of white
once again okay so that's being drawn in the middle we'll update the display
so pigeon.display.update

like that and then we're going to say for event in pygame dot event dot get so
similar to what we've already typed up top we're going to say if event dot
type equals equals pi game dot quit we always want one of these not quit q
then we are simply going to say run

oops run is equal to false and then we can tab out here and we can just make
sure that we are actually quitting the display so dot quit and we'll get rid of
this pie game.display.quit and then we're going to add one more event and
this event is going to be a key down so whenever they press any key on the
keyboard then that is going to move us forward and we're simply going to
call this main function where we'll play and i'll explain how this kind of flows
in just a second because it's really nice okay so if event dot type equals equals
pygame dot all capitals keyed down so if they hit any key then what we're
going to do is we're going to say main like that okay and i believe that is
about it okay yeah so let's see here pie game.display.quit looks correct okay
so the way this is going to work pretty much is when we run the game we
start by running main menu so we run main menu and then we go into this
main loop where all it's going to do is just say press any key to play and that's
going to be drawn in the middle of the screen once that happens we're going
to check if they're hitting any key if they hit any key we're going to call mate
in which case let me close this so it's easier to see if we hit main then we go
into the main game loop and we go and we do this loop until eventually we
lose once we lose it displays you lost on the screen makes this loop equal to
false which means it brings us back into this main menu loop and we can play
again by hitting any key pretty straightforward okay so let's test this out and
make sure this is working draw text missing one potential argument color ah
because i didn't give a surface my bad so let's just do win and there we go
okay so press any key to play press space missing one protect main okay
sorry guys and this is why we test our program okay win and now let's try
there we go and now we're playing it shows the score and you guys can mess
around with i haven't actually tested the score so i'll just do this really quickly
and see if i can clear row without having to fast forward which we may be
able to do not using that one okay let's see there you go and score is equal to
10. so the score system is working as well and that's a relief because i hadn't
even tested that before i put this in the video okay perfect oh when you press
the x brings you to press any key to play if you press it again you can do that
so if we wanted to change it so when you hit the x key in the main thing and
you want to close the game then in the main loop here sorry what you're
going to do instead of saying run equals false just do pi game display dot quit
so you can do both you can say run equals false and then you can quit the
display as well okay so what's next so i said we were going to save the score
and potentially display that so if we want to save the score we're going to
have to do something when we lose so we're gonna have to update like the
current score and we're gonna use a text file to do this so that you can play
multiple times so what i'm gonna do i'm gonna say new file uh to create a
new text file i'm just gonna call this scores dot txt okay and here i'm just
going to put 0 as a default value it's really important you put a default value
to start otherwise you might run into some issues so just create a new text file
make sure it's in your directory uh with the main with the script okay now
what i'm going to do is i'm going to create another function it doesn't really
matter where it goes i'm going to say define update underscore score and
we're going to give it score okay now in here what i'm going to do is i'm
going to say with open and this is how we're going to open our text file and
like update the display with openscores.txt in r so in read mode and this
actually needs to be in quotation marks as well we are going to say f ah i have
to do this as f sorry and i say f dot read lines like this okay and that'll be equal
to lines is equal to f dot read lines so that means our score is going to be well
the first line so score is equal to lines zero and we're going to add this dot
strip so that we remove uh any like backslash ends because if you don't know
in a text file when you hit the next line the way that it actually tracks that you
have another line is it puts a character that looks like this on the line it's
invisible to you in the text file when you're viewing it but when you read it in
with code you actually read in this character so we just want to make sure we
strip that off in case it is there we're going to say score equals this and then
we'll just set okay so we've done that and since we're tabbing out now it's
going to automatically close our file what we're going to do now is we're
going to open the file again except in this time we're going to open a write
mode which means we're going to overwrite whatever is in the file and we're
simply going to say if score is i guess i'm going to change this to n score
standing for new score if score is greater than n score then we'll say f dot and
we'll say right lines actually right i think and we'll simply put in str of score
which is this updated score otherwise so if that's not true we just have to write
back the other score because we're clearing it when we open this with w
mode okay so we're gonna say f.right and then sorry this is going to be what
am i doing n and score yeah sorry so i kind of messed up in this way it should
be the other way around but whatever we're just checking if the original score
is greater than the new score if it is we'll write the original score otherwise
we'll write the new score so this works still just not the way that i was
thinking about it when i was kind of talking about that okay so update score
should work and then you know we can actually return let's just return
actually now we don't need to return anything so i haven't pre-written this yet
so i'm kind of still just going through how i want it to work okay what we'll
do here after we set round equal to false we'll say update score and we'll give
it whatever the current score is and then this should be working in the
scores.txt file so let's run this i'll fast forward through and make sure
everything's working

okay so we got an error not supported between instance of string and int okay
so if score greater than square so we just mean we have to convert this to an
end so if we go back up to score and where did i make this okay score is
gonna be int score like that okay and that should hopefully work because n
score comes in as an int and we'll run it one more time one more fast forward
sorry about that guys okay and another issue lines zero linda list index out of
range okay i'm gonna have a look at this and come back okay so this code is
actually working just fine the issue was that since the last time when it
crashed uh we didn't end up writing anything into the file so we had a blank
file and then we were going lines zero where is it here and obviously there
was no line zero so that crashed but if you just add any number so if i add
zero back in here to squares.tx and save it then this works fine okay so that's
it for saving scores now we need to display those saved scores so i'm kind of
going to leave this up to you guys where you want to display it i don't really
know where i want to put my saved score like high score maybe on the left
side of the screen it doesn't really matter so if i want to draw it on the left side
of the screen then i can do something like we're gonna have to first get this
max score right so i'm gonna have to make a new function called define max
score or last score whatever you want to call it and if you call max score what
we're gonna do is we're just going to do the exact same thing we did here so
we can say with open squares.txt score 0x line 0. strip except in this time
we're going to return score like that okay now what we actually do here too is
we could just simply replace this whole line with max score and just say
score equals max score be the efficient way to do it and i mean feel free to do
that if you want or leave it the other way okay so now we have something
that's getting us max score so how are we going to use this well when we call
main i guess when we call main or we can call main menu does it like you
guys if you want to draw it in the main menu you can do that otherwise just
draw it in the main to draw it in the main all you're going to do is going to say
like last score is equal to max score which is going to be whatever is stored in
that uh text file and then to draw this well we're going to have to pass this
again into when we're redrawing the window so in draw window i'm just
going to say last score we can go up to draw window again we'll say last
underscore score equals zero and you're pretty much going to copy exactly
what we have here with this font and the split so let me just comment this and
say this is

current score just so i can remember i'm going to add a comment say lost
score high score whatever you want to say here and then we can just say
score and we can actually get rid of this font because we already defined it
we'll say high score equals and in this case last underscore score okay draw
that to the screen this is probably not where you want to draw it you probably
want to draw it top left x minus like some value like minus 30 top left y uh
maybe plus i don't know like 300 or something so now we can see where this
is actually going to draw if we check this out so let's run this press any key so
it's not obviously showing up where we want to so we have to subtract more
from this so let's subtract like i don't know 100 and then this was plus too
much let's do plus 200 and high score so again like you got to move it over
more so we'll move over to under this time and hopefully this works okay so
high score zero score zero and that's obviously because at the current moment
we have no our score is just zero in that text file okay so i think that is pretty
much it for this video

so essentially this is online game development with python which means


we're going to be using sockets and networking to connect what's known as a
client and a server or multiple clients to a server where they can send and
share information and therefore we can create an online game so we're going
to start off with just the absolute basics and just get shapes for example like if
i move a shape on my computer um it moves a shape on your computer like if
you're the other client and then we'll start getting into some more advanced
stuff where we create a legitimate game and start sending mass amounts of
information to the server and back to the client so we'll start really simply by
just getting everything working on our local network and then once it's
working on our local network we'll deploy that to an external server which
will allow us to play from anywhere in the world not just against people on
our local network

okay so what i'm showing you right now is actually an online game that i
created with python pie game and networking and this is similar to something
we're going to make obviously not as advanced but it works on the same
principles so essentially i have what is known as two clients now if you don't
know the way that any online game works is we have multiple clients
connecting to one main location which is known as a server now right here
on my screen we have two clients so this client on the left that my mouse is
kind of going over that has this red uh highlight like where the rook is or
where i just am about to move this knight is client one and then this black one
over here so like you are block where i just moved this pawn is client two
now you can see in the background i have this command line thing going and
it's sending and receiving information and this is essentially how a online
game works and you might see uh whenever you guys play an online game it
says waiting for server or connecting to server and that's because it's doing
exactly that it's waiting to get a connection to the server and then grab
information from that so that's the way that we're going to be doing things is
using the client and server now i'm not going to be using any frameworks that
are pre-created like i know there's like twisted and some other frameworks
for python the only module we're going to be using that's external is pi game
and that's just to create some very basic graphics okay so let's close this i just
want to give you guys an example of what an online game looks like and you
can see when i was moving something on one client it would move it on the
other so let's close that up uh and let's actually get started with the tutorial i
do not mean to open that so i'm going to be working with pycharm uh for this
tutorial now if you don't know what pycharm is it's an ide to download it all
you have to do is just go to the internet type pycharm and you can go here
and click download whenever it loads up now if you guys don't want to use
pycharm that's absolutely fine you can do everything using the standard
editor like idle you could use atom you can use whatever you want but if you
want to follow exactly with the tutorial i'm going to be using pycharm now
the next thing we're going to need um other than ide i guess you don't need
pie charm is we're going to have to install pie game now for 90 of you the
way that you're going to be able to install pie game it's just by going to
command prompt loading it up like this and just typing pip install pie game
and then hitting enter now uh if this doesn't work for you i'll put a card in the
top right hand corner of the screen right now which tells you where you can
go to install pygame and i have a video explaining you exactly how to do this
and if this command doesn't work for you you can follow that video and i'll
explain to you how to do that so once we have pi game then we're ready to
actually start writing a bit of code so while i launch up pycharm right here
and create a new project let me just tell you about i don't know some of the
things we'll be going through in this tutorial series so obviously we're going
to be working on coding both a client and a server and i'm going to explain
obviously exactly how those things work and how we can create them and
then what we're going to be doing is we're going to be dealing with a bit of uh
server like administration if you want to say that so actually deploying things
to an external server um distilling in pen installing dependencies uh working
with like a linux server to deploy our game to and that'll be at the end of the
series that we do that right now we're just gonna be working with what's
known as localhost which means that we're just gonna be doing it on our own
network so right now the games that we create are only going to work on our
what do you call it against people that are on our wi-fi or on the same
network as us and then later it'll work against anyone in the world that has
that client downloaded okay so let's just create a new project here my new
project i'm just going to say is tutorial i would say network tutorial 1 or
something

and just as a what do you call it here just letting you guys know i did actually
mess up my thumb a little bit it's kind of swollen so if my typing is not the
best that is actually my excuse for that so now that i've got a new project
open i'm just going to create a new python file let's just call this tutorial one
actually let's call this client okay and just save that as okay because that's all
we're going to be coding in this video it's just a very basic client okay so now
we've got client so what i'm going to start off by doing is creating a
configuration for my client and keep in mind if you guys are using something
else you don't have to worry about what i'm doing with this pie chart specifics
this is just the way you have to set up a project in pi charm so i'm just going
to set a client i'm going to go to script path network game client okay apply
okay now quick side note all the code that i'm about to write is available on
my website techwithtim.net usually i have as well as that a text-based tutorial
version i'm not sure if i'm going to be able to write the text-based tutorial
while this first tutorial is out but you will see it on there at some point import
tutorial import pi game uh but yeah all the code will be available in there in
case you guys missed something or something's not working so we're going
to start by importing pi game and make sure that that's working once that's
working we're going to create a window so to do that we'll just say win
equals pie game uh dot display dot update all right what am i saying pi game
dot display dot set underscore cap set underscore mode wow bit tired today
guys and then in here we're just going to type width and height and then we're
going to create these variables so we'll say width equals 500 height equals
500 okay so there we go with height win and now we're just going to set up a
few global variables that we're going to have to use after we create a caption
so let's just say hi game dot display dot set underscore caption and then here
we'll just give it a caption let's just say client okay all right so now let's set up
a global variable that we're going to use and what we're going to do for this
global variable is it's going to hold um the current like clients we're going to
say like client number and we'll just start by making that zero but we're going
to increment that based on like once we connect to the server which we'll do
later okay so now that we've done that uh there's a few basic things this is
what we always do for like a pie game project or whatnot i'm just going to
define redraw window okay and in here all we're going to do is just pie game
dot display dot update like that and we'll also fill the display before we do
that oops didn't mean to do that uh with win dot fill and we'll just pick a color
in this case i want to do whites which is 255 255 255 okay now yeah i just
realized this is actually gonna be a lot harder to type than i thought because
my thumb so just excuse me guys if i'm making a few mistakes here okay so
we got our redraw window now and what we can do next is we can um code
our main loop so i'm going to say define main and then here i'm just going to
create a game loop and this is going to run continuously while our program is
going and it's just going to be what's checking for collision checking for
events can constantly asking the server for information and you guys will see
how this works in later videos more so we're going to say run equals true and
here we'll say well run and we'll just set up some very basic things that we
always do for pi games so for event in pie game dot event dot get okay and
then all we're going to do is say if event dot type equals equals pie game dot
quit with all capitals then we'll simply do pie game dot quit like that i don't
need a semicolon i guess we can say run equals false as well okay uh for
events that looks good and then what else we'll do in here is we'll just call
that redraw window function so redraw window like that now what i'm
thinking we should do next is probably set up a class for our character okay
now our character is gonna be just the only object we're working with right
now and it's just gonna represent like a rectangle that moves like left down
upright around our screen and i guess we'll do that on this video moving that
character around and then we'll connect it to uh the server in the next one so
let's create a class and we'll do that up here and we'll say class player like that
okay so we'll give it a knit function and if you guys don't know much about
object oriented program and programming and you want to learn i do have a
tutorial series on my channel um that i would recommend you go through if
you don't understand a lot of the stuff that i'm doing right now okay so x y
with heights will be what we get in here and this is just going to represent
actually let's give it a color as well because that'll be good to have x y with
height color and yeah this will just represent kind of our player and what
variables they're going to have so we'll pass these values in when we create a
new player so self. y equals y this is very straightforward self.width equals
width and self.height equals height and finally self.color equals color so these
are just our initialization here uh this is what we're going to use when we're
drawing the character when we're checking for a collision or stuff like that
um and what i'm also going to do to save us a bit of time in the future i'm
going to say self.rect equals and then in here let's do this okay so x y width
height like that okay and this will just make it a bit faster when we're trying
to draw our character so the next thing we're going to need is define draw
now in the draw method here we're going to take a window so we'll call that
win and all we're going to do is just draw a rectangle that represents our
character onto the screen and it'll obviously be the appropriate color so to do
that all we have to do is just say win dot oh no we don't have to do that we
have to do pygame dot draw dot rect standing for rectangle we have to first
give the window so we'll give win we need the color so we'll do self dot color
and then we need a rect which will be self dot wrecked okay and that's
actually all we need to do to draw the rectangle to the screen now we need
one more method we're going to use and this is going to be called move and
move actually i believe yeah we don't need to do anything else in there right
now as a argument sorry so for move what this is going to do is it's
essentially just going to check um what do you call it if they press like left
key right key what not how can we move them around the screen so the way
that we can do this really basically essentially is just do pie game dot uh what
do you call it dot keys dog get underscore pressed i believe that's it it might
be key um might be keys we'll see we'll see if which one works so this is
essentially going to give us a list of all of the keys actually a dictionary of all
of the keys and essentially each key is going to have a value of either 0 or 1.
now if 1 is true that means we're currently pressing the key if 0 is there then it
means we're not pressing the key so the way that this is useful as opposed to
doing what we could sometimes do which is just check for events in here is if
you're pressing more than one key at once it'll allow you to move like
diagonally or whatnot okay so what we can do in here now is we can just
check if certain keys are pressed and then change the x and y values
accordingly so we'll say if um what do you call it oh i guess we should
probably put this in a variable let's just say keys equals pi game dot maybe i
feel like it's key we're going to go key for right now pi game dot key don't get
underscore so say if keys and then pie game dot k underscore left standing for
our left arrow key and that's all we need to do for that one and then we'll say
if keys and then pie game dot k underscore is this should this be all capitals i
think it should be okay underscore right and then the next one if keys pi game
dot k underscore up and then our last one obviously is down and then we'll
change our values accordingly inside of these if statements so pie game dot
okay underscore down okay so left right up down so if we press the left arrow
key obviously what we have to do is subtract from our x value so to do that
we'll just say self.x minus equals self.l now val is something we need to
define so let's do that up here self.bell equals and let's do a value of like three
for right now okay so if we're going right we need to add to our x so we'll do
this very similar so self.x plus plus equals self.bell okay if i could type that
correctly and then to go up we're going to subtract from our y value so self.y
minus equals self.l and to go down we'll do self.y plus equals self.l and that's
the way the coordinate system works in pi game our coordinates actually at
the top left hand of our player or our screen so if we want to go down we
have to add to it and then left and right is the same in terms of subtracting and
adding okay so that should successfully move our player uh we can add like a
jump and stuff in here another time but for right now that's all we need i'm
trying to think of anything else that we could do right now um we should
probably create a player object and draw that to the screen just to make sure
everything's working so to do that let's create a player um should we do it up
here let's do it right above our main loop here okay so we're just going to say
or actually we'll do it inside the main loop this will work better we'll say p
standing for player just equals player and then we'll give it some value using
x y with height color so for x y we'll just start him at like 50 50 and then for
our width let's just do 100 by 100 so he's nice and big and we can see him and
then we'll do a color of green so that would be red green blue like that so 255
for green and then what we're going to do actually is we're going to type in
here insert in redraw window we're just going to pass p to our redraw window
so that we can draw him and before we do that we'll call p dot move and what
this will do is move our character based on what keys we're pressing so inside
redraw window let's add a player what do you call it argument attribute
whatever you want to call that sorry parameter that's the correct name and
then we'll just say player.draw like that and we'll pass win in here which
probably should be passed in here as well because we do use wind quite a bit
so let's do p let's do win and then p okay so let's run this now and see if i
made any mistakes i likely did process finished oh we're never calling the
main function so let's call this main function from down here so we're
actually executing that code that we wrote and there we go so now we have a
little green square and you can see hmm interesting it's not working for me to
move this around so let's check this one more time p dot move what is move
doing get pressed let's just add i want to add something here and make sure
this is working so let's we're going to say clock equals pie game dot time dot
clock okay and then in here we're just going to do clock dot tick uh and we'll
do 60 fps i just want to see if this is working if not i do know how to fix this
um okay so we're not able to actually move this oh i know why so very
interesting we are not updating this rect but we are updating um what do you
call it like up down left right so at the bottom here all we're going to do is just
redefine our rect by doing self.x self.y self.width and self.height now i'll
really quickly explain why this error was happening essentially we're
defining rect up here based on the input parameters when we're creating our
player so that means we're always just constantly drawing our rectangle in the
same position because we're never updating this rect variable we're only
updating like xy width height right so we just have to redefine a rect variable
every single time that we're moving which is fine and we can do that so now
let's see and we can move our green square around the screen i actually quite
like the speed this movement um so yeah so essentially in the next video
what we're going to be doing so i'm wrapping it up here is we'll add a little bit
more to this client and then we'll start working with sockets so we can
connect this up to a server and we'll start talking about all the networking
aspecting then

so in this tutorial we're going to be working on coding the server and then in
the next video we're going to be connecting this client that we made in the
last one to that server and then sending information to and from the server uh
so let's get started and let's create a new file that is gonna be our server file so
i'll just call this one server.py and then in here we're just gonna have to
import a few things and i'll talk about exactly what they're gonna do for us
once we start using them so let's start by importing sockets or socket then we
can import underscore thread and we'll also import uh os okay so actually not
os sorry sys that's all we need for that so what we're going to be doing like
i've talked about is we're going to be using sockets and threading to handle
connections to our server and essentially what that means is we're going to set
up a socket and it's going to allow for connections to come into our server on
a certain port so we're going to start by just defining a server which is going
to be a string and port which is going to be a number now for ports you guys
probably know what ports are you might have heard them before for example
like a common port you would use on uh or common port that is used on your
router would be port 80 and that is for http connections there's also a port like
443 there's there's tons of other ports that have um distinct uses but there's
also a ton of ports that don't have any uses and they're just left open for
programs like this or for different things to be used for so what port i'm going
to use which is typically open it depends on like what router you're using and
your internet connection but typically a port that's open is five five five five
so we're gonna use this port to connect to and from and it's just a safe port to
use as opposed to trying to use another number uh that we might not know if
it's being used for something else or not okay so once we've done that we've
created a server and create a port what we're gonna do is we're gonna set up
what's known as a socket okay and we'll talk about exactly how this works in
a second but we're just going to say s equals socket dot socket and then here
we're going to type something that's probably going to mean nothing to you
but i'll talk about what i mean so we'll say socket equals af uh underscore inet
okay and then socket dot sock stream like that all right now these are just the
types of connection so since we're going to be connecting to a ipv4 address
which again we're going to keep talking about all this stuff as we go through
in case you guys are unfamiliar with networks this is the type we're going to
have to use and sockstream just i believe represents like how this server
string comes in i could be wrong on that but um this is the type we're going to
use and for any kind of applications like this this will be what you use for
your socket okay so we're just initializing that and now the next thing to do is
to bind our server and our port to the socket so to do this we need to do a try
and accept and the reason we do this is because like i talked about we don't
know if this is actually going to work initially doing it there could be in some
instance this port is already being used for something and if that's happening
that means that this is going to fail so we need to try and accept this so it will
accept uh what do you call it uh error as e so we say socket dot error as e and
we'll just print that out to the screen just so we know why we're not working
there uh otherwise what we'll do is we'll say s dot bind and then here we're
gonna put server comma port okay so we'll bind to whatever ip address we'll
put in here to this given port okay so i hope everything's making sense so far
essentially what we're doing when we do sockets is we're setting up a
connection or we're using a port on our server on our network it's going to
look for certain connections and then we'll be doing this on the client side as
well will be binding or not i don't know if it would be binding we'll just be
connecting to a certain server and a port and then since we're connecting to
that this server script that we're going to have running will see that
connection and handle it in some way okay so now that we've done that i'm
trying to think what else we have to do okay so what we're going to start by
doing is we're going to start listening for connections so we're going to do s
dot listen now s dot listen essentially just opens up the port so now we can
start connecting to it and having multiple clients connecting and whatnot so
in here this actually takes one argument now it's optional and if you leave it
blank it means it'll allow for unlimited connections to happen now depending
on what kind of program you're writing is what you're going gonna do for this
now for me i only want two people to be able to connect to my uh what do
you call it yeah to my server so we're just gonna do s dot listen to now this
might actually be one because it might be like zero one but i think two may
be the correct thing so the s dot listed for now uh and then what we're gonna
do is we're gonna print after we listen uh we'll just say waiting for uh
connection and we'll say server started or something like that because once
we get to this point we are running the server and everything actually is
working like we're listening for connection we're ready to go okay so the next
thing we're going to do is we're going to define something known as a
threaded function okay and we'll i'll talk about again what this means um but
let's just do threaded uh threaded underscore client for now and i'm just
putting you don't actually have to name it this you can name it whatever you
want i'm just putting threaded here just so we know this is threaded and then
it's gonna take one argument which is going to be connn which stands for
connection and let's just pass in there for right now so the way that threading
works uh actually let's let's do the threading and then i'll talk about how it
works because i'll probably make a bit more sense so let's do a while true
down here okay so once we set up our server our port we bind it doing here
we're starting to listen waiting for connections starting the server then what
we're going to do is we'll be get put into this while loop and what this while
loop will do is we'll continuously look for connections okay because right
here we're just listening uh like once right to see if anything's on that server
report but down here we want to continually try to grab connection let's see if
something's connected and if it does then we want to print something to the
screen or we want to send information or we want to start a new thread which
we'll talk about in a second so in here what we're going to do is we're going
to say connection which co n and then adr equals and then s dot and then
we'll say accept and what s dot accept is going to do is it's going to well
accept any incoming connections and then it's going to store the connection
and the address and the connection is by the way an object representing like
what's connected the address is going to be an ip address in these variables
okay so if we get a connection uh what we'll do is we'll say print uh
connected to okay and then atr and this is just going to show us what ip
address is actually connecting so we can have a look at that and then what
we're going to do is we're going to do start underscore new underscore thread
and then in here we're going to do what was that name of the function that we
had was threaded client okay and i believe we do comma and then in brackets
here we do con like that okay so start new thread is there a reason that's not
working um give me a sec guys i want to see why oh that's why so up here
instead of saying import thread we're going to say from underscore thread
import star okay and that's just going to make it so we can just do this start
new thread thing and you know what i don't know if we're going to need this
sys but let's just leave it there for now okay so let's talk about what threading
is going to do so essentially the way that you guys are used to programs
working i'm assuming unless you have some familiarity with threading is that
say we're in this while loop right and we were to call the function threaded
client well before we continue going with this while loop we would have to
wait until this function was done running in other words we return back from
this function some value or for example like he does like x equals five we
would have to wait for this x equals five to execute and then it would come
back in this while loop and keep going now we don't want that to happen
because we're going to be having multiple connections going at once so what
we want to do is we want to start what's called a thread and a thread is just
another process that's running in the background so that just means when we
do start new thread and we do threaded client it's going to run this function
but it's not going to need this function to finish executing before it continues
the while loop so this is going to be running in the background as like process
2 while process 1 is still running and still going so that means say we connect
to 100 different things we're going to have a hundred different functions
running so 100 different threaded clients on the stack or like keep going and
then what we're going to have is this while loop still continuing to go what
did i just do i'm still continuing to run to look for another possible connection
you guys will see more how this works but essentially just means this will
run in the background and we don't have to wait for it to finish executing
before we can accept another connection that that's the basic kind of way to
that works so now let's start working with threaded client and then we will
test the server out and see if it's working and then obviously in the next video
we're going to connect to it and do all the connection stuff okay so in here uh
threaded client so what should happen when we connect to a client well we're
going to have to do a while open here so we're going to say wow true because
we want this to continually run while our client is still connected okay now
what we're also going to do is we're just going to say reply equals blank like
that i'm just copying from my other screen because this one is a bit finicky i
don't wanna mess it up we're gonna put a try in here and what we're gonna
say is we're gonna try to receive some kind of data from our um connection
okay from whoever's connected we want to receive some kind of data so what
we'll do is we'll say i believe it's uh s con dot receive that might be right yeah
i think that's right and then in here we're gonna put the amount of bits okay
now if you guys know anything about computing you know like how what
bits represents um but essentially this is the amount of information we're
trying to receive now if you're getting an error when say you'd like do this
and you connect up and you get some area that says um what do you call it
like object was truance or like uh you you're getting any errors just increase
this size okay and you can just do that by like putting this like times eight or
something just note that the larger this size is the longer it's going to take to
receive information and that's obviously because the more information you're
getting the longer it takes to send that over the server so 2048 bits is not a lot
it doesn't take very long it happens almost instantly but if you bump this
number up to a ton then it will take uh longer to do that okay so data and
we're gonna say reply equals and then we're gonna say data dot i think it's
actually string dot d code hmm let's see this oh data data.decode because it'll
be in that that kind of object but that data.decode and then here we're going to
do utf comma 8. now the reason we have to do this is because whenever
we're sending information over a like client server system we have to encode
the information and you'll see that in the next step that we're going to encode
information before we send it back to the client but that means that we're
receiving encoded information so to actually be able to read it like a human
readable string we need to decode it first so it's really easy to do that we just
do decode and we're just giving the format which is utf-8 okay so reply
equals that and then we're going to say it's going to say if not data we're going
to print

disconnected okay and then we're gonna break and this just means if we try to
get some information from the uh what do you call it the client but we're not
getting anything we're gonna disconnect and we're gonna break and that
likely means that we've well disconnected from the client or the client's left or
something like that so instead of continuing to run this while loop and trying
to get information from a client that's disconnected we're going to break this
just kind of a fail safe to make sure we don't get into any infinite loops and
it's also going to show us if we're running into any issues with like receiving
the data and decoding it which we'll talk about later okay so otherwise so if
we are getting information all we're going to do is we're going to print
received is that how you spell received maybe uh and then we're going to put
what do you call it reply okay i didn't mean to do that let me see if i'm
spelling this right i'm not okay received reply so this just means we received
from the client this reply let's print it to the screen see what it looks like and
then we're going to print

sending colon and we'll just print reply okay and then we'll talk about this
again in a second why does this keep happening okay reply next now after
this if not data breakout what we'll do down here is we're going to say con dot
send all and we're going to send str dot encode reply now again remember
that since we're sending information over the server we have to encode our
information so all this is going to do is just encode our string reply into a
bytes object so that means when we read it in from the client side again we'll
have to decode that information it's kind of annoying but i mean it's a security
thing right so now we're just going to accept uh i guess what kind of error
would it even be i don't even know if there's going to be any errors if we run
into anything let's just break just to make sure that we're not you know
getting in that infinite loop or we're not gonna ruin the program by doing that
okay so this is actually about it for our server uh let's see how much time
we're at 30 minutes okay so now what we need to do is figure out what the
server number is and then we can actually test it and see if this is working uh
so what we're going to do now is we're going to find the server number now
to do this we're going to be doing this over uh localhost okay that means that
our we're only going to be able to connect over our local network meaning
that like anything on our wi-fi network that can see each other that'll work
fine but as soon as we go outside that network it won't work so we're going to
be using what's known as local ip addresses so to find the local ip address of
the machine you're currently on you're going to go to command prompt in the
bottom left and then you're just going to type ip config okay now um some of
you guys are probably freaking out because you can see my ip address right
now this is a local ip address and that means that it is locally assigned to my
network no one outside of my network can see this ip address or companion
or can ddos it or anything like that okay so it's perfectly fine if you guys see
this address or if other people know what this local address is okay just as a
note so we're going to do is we're going to take this ipv4 address so i'll just
copy that and we're going to paste that inside of the string here okay so
10.11.250.207 is mine now yours likely is like 192.168.something okay but
since i'm on like a massive network usually they use 10.10 like as the default
gateway which is what they're using so my p address starts with the 10. yours
likely starts with 192.168.1 dot like 5 or something like that and then the rest
of it okay so that's the address we're going to use and this is going to be our
server address so whatever machine that you're going to be running the server
script on that's the address you want so say you want to run this server on
your laptop and you want to run clients on like your pc and your mac or
something like that then you want to make sure you get the ip address from
your laptop and you're putting it in that script okay and we'll talk about more
of this in the next video and we actually connect to it okay so now that we've
done this i probably made a mistake but let's actually just create a
configuration quickly for server and run this and just see if we're getting any
errors as of now now it is worth noting that we're not going to connect
anything yet so there's not really going to be much we can see or really do but
for now let's just test this out so let's have server let's run this and you can see
he's waiting for a connection server started so that's actually good if you're
getting this string of text everything is currently working in the next video
we'll probably have to debug a little bit once we start connecting to this but
for now that is the main server script now i'll briefly just talk about before i
end this video how it's going to work in terms of running the server script and
running the client script the server script always has to be running okay so
whenever you're trying to connect you have to have first run the server script
and then you can run multiple client scripts from wherever on the network
you want now the server script has to be running on the machine that the ip
address is like this little string here okay it has to be running on that machine
and you can run a client script on the same machine that the server script's
running and you can run multiple client scripts on the same machine so like
for example what i'm going to do to test this in the next video is i'm going to
run the server and then i'm going to run two clients on this machine and we'll
see that it like is moving back and forth for them

so what we're going to be doing in this video is we're going to be coding the
kind of client side of this so connecting to the server i know we already coded
a client but we're going to code like the network aspect of the client so that it
can connect to the server uh it's not as much code it's a bit more
straightforward and then we're just gonna test out sending very basic
information to the server and hopefully getting some back see if that's
working okay and then in the next video we're gonna be connecting this so
like the little user interface we created with moving that block around in the
first video we're gonna be connecting that um so that we can have multiple
clients running and we can see like different blocks moving on each screen
okay so that will involve a bit more work um hopefully by video five we'll
have like a fully working kind of game that's working over the network okay
that's the goal so within this video i just want to start by saying on this server
class here or sorry server file i did actually forget two lines of code in the last
video so after this accept break in threaded client just need to add this print
loss connection and then connection.close all this is doing is once we break
out of this threaded client we're just letting the we're just going to print this to
the console so we can see what it looks like and then we're going to close that
connection so that we can possibly reopen it in the future okay really
straightforward that's all you gotta add so just make sure you add that before
moving on okay so next what we're gonna do is we're gonna create a new file
um and i'm gonna call this network okay now you don't have to put what i'm
going to in a new file it's just a lot easier so that's why i'm going to do that so
let's do network and in here we're going to import socket now what i'm going
to do is i'm just going to code a class that is going to be responsible for
connecting to our server this just makes it like so i can reuse this class in the
future and you guys could reuse this class in the future and it's just a bit
cleaner and nicer and that's why i like to do things so i'm gonna say class
network again call this whatever you want and in here we're just gonna set an
initialization function uh we'll take actually his network do we need anything
in network uh no i think we'll just leave like that so we're gonna say
self.client equals socket dot socket it's gonna be the exact same arguments as
last time so let's say socket dot i f net income is that what it is if underscore
net uh af underscore inet okay and then we'll do socket dot sock stream like
that okay now we're gonna define the server and the port again so self.server
equals uh self.port equals five five five five now for the server this again this
number has to be the same as the one you used in the server uh what you call
the server file here so no matter what like no matter where you actually are
um like what client you're using this number is gonna stay the same because
this is the server you're connecting to it's not the client's address uh we don't
actually have to define the client's address anywhere it'll automatically get
that for us okay so what we're gonna do now uh we have client server port we
need to do this self.adddr equals and we're gonna say server so self.server and
then self.port in here okay and then self dot what do you call it self.id is
gonna be equal to self.connect okay uh now you guys actually let's just do
self.connect for right now and we'll talk about why i was going to add this id
later once we add that functionality to the server okay essentially i wanted to
have an id that was returned here or like that was stored in this network
object just because we are gonna have to like be sending an id to each of our
clients so they know if they're like player one or player two but we'll do that
later um because we don't really we can't really do that yet okay so we've
called this connect method so we need to write that now so let's say define
connect okay and in here i believe we should probably be given actually it's
probably fine just use self right now and what we can do is use
self.client.connect okay and then here we do self.addr now we're going to
throw this in a try uh and accept just in case you know this isn't working so
we'll say try say accept uh is we can do socket error um let's say accept and
we'll just pass right there okay just in case this doesn't work so we'll try this
we'll try to connect uh accept pass now once we actually connect what we're
gonna do is we're gonna return um i'm just looking at my other screen right
now self.client.receive and then we'll do 2048 dot decode okay so what this is
going to do uh i'll talk about this because it might be a little bit confusing is
when we connect we want to actually send some kind of information
immediately back to the object that connected to us so like for example let's
go in this i didn't mean to close that let's go into server here and you can see
when we initially connect we're not sending any information until we receive
something now that's fine but when we connect we should really send some
kind of like validation token or like id back to our network object or back to
our client so what i'm gonna do in here i'm gonna say con dot send okay and
then in here what we're going to type is let's see what should we really type
here um str dot in code and then here we'll say connected like that okay uh
just so we know that we did indeed connect so that means if we set this equal
to a value so self thought i don't know let's say id equals self.connect what'll
happen is when we connect uh we'll return that string connected so this will
get connected and since it's encoded we need to decode it obviously so if we
want to print actually in here self.id it should say like connected okay let's see
if that works okay so now that we actually have that um let's see if we can
connect to the server and then we'll deal with sending information from the
client to the server as opposed to just getting it from the server okay i know
it's a bit confusing right now i'm just trying to figure out the best way to do
this um so let's try this okay so we're going to say n equals network we'll just
type this at the bottom of the script we won't do this after we'll delete this just
for testing purposes and then we're just going to say actually that's probably
all we need to do because it'll just print our id okay so let's create a
configuration for network uh so new configuration

type network in here and then select that path and then let's test if this is
working so remember what i said when we're going to connect right to our
server what we have to do is first run that server script so let's run the server
script here waiting for connection server started okay let's run this network
script now uh invalid argument was supplied s dot listen to

okay so i had a quick look here i realized the mistake was i was actually
running this server two times so obviously that's not gonna work for us so we
can put two back in this listen i'm not sure if you guys we'll see if i left that in
the video or not but let's go to network and we also need to change this to af
instead of if i don't know why i typed if i literally said af when i was typing it
but that's fine uh and we have server i'm actually running it right now so
make sure you guys run that and then let's run network and see if this works
okay sweet so um i know it doesn't seem like much but you can check here if
we go to server it says connected to and then gives us that address and it's
also printing out some other thing that i honestly don't know what that means
and then saying disconnected and lost connection sweet that's actually really
good and that means that we're everything is working and you can also see
that we have connected being printed here so that means when we connect to
the server we're actually getting the value that it's sending so we're getting
this uh connected and we're printing it out uh decoding it all fine so that's
really awesome so now the only next step is to actually send information to
the server and keep like a loop going like sending receiving settings receiving
sending receiving now let's actually just test um if i run this again uh you can
see again obviously it's working again so this is the server just continually is
running i don't actually have to stop this unless i want to make modifications
to it so let's just keep that running for now and let's add something to our
network class so in our network class we're going to define a method that's
going to be sent now this method is going to be very useful later on because
it's going to save us a lot of time so in send we're just going to take a string
which is going to be data okay and all we're going to do in here is we're going
to try to self.client.send

and i'm going to say data str actually dot encode data and then we're going to
get a reply from that server so we're going to say return so exact same thing
that we're doing here self.client.receive
2048.decode and we'll accept and i believe this is a socket error yeah it is
socket dot error as e and just print e so if we get into some error where you
know either we're sending or we're receiving it's not working let's just print
that error out to the screen so we have a look at what that really means so
now let's do a test and try to send information to the server and then get
something back okay now the information that we're getting back should just
be the same information because that's what we have in server we're just
going to send exactly what we got right back right so um doesn't really make
sense right now to do that but we'll talk about like what we can what valid
information we can send how to send receive information in the next video
when we connect up the client to the thing okay so what we're going to do is
we're going to say n dot send and we'll print n.send okay and we'll print
n.sound again and let's just send like a few bits of information and see if
everything is indeed working okay so n.send and then in here let's just type
hello and we'll type working okay and see if this works so we have actually
we should have yes server is working let's run our client and you can see we
get connected hello working and if we come here it says received hello
sending hello received working sending working so that's awesome that
means our network class is working sending information receiving
information is working server is working and now the only thing that's left to
do essentially is to connect that up to this so use this network class in some
meaningful way here and then to actually store information on the server and
then send that information to multiple clients which we'll be doing in future
videos

what we're going to be doing is we're going to be hooking up our graphical


client to our server so we can send information back and forth and ideally at
the end of this video what we're going to have is we're going to have two
rectangles on each client so we'll have like two clients running and when you
move the rectangle on one client it moves on the other and vice versa okay so
you guys will get the idea when we go through but there's a little bit of work
we have to do and we're going to be modifying a few things within a lot of
the files we've already created so just make sure you guys are paying
attention and again if anything is going wrong feel free to download all the
code off of techwithtim.net it'll be available there and it'll be exactly the same
code that i'm writing right now okay uh so first thing we're gonna do is in this
network class we're just gonna delete a few things so this testing stuff we
don't need anymore um this print statement for the self.id we don't need that
and we're actually going to change this self.id to be self.pause okay and you
guys will see why we're doing that in a second and we're going to add one
quick method in here and we're just going to say define get pause okay and
all we're going to do here is just return self.pause all right and again we'll
you'll see why we're doing that but i just don't want to have to come back to
this network class so we'll do that right now okay so from inside our client
now what we're going to do is we're going to import this network class
because we're going to use it in here so we're going to say from network
import network and then in our main function down here what we're going to
do is actually above player we're going to say n equals network okay like that
and then what we're going to do is we're going to say start pause equals n dot
get pause so essentially why i'm doing this is because when we first connect
to our server what i want to happen is i want it to return to each of our clients
the starting position of their character right or of their cube okay because it's
going to depend where they're starting based on if they're player 1 or if
they're player 2. so then on the client side what we're going to do is when we
initially connect to the server which is what we're doing when we create this
network object we're connecting to the server we're going to get that starting
position and then for creating our own player we're going to use that starting
position to determine like where we're starting so the position is going to
come in as a tuple all right and we'll be coding all this on the server side in a
second but it's easier just to go through each file rather than going back and
forth it's going to come through as a tuple that looks something like this so
it'll be like 50 100 okay so what we're going to do is we're going to read this
tuple in because it's actually going to come in as a string like you'll see how it
comes in we're going to get the two aspects of it so like the x value and the y
value and then we're going to use that inside of this player initialization to
like set the initial position so that uh reminds me what we're going to be
doing when we're sending information to the server is we're going to send it
using string data right and that's what we're doing in the last video is we were
sending everything with strings so we're sending like hello and then we're
decoding it and encoding it now this is not the only way we can send
information we can actually send information with objects and i'm going to
show you the advantage of doing that in the next video but for now we're just
going to send strings so since we're going to be sending strings the strings
that i want to send are positions okay i want to from each client send the
current client's position to the server the server is going to get that position
updated on the server side and then send the other clients position back to the
client you guys will see how it works in a second actually let's see if i can do
a quick drawing to illustrate this because it'll make things a bit easier okay
let's i don't know why i had this let's delete that okay so let's do a quick
drawing so we're going to have is going to have client one and excuse me
because i'm drawing this with a mouse and client two okay so it's going to be
one and this is going to be two all right this will do it as a red box is going to
be our server and on the server what we're going to do is we're going to store
positions so let's say like one has position like one two okay sorry this is hard
with the most guys and then client two will have position like three and one
okay so it's going to store these positions so what's going to happen is when
we initially connect client one is gonna go to the server it's gonna connect to
it and then it's gonna be sent back the starting position for the client okay so
it's gonna be said okay so you're client one so that means you're gonna start at
position one two client two it's gonna connect it's going to say okay we're
client two so i need to send client two's position so let's send that back all
right now let's say we've already connected client one's there clients two is
there and we've set their starting positions what we're gonna do next is now
we're gonna continually call to the client and update the position so what
we're going to do is say let's it's say we're working with client one okay what
it's going to do is it's going to send its position to the server so it's going to
say let's just say pause okay it's sending its current position let's say that
position is like four uh five sorry this is really hard with a mouse okay four or
five what's going to happen here is we're gonna say okay so you're updating
your position so then it's gonna go in here it's gonna say okay client one will
update your position to be 4 5 like that okay and then what it's going to do is
instead of sending back this same position because we already know what the
position is it's going to send back the position of client 2. so it's going to send
3 1 and then on here we can draw that client so that it looks like it's moving
right so we're getting we're sending our information and then in return we're
receiving the other client's information now the same thing works here with
client two so if client two connects right and it's sending information it's
gonna send its position let's say it sends the position one three okay that's its
updated position so this is going to change to be one and three and then
what's gonna happen is it's gonna say okay well we don't need clients two's
position we need clients one so what's client one position well that is four or
five so let's send four five over to client two and then on client two we can
draw four five so you'll see um they'll simultaneously be moving i hope that
makes sense i just want to draw it out for you so you guys know what i'm
about to do in this video okay perfect now the only thing is we need to send
these positions as strings so we're actually going to have to implement two
helper methods so that we can convert those positions which are going to be
tuples into strings and then we can also read the string into a tuple so what
we're going to do is we're going to say define and i want to remember what i
call this one we'll say this one is read underscore position which means we're
going to take a string value and we're just going to read the string ends we'll
say str equals str.split and we'll split it at a comma okay and you guys will see
how this works in a second and then what we're going to do is we're simply
going to return the end of string zero so str zero okay comma int of str 1. so
what we're going to do is we're going to take a string in that looks something
like this it'll be like 45 comma 67 okay in in string value 45 67 we're going to
split it which means we're going to get a list that has the string 45 and the
string 67 and then we're just going to convert those to ins and return them as
a tuple so now we get that converted to something that looks like this which
is useful information that we can actually use okay so that's what read pause
is going to do but we need to make one more which is going to convert that
position into a string so we're going to say make underscore position and in
here what we're going to have is we're going to take a tuple so let's say top
standing for tuple and what we'll do here is we'll say um let's see here return
uh top actually str of top zero

and then we're gonna add that comma in so sorry i'm butchering my typing
right now comma plus str of top one and i hope that makes sense how we do
that so that's returning the string value so we're reading pause and making
pause and that's all we need to do for those helper functions okay so that
means though that when we get the position initially from our server it's
going to come in in that string value right it's going to look like 45 67. so we
need to convert that so what we'll do is we'll say read pause and we'll just put
that around n dot get pawns because it's going to return to us that string
position so we'll read it in and now what we're going to do is for our player
we're going to say start pause zero and start pause one okay and what this is
going to do is just set it to the initial start position we're going to code all the
server stuff after it'll start making a lot more sense okay now what we also
need to do is we need to create a second player because we're going to have
to draw the first player and the second player on the screen right so we're
going to say p2 equals and we're literally just going to copy this except um
for start position we're just going to put it as 0 0 for right now and we'll
update that in a second okay so we have p p two um and for now that's what
we'll do actually let's we can continue working in here so that we don't have
to do anything else in here after we'll just code the server side so what we'll
do now is we're gonna send our current position to the server right that's like
the algorithm we've developed essentially we are when we connect we're
going to get the starting position we're going to set that starting position and
then every time after that so like every time the frame updates we're going to
send our position and then get the other person's position so we're going to
say is we're going to say p to pause is going to be equal to n dot send okay
and we're going to send make position of and then what we're going to have
to do in here is it's a little sketchy but we're going to do p dot x p dot y now
right because that's the position of our player the x and the y coordinate we're
putting it in tuple form we're sending it to the function make position which
is going to turn it into a string and then we're sending it to the server right
okay awesome so i think that makes sense and then what we're going to do
simply is for p2 we're going to update is its position so we'll say p2.x is going
to be equal to actually n2.send but we're gonna have to put around here sorry
is make pause read pause because right it's coming in as a string so we need
to convert this into our actual position so f p two pause is gonna be p two
position zero and then p two dot y is going to be equal to p2 p2 pos1 okay
now the only thing that's left to do here is what do you call it draw p2 and
update p2's rectangle so what we're going to do now is in the redraw window
down here we're going to put p2 we're going to go to redraw window we're
going to say player 2 here and then we're going to do player 2 dot draw
window because again it's going to be a player object so that'll be fine and
then last thing to do is just update the rectangle so what i'm going to do is i'm
going to say p2 dot update and we're going to go to player object now we're
just going to add this one function that is define update and then so you see i
just made like self.rect equals x y with height and then in here i'm just going
to say self dot update like this okay um so i know this might be getting a bit
confusing but we're almost finished i just gotta do the server side and then
we'll recap through everything what we've done explain things i kind of have
to get this content out uh okay so define update so what we're doing again
here is before we just had this line of code here um so we're just replacing
that with an update method uh that's pretty straightforward i hope that makes
sense to you guys and that's just again so when we change the x and we
change the y value of p2 directly then we are updating the rectangle so when
we draw it to the screen it's in the correct position okay so i believe that's all i
have to do for the client side so now it's time to go to the server side and the
server side is pretty straightforward now the server needs to keep track of the
positions right it needs to hold player one's position and players two position
um consistently so we can decide if we want to store that let's say like on a
hard drive or if we wanted to store that in memory now in our case it's not a
lot of information so we're just going to store it in the memory of the server
right so what we'll do for that is we're going to create a list and we're going to
say pause equals and just a blank list and this list is going to hold the
positions of our players now actually that reminds me we're going to put two
tuples in here and these are going to represent sorry the starting positions of
our players so we'll start with zero zero and like a hundred a hundred so
player one will start at zero zero player two will start at a hundred hundred
okay and that's all we're going to do for that little list there and then what
we're going to do down here uh well this while loop is we're going to keep
track of how many players have connected in our case we only want two to
connect right and then we need to keep track of well those players so we're
going to say is where i say current player equals 0. now this is because when
we connect we're going to add 1 to this so that when we go back into this
function it'll be you guys will see how it works but essentially every time we
create a new connection so every time this we accept a new connection we're
going to add one to our current player so we'll actually do it at the bottom of
the while loop we'll say current player plus equals one this is just to keep
track of which player we're using so that we know what position to update
what position to send to that player based on the connection right okay so
keep track of current player and now what we're going to do is when we start
this new thread so this threaded client we're also going to pass another
argument which is going to be the current player so instead of just passing
connection we're also going to pass player in here okay current player like
that okay because that's going to be important information to know all right
so we're actually almost finished we just got to update a few things so let's
actually grab these two methods from our client class or client file and throw
them onto server here so we're just going to put them right above position
because we're going to need to use them read pause and make pause so now
when we initially connect to our player right this is what happens when we
initially connect the first thing that's sent is this encoded message that is
connected now in our case what we want to send is we want to send the
starting position so how do we do that well we know what player we are
we're either player zero or either player one right because we only have two
players when we start with player zero after player zero connects then we do
player one right so what we'll do is we're going to send pause player now that
won't work because it's just a tuple right we need to first convert that to a
string and then encode that string and send it so let's actually go back here i
want to keep this string down in code so string dot encode and we'll say make
underscore or pause and then we'll just put pause player in here and what
that'll do is it'll convert it into a string for us and then it'll send that to the
player for us right and then they'll read that string in convert it to position and
update the position accordingly okay making sense hope so okay so that's
how that works for player now the only thing we need to change now is what
information we are sending um every time this loop is running right every
time we receive something from the player we want to send back the other
player's position so to do that what we're going to do is we're going to say
con.receive.decode so we'll get rid of this for now and then what we're going
to say is we're going to turn this data into uh like readable a readable tuple
right so to do that we're going to use the read position method that we've
already created or function so say read pause con dot receive and we'll turn
that into from that string like this right or whatever it was like 45 67 we'll
turn that into something that looks like this so that we can actually use it okay
so now that we have that it's turned into that what we're going to do is we're
going to update our current player's position so we're going to say pause
player equals data right because this is the position they sent to us so let's
update it on the server so yeah so it's updated information okay sweet so
we've done that now all that's left to do is send the other player's position
back to our client so to do that what we can do is simply say reply equals and
we're just going to say pause or actually uh let's not do it up here let's do it
down here okay we're going to say if player equals equals one so if we're
player one we're going to send player zero position right so we'll say reply
equals and then pause player uh or not pause not not player zero sorry and
then else we're gonna send so we'll say reply equals pause one okay so if
we're player one we send player zero position if we're player zero we send
players one position right like i was talking about with that little algorithm
we're going to use okay and then instead of saying received and sending
actually yeah we can say received reply sending reply or we'll say received
data sending reply that should work fine okay uh now what we'll do is we're
going to send all the reply but the thing is our reply we need to first convert
into a string so to do that we're going to say make underscore pause right that
function we've already created and then that should actually be about it now
i'm probably made a mistake or two here but let's just test this out and see if
everything's working so let's start by running the server and then let's run two
clients and see if we can connect if there's any errors okay so we've
connected with client one let's run client two and let's see what happens so
i'm on client one right now you can see that when i move my green square it
moves on the other client okay let's go to the other one and when you look at
this when i move it on here it moves on the other client so we have
successfully set up and connected our two clients together now the only thing
i want to change quickly is just the color of these so that we know who is
who like which square am i um so to do this we're just simply going to go uh
we'll actually close the server class otherwise you're going to run into an
issue or server instance whatever it is go to client and instead of having the
same color here we're just going to change this to be 255 for player 2. and i
want to show you what happens because some of you are probably going to
be confused with what's about to happen here but it's kind of interesting so
let's run server let's run client 1 let's run client 2 now notice that these colors
are inverted now can anyone think of why that might be so green right is
gonna be uh your current player so right now i'm on here i'm on this where
my mouse is and i'm moving the green square that's near the middle of the
screen okay but notice on the other screen it's moving the red square that's
because on your client it's unique to you so on your client you are green and
red is the other person meanwhile if i go to this client and i start moving see
green is me and red is the other guy right and he's not currently moving now
if i wanted to move these at the same time i would just have to be running
these on different computers or i would have to change like the arrow keys to
move them and that's just because obviously right like if i'm pressing the
arrow keys on here it's not going to work on this client but if i were to load up
my laptop and try doing it on there this would work fine as well

there's quite a few issues that we may run into when we're doing this so i've
set this up essentially to be kind of like an example program or like an
example problem to give you guys an idea of the way we go about doing
things in terms of server and network but it's really not ideal the way that
we've coded things so far now i did plan this for uh to do what we're about to
do but essentially i'm going to redo what we've just done in a much more
elegant and nicer way that's going to allow for better scalability of this
program okay so what we're going to do is i'm going to redo it here i'm going
to show you how we can actually send physical oh not physical but like send
objects to the server and from the server back to the client rather than just
string data and then in the next videos we're actually going to scrap all this
code that we've written and we're going to start from fresh and code like a
networking game it's going to be a lot more complex than just a few squares
moving around the screen so that's my plan for this series let me know what
you guys think of that i know it might be a little bit frustrating to get rid of
this code but now that we understand how a lot of this works it's going to be
really fast to rewrite it in a much more elegant way so uh what i need to first
start by doing is just taking this player class okay and i'm just going to copy it
into its own file so really straightforward i'm just going to go to new python
file i'm going to call this player with a lowercase and then just copy that
player class in there and just import pi game up here okay import pi game
now i'm just going to go back into client we can delete this player class now
and what i'm going to do really basically is just from player import player
like that okay and that's the first step now remember i said we're going to
send objects so that actually means that we're not going to need this read
pause and make pause thing and it's kind of annoying how we've had to well
take that tuple object decompose it turn it into integers and then change
object properties and then when we want to send something we got to put it
into a string and we got to send it it's just a pain and we don't want to have to
do that especially when we're sending tons of different bits of information not
just that same positional data right so we'll get actually going to delete this
we can delete this client number i don't know why i have that there um and
we're going to start just making some modifications in terms of sending data
and receiving data so we'll start on the client side and then we'll go over the
network uh the server side and fix some of that so wherever we see like read
pause and make pause we can just get rid of that for right now um we don't
actually need any of that we're not going to need this p2.x stuff uh we don't
need p2.update we'll we'll get rid of all this for right now and you know
actually let's get rid of start position let's get rid of p and let's get rid of p2 and
we're going to recode all this okay so actually um p2p that can stay there p
dot move is fine okay so we got rid of all that and you can see we've just
cleaned up this file a bit and we'll start working with some more stuff in a
second now what i want to do actually is go to this network file that we have
and we're going to start making some modifications in here as well so what
we're going to be doing is we're going to be sending objects so that means
we're going to send like an instance of the player class uh and that's actually
what we're gonna be sending instance of a player class to our server as
opposed to sending like string data and then updating the object on or then
updating the string data on the server and then sending it back and then
updating the object it's just a lot of work it's a lot easier just to send the actual
object so we can do that using something called pickle okay now it's a weird
module name but it comes default with python and this allows us to do
something that's called serialize objects and that just means we turn it into
byte information which is like all the zeros and ones send it over the uh what
do you call it send it over the network and then we can decompose that turn it
back into an object and use that it's really easy to do that so what we're going
to do here is we're going to modify a few things in our network class so first
thing instead of having self.pause we're going to say self dot p okay it's going
to be equal to self.connect instead of saying get position we'll just do get p
and then we'll return self.p okay and that's all we need to modify for that but
now in the connect in the send we're going to change a few things as well so
since we're going to be getting object data what we have to do in the connect
is we have to decompose that object data so to do that you do pickle dot loads
okay now what this stands for is it stands for load byte data okay and we'll
we'll talk more about this as we keep going through but that's essentially what
it means and same thing here in send instead of encoding this data what we're
going to do and i guess decoding as well is we're going to dump it into a
pickle object and then send it so to do that we're going to say pickle uh is that
useful pickle yeah dot dot dumps like that and we'll just put data in there okay
and then when we receive we'll do the same thing as before we'll say pickle
dot loads and then we'll load that in so now essentially what we're doing is
we're going to be receiving an object decomposing that object getting the
actual object not the bytes um form of it and then we're sending it we're
gonna first like what do you call it encrypt it like send it into that byte
information and then on the server side we'll decompose that as well okay so
we'll we'll go through that but that's all we need for the network side so now
let's go to server and start making some modifications so same thing here we
no longer need this read pause and make pause functions we're not going to
be using those and we don't need this pause list either we're going to change
this actually to be players and it's going to be equal to two new players so
notice that we're going to actually store the player object on the server as
opposed to on the client side and this is not only like safer because it means
that the player technically can't really mess with the player objects they can
only like do commands to update them um but it's also just like it's gonna be
a lot easier you guys will see how it works we're gonna say player and we'll
do another instance of player and in here what we're gonna do is we're just
gonna create two new players so we're gonna say zero zero fifty fifty and
we'll give it a color in this case the first color will be red so we'll say red
green blue like that and for the other player we'll start him at 100 100 like
before we'll do 50 50 and then we'll make his color uh blue why not so do
that okay so now you notice that we're getting a little error for player here just
because we forgot to import it so we say from player import player like that
uh and that's why i made this new file by the way just so that we'd be able to
see it from the server side and the client side as well and then wherever we're
doing this like send encoding stuff we're going to change this so let's do that
now actually so instead of con.send instead of encoding some string
information we're just going to send the player object so what we'll do is we'll
say players like this and then player right so exact same kind of concept as
before in that we're going to send the initial like starting position of the player
or like the but in this case we're just setting the initial player object which
means any information that's stored in that player will be given to the client
as opposed to just the position okay so next what we'll do is instead of saying
data equals read pause and decoding we're going to get rid of this dot d code
and we're going to put pickle dot loads okay and actually when i'm sending
this player object my bad here guys we gotta do pickle dot dumps okay and
then we're just gonna have to import pickle up here so import pickle all right
sweet okay so pickled loads pickle.dumps and that is obviously instead of
pause player equals data we're going to say player players player equals data
and again same concept as before what's going to happen is the what he
called the client is going to send us a player object we're going to replace the
existing player object with that new player object and then we're going to
send back the other player objects like the other clients okay so now what
we're going to do is just change these pauses to be player or players like that
okay same thing here players and then when we send it back what we'll do is
we will just turn it into a object right so we'll just do that pickle.dumps and
send it back so say pickle dot dumps reply like that and that should actually
be about it so let's go back oh sorry there's something we need to do in client
um so now what we're going to do is essentially we've set up our network
class so that we're going to be able to send that object data we've set up the
server so we're going to be able to receive that object data we're going to
modify the objects we're storing in the list here and then we're going to send
back the other one so the other client so in clients all we have to do now is set
up player 1 and player 2 and then send that data so really straightforward it's
very similar to before what we're going to do first of all we're going to say p1
or actually just p i guess is equal to n dot get p okay because in the network
class remember what we're doing is when we initially connect so let's go back
to server we're just gonna send the initial player object which is gonna be
whatever player it is so zero or one so let's just say that this client's player
object is going to be n dot mp okay and then we'll say actually i think that's
all we have to do for yeah that is all we have to do for that inside this while
loop now what we're going to do is every frame we're going to send this
player object which will be updating with p dot move and we'll just get the
reply and say that that's p2 so we're going to do is going to say p2 equals and
then in this case we'll just say p dot or not p n dot send p and that's all we
have to do and notice here that we don't have to do with all this like make uh
what do you call it make pause read pause all that stuff and i believe this
should be working if i didn't make any mistakes let's cross the fingers and
let's try this out waiting for connection let's go to client one run that okay and
client two running that and now notice that these rectangles are the same
color and watch what happens if i move this red one see how it's red on the
other screen as well now that already shows us one of the advantages of
doing it this way is that we can store information like color as well not just
position and if we wanted to store maybe like there was a text attribute on
each of these players we could store that as well if we wanted to store more
information in the player like a health or something like that it'd be a lot
easier to do that by just sending the actual player object that has like an
unlimited amount of attributes rather than just sending that little tuple that has
like five six right which is the position so the reason i went through the
trouble of showing you the other way is to show you the massive advantage
of doing it this way and just to give you kind of perspective if you're making
something really simple and you don't use any objects that's how you can do
it with string data but i think this way is a lot easier and we've just cleaned up
quite a bit of code we've gotten rid of a bunch of functions and moving
forward this is going to make things a lot easier for us

i'm pretty much gonna be gutting everything we already did uh we'll keep a
little bit of it but we're just gonna really add to a bunch of that and just yeah
we're gonna be gutting most of it uh and we're actually gonna be working to
create online rock paper scissors now i know this sounds like kind of a lame
game but let me show you because it's actually pretty complex and if you can
understand how to make this game then you're going to be able to understand
how to make any other kind of online game because the principles are the
same in terms of sending information waiting for players to go and there's a
lot of different things that you might not think about that we actually have to
do to code something like online rock paper scissors okay so let's this is client
number one i'm just running another pi game window uh or pi charm window
with the server running on it you can see obviously it's a bit oversized but it
says waiting for player okay so i'm gonna launch another client and then
excuse me you can see when i launch that it loads both of them up into the
game and it says your move opponents you remove opponents and currently
it's waiting so i believe this one's player two and this one's player one so if i
make a move here on uh let's say rock it'll lock in my move it says your move
is rock and then over here it says obviously the opponent's move is locked in
because it's like looking for this guy's move and now if he makes a move like
let's say scissors then it says you win you lost and then it just resets and you
can keep playing games now i'm also going to be adding more to this this is
just like the beta version i'm going to have wins ties and losses keeping track
in the top hand corner and when you load in you're going to be brought to a
menu screen which will allow you to like start a new game or to leave or
we'll add that later as we go but this is the main function in game and you can
see obviously it's working well tie game and it restarts this also allows for
unlimited amount of clients to play so for example if i launch another two
windows you can see these guys now have their own game going um it's kind
of difficult because i can't really get four on the screen but anyways if i go
like scissors paper that works independently of these games and these games
can kind of play at their own time which is really interesting and really cool
and if you disconnect one of them it automatically disconnects the pair and
that's just because obviously you can't play against no one right so yeah okay
sweet so that's that um let's start getting into the code okay so first thing we're
gonna do is we're actually gonna code a uh a game class okay and this is just
gonna be responsible for holding all the information for our game that we
need so for example did player 1 go yet did player 2 go yet what move did
player 1 make what move did player 2 make are both of them connected to
the server information like that and you guys will see how much information
we actually need it's also going to store things like keeping track of who won
or who lost how many ties how many wins so that's what we're going to do
with this game class so let's start making it so class game i'm doing this in its
own file by the way just called game you are going to need it in its own file
because it's going to have to be accessed by both the client and the server
okay we're going to define our initialization uh in here we're going to take id
i'm going to say self dot p1 went equals false self dot p2 went equal is false
and obviously you guys know what this is going to do it's just going to stand
for if player 1 has made a move or not if player 2 has made a move we're
going to do self.ready equals false if i could type that correctly we're also
going to add self.id so self.id equals id and this is going to stand for the
current game's id so each game we create is going to have its own unique
numeric id so that we can determine who's like what clients are a part of what
game and whatnot we're gonna do self.moves equals and then we'll just do
none and not in here because currently the moves are none but we'll just store
two positions so we can change that we'll say self.wins equals and then zero
zero obviously this one is gonna stand for player one this one's gonna stand
for player two we'll say self.ties equals zero that's all we need for the init so
the next one is gonna say get underscore player underscore move now what
this is going to do is exactly what it says it's just going to get i don't know
how i added that there you're just going to get the player move that we asked
for so we're going to take p which is going to be either 0 or 1 and we're going
to do is simply return self dot moves and p and just to remind ourselves we'll
say that p is in the range of zero and one so we're only going to take value
zero one and then we're going to return a move so let's say move here okay
and that's just to remind ourselves that we have to pass zero one obviously
zero is going to represent player one and one is going to represent player two
okay next one play so this one's a bit more complicated not crazy we're going
to take play we're going to take a player and we're going to take a move and
what this is going to do is it's simply going to update our moves list with that
player's move pretty straightforward so what we're going to do here is we're
just going to say if player equals equals zero then what we'll do is we'll say
self.moves zero equals move um oh actually you know what let's do this
sorry i'm just looking at my other screen right now we'll say self.moves
player equals move but now what we have to do is based on the player we
have to update if p1 went or p2 went okay so what we'll do in here is if it's
player one obviously we'll do p1 went um equals true i'm gonna need a self
before that and then we'll call we'll just do a little else here because it's not
player zero it must be player one we'll say self.p2 want if i could spell went
equals true so that'll just keep track of if we've gone or not sweet next method
this one's really easy it's going to be called connected and this is going to tell
us if the two players are currently connected to the game if they are it will
allow us to load in and that's how we can determine whether we should show
waiting for player or not on the screen right so we'll say return self.ready and
that's just going to tell us obviously if we're ready and that'll be updated from
the server side which we'll do later next method define uh both went this is
just simply going to return if both of our players went so to do that we're just
going to say self.p1 want and why can i not spell that word and self.p
itself.p2 went like that okay next one is winner this one is a bit more
complicated but it's just going to keep track of where it's actually going to tell
us who's won the game so if we call this method we're assuming that both
players have gone we're going to check their moves excuse me against one
another and see if they want so we're actually going to have to check nine
possible cases because there's three moves each player could do three times
three nine um so what we'll start by doing is we'll just say p1 equals
self.moves zero dot upper and then zero the reason we're doing this is
because we just want to get the first letter of the move because the move is
going to be stored as rock paper or scissors the string and it's just going to be
easier for us to type out for example r or s or woody or p to check the moves
as opposed to having to check the entire word so we're just going to get that
first letter by doing move 0 we're going to upper it and then we're going to
take that first letter we're going to do the exact same thing for p2 except
obviously we're going to need oh i don't know what i did there we're going to
need moves1 dot upper and now we can start checking to see who's won so
we're going to say to start winner is equal to negative 1. now that's because
there could be no winner there could be a tie so if it's tied we're going to say
negative 1 if player 1 is the winner it's going to be zero if player two is the
winner it's gonna be one okay so we're gonna do is we're gonna say p1 equals
equals r and p2 equals equals scissors what we'll do is we'll say winner equals
zero because player one won that we'll say l if p1 equals equals s and p2
equals equals r then we'll say winner equals one i believe do another lf and i
know this is tedious but this is the way you have to check for rock paper
scissors i don't think there's an easier way to do it if you know an easier way
let me know and p2 equals equals r and if you guys don't want to type this
you can always copy it from my website techwithtim.net okay so say winner
equals paper beats rocks that'll be winner equals one or zero sorry we'll say l
if p1 equals equals r and p2 equals equals p then winner equals one and we've
just got two last ones to check here so we'll say l if p1 equals equals s and p2
equals equals r and then p2 is the winner so winner equals one i believe that's
oh sorry i'm going to mess this up this should be p think so p rock rock paper
scissors paper yeah winner equals zero um okay l if p1 equals equals paper
and p2 equals equals scissors then winner equals one and i believe that should
be correct one two three four five six okay sweet and then the other cases are
if it's a tie so if none of this is the case then they must have tied and then all
we're going to do is simply return winner like that okay and one very last
method then we're actually done with this class we can move to something
else is define reset went and all this is going to do is say self dot p1 went
equals false and self.p2 went equals false pretty straightforward and this is
the game class i know i kind of sped through this but it's pretty trivial how
this works uh we just need to get this out of the way so we can start coding
some other stuff okay sweet so we've done this class um next thing i think we
want to work on is network so network actually you guys are going to have to
modify yours to look like mine now get p and uh what do you call it so this
first half so init and get p are going to be the same as what we had previously
the only thing that's changed is connect and this send so in connect instead of
um what do you call it like unpickling an object so like pickle.loads what
we're simply doing is we're going to just connect to the client like we did
before but instead of unpickling it we're just going to decode it so we're going
to say self.client.receive2048.decode

would return that value and that's because when we initially connect to the
server what we're going to get from the server is our player number which
means we're either player 0 or player 1. now that's important because that's
going to determine where on the screen we're drawing certain things and how
we're sending information back to the server and updating player 1 or player
2 right because technically each player thinks that they're player one but each
one needs to be assigned either a zero or one by the computer so we know
where to store information right okay so that's how we modify that just do
decode instead of pickling um sending i believe is the same except what we're
going to do is instead of pickling an object to send we're simply going to send
a string and we're going to load an object so that means we're going to send
string data to the server and we're going to receive back object data so when
we receive something we have to pickle that loads it in but when we're
sending it we just have to encode the string okay so just make sure it looks
like this i don't think i need to go through this we've already done this for the
past two three videos and that's the network class so game and network are
done the next things to do are server and client now server and client are a bit
more complicated so inside of server i guess we could do this first because it
doesn't really depend on the client to work where the client kind of depends
on the server we're gonna change a bunch of things so this is what mine looks
like now i've kind of gutted the entire threaded client i got rid of most of the
stuff like most of the other stuff i just left this beginning thing so the server ip
the port the socket connecting listening waiting for connection so by the way
some of you were saying you're having issues with f s don't listen you can
just make this zero it doesn't really matter um what's in here and some of you
were saying like you're having issues just you can just delete it and type it in
again and apparently that works that's what someone said so i don't know
don't ask me about that but if you're running into issues do that okay so what
we're going to do now is we want to make it so you can have unlimited
connections at once now that means we're going to have to have unlimited
games running at the same time so before what we were doing when we had
those players moving around the screen is we were just storing like player
one player two and we just had a list that had two entries that's how we were
doing that what we're going to do now is we're going to have a list that
contains a bunch of different games and those games actually are sorry it's
going to be a dictionary those games will be accessed by their id and you
guys will see how this works um it's a bit complicated but just follow along
and yeah so i gotta just open up my other file so i don't make any mistakes
here okay so what we're gonna do is we're gonna do uh connected equals set
we're gonna define some variables we'll talk about what these do games
equals a blank dictionary and id count equals zero so the reason we're adding
these is games this dictionary is going to store our games so it's gonna have
an id as a key and the game as like a game object like this okay as the value
this connected is just going to store the ip addresses of the connected clients
we're storing in the set just so it's easier to access later i don't actually know if
we use this we might um but we'll see okay id count obviously is just going
to keep track of our current id so that means what game we should recreate so
we don't override games and say like two games have the same id because
obviously we can't have that happening okay so that's fine for that we're not
going to deal with anything threaded client right now we're going to go down
to our while loop and this is where we're going to create new games based on
new people joining or possibly delete games actually we'll delete games from
threaded client so we're going to do right now is when someone connects this
this runs right and we run a new so like once we accept a connection
everything after this runs so what we're going to do is we're going to say id
count plus equals 1. if you notice me looking away i'm just looking at my
other screen to make sure i don't make any mistakes on this now what id
count plus equals one is gonna do obviously is it's gonna keep track of how
many people are connected to the um the server at once because obviously
right like once this happens we accept then we go down the while loop we
start a new thread and then we wait for another connection so we're just going
to keep track of that what we're going to do is we're going to say p equals 0
just standing for the current player we're going to say game id equals and this
is going to be weird but just follow along with me we call it id count minus
one integer division two now what this is going to do is essentially every two
people that connect to the server we're gonna increment game id by one and
what game id is going to be or we'll say it's yeah we'll add it by one what
game id is going to do is keep track of what id our game is going to be so like
for example if we have 10 people connected to the server we're going to have
five games right so that's what this line of code is doing for us it's keeping
track of how many games or if we need to add a new game because obviously
if we have like six people connected all of them are going to be playing each
other a seventh person connects well it doesn't have a game to join we have to
create a new game for it to join hopefully that makes sense okay so what we'll
do next we'll say if i do count modulus two equals equals one and what this is
going to stand for is if you're gonna be player one or player two and if this
happens is actually we need to create a new game because this means that we
don't have a pair for our new player so for example like say this number is
three that means two people are already playing so that's one person just
connected so we need to create a new game that's what this modulus 2 is
getting okay so to do that we're gonna say games game id equals game game
id okay and i believe it's actually a speed capital so obviously uh sorry at the
beginning of this i forgot to mention i imported game so from game import
game that is important and yeah essentially what we're doing is we're just
going to say that um game id which is that key in our dictionary is now equal
to a new game so we can access that and add players to it and whatnot sweet
so that works let's actually print out a message here and just say creating a
new game dot dot just so that in our server we get some kind of output and
we can have a look at that if something's going wrong so otherwise if there
we don't need to create a new game meaning we have let's say three people
are connected so that second game already exists and another person connects
well that person has to be a part of this new game so what we're going to do
then is we're going to say games game id dot ready equals true now what this
means is that the second player connected so there's two players now
connected to our game so now we can say that that game is ready to start
playing because both the players are connected so that means that they can
we'll obviously play against each other right so that's what we'll do we'll set
that dot ready equal to true and obviously we're storing all the games on the
server side as opposed to on the client side and then what we're going to say
is we're going to say p equals one and what this means is player equals one
and you'll see why we need to do this in a second okay so now we're going to
do start new thread now notice and start new thread i added two new
parameters p and game id so this means the current player so it's either player
zero or player one and the game id and game id is going to stand for which
game in this game's dictionary are we playing in this threaded client like
which one of our clients that's connected here uh is playing which game that's
why we need that so let's pass that information so we're gonna pass p which
is either gonna be zero or one like we have there and we're gonna pass game
id and then we'll have that up here and just remember that threaded clients
one of these functions is continuously running for every single one of our
clients so if we have a hundred clients we have a hundred different functions
of this running in the background at the same time okay awesome so that's
how that's working inside our threaded client now

excuse me i try to take a break there inside of our threaded client we now
need to add some things so the first thing we're going to add is id count we're
going to global id count because if someone leaves our game or disconnects
we're going to need to subtract from that so we can keep track of accordingly
like how many people are connected how many games are running and all
that stuff okay now the first thing we're gonna do when someone connects to
our uh what he called our server is we're gonna send them what player they
are remember what i was saying in this game class or in this network class
story then when we connect we're initially just going to decode a string that's
either going to be 0 or 1 to tell us what player we are okay so what we're
going to do is we're going to send con.send str dot in code uh and i believe
this should be actually string p like that so that we know for player zero or if
we're player one that's the first step next we're going to say reply equals a
blank string i'm going to say while true and this is where we're going to start
doing some more serious stuff in here so the way that it's going to work in
terms of sending string data from our client to our server is we're going to
send one of three different options we're going to send get we're going to
send reset or we are going to send a move and the move is going to be like
rock paper or scissors so if we send get what that means is we want to get the
game from the server so we're going to send that every frame we're going to
send get that string get and then the server is going to look and it's going to
say okay what are you sending you're sending get all right we'll send you
back the game that's how that's going to work another option is reset reset
means reset the game the game has finished both players played reset and
that's going to be sent from the client side because the client knows when we
want to reset right the last one is a move same thing when the client makes a
move so like rock paper scissors if they are allowed to make that move which
we'll check on the client side we'll send that move to the server the server will
update the game accordingly and then it will send back the game to the client
and that's how that's gonna work sweet so what we'll do now is we're going to
say well true i'm going to say data equals con dot receive and then we're
going to say 4096 in here instead of 2048 which we're using before dot
decode the reason we're doing this is just in case uh we're setting too much
information that is more than 2048 bits we want to just double this number so
we can get more if you run into any issues that say like pixel data was
truanced or like ran out of input just increase this number okay you can
literally just do multiply by two in here and that should hopefully fix the error
if it doesn't work you can like multiply by four multiply it by eight um and
that should hopefully fix your error for you okay so now what we're going to
say is we're going to say if game id in games now i'll talk about why we're
doing this in a second but we're going to say they're going to say game equals
games game id so essentially every time we run this while loop we're going
to check if the game still exists and that's what we're doing right so in this
games dictionary we're seeing if this game id which is the key to access the
game is still there now why would we check that well if one of our clients
disconnects from the game we're actually going to delete that game from the
uh what do you call it the games thing now what that's doing for us excuse
me is not only like keeping track of our memory which means that we're not
going to just continually keep creating games so like say our server ran for
weeks and we never deleted any games then we'd probably run run out of
memory on our computer right if we're playing a lot of games but it's also
going to tell the other client that was connected to that game that hey this
game no longer exists that means the other person must have disconnected
from it so we have to do something accordingly go back to the menu screen
right do something like that okay so that's we'll do there and then we're going
to say in here is going to say if not data we're going to break this similar to
before so i'll go through it a bit quicker we're going to say else and now we're
going to check the three different things that could have been sent right so
we've received the data so we're going to check if we got reset get or if we
got a move so first thing we'll check we'll say if data equals equals reset okay
and we're going to say if data does not equal get and then else sorry this
should be an lf i'll left out it does not equal yet else we'll do something else
uh actually do we need an else no we don't need else okay so if data equals
reset what we're going to do is we're going to say game dot reset right
because we already have the game and if we look in here what resets doing is
essentially it's resetting both players once we can play another game really
straightforward for that next one if data equals get what we're going to do is
say game or if data does not equal get sorry so if it didn't equal reset and it
does not equal get well then it must be a move so it means we're either
getting rock paper scissors so we're going to send that move to the game to
update it so to do that we're going to say game.play and then we're going to
do the current player number which is p and then the move and the move is
going to be whatever this data is right so it would be data okay and then
otherwise so i guess after that um what should we do here we'll say reply
equals game and now what we're going to do is we're going to do con dot
send all we're going to say pickle dot dumps uh and not done sorry reply okay
and what this is gonna do let me just make sure i didn't run to any errors here
is simply going to package up our game into that nice um sendable form
we're gonna send it over to our clients clients going to receive it unpickle it
and then use it to obviously make moves and do different things and draw it
to the screen and all that okay all right so i think that makes sense we can go
through it really quickly what time we got 25 minutes all right so we'll go
through really quickly essentially what's happening when you connect we're
going to check if we have an even amount of players or an odd amount of
players if it's an odd amount of players when you connect that means we need
to create a new game so we create a new game if it's not that means we need
to assign you to a game so what we're going to do is make the current game
that only has one player in it ready we're going to assign you to that and start
a new thread when we start the new thread what's going to happen is we're
going to send to the client what player they are either player 0 or player 1 and
then what we're gonna do is we're going to constantly receive string data
from the client if the game still exists then what we'll do is we'll check if
they're sending us reset get or remove if they're sending us a move we'll make
that move they're sending us reset we'll apply that reset to the game and then
we're just going to constantly send back to them the game object and now
what we need to do is just really quickly add some else statements in here so
that if some of this stuff doesn't happen we have like a catch for it okay so
what we'll do here is we're just going to simply say else break okay that
should be lined up here and we're just going to add a try and accept up here
so we're going to say try and we're going to indent all this by just highlighting
and pressing tab i'm going to say accept and then pass i think that's yeah no
not passer accept and then break just in case you know something goes wrong
with this data dot receive we want to make sure the server keeps running so
we have that try and accept and then underneath this except in line with the
main function indentation what we'll do is if we break out of this while loop
we need to close the game and delete it so to do that is actually we're going to
print some on my wrong file here we're going to print lost connection

and then we're going to print what do you call it closing game okay actually
we can print that game id too if we want to see what game id we're closing so
we'll say lost connection closing game game id okay and then we're going to
try to delete games game id otherwise we will accept and pass okay and then
underneath here last thing we're gonna do is gonna say id count minus equals
one and we're going to say connection dot close now that i actually think
about it we should probably put this closing game only in this try after we
delete just so that we don't we only close the game once we don't say we're
closing the game twice okay so what we're doing down here essentially is if
we break out of this while loop so for example if the game no longer exists
uh we're gonna break if something goes wrong with this getting data so like
the player disconnected we're gonna break we're gonna say lost connection
we're gonna try to delete that game the reason we have this try here is
because if both players disconnect at the same time one player will delete the
game before the other so if we try to delete a key that doesn't exist we're
going to run into an issue so we try that if that works we'll say print closing
game and then we'll say that game id otherwise we're going to pass we're
going to subtract from the id account and we're going to close the connection
sweet so we're rolling we're going pretty fast here now all we got to do is
code the client now this is probably the most amount of code i think it's about
100 lines it just is a lot of drawing stuff okay so i'm going to take a break
we'll be back in one second and we're going to code the client

all right so i'm back now and we've got about 150 lines to write for this file
it's pretty tedious because a lot of the stuff is to do with the drawing like we
need those buttons to be working we need um like all that text to be showing
up so that's like 90 or not 90 but like 70 percent of the code we're about to
write it's just going to be cosmetic stuff um but i mean what do you want me
to tell you that's what we need to do if we're going to make an online
graphical game right so uh let's start by just coding a class and this is going to
be our button class uh just that when we have those three buttons you know it
just makes things easier so we're gonna do our init uh what do we need in the
init i'm gonna go for uh text sorry i'm coding in the wrong file text x y and
color and we're just gonna say that the width and the height will be uniform
in here and we'll just make it the same for all of our buttons so we're going to
say self dot text equals text self.x equals x

self.y equals y and self.color equals color okay sweet we'll also add a width
and a height here so we'll say self.width equals 150 self.height equals 100 and
feel free to play with these numbers this is just what i decided by the way
guys um just really want to say this i'm not focusing on how good this game
looks i know it looks like crap but you guys i know can go through and tweak
the colors and tweak the positions and all that um i just don't want to focus on
that because i want to get the hard stuff out of the way in the tutorial okay so
let's do a draw method in here pretty straightforward we're gonna do pie game
dot draw dot rect and then for the rectangle we're gonna take window which
is that parameter for the draw and then we're gonna do oh what should we do
color so self.self.color and then we're going to need that rectangle position
which is going to be self.x self.y self.width

and self.height like that okay and then i guess let's see if there's anything else
we need to add to that no that's fine we're going to define a font so we
actually need to make sure we just add this to the top pie game.font.init okay
make sure you guys add that and we're going to do font equals hi game dot
font dot s sys font should help if you spell font correctly and then here you're
gonna pick your favorite fonts i like comic sans i'm gonna make this how big
should this be uh let's make it 40 and then what we're going to do is we're
going to render some fonts we're going to say text equals font dot render and
we're going to put self.text we're going to do one and we're going to do the
color which will be i guess in this case black or white 255 255 255. okay next
we're going to draw this on the screen now we want this to be centered on the
button so i'm going to do some like i don't know decently complicated math
uh it's not really that crazy but we're going to just say win.blit text and then
we're going to say self.x minus is it minus no it's plus self.x plus in brackets
and we're going to round in these brackets i know this is confusing we're
gonna do self.width over two minus round and we're gonna say text dot get
underscore width over two now what this is doing essentially is we're starting
out our exposition but obviously we want our text to be centered so to center
our text we need to know not only the width of the like container of the
button but the width of our text so we're going to get the width of our text or
of our button we're going to subtract that from the width of what do you call
it our text so that way it should add like 20 or 30 pixels from the left side so
our text is centered okay for the y we'll do a similar thing so inside make sure
you don't mess up these brackets inside here we're just going to actually copy
this and we're going to paste it right after a comma and we're simply going to
say self.y plus round self.height okay plus text dot get underscore height or
minus text again let's get height over two and that should center our button
um yeah okay next we're gonna say define click we're gonna add a position
here this is just going to tell us if we clicked on the button or not so it's a
really basic uh if statement here so we're just going to say x1 equals pause 0
and y1 equals pause 1. now what we're going to say is going to say if self.x is
less than or equal to x1 less than or equal to self.x plus self.width and self dot
y is less than or equal to y1 less than or equal to self.y plus self.height i
believe that's correct let me just check this uh yep that's correct then what
we'll simply do is we'll return true indicating that we did press the button
otherwise we will return false now i know i'm speeding through this but just
because it's really basic pygame stuff and we're doing online games so make
sure i change that so i don't want to focus too much on the cosmetics but
essentially what this is doing is it's checking if the coordinate which we're
going to pass in here which is going to be a tuple of x and y of our mouse
position is actually in the button and the way we're doing that is we're saying
we go on the x right we check if it's greater than the x we check if it's less
than the x plus the width so like if it's in between the little box and then for
the y value we do the same thing but we're checking vertically to see if it's in
that box if you don't understand that i have pi game tutorials where i go
through like collision and how all that works i'm not really going to talk
about that right now okay sweet so we've got that working now what we're
going to do is actually let's see what i want to code now

let's code the main function and then we'll get into redraw window so the first
thing we're going to do is we're going to define those three buttons that we're
going to have at the bottom of our screen so rock paper scissors do that we're
going to say buttons equals and we're just going to make three buttons first
button will be rock so we're going to say rock we're gonna start it at 50 500
and then we're just gonna go and give it a color of zero zero zero okay we're
going to create another button we'll say button and then we'll say scissors
we'll give it a let me just check here 250 as an x

250 is an x 500 as a y and for the color for that i got to check what color i
made this i believe that i made that ah red okay so 255 0 0 and then one more
button can anyone guess what this one is going to be it's going to be paper
we're going to put this at a position of 450 so if we can go here 450 500 and
we will simply make it blue or green sorry zero 255 zero so red green blue
okay sweet so that should be it for our buttons um and now we'll get into the
main function and start coding some stuff the first thing we're gonna need to
do is gonna need to say run is equal to false or is equal to true i'll just do that
we're going to say clock equals pie game dot time dot clock uh capital c here
my bad okay next we're going to say n equals network right because we're
importing network up here we're going to do a very similar thing to what we
did before in all the previous tutorials where we just connect initially by
doing that initialization and then we're going to say p equals actually player
equals n dot get p right and you should already have that method um it's just
returning that uh like connect what we connected to right so when we connect
we get the player number which is either zero or one so we need that now it
reminds me it's going to be a number so we got to put an int around this so
that we can compare it with other integers okay and last we're going to just
print just so we have this you are player now this just indicates to us like
when we initially run if we know we're zero or one just to make sure
everything's working fine now we're gonna make a while loop we're gonna
say it's our main game loop we're gonna say wow run and then in here we're
gonna do clock dot tick clock.tx60 very similar to what we've done before
guys i'm going to start adding some new stuff in a second okay so now that
we've done this it's time to start actually connecting and asking the server for
information so what we should be doing here is every frame we should be
asking the server to send us the game especially at the beginning of this loop
because right now we haven't actually created a game class right we need to
get that from the server so we're connected now we know what player we are
so now what we can do is we can try to get that from the server so to do that
we're going to say game equals n dot send get and that's literally as easy as it
is we just need to do an accept and then we'll just call it we'll say run equals
false and we'll say print

couldn't get game okay and the reason we're doing this and we're going to
break as well is because when we if we send this and we don't get a response
from the server that means the game doesn't exist and what what if that
happens well then what we should do is we should exit out of this game we
should print saying we couldn't get the game and then we should try to
reconnect or start a new game with someone else so this main function is
going to be like the actual game running but once we exited this main
function we're going to go to a main menu and the main menu will allow us
to choose like who we want to play against and a bunch of other stuff as well
okay you guys will see that later okay so that's how we do that next what
we're going to do is we're going to say if game dot both went now what we're
going to do here is if both players went well we're not waiting for anything
now we need to see which one won so what we're going to do here is going to
check which player one and we're going to display that message accordingly
on the screen so what we're going to do initially is we're going to redraw the
window the reason we do this right away is because we want to make sure
that if both players went we're updating um the window and on the window
it'll check like if both players have gone like in this redraw window and it'll
draw the player moves for us so you guys will see how that works in a second
we're going to do a delay let me pie game.time.delay 200 and now what we're
going to do is we're going to try game uh sorry game equals adam.send reset
now why we're doing this obviously is because well if both players went we
need to tell the server to reset um those player moves right so inside a game if
we call reset went we're just going to reset it so that we were able to play the
next round after okay we're going to accept uh accept of course i can't spell
that we're going to say run equals false we're going to do the same thing as
before we're going to print couldn't get game couldn't get game and then
we're gonna break okay now under this so after we send that reset now what
we want to do is we want to display a message on the screen indicating
whether player one one or player two one are like if you won or if the other
player won so the way we're gonna do this and it's actually a decent amount
of lines is because we have to like render font and then we gotta determine
where we're gonna draw the font and what's gonna be on the font so we're
first going to start by defining font so we'll say font equals pie game dot font
dot sys font okay in here we'll say comic sans font size let's go 90 for this one
now we're going to say if game.winner and remember if we go to game
winner is going to respond to us with either a zero a one or a negative one so
you have to check if winner is one and player so whatever our current player
is 1 then we're going to say u1 if winner is 1 but the current player 0 we're
going to say you lost right so that's how we can check this so to do that we're
going to say if game.winner equals equals 1 and player equals equals one and
remember we got that player from the server so we know if we're either
player zero or player one on the client side and uh is actually do i need an end
uh oh sorry or that's what we need to do or game.winner equals equals zero
and player equals equals zero so essentially what we're going to do here is
we're going to check if this player won so we know what player we are and
we know what player one so if that coincide like what player we are and the
player that won then we'll print out and we'll say or we'll put on the screen u1
right telling that client they want so we'll say text equals font.render and then
here we simply say uh u 1 exclamation point and then we can just do one and
then a color and obviously color we just do like red like that okay on the
screen okay so else actually l if and now we're going to check if they lost well
actually i think we could do this easier we're going to say l if uh game dot
winner equals equals negative one so if it if we tied what we'll do here is we'll
say text equals font.render and we'll just say tie game exclamation point one
again we'll put that in red okay and now else so if we didn't win and we didn't
tie we must have lost so we can literally just copy this and we'll just say you
lost uh as the text okay so you lost dot dot sweet and now what we're going to
do is just render that font put it on the screen so or not render it just put on the
screen so say win.blit uh text and now we're going to do the exact same thing
that we did before to get it in the middle of the screen just be a little bit easier
so we're just going to say i believe do i need another bracket so i don't think
so we'll say width over 2 and that's the width of the actual screen minus text
dot get underscore width we need those brackets over 2 we're gonna do
comma and now we'll just do the same thing with height so we'll say height
over two minus uh text dot get underscore height over two okay so that's
going to put it in the middle of the screen we're gonna update the display
highgame.display.update

and we're going to delay so pygame dot time dot delay and i'm going to put
2000 for two seconds you guys can put whatever you want in here okay so
let's break this down really quickly if both players went that means now we're
going to check who won so what we're going to do is we're going to redraw
the window we're going to what do you call it uh apply a small delay of 0.2
seconds just so that we can see what both players did before it immediately
pops up who won and who lost so actually let's make this delay half a second
we're going to send to the server reset so we're going to reset both players
once so the next time that we start playing we can both players are allowed to
move we're going to say run equals false if this doesn't happen if this doesn't
work we're going to print couldn't get a game we're going to break um now
otherwise so like if this worked we sent the game we're going to create a font
we're going to check who won so either we won we tied it we lost we're
going to display that to the screen we're in delay for two seconds and then
we're going to play the game again after okay awesome so we're almost done
we're just going to add this pretty actually complex for loop in here so we're
going to do now is we're going to say for event in pygame.event dot get very
standard for poggy you've probably seen this before i'm going to say if event
dot type equals equals pi game dot quits then what we're going to do is going
to say run equals false and we're going to say pie game dot quit so this just
means that they hit that little x button at the top of the corner now we're going
to check if they actually press their mouse button down so this is how we're
going to check if they pressed a button that's what we're going to do now let's
say if event dot type equals equals pi game dot mouse button down then what
we'll do is we'll get the mouse position to do that we're gonna say if we're
gonna say pygame.pause uh pygame.mouse dot get underscore pause so what
we're doing here is we're checking if they press right middle or left mouse
button if they do let's get the mouse position now for every single button
we're gonna check if we click that button if we did we're gonna do something
accordingly okay so we're gonna do now i'm gonna say four button in btns
remember we defined buttons up here then what we're going to say is if btn
dot click pause now if they did click the position there's a few things we need
to check oh and elsa we need to check this sorry and game dot connected
sorry so what this game.connected is doing is just making sure that it's not
going to let us press like rock paper scissors unless we both players are on so
just so that we don't run into an issue where we can make a move before the
other player uh connects okay so just add this and game.connected what we'll
do now is we're going to check what our current player is because this is
going to determine how we send a move so we're going to do now is going to
say if player equals equals zero if not game dot uh what do you call it p1
went then we'll do something otherwise so we'll just put uh else here and
we'll check if not p2 game.p21

okay so what we're doing now and i haven't coded the rest of it yet is we're
just going to check if we press one of the buttons so remember we have that
click method in our button that tells us if we clicked on it so if we do click on
it and we're connected to the game what we're going to do is we're going to
check if our current player is 0 or 1. now what we're doing is if we're player 0
well we're going to check if player 0 has gone yet if they've gone obviously
we're not going to let them make a move right because they've already made
that move they can't change their move once they made it same thing with
player 2. so if we're not player 0 we're player 1 clearly so that means we're
going to check if player 2 is gone yet and if they haven't gone we'll allow
them to move okay so what we'll do in here now is we're going to make a
move now to make a move remember we just need to send to the network our
move so we're going to say n.send or to the server sorry and all we're going to
do is we're just going to send the text of the button now the text of the button
will be rock paper or scissors right and that's precisely the move that we're
going to make depending on what button we're clicking so it's a really nice
dynamic way to do that now once we've done that right so if we go to server
what happens here is if we send that we're going to play that move and we're
going to update it on the game so that the other client when it gets that game
board again will have that updated move you guys will see how this works in
a second okay so that's working well now all we need to do is just add in line
with this right here we're gonna say redraw window we're gonna give it win
we're gonna give it uh what else do i need to give it game and p which stands
for current player and that's actually it for and make sure you just call our
calling main down here at the end of client that's actually it for this main
function so now all we need to do is do redraw window and we're really close
to done so we got another like 20 lines and then once we do that we're
actually finished this game and then we can start testing it out and talking
about some more things we can add to it okay so what we're going to do now
is yeah it's actually quite a bit of work is we're going to draw all the stuff on
the screen now so we've done all the logic aspect of it down here in this main
function now we need to draw everything so it's more tedious and it is
difficult but we're just going to first start by checking if not game.connected
now this just means if we have not yet had the other player connect then all
we're going to do is we're just going to print on the screen waiting for player
and we're not going to show anything else so to do that we're going to say
font equals pie game dot font dot sys font name obviously is comic sans and
then the how big should it be let's make it 80 okay and then we're going to
say text equals font dot render in here we're going to say waiting for player
dot dot one color let's do nice red and let's actually add true here for bold
okay okay so we're going to blit this on the screen so to do this we'll say win
dot blitz and we're going to do again that same i know a tedious thing to get
in the middle of the screen so we're just going to say with over 2 minus text
dot get underscore width and then we're going to say height over 2 minus text
dot get underscore height and actually we need to make sure we're dividing
both the width and the height by 2. so let's do that okay that's it for that now
else so this means if we actually are connected both players are in now it's
time to start drawing the real stuff on the screen so we need to draw that what
was it so actually let me pop up client for you guys so you can see what it
looks like uh let's run server rotten client client right so if we want to see the
client what we should do is we need to draw this this this this and then the
three buttons okay so we're gonna have to do these four texts and the thing is
these texts need to change um on like they're going to be different depending
on what player is looking at it right so for example here it's showing us what
our move is but notice it just says locked in for opponents it doesn't tell us
what our move is and with the other player's movements right so we need to
do that as well okay so to do that uh let's start we're gonna make another font
i'm gonna say font equals pie game dot font dot sys font comic sends size of
this font let's make it 60. and then what we're going to do is just say text
equals font dot render and we're going to do your move so we're going to
start by just doing your move and like opponent move because those aren't
going to change they're going to stay the same no matter what and for that
we're going to do one and the color i had there was like a nice cyan i think
right so we'll do this feel free to change the color i know it probably doesn't
look the best and let's just split this at a static position on the screen so we'll
say text and let's go 80 200. okay all right next so actually still in this else
statement we're going to copy this i'm just sorry what am i doing just this text
and this win part and we're going to put it down here and say your move
we're going to say opponent move is that how you spell that let's change that
to opponents and actually let's just get rid of moves to be too big opponents
and same color except we're just going to change the x value so that we draw
it at uh what do you call it 380 like that okay so that's it for your move and
opponents next what we need to do is bit more complicated because now we
have to draw what the actual moves are so remember we're obviously we
don't want to show the other player what one of the players moves is unless
both of them have gone it's like we want to know what our move is but we
can't know what the other players move is until we've both made a move so
to do this what we're going to do we're going to start by just getting both
player moves so we're going to say game dot get underscore player
underscore move we're going to get move 0 and actually we'll copy this and
just do move 2 and change this to 1. so we'll start by getting the moves and
then now we're going to check if we should show those moves if we should
show waiting or if we should show locked in okay so to do this we're going to
say if game dot both went okay like that what we're going to say is going to
say text 1 equals font dot render and we're just gonna use the same font as
before and what it's gonna be is move one comma one comma and we'll make
this black so zero zero zero okay and we'll copy this and we'll do the same
thing except text two is going to be equal to move to so essentially this is
saying if both of the players have gone well we can show their moves
because they both made them so let's do that and it's just rendering that font
and we'll display the font after uh you'll see that works so now otherwise if
both players have not gone what we need to do is we need to actually let me
just check something for a second is we need to determine if we're going to
show locked in meaning the other player actually has gone but we're not
going to show their move or if we're going to show waiting which means the
other player hasn't gone so to do this we're going to say if game dot p1 went
and p equals equals zero so this is saying if we have gone and it's our current
uh like we are the player we're player one so player one is gone and we are
player one what we're going to do is we're gonna say text one equals font dot
render move one which is the move we've done which is fine if we see that
and then we're gonna say one in color zero zero zero okay l if game dot p2
went and uh is this one it is actually sorry game.p1 went you guys will see
how this works in a second what we're going to say i'm going to say text 2
equals the same thing now this might be confusing but essentially what this is
doing is it's saying if player 1 is gone and we are player 1 we're going to say
uh if i spell render correctly render like that render sorry i got interrupter
there okay so if player one is gone and we are player one then we wanna
show underneath like your move what our move is otherwise what we want
to show is we want to show that uh like locked in so we're going to change
this to locked in underneath opponent's move because it means player 1 went
but it's not us so it's not our move so that means we want to show it under
opponents move so you'll see how this works we're going to say locked in
like that okay all right now we're just going to do else so this actually just
stands for if game.p1 hasn't like if they haven't moved yet we're just going to
say text 2 equals waiting so we'll say waiting

i believe that's correct um actually sorry these all need to be text one my bad
okay all right i know this is confusing but we'll go through it after all right so
we're gonna actually copy this and we're just gonna change everything to two
so this is gonna be p2 this is gonna be 1 this is going to be 2 it's going to be 2
and it's going to be 2 and this is going to be 2 as well and let me just make
sure that i did that correctly i believe i did okay sweet and now we are going
to actually show these we're going to blit these on the screen we're actually
really close to finish guys so to do this we're going to say if p equals equals
one so if we're player one what we'll do is say win.blitz and we'll say text two
and then where we're gonna show it we're to show it at 100 and 350. okay
now we'll copy this so ctrl d and we'll blit 1 except instead of at 100 we're
going to change this to 400. now we're just going to put an else so if we're not
player 1 clearly we must be player zero so we're just going to reverse these
player one player two now the reason we're doing this is because this is going
to be where like player one and player two's moves are shown on the screen
so we want it to make so that for each of our clients rather than saying like
player one player two and having one of the clients have their move on the
right side and one of them have it on the left side we want it to be the same
for each client you guys will see how this works when we actually run the
thing so let's actually just uh let's add in drawing the buttons so to draw the
buttons we could uh we could draw them in this else statement actually that
might be better yeah let's do it inside of this this else okay so we're gonna say
for btn in buttons we're just going to say btn.draw and give it a win and i
think that's actually all we need to do and lastly we're going to update the
display so pi game dot display dot update now assuming i didn't make any
critical errors this should actually be working so i know this has been a lot of
code and a lot of writing but i think i've kept it to just about an hour now
actually um and that's actually pretty decent time for creating a game like this
so you guys will see how this works now okay so let's try running our server
and see if we get any errors first of all okay server waiting for a connection
server started good sign so far okay clients let's try running a client so i'm
going to client oh name p is not defined win game p ah okay so what we're
gonna do for client this is a really easy fix just change this to player and i
might have to change oh yeah up here when i do redraw game window as
well we gotta do win um game and player okay so fix that all right client run
waiting for player all right good sign let's run another one and would you
look at that okay they both launch in now so you saw that waiting for players
showed up but as soon as we are ready now both of them are showing up
okay so this should be player one this should be player zero or player uh
player one player two right okay so let's try this now rock ah ran out of input
self.client i received 2048. okay so let's just have a quick look at why this
might be ah so i think i might have find found the issue i'm actually i don't
know if this is the issue exactly but we do need to fix this uh where i do game
dot reset inside of server here it actually needs to be reset went uh because
that's what i called it inside here reset went so we just gotta make sure we do
that okay guys so really silly error here actually um the issue was on the
server side here i'm calling play right like game.play and so actually i need to
get rid of the six i was just printing out the exception so i can see what it was
uh but essentially play doesn't actually exist because i misspelt something on
game i misspelled it i misspelled player it should be play so that was the issue
i was running into um it just it was very difficult to see because it was just
accepting it and not like not printing anything out just continuing to run the
server so i couldn't find it but essentially if we run the server and run the two
clients now we should have everything working i haven't actually tested it so
let's pray if i go paper sweet so it goes paper here we're not getting locked in
over here so that might be an issue but let's see if we make something here
then since you lost and you won okay so we have a slight issue but it's pretty
easy fix let's just go up to uh client just look through we're just probably
messing something up in the drawing code here so oh that would make sense
well we're not actually end up drawing yeah so this if p equals equals one this
just needs to tap back one um one indentation level and now we should have
everything actually working fine so let's try this now client client and let's go
rock okay so that works but it's not doing the locked in for some reason so
let's check this this locked in portion i just did close that server and make sure
that this is actually working ah so that needs to be p2 went and well if this
one should be working that was what's confusing okay so actually so that one
just need to be p2 went game.p2 went um let's try this server and let's go
client and let's run it again and go scissors locked in sweet so that's actually
working and the game is pretty well finished all we gotta do is add a menu
screen then we're gonna be done so now let's go scissors this is the scissors
scissors that's not correct we gotta fix that as well okay i thought i had
everything working guys i really thought so ah okay so i actually i do i do
know the issue it was it's pretty straightforward so in main here when we
check the uh let's see here the winners where do we check winners if it equals
equals one because equals negative one um ah okay so game.winner needs
brackets of course it does so we need to add that so obviously just some silly
errors guys so server's running right now let's run these clients see if
everything is indeed working as as it's supposed to be now okay so let's try
this paper blocked in scissors you lost you won yay okay everything's
working okay paper paper tie game sweet okay so you guys can obviously
mess around with the timing but you can see how this is working so the only
last thing to do now is watch this if i disconnect it disconnects both of them
so what we're going to want to do now if that happens is instead of just
completely like exiting the game we're going to want to bring them to a menu
screen where they can just click to reconnect and this is a really this actually
really easy to do um so what we're going to do is we're going to define
another function i'm going to call this menu underscore screen okay and in
here all we're going to do is have a really basic while loop that just checks if
you click something and all it's going to do there is click the uh run that main
function so we're gonna do is gonna say run equals true we're gonna say wow
run okay and then in here we're gonna say for event in pi game dot event dot
get and then obviously we're gonna check if they click exit so if event dot
type equals equals pi game dot quit then we will do is just do pi game don't
quit run equals false otherwise if they click any key so we'll say if event dot
type equals equals pi game dot and we'll just say mouse button down so i
should just get it they'll click the mouse button then what we'll do is we'll
simply say run equals false and at the bottom of run equals false what we're
going to do is we're just going to call main so all this is going to do and we'll
call menu underscore screen here so we'll say while true comma menu screen
okay and i'll go through this in a second or say while true menu screen okay
so we're gonna do is in menu screen if they click something we're gonna call
the main function which is simply going to uh what do you call it do all of
this stuff in here and then if they exit out of the main function so if you say
like run equals false because they disconnected it'll just rerun the menu
screen which means that they'll be prompted to reconnect to a new game
awesome what we'll do in here is a lot of clock as well this will say clock
equals pi game dot time dot clock give it a tick so clock dot tick 60. uh we'll
do we'll just draw something in here we don't need to use the redraw window
function uh we'll just do font equals pi game dot font dot sys font in here
we'll go comic sans we'll go 60 and then we're just going to render some text
we'll say text equals font.render in here we'll simply say click to connect or
click to play exclamation point one some nice red text and we can just
continually actually we can just window fill um so wind.fill and we'll just fill
it with white 0 0 0 or what am i saying gray actually 128 128 and we should
just where is win do i define it up here somewhere yes i do so that's sweet
winds up there so what we could do is just fill the window run into this while
loop put some text on the screen we may actually have to fill this every frame
let's get rid of one of those brackets i created so let's fill this every frame
actually okay so we'll fill it we will blit this font so let's say wind.blit text and
you know what for right now i don't want to deal we'll just do it statically
we'll just do like 150. so it's not at the top of the screen actually let's go 100
okay and go pie game dot display.update

python is more than just a programming language it is also a great place to


begin if you're just starting to code with the popularity and versatility that
python bags no wonder it is a great time to learn python programming hi i
welcome you all to this full course session on python programming and what
follows is hopefully a crash course of everything that you need to know to
start out with python but before we begin let's talk about our agenda for today
so we're gonna start out by introducing you to python here we are also going
to talk about the market trends and overview of python also we're gonna give
you a guided way of becoming a python developer now next we are going to
talk about the step-by-step installation of a python ide and we are going to
also help you run your first python program across various ides now next we
are going to talk about python basics here we are going to talk about
comments variables data types and operators in python now followed by
which we're going to talk about a few popular python libraries like numpy
and scipy now next we're going to get a little deeper here we're going to talk
about file handling and functions in python we're also going to discuss
concepts such as object oriented programming classes and inheritance in
python now followed by that we have a final topic which is web development
and web scraping in python here we are also going to talk about frameworks
associated with python like django flask and web to pi with that i come to the
end of the agenda also kindly take up this time to subscribe to us and don't
forget to hit that bell icon to never miss an update from the edureka youtube
channel also check out our python programming certification course the link
to which is in our description box below so without much to do let's get
started

python is the fastest growing language in terms of developers libraries and


applications that it can be used for it could be machine learning artificial
intelligence web development anything that you can think of python has
always got you covered now before we get started please subscribe to the
channel and turn on notifications for all of our future videos with that let's go
ahead with the agenda for today's session we shall understand what python
exactly is and why it is so popular thereafter the features that python has and
where it is used in the industries finally we can take a look at how to get
started off with the python basics and end our session with the career
opportunities that python holds for us let's move ahead with the first topic for
today what is python well python is a general purpose programming language
which is high level easy to learn and dynamically initialized the development
of python started out as a hobby for its creator judo van rosen because he
wanted to make a language that was beautiful to look at and easy for
everybody to read to do this he used indentations instead of curly braces to
basically describe the blocks of code that came inside the language the
language went on but did not receive love as it was slow compared to the
other languages now with the rise of machine learning and artificial
intelligence python has come into the spotlight because it makes the work
much more productive and much more easy why is that well it is because of
the amazing computing power that we have we just want work to be much
more productive even if it takes a lot of time so that basically wraps up this
topic of what is python having that understood let us move ahead and
understand why python is popular comparing it to the other languages python
is the best language to get started off with its easy syntax and high level
features make it one of the best language for anybody to get started off with
programming may it be kids or veterans it is the language for everybody the
next reason is that python is an open source language meaning that it is free
for anybody to use every day there are thousands of programmers who come
together online in making python better and efficient you modify the code
you break the code and you make the code you're allowed to do it without
any problems moving ahead python can be used to make almost anything gui
applications web applications mobile app server-side coding artificial
intelligence machine learning algorithms anything that you want to make
python will always have the way to do it lastly there is a huge community of
people who come together to make the libraries or modules that can be used
to obtain your solutions just for an example machine learning algorithms are
already available and you can use them to obtain your solutions better your
productivity right up there your code is much more lesser you can see why
people around the world prefer python so much features make a language
attractive and that is what python is made up of features that make anybody
want to start coding with it let us now see the different features that python
has in store for us the most well-known feature of python is its simplicity
python has made programming fun because it is simple it makes you think
more for your solution rather than the syntax the next important feature is that
python is an open source language which means that it is free for anybody to
use modifications to python are also allowed without any problems which
brings us to its next feature portability python supports portability which
means that you can write your code and share it with anybody that you want
to and it would work the same way as it does for you when you run the code
this makes movements of projects and systems much more easier our next
feature are the embedding properties chances are that certain languages may
perform certain functions better than python but that does not stop you as
python suppose adding code of other languages into itself to run those
functions which makes python all the more powerful with that let us move
over to the next feature interpretation python is interpreted line by line which
means the management of memory and cpu and debugging of the code much
more simple if you wonder by now whether python is the language to get
started off with let me tell you that it is python has a huge library support
which would help you to obtain solutions to your problems easier you can get
started off with data science web development on the go with python you
may have had questions like how do developers make applications that are so
well related to a domain that is because of object oriented concepts python
supports oops meaning that you can model a real world problem into your
code and have security for it such that access to them is restricted which
helps you replicate real world scenarios now that we know all the amazing
features that python has for us why don't we look at a few of the most well-
known companies who use python google is the most known tech giant who
uses python to provide better search features to its users dropbox is a cloud
platform to save data online its client and server applications have been coded
using python netflix uses machine learning with python to learn the taste of
its users cluster them into groups and then recommend them shows to retain
them for longer the national security agency uses python for cyber security
analysis and for the encryption and decryption purposes the bittorrent
application which is used for peer-to-peer communication started out as a
simple python file nasa scientists use python to perform calculations which
helps them reduce time and makes their work easier so these are the major
companies who use python as you may know python is a very important
language and it would definitely be beneficial if you start learning it now you
would wonder how do we get started off with learning python let me help
you with that so to get started off with learning this amazing programming
language you would firstly need the basics which are variables data types and
operators which helps you to understand data and the different data types that
you can use such as numeric lists tuples and so many more naming data and
performing operations which can help you to obtain logic or simple addition
or subtractions and so forth once you understand that you can move ahead to
understand arrays which can be used to store data in a structured manner
nextly understand the flow control working and how you can manipulate it
using loops such as the for loop and the while loop and conditions which are
the if-else statements you can then study about how to make methods which
are basically used to perform certain functions which can be as simple as
adding numbers to performing the most complex of work that you can think
of later learn how files are handled where you can read data from files and
write data to the files you can then learn about oops by understanding classes
and objects and what their importance is and finally to master it all you need
to practice python as much as you can because practice is what makes you
better at it once you are done understanding the basics what do you do you
master it there are a variety of careers that are at your disposal stick to the one
that you feel is your goal and start mastering it which brings us to the career
opportunities that python holds for us web app development is an option that
you can choose you have frameworks such as django and flowers that can be
used to create web applications game development is also a career option that
is available where you can create ai enemies and bosses and graphic textures
accordingly big data analysis is a booming field which can be used to obtain
data helpful to make decisions and help take risks for better profits web app
testing is also an option where you can report bugs and make sure that a
website works as needed data scientists machine learning engineer artificial
intelligence are some of the fields that everybody wants to get into and it is
clearly one of the jobs that looks like it would have a long life cycle smart iot
devices are another place where you can use python and build better
infrastructure for connecting the world so those are some of the most well-
known career opportunities that python has for you there are many more such
as a software developer automation engineer and much more so now i hope
all of you know what python is and why everybody loves it so much i hope
all of you would consider learning python because it is just fun to learn and
easy to program with

netflix is the leader of its clan for video streaming and for all tech savvies this
market giant has revealed that python is the secret to its success before we
begin just make sure you subscribe to our channel and hit the bell icon to stay
updated with all the latest edureka videos coming back towards this session
let's first begin with a small introduction to netflix and then we shall move on
to see how netflix uses python in various sectors such as for its cdn which is
open connect for demand engineering and machine learning big data
analytics and scientific experimentations video encoding animations security
and finally for monitoring and auto remediation so without any further delays
let's get started netflix as we all know is an american company which renders
video on demand services it has about 148 million subscribers throughout the
world and the number however keeps growing each day in a period of
approximately two decades netflix has emerged as the king of its clan for the
biggest tv series and movies throughout the world being the fastest growing
brand of america and having a revenue of 20.5 billion till june 2019 it's
enough for it to be an eye-catcher thereby interesting all into its technical
spheres let's move on to see how netflix uses python in its various domains
engineers at netflix admit that they use python for the full content life cycle
from deciding which content to fund all the way to operating the cdn that
serves the final video to 148 million subscribers now that we've taken the
name of cdn over here let's move on to see what this is and how it makes use
of python the cdn or content delivery network that netflix makes use of is
open connect this basically comes into picture when you hit the play button
all the content delivered to the end user is looked after by this cdn
openconnect basically requires various other softwares to design build and
operate it which are in turn written in python not just this the network devices
underlying this cdn are python applications since python is prominent in
solving network issues now that we are aware of the first component
openconnect let's move on to see how netflix uses python for its demand
engineering the demand engineering team is responsible for handling netflix
cloud's regional failovers traffic administration capacity operations
management which is looking after the limit up to which the content can be
made serviceable and fleet efficiency the library is used by this team are the
numpy and the scipy library which is used for performing numerical analysis
boto3 which is the software development kit of the amazon web services for
python this helps python developers integrate python into aws thereby
allowing development in the infrastructure radius q or rq which is a python
library which helps to keep track of the tasks that are present in the queue and
allows their execution thereby allowing the management of asynchronous
workloads flask netflix uses flask for python web development netflix uses
flask apis to bind all of the previous segments together not just this netflix
also makes use of jupiter notebooks along with interact which is an extension
for jupiter on a large scale jupiter is known to be popular for data analysis it
serves very well in operation data analysis and visualization which in turn
help in detecting capacity regressions now let's move on to see how python is
used for machine learning machine learning ranges from creating
personalization algorithms to figuring out the use cases personalization
algorithms help to train the machine learning models as per the netflix
standard it also provides personalized recommendations outlines on a day-to-
day basis label generations etc the library is required to learn deep neural
networks are tensorflow keras and pytorch whereas xg boost and light gbm
for gradient boosted decision trees netflix has also developed quite a few
higher level libraries that help in combining with the work areas such as fact
logging feature extraction publishing etc apart from all this netflix also makes
use of metaflow to create machine learning projects the big data team is
responsible to execute the etl or the extract transform load and ad hoc
pipelines a major part of this orchestration is written in python this team uses
a scheduler which runs on jupiter notebooks with paper mill to produce job
types with templates for example spark presto etc in addition to this the team
has also created an event driven platform which is built completely on python
they've created a number of events and combined it into a single one allowing
netflix to filter react and root events okay so now let's move on to see how
python is used for scientific experimentations this platform is basically
created for experimentations and to allow a b testing guys a b testing is also
called as split testing and it deals with comparing two versions and figuring
out the better performing variation among them the scientific experimentation
team can also present new innovations in data statistics and visualization the
python framework that is implemented here is metrics repo which is based on
pipica and allows writing of reusable parameterized queries for the statistics
sector pi arrow and rpy2 are used to calculate the statistics in either python or
r plotly helps in visualizations video encoding or media cloud engineering
this team is responsible for encoding and re-encoding tasks for the netflix
catalog python is used approximately for 50 projects such as the vmap which
is video multi-method assessment fusion and mezzanine file system computer
vision solution which deals with imagery using archer etc netflix animation
and nvfx python forms the base for all animations and visual effects at netflix
maya and nuke which are 3d and 2d computer graphic applications are united
using python now let's move on to see how netflix uses python for its
information security netflix uses python part information systems for auto
remediation security automation risk classifications etc the most active open
source project of this team is security monkey netflix also uses bless which
stands for bastion's lambda ampheral ssh service to protect secure shell
resources repo kid is used to grant iam permissions and tls certificates are
allotted through lemma both of these tasks rely mainly on python finally let's
move on to see how python is used for monitoring and auto remediation the
monitoring and auto remediation team is also known as insight engineering
team they build and execute tools for operational insight diagnostics auto
remediation and altering for most of its services this team makes use of
python for example the spectator python client library this library is used for
recording dimensional time series along with these libraries products like
winston and bolt are also built on python frameworks which are flask unicorn
and flask rest plus summing it all up one can easily claim that python is the
driving force for netflix

python has swallowed all its rivals in popularity and this popularity is directly
proportional to money making so before we begin just make sure you
subscribe to our channel and hit the bell icon to stay updated with all the
latest edureka videos coming back towards this session we shall first take a
look at who are python developers and what are their job trends then we shall
take a look at the average salaries drawn by these developers based on three
factors which are experience location and skill set so without any further
delays let's get started a python developer just like any other developer is
someone who designs programs and delivers software applications but using
python some of the most important responsibilities include writing effective
code for back-end components testing and debugging programs creating
applications that can be integrated with the present ones etc the current salary
trend of these developers has also remarkably increased but before taking a
look at that here is a survey that reasons out why python developers are
heavily paid python's popularity in 2019 is record breaking according to stack
overflow python has emerged as the most questioned language leaving
behind its fierce competitor javascript github grants python top slot in the
race for popularity so as you can see on the screen python stands first java is
second followed by javascript etc this popularity is also a reason for the
growth in job trends for python developers these developers are in great
demand all over the world in august 2019 indeed shows about 69 000
openings for a python developer most of these jobs are in sectors like web
development big data machine learning data science etc new york city has the
most number of job postings for python developers followed by chicago and
san francisco so given this i know you all will be eager to know what is the
average salary drawn by these developers the average salary depends on
many factors the three most important factors are experience location and
skill set so talking about a python developer's experience an entry level
python developer earns a minimum of 2.4 lakhs per annum the upper limit
however depends on the organizations and the skill set possessed by the
developer on an average the python developer's salary at an entry level is
about 5 lakhs per annum in india and about 88 000 dollars in the us the next
level of these developers is becoming a senior python developer and at this
level the average salary comes about 8 lakhs per annum the biggest leap in
salaries is seen after the senior level for developers so now let's move on
towards the next factor which is location salaries of python developers also
vary geographically in the u.s the best location for a python developer seems
to be california having an average of 122 000 dollars per year california
stands at the top of the list for best work locations for python developer when
it comes to india the best location for a software developer with python skills
is gurgaon having an average pay scale of 7 lakh 31 000 per year okay so
now moving on towards the next very important factor which is skill set
having the knowledge of python along with other skills proves to be a very
crucial factor influencing python developer salaries according to cv compiler
the most in demand skills preferred along with python are aws and django the
average salary for a python developer having knowledge of django is about 6
lakhs per annum which is much higher compared to the average scene earlier
in the session

how to become a python developer so guys i'll be discussing everything


related to a python developer you know who is a python developer what are
the various job roles available in the market who can become a python
developer and then prerequisites and everything around you know if you're
looking to you know uh make a career in python let's move forward and have
a look at the agenda for today so this is what we'll be discussing today will
begin my understanding who is a python developer and why one should even
consider python as a you know as a preferred programming language then the
question is how should i start i mean how should i go about becoming a
python developer then we'll focus on various job roles for a python developer
and let me tell you that there are a lot of job roles out there right so if you
think about python you have a lot of fields a lot of domains that you can go in
right then a few projects for practice i mean you can just find it on the
internet and then it's available uh and i believe the best way to learn anything
is to start working on it and you should start working on the project so i'm
going to give you a small introduction to a few of the projects that you can
start with now the question is who is a python developer so let me tell you
that uh first of all a python developer does not um it is a very uh subjective
term i would say why because you know there are a lot of domains there are a
lot of different types of job rules available and available in python right so
when i say python developer does not necessarily mean i'm talking about a
software engineer does not necessarily mean i'm talking about a web
developer or a mobile app developer right so a python developer is a very
vast field i mean uh something which doesn't exist right because there are
certain uh fields or sub domains in python that you can you know come up
with a job rule around that that's what i mean right so you know he can be a
software developer a software engineer he can be developing web apps uh
mobile apps he might be even into testing right because you can use python
with selenium then he can become a data analyst as well or he can be a data
scientist machine learning engineer artificial intelligence engineer so there
are different types of job rules available in the market next up we are going to
focus on you know why become a python developer because everything
exists for a reason right and uh let's try to figure out why one should even
consider python as a programming language when you have java javascript
and other different programming languages and the best answer given to this
question is by stack overflow so have a look at the graph guys right i don't
have to explain anything here because the red line the red curve that you're
seeing is of python right so from 2012 to 2018 you can see that it's it's an
exponential uh growth right uh this is it's a straight line i'm sorry right uh so
yeah i mean it's growing pretty fast and i would also tell you one thing guys it
always makes sense to learn something when you know there's a demand
there's no you cannot you know surf when there are no tights right so uh just
to explain you that now python comes with really really cool features so let
me just talk about those features first of all it is very very easy to learn so all
the people who are actually scared of coding uh don't you don't have to be
scared of python i'm i'm being really honest because it is very very easy to
write code in python the syntax is very easy right then tons of libraries guys if
you are talking about machine learning web development uh numeric
computation scientific computation whatever comes to your mind any type of
application python gives you a very good library around that whether it's
computer vision anything you can think of right so there are a lot of libraries
available uh with python that you can use for multiple purposes right uh next
is it is free and open source that i think a lot of you might already know right
and the best part is it has a very active community guys right high demand as
i've just proved uh with the stack overflow graph apart from that since python
is not only used for one particular domain or one particular purpose so if you
learn python you can go into any field right it's like you know a typical indian
household you know parents who tell their kids to go ahead and study
engineering and then he can decide what he wants to do well something
similar but uh this makes more sense right so uh these are the various features
guys right and a few companies few giants who are using python and let me
tell you guys each and every company out there in the market nowadays use
python right i've written down a few big names so that you can actually relate
google nasa you know firefox youtube netflix facebook dropbox raspberry pi
ibm walt disney all of them are using python and are very happy about the
services and uh you know basically whatever the python whatever python
comes with right next up we are going to talk about salary trends this is uh
something that you can see it on your screen but i would definitely tell you
guys it is a average number and generally a data scientist is not going to earn
you know eight lakh per annum uh eight lakh rupees per annum it will be
definitely more than that it's just an average we have taken it from a pay scale
it is definitely more than that i'm telling you that through my experience right
and devops engineer also earns a lot more than what it is here apart from that
there is also a start um around the python developer salary in popular cities
right uh so we have san francisco which is paying somewhere around 137
800 389 us dollars to python developers which is pretty great if you ask me
and uh i i am definitely sure it is a way above than 150 000 dollars in u.s as
well right but for now let's focus on how should i start how to you know go
about becoming a python developer obviously everything starts from basics
right you have to understand the fundamentals to reach to certain level so first
of all install python go ahead type on google install python right you'll go to
their official website you'll find a lot of a lot of things out there i can actually
show you that let me just open it

so if you click on install python you'll be directed to this website download


python here just select the version select the os that you're using and you are
good to go right choosing an id is uh you know it varies from person to
person i prefer pycharm you can also download python let me just take you to
one more link

download pycharm you'll be directed to a jetbrains website and here we go so


just go ahead uh click on the community version because the professional
version is uh you know you have to pay some amount for that all right so go
ahead click on the community version download it and it's very cool guys
because it gives you auto complete features and a lot of other benefits as well
you don't have to manually go and install the libraries using cmd you can just
go ahead and use python and do it right uh choosing an id is done a simple
hello world program right so i've already installed python i have python i'm
just going to show you how easy it is to write code in python right uh so let
me just quickly open my pycharm and all i'll do here is print hello world
all right i just have to click and select the interpreter as well let me just go to
the settings i'll just go to the interpreter

just have to select the interpreter and we are good to go now let's go ahead
and try executing again

it is again saying that you haven't selected an interpreter i just did that's weird
let's see yep i can see there is an interpreter so just waiting two minutes to
process uh let's just wait for that and we'll go back to our slides till then and
uh we'll continue so i'll tell you how to execute a simple hello world program
just give me like five minutes uh after that let's see what we have next we're
going to talk about a little bit about the basics so obviously as i've told you
earlier as well to become a python developer to become a data scientist or or
you know to go to a level in your in your career you have to start everything
from basics right so we have talked about we all we already talked about how
you can install python how you can install python id which is pycharm right
now let's talk about what are the basics that you actually need to learn now
people who are from a programming background can easily understand this
but uh people who are not uh let's just focus on them so variables and data
types you need to understand how to declare variables how to uh what are the
different types of variables that we can declare so there are numeric uh
variables that there can be uh you know list tuples sets dictionaries all those
data types you need to study there are a separate tutorial on all of these you
can go ahead and check out that in the python playlist but for now let's focus
here what i'm talking about then we have functions exceptions and input
output operations so how you input output operations basically mean how
you can open a file how you can delete a file how uh you can give our input
to the uh programming language right if you want to input something the user
wants to input some variable uh value right so input output operations plus
how to open close files delete files add certain things append certain things in
a file so all those things apart from that exception handling right what about
one by zero some some term like that comes which has no answer right so
how will you handle those exceptions that'll be covered in exception handling
there are functions which are nothing but useful code blocks right so that you
don't have to again and again write the same thing right if you have for
example if you want to calculate factorial 10 times in a program you don't
have to write the logic 10 times you can write a function and execute it 10
times just an example guys then loops control statements and conditional
statements which are very important right i am pretty sure you guys know
what are loops right if you have a set of uh you know if there's a logic that
you want to repeat again and again and you have a condition defined then
you can go ahead and use loops for that right so there are different types of
loop there there is a while loop right there's a for loop and yeah so there are
nested loops as well where inside one loop you can define one more loop uh
conditional statement if and if if statement so if a particular condition is true
execute this if it is not then execute the next statement so those kind of things
are called conditional statements uh data structures then you have oops
concepts what uh oops concepts basically you know your polymorphism
encapsulation classes objects how to declare them what are global variables
uh you know all those things uh it's basically a very vast field oops and it is
very very important and python is one of those programming languages
which have object oriented as well as procedural concepts right and file
handling i've just told you in the beginning itself how to open close delete
add append all those operations with a file right how you can do that with the
help of python right so now let me just go ahead open my python again and
i'll execute that hello world program so i think we can execute it now just a
second guys

it is just indexing right now

or how about i go ahead and create one more python file let us name it as test
and i'll type here print

hello world and here we go yup so with one line of code i can do this try
doing that in java

so guys that was a very simple hello world program that i've written there are
separate tutorials i'm again and again telling you guys um all right so now
let's talk about the job rules which i'm pretty sure everyone is waiting for it
uh next we have uh job rules as as i was mentioning so there are software
engineers and developers right these people might be writing apis for your
web app right these people might be uh you know helping with uh mobile
application these might be mobile application developer web application
developers right so basically what are desktop gy developers or game
developers all those people right uh so what sort of skills you know industries
look for in in such a for such a profile right so core python basics right which
i've just mentioned at the beginning where i was talking about data types
variables functions oops concepts file handling conditional statements loops
control statements all those things right apart from that you need to have
basic knowledge about the web frameworks right object relational mappers
restful apis you need to understand all these terms guys i cannot go into detail
of all of these terms but uh uh just to give you a knowledge basically you
need to understand how the web works you should you should know the
basics of web front and back end and you should be aware about of libraries
such as django and flask which are very famous python libraries for web
application development right database knowledge is a must because where is
your data anywhere going after you know somebody does any sort of activity
on your website it will go to a database right so that database knowledge is
very important for any developer out there in the market when i talk about
talk about script writing so scripting is a little bit different than programming
right so scripting basically is um suppose i want to execute seven programs
sequentially right so what i can do is i can write a script that can execute
those seven programs in an order that i have defined right so it basically
automates a lot of tasks right in this case i can write a script that will
automatically take my data and you know create a schema and store it in the
database so there's a lot of other things that you can do with a particular script
right so just wanted to tell you the difference between scripting and
programming and i hope you have i hope you have understood what you need
to understand what you need to learn what are the skills required in order to
become a developer whether you are a web application developer or any sort
of developer right let's move forward guys and let's see which is the job role
we are going to focus on next uh so we're gonna talk about uh a python web
developer right we just spoke about our web developer uh like uh in the
previous slide as well so here it's all about uh you know understanding the
web html css django flask mvc mvt architecture model view controller
template so these are all things that you need to understand right i mean these
are a few things which you will know once you start going and researching in
that particular field right database knowledge as i've told you it is a must for
any sort of developer right script writing is also very important because
without scripting guys there's no automation right any automation tool that
you use now also uses script right so just to clear the doubt uh you know
scripting is also very very important right now let's see which job role we are
going to focus on next

all right uh so a data scientist sexiest job of the 21st century right now what
do you need to learn to become a data scientist what skills are industries
looking for in a data scientist so you definitely require core uh skills right
core python skills which i've just discussed mathematics and statistics is the
core or you can say the foundation of a person who wants to become data
scientist that is very very important these fundamental topics are very very
important guys and people generally ignore them right so basics of
programming core python skills mathematics and statistics apart from that
you also require uh skills like you know data visualization or data wrangling
you might have to clean the data before processing it right then there's a skill
called eda data exploratory data analysis where you just figure out you just
look at the data understand the data what it is talking about what should i
predict what i can't predict which rows are useful for me which columns are
useless for me can i subtract a couple of columns and come up with a new
column that might be more useful for me so these are the things that you
know uh uh you should have that it only comes with experience and that's
how it works apart from that a very important skill is machine learning and
artificial intelligence so you need to be very uh you know you need to
understand all the machine learning algorithms you need to understand where
i can use which sort of a machine learning algorithm and if you want you
might come up with a different algorithm as well so how you can achieve that
with python so with python there are a lot of libraries that you can work on so
there's a library called pandas which is you know for creating data frames so
you can import any sort of data with the help of pandas whether it's a tsv file
csv file excel file doesn't matter you can import that data you can perform
basic operations joining concatenation merging any sort of operation then
you have numpy because python does not support anything called arrays
there's no there's nothing called arrays right so there are numpy arrays that
you need to create with the help of numpy package right so any sort of matrix
operation you can perform with the help of numpy scikit learn is a library
used for machine learning so it has predefined methods for different
algorithms whether it is knn k means all those algorithms there are there are
predefined functions or methods in this particular library that you can use and
very cool feature about this library is that it comes with sample data sets so
you can practice those data sets you can you can practice those data sets the
way you want i mean uh you you getting data sets guys you don't have to
download it what else you what else do you want so i've just received a very
good comment the explanation is very good and helpful uh thank you
mumtaz uh is it easy to learn sravya reddy well let me tell you this is the
easiest programming language that i have ever come across uh okay so
shiravayadee has one more questions i am fresher to learn python is it useful
in future please tell me well python is growing at a very very you know it's at
a very good rate uh you i just showed you the graph of stack overflow python
is very uh it's in demand right now and uh whether it is any domain python is
useful and definitely it will take over all the other languages in another five
years right because of the kind of community that they have and the kind of
packages that they come with right so let's move forward guys so uh now
we're gonna talk about uh data analyst right so data analyst is someone who
understands data and uh who understand a lot of things who understand the
entire data life cycle uh who can take care of data wrangling who can take
care of data exploratory analysis right all those things but they have only
implemented simple linear regression models right they uh you know are not
aware of those complex algorithms or some neural networks or some
complex machine learning algorithm which can be unsupervised for example
k means so they build prediction models simple regression models you know
sales forecasting and things like that uh they are very good with data
manipulation and they have this skill which is very important and it is called
as uh data driven problem solving approach so you need to understand you
know what sort of approach should i take for this particular data and that only
comes with experience right so uh that's how things work because um you
know you cannot just apply one algorithm to all the data sets that are there in
the market right you need to figure out what sort of a problem is it is it a
clustering problem is it a you know all those things so basically i don't want
to go into too much detail here but that's what a data analyst is right

so let's see uh emerging job roles so ai and ml engineer artificial intelligence


are properly also called as machine learning engineers these people are not
bothered about data pre-processing they get the good data they get the data
where they have to predict something it might be a regression problem where
they're predicting something it might be a clustering problem where they
might be clustering different people right it might be a classification problem
where they are classifying whether the given input is x or y right so that's
what the major job role of machine learning engineer or an ai engineer is so
they require programming skills data science skills and machine learning
right so that is what basically an ai ml engineer should have right uh apart
from that neural networks is what people are talking about right now it is a
buzzword in the industry and it takes machine learning to the next step and it
is called deep learning i cannot go into detail here i hope you guys can
understand but uh deep learning is very very interesting guys and there are a
lot of libraries that python has for deep learning one is tensorflow right and it
is a it is given to us by google so i hope you guys trust google right so you
know it's it's a very good library and i find it pretty interesting uh i have
separate tutorials on tensorflow as well right i have worked on tensorflow so
you can go ahead and check out my videos uh next is python automation
testing so what is python automation testing is basically you know you're
using okay let's talk about selenium because i can see only selenium in the
slide um so selenium uh you can write scripts in python using selenium right
uh you can perform functional testing uh basically you know testing login of
any website testing any feature whether it's login whether it's search engine or
any sort of feature whether the link is clickable uh the button is working all
sort of functional testing or you can say user acceptance testing can be done
with the help of python in a very automated fashion next is a deep learning
engineer so deep learning engineer focuses mainly on neural networks so he'll
need to understand different types of neural networks whether it's a recurrent
neural network it can be a convolutional neural network it can be rbm auto
encoders uh you know fully connected networks or or single layer multi-layer
perceptron so they should be they should have that thing where they can
understand all these different types of networks and have good experience in
working on applications such as video processing image processing computer
vision um you know speech to text text to speech uh image recognition so
how do you think that the facebook auto attack feature works right so it
works with the help of deep learning only right and uh right so that's how
that's how it is

now comes the road map guys okay so i have uh you know i'll talk about each
and each and every job role one by one so how you can master core python
so what you need to understand you need to learn variables and data types
file handling exception handling oops concept data structures iterators
generators rights these type of things where basics of programming you need
to understand right then well let's talk about master web frameworks so
django or flask whatever you prefer right uh tkinter is basically for gui based
uh web apps right uh then we have mvc mvt architecture that is basically a
model view controller and template that you need to understand html css is a
must for any web developer guys right it's it's and there's no rocket science
here i think people should be aware about it that web developers have to learn
html and css okay just a second towards data science if you want to go
statistics applied math data visualization analysis basically any sort of data
manipulation you need to understand that on top of it you need to understand
machine learning and you have you know python libraries to make your life
easy machine learning and artificial intelligence you need to be very good
with the machine learning algorithms understand you know libraries like
scikit-learn tensorflow probability statistics you should be very good with
apart from that neural networks and deep learning if you're looking to
become a neural network or deep learning engineer right

so deep learning again there's a neural network architecture that you need to
understand so machine learning and deep learning there's a very thin line here
but deep learning is nothing but an advanced machine learning right so don't
get confused here uh both are the subsets of artificial intelligence right
artificial intelligence is an umbrella term which encompasses machine
learning and deep learning together so this is though i don't want you to i
don't want you guys to uh be confused about it i mean it's very easy to
understand machine learning the next step after machine learning is deep
learning which uses neural networks so it's nothing but advanced machine
learning

and opencv for computer vision web scraping with bs4 predictions models etc
is what you should be knowing so opencv is basically a library which is used
for computer vision again i have a separate tutorial on opencv as well so you
guys can check that out apart from that web scraping is nothing but scraping
data or collecting data from different uh websites web pages that you can
easily do right and prediction models is i think you guys are already aware of

let's take a quick look at why you should consider learning python well guys
python is a general purpose language but it has a wide range of applications
ranging from web development scientific and mathematic computing and
even designing your own graphical user interfaces so you can make use of
django and bottle for web development you can make use of numpy and
senpai for mathematical computations and you can design your own games
using pygame as well and so much more guys and also the syntax of the
language is really really clean and the length of the code is relatively short it's
fun to work in python because it allows you to think about the problem rather
than focusing on the syntax itself guys and every fortune 500 company that
exists today uses python in one way or the other guys you don't even have to
do any digging to know this fact and again as i said python is extremely
popular among both the startups and established industry giants and
programming in python is definitely fun guys it's easier to understand and
write python code again why because the syntax feels natural guys and on
that note let us come to the main agenda of the session which is to help you
all to install and set up python let us begin so guys to begin with and install
python the easiest way is to come to the official documentation page and go
about from there so here i have opened up the officialpython.org page and we
are in the download section of the page as you can check the url we're at
python.org downloads slash windows guys since this tutorial is mainly
focused on installing python for windows we're here guys just in case if you
had to install on linux or something the steps are quite different from what we
do for windows however coming back the latest python 3 version releases
python 3.7.2 and the latest python 2 release is 2.7.15 well based on your
requirement and your needs at this point of time you should already know
which version of python that you should use and just in case if you don't you
can actually install both of these versions python 2 and python 3 into your
machine and go about from there as well guys well as you can check out
3.7.2 is the latest version of python at the time that this session was curated
guys so basically we need to go and download this from the official site well
all you need to do is click on the latest release version there and take it to the
download section desk however the first section is actually all of the changes
and the new features added in python 3.7 and there are multiple
documentations here as well so basically this is all the change log of this
particular version of python guys well all you need to do at this point of time
is to scroll down to the files section and then search for windows out here
well as you can see there are multiple versions to install right so you actually
get an embeddable zip file which is actually a zip file where you have to
unzip it and then install it manually or you actually have an executable
installer guys and if you can notice there are two versions here as well one is
the 32-bit version and the other one a 64-bit version guys well basically you
need to know if your machine is either running a 32-bit version of windows
or a 64-bit version of windows guys but however do note that the 32-bit
version is actually backwards compatible with 64-bit as well so what i mean
by that is in case if you have a 64-bit machine you can still go ahead and
install python 32-bit and it would work absolutely fine but if you have a 32-
bit windows then you will not be allowed to install the 64-bit version guys i
hope i'm clear with that and now that you would be familiar with your
particular version of windows both are actually of the same installer as well
well as soon as you go ahead and download it and basically all you need to
do is open it later guys giving it administrative privileges is a choice but then
it is always recommended so as soon as you run it as an admin you will be
greeted with the following screen guys so basically it is telling you the
python version right now and it has automatically selected 64-bit version for
my machine guys so basically you can actually customize the installation at
this point you can choose the location and the features you need as well and
all of that one main thing that i want you guys to do is that make sure that this
particular option is checked it says add python 3.7 to the path i will let you
know why this is really important but just make sure to check this at this
point guys and all you need to do is hit install now and python is ready in
your machine guys well basically as you can already see there it says that a
program called idle is also installed with it right so idle is nothing but a
graphical user interface which is used to work with python guys so let me
quickly open up idle to show you what it actually is well as you can check
out it is basically a python 3.7 shell guys so here you can actually type out
anything that you want so let us say printo hello edureka as soon as i hit enter
that is executed right so basically you can run any of the python programs
here as well so let me go ahead and do another x equal to 10 print x into 2 so
x into 2 is basically 10 into 2 20 and that is good right so it basically provides
a gui for python guys as simple as that but do note that if you actually have a
windows machine there is a very good chance that python might already
come installed on your machine guys however there is one more thing that
you need to do well that is to actually check out your environment variable
guys so basically you need to right click on my computer and go to properties
guys and in properties you need to go to advanced system settings and
environment variables and here you need to check if the path of the user
variable actually points to your python installation location guys so this is
basically why we had to have the checkbox during the installation well if this
is not the case then you have to manually come here and add the path in the
system variable guys so why is this required i'm pretty sure you guys could
have already guessed it at this point but let me quickly go over and show you
a demo let me open up my command prompt and if python is in my path as
soon as i hit python it is supposed to open up the interpreter and be ready for
me to execute commands guys and since i already have the path established it
is actually done so it is as simple as this guys well installing python is
actually pretty straightforward and simple but let me quickly push you on
another concept right well so next up on this session we'll actually check out
the different development environments available for python guys well
python has a large supporting community and there are numerous active
forums online which can be handy if you're stuck anywhere guys well at
edureka we have a vast community for python lots of blogs and these
amazing videos created by our subject matter experts as well so make sure to
check them out all right so we have multiple development environments for
python guys so we have pydiv for eclipse we have pycharm we have notepad
plus plus and bluefish for you all mac users as well we have commodo and
vim2 guys these are some of the many ids that's out there that you can
develop code in well i suggest you use something that you're comfortable
with and then go from there guys well choosing an ide is like choosing an ice
cream flavor you need to first try it out practically and see if it suits your need
perfectly if it does then go ahead and make use of it guys well personally in
my case it has been a long journey with python guys i have tried multiple ides
and i have a personal liking towards pycharm it is really simple and amazing
to work with and i am sure a majority of the entire community agrees with
me when i say that pycharm is the number one ide for python guys

let's talk about how you can write a simple hello world program in python or
before talking about a simple hell world program let me talk about the python
interpreter or python is also a piece of software called an interpreter the
interpreter is the program you'll need to run the python code and scripts
technically the interpreter is a layer of software that works between your
program and your computer hardware to get your code running now
depending upon the python implementation that you're using the interpreter
can be when you're writing a program in c it's going to be c python and if
you're writing the program in java it's going to be jpython or chaitan and then
we have a program written in python itself then we have pi pi and for the
program implemented in dot net there is going to be iron python as the
interpreter so whatever form the interpreter takes the code you write will
always be run by this program so therefore the first condition to be able to
run python scripts or python program is to have the interpreter correctly
installed on your system now the interpreter is able to run python code in two
different ways which is basically as a script or a module and the next one is
as a piece of code which is typed into an interactive session so talking about
the hello world program guys in python if you want to write a simple hello
world program it's very easy you just have to write a print statement and
inside the print statement you just have to specify the string which is hello
world inside the inverted commas so let's take it up to the command prompt
guys which i have opened the interactive session already so to print the hello
program what i'll do is i'll just mention hello world over here as a string
inside the commas and when i press enter it is going to show me the output as
hello world so this is as easy as it looks guys so this is how you run a simple
hello world program in python the syntax is pretty easy since it is python
programming and one of the salient features of python is the easy syntax so
what you have to do is just write a print statement and inside the print
statement we have written a string which is hello world inside the inverted
commas so now that we are done with how we can write a hello world
program in python let's see how we will run it using a dot py file and other
different approaches as well guys so i'll exit from here now okay let me open
idle guys which is what you get when you install python guys so i'll make a
file which is a new file of course so i'll just write print hello world over here
now i'll save it guys so i'll save it on desktop and i'll just write it as hello dot
py so this is going to be my dot py file guys so now when i run this i'm
getting the output as hello world so this is how you run a dot py file in idle
guys so this is a python shell guys so to print the same thing i'll just write
hello and eureka learner let's see what is going to happen now okay now
when i print this it's going to show me that the string that i have provided
over here now one more thing i want to show you guys when i open my
desktop over here i have a file which is demo and hello as well so these are
my dot py file extension guys so to run it in using the command prompt what
i have to do is i'll just write python over here and mention the file that i have
saved using the dot py file extension and you will see that okay we are not in
the same directory guys so you have to make sure you should be in the
directory where your file is actually saved so now when i run python and
mention the file name i'm getting the output as hello world now i'm check the
file i'll check the file over here

as you can see i'm getting the output over here so this is how you actually
execute a dot py file guys and a dot py file is nothing but a simple file which
has a python code and it is saved with an extension dot py which contains the
code or the script guys

we always like to have options in everything but choosing the best among
them especially in case of ides gets confusing so if you have any issues
regarding this here is the top 10 best ides for python to help you narrow down
on the most suitable one for you so before we begin just make sure you
subscribe to our channel and hit the bell icon to stay updated with all the
latest edureka videos moving on towards the session we shall first begin with
understanding what exactly is an ide and the basic features of it following
that we shall take a look at the top 10 best ides for python and the factors that
need to be in mind before selecting one of these so without any further dues
let's move ahead straight away to learn what exactly is an ide guys ide stands
for integrated development environment it's a graphical user interface where
programmers write their code and produce their final products and ide
basically unifies all essential tools required for software development and
testing this in turn helps the programmer to maximize his output now that you
know what is an ide let's move on to see what are the basic features of an ide
many of us do not know the difference between code editors and ides code
editors are applications that are able to write and manipulate source code they
can either be standalone applications or can be integrated into ides the only
feature a code editor should support is being able to edit text on the other
hand an ide is a complete environment where you can create software
applications in addition to code editors ides also have other features such as
syntax highlighting which is used to mark the syntax of the base language in
different colours and fonts the autocompletion feature is designed to
minimize the time consumption a debugger is available which is required to
test and debug the source code ides also consist of compilers now these are
tools that translate source code from one language to another finally ides can
either be language specific or may have support for multiple languages the
choice relies on the user to single out and embrace the ides of his choice now
that you know basic features of an ide let's move on to see what are the top 10
best ides for python at our position 10 is idle it's a platform open source ide
which comes as a default implementation along with python and it's written
completely in python as well its name is presumed to be in honor of eric idle
who is one of the founding members of monty python this ide is considered
to be extremely suitable for the education industry due to its simplicity it also
provides special features such as availability of a python shell with syntax
highlighting a multi-window text editor program animation or stepping which
refers to executing one line of code at a time breakpoints are available to ease
the debugging and the call stack is clearly visible at position 9 is tony this is
an ide that was developed for beginners it provides step-by-step assistance to
the programmer it has separate windows that are provided to execute function
calls line numbers are available to the user to keep track of each line log of
the user actions is available so as to assist the user in future statement
stepping without breakpoints is also possible moving on towards the next ide
which takes the eighth slot is atom atom is an open source cross platform ide
built using web technologies atom is based on the electron framework which
is built by github it also provides some remarkable features such as support
for third-party packages and themes so as to format the editor atoms apm
allows installation and management of packages it also provides support for a
number of languages other than python such as c c plus plus java etc atom
also consists of an exception reporting package at the seventh place is eric
python eric python is an open source cross-platform ide which is written
completely in python its source code is available freely and can be studied
and recreated by anybody some of the quality features provided by eric
python are formatible window layout formatible syntax highlighting code
folding which is selectively showing or hiding some part of your code it is
also furnished with a class browser and has built-in support for unit testing
and django at the sixth position is wing this cross-platform ide was created by
wingwear it is a lightweight ide and designed to allow quick programming it
comes in three variants namely wing pro wing personal and wing 101 wing
pro is a professional version which is priced somewhere between 95 to 179
wing personal and wing 101 on the other hand are simplified free versions
that are available for students and beginners wing provides special features
such as automatic multi-process and child process debugging remote debug
process is possible it also has a module browser and allows refactoring which
is a process of structuring existing computer code it also provides auto
completion feature for non-python files as well now let's move on towards
sublime text which stands at the fifth position guys sublime text is a cross
platform ide priced at 80 it is developed and c plus plus and python in
addition to python it provides support for other languages as well the features
of this ide can be enhanced using plugins the go to anything feature allows
quick access to files symbols or lines its command palette provides robust
matching for keyboard invocations python based plugin apis are supported
this ide also allows simultaneous editing and the preferences can be made
project specific at position 4 is rodeo rodeo is an open source cross-platform
ide built in particular for machine learning and data science rodeo makes it
very convenient to load and compare data it also allows data experimentation
and is furnished with python tutorials to guide the users it also provides cheat
sheets for material reference files and package search is made very easy
rodeo is a simple and a lightweight ide at the third slot is pydiv this is an open
source cross-platform third-party package which serves as a plug-in for
eclipse which in turn enables it for python development pydev provides a
remote debugger wherein the files which are not launched in eclipse can be
debugged it also provides the code folding feature so as to selectively hide or
display sections of code it provides support for python 2x and 3x syntax the
auto edit feature can automatically edit the parenthesis add self parameter to
the class methods and can also add import keyword in the import lines
standing at number 2 spyder is an open source cross platform ide designed
mainly for data analysis and scientists it's considered to be a powerful
scientific development ide written in python spyder is integrated with many
scientific python libraries such as scipy numpy matplotlib pandas etc
pertaining to its scientific use spyder provides advanced support for editing
analysis and data exploration it also allows static code analysis wherein the
analysis is performed without actually executing the code the features of this
ide can be expanded further through plugin system and api the ide that takes
the top slot and is at position number one is my personal favorite pycharm it
was developed by the zek company jetbrains and it's a cross-platform ide it
comes in two versions wherein the community version is free and the
professional version is priced at 199 dollars per user pycharm is considered to
be one of the best ides and also the most widely used because of its
remarkable features such as specialized project views allowing quick
switching between files it also facilitates web development along with django
flask and web 2 pi pycharm is equipped with more than thousand plugins so
programmers can write their own plugins to extend its features 81 of the top
100 companies make use of pycharm before ending the session let me just
help you guys to narrow down on the best ide that's suitable for you before
choosing an ide keep the following points in mind the level of expertise of
the programmer the type of industry or sector where python is being used
ability to buy commercial versions or stick to the free ones the kind of
software being developed and the need to integrate with other languages once
these points are decided upon the programmer can easily select among the
ides which we have discussed earlier based on the given features

so now exactly on that note let us start checking out pycharm so guys many
programmers nowadays opt for python to build software application right so
they need the code to be concise clean and readable as well they can even
accelerate custom software application development by actually taking
advantage of the number of ides supported for python well a company called
jetbrains has actually developed pycharm as a cross-platform ide for python
in addition to supporting versions 2.x and 3.x of python pycharm is also
compatible with windows linux and even mac os and at the same time the
tools and the features provided by pycharm helps programmers to write a
variety of software applications in python very quickly and efficiently guys
so the developers can even customize the pycharm ui according to their
specific needs and preferences also they can extend the ide by choosing over i
think say around 50 plugins as well to meet their complex project
requirements so again it is a win-win for everyone starting from the beginner
to the advanced user as well so pycharm is one of the most widely used ides
for python programming as i mentioned at present python ide is being used
by all of the large enterprises like twitter we have pinterest we have hp we
have semantic and even groupon guys so this is really a good thing in terms
of industry traction so now that that's done we need to check out why
pycharm is so popular i'm sure you guys were thinking about this right so let
me quickly walk you through all of the features and the tools provided by
pycharm guys so first we'll look at the features and later we'll move to the
tools so the first important tool we have is the code editor guys so what is the
code editor feature so basically the intelligent code editor provided by
pycharm enables all of us programmers to write say high quality python code
directly guys so the editor enables programs to read code easily through their
different color schemes insert indents on new lines automatically pick the
appropriate coding style and avail context aware code completion as well and
at the same time the programmers can also use the editor to expand the code
block to an expression or a logical block they can also avail code snippets
format the code identify the errors and misspellings as well they can even
detect duplicate code and auto generate code too also the editor makes it
easier for developers to basically analyze the code on the whole and identify
the errors while writing the code guys now that was an important feature right
so next one i want to talk about is code navigation guys so the smart code
navigation options provided by pycharm basically help the programmers to
edit and improve the code without putting any extra effort or time the id
basically makes it easier for the programmers to go to a class or a file a
symbol and go along to the declarations invoked from a particular reference
as well and the user can even find an item in the source code or the code
snippet ui element or a user action almost immediately so basically they can
further locate usage of various symbols and set benchmarks in the code and
also at the same time the developers can even take advantage of the code
navigation feature to scrutinize the code throughoutly in this mode called as
the lens mode guys so next up we have refactoring well pycharm definitely
makes it easier for the developers to implement both local and global changes
really quickly and efficiently guys so the developers can even take advantage
of the refactoring options provided by the ide while writing plain python code
and working with python frameworks they can avail the rename and move
factoring for files classes functions methods even properties parameters and
local and global variables as well also likewise they can improve the code
quality by extracting variables fields constants and even parameters also
pycharm allows programmers to break up longer classes and methods
through the extract method so next up is support for web technologies guys
pychar makes it easier for programmers to write various web applications in
python so python basically supports technologies like html css javascript
typescript and even coffeescript right so the web developers can basically use
the live editing preview options provided by the ide to view a single web
page simultaneously in the editor as well as the browser so at the same time
the live edit feature provided by the ide enables programmers to see the
changes made to the code instantaneously on a web browser pycharm further
allows developers to avail a javascript debugger as well as coffeescript and
typescript editors as well do note that it even simplifies isomorphic web
application development as well and this is done because it supports both
angularjs and node.js guys so the last feature is support for python scientific
libraries so guys pycharm further helps programmers to use python more
efficiently in big data and data science projects as well so it supports some of
the widely used scientific libraries for python starting from numpy anaconda
and matplotlib as well so the developers can work efficiently with all of these
scientific libraries by availing the interactive graphs deep code insight even
array viewers provided by the ide they can even run the repl python console
provided by python to avail robust features like on-the-fly syntax check and
code inspection as well and at the same time programmers can also integrate
the ide seamlessly with the ipython notebook to create innovative solutions
without putting extra time and effort as well so that is a really good added
advantage as well right so now that we're done with the features let me
quickly walk you through the important tools well all these tools definitely
give pycharm the upper hand so let's check it out so the first one you'll be
checking out is database tools in addition to supporting various python
libraries and frameworks python allows developers to work with a number of
relational databases including oracle sql server mysql and even postgresql as
well so the developers can further use the ide to run the queries edit the sql
code browse data alter table data even analyze the schemas as well well guys
pycharm further supports sql alchemy library and inject sql code into code
which is written in various programming languages as well the professional
edition of the ide further makes it easier for the developers to handle large
volumes of data efficiently through the data grids and next we have visual
debugger so guys the visual debugger provided by the ide basically helps the
programmers to debug python javascript and django code directly the
developers can use the inline debugger to see live debugging data directly on
the editor likewise they can build multiple python processes simultaneously
and step through the code bypass libraries as well pytham further creates
reusable and customizable configuration for each test script or debugger
execution the user can have an option to facilitate remote debugging by
integrating the visual debugger with the remote interpreters directly and the
next feature we have is built-in terminal well guys pycharm comes with a
local terminal for windows linux and mac as well so the built-in terminal
basically enables the programmers to continue the code and test without ever
leaving the ide also the programmers can use the ide to basically run the
python files and configure custom python environments well well this is done
according to the precise project requirements as well so that's good and at the
same time they can run interactive python or django console directly into the
ide and the console provides useful features like code completion automatic
braces management and dynamic center exchange the programmers even
have an option to integrate the console with both local and remote interpreters
so the terminal is a really big advantage guys and next up we have software
testing so like any other ids pycharm also comes with features and tools to
simplify python application testing it allows developers to perform unit
testing through popular python testing framework like nodes ad tests and doc
tests as well so the testers even have an option to run individual or multiple
test files and test classes guys they can further integrate the ide with
coverage.py to measure the code coverage while testing the applications as
well and while testing multi-threaded applications the testers can use a thread
concurrency visualization option provided by the ide to control the
application fully and efficiently at the same time python enables users to
deliver high quality software by implementing behavior driven development
guys in short we actually call this as bdd and lastly we have remote
development capabilities guys python allows developers to connect with
various machines and build software applications remotely the programmers
can avail the built-in ssh console provided by the ide to basically connect to
machines and perform various development tasks remotely through ssh so
they can even run debug and profile the python applications in a remote
environment by replacing the local interpreter with that of the remote
interpreter and also pycharm enables programmers to create reproducible
development environments through a robust tool called as vagrant guys and
this basically simplifies distributed application development and this is done
using docker the users even have the option to integrate pycharm seamlessly
with issue tracking systems as well so in my opinion that is enough of
knowing what it offers so let us dive right into pycharm now and i'll walk you
through the interface let me open up my pycharm so guys this is probably the
first screen that pycharm greets you with so on the left here you will basically
have all of the codes that you have actually worked with or any of the recent
projects that you opened um i have a quite so i have a handful of projects
right here so basically this might be blank for you if you're installing pycharm
for the first time and guys installing pycharm is very simple so it is free and
the installation is extremely straightforward as well so all you need to do is
go to the official website and it's a single step download procedure i already
have it installed on my machine as you can see so first let's go ahead and
create a new project in pycharm guys so all you need to do is hit create new
project on the right side and give a name for the project so let me just type it
out as pycharm test and then for now you might not have the python
interpreter i'll just come back to this so for now let me just hit create and let
pycharm take us to the ui so basically it has created the project folder for us
as you can check out on the left and it is blankets and this part actually
queries all the skeleton procedure and this is the time where it actually sort of
scrolls through and checks all of the installed packages and also it probably
will take a while and you could actually catch it rotating somewhere here
guys so this is good so let us quickly go ahead and create a new python file
that we can write into so click new new scratch file what type of file are we
trying to do here cbs so the file we're trying to do is python here right so that
and you can write in different languages as well so basically you can use
xhtml xml html dtd command line as well so right now since we're doing
python let me quickly go ahead and type in python so as you can see we have
a scratch file which says scratch.py guys so you can basically right click
refactor and rename this to whatever you want but since this is just a demo i'll
leave it at scratch so then there are multiple options to go with as well but if
you want to get started really simple just follow all the procedure until now to
create a scratch file and later you need to add the configuration to actually use
python to run this guys so we click on add configuration click on the tiny plus
icon python and then we don't have any configurations right so let me name
this test config and then the script path the script path basically is providing
the path to the particular script so it's pycharm test and then as soon as we
come into the environment here is where you'll be actually checking out our
interpreter guys so i have multiple versions of python installed as you can see
i have 3.7 and i have 3.6 as well so there is a very good chance that this might
not show for you because you have not installed python and it is very simple
to install python guys so i'll just show you that in a second so this is the part
where we actually select our interpreter 3.7 and all we need to do is okay so
this is actually ready to execute with our test configuration guys so enough
coming back to how you can install python okay so basically we open file
settings and in settings we actually come to project python test guys so click
on the project interpreter and on the right side you can actually check out the
interpreter so basically we have multiple interpreters here and for this case
i'm going to use mini conda 3 and that's what i've used so for your case if you
have not installed it so go to the gear icon on the right and click add sure you
can actually use the system interpreter which has python in it guys so in my
case i've installed it using anaconda so it says anaconda so make sure you
click this and hit ok and you're done guys so apply so now that all that is done
right so how can we add all the packages to python not everything comes in
built right so again go to file settings this is pretty much almost same guys so
we go to the interpreter and then we have the packages tab under this so
basically we use the gear icon to actually check out our interpreter now check
out all the lists we have guys so basically these are all of the packages that is
installed for my particular case so these are all of the libraries that are
installed guys so in case if you need to add a library hit on the plus icon on
the right side so just type in any of the libraries that you require right so there
are multiple installed as well as you can see whatever is in blue is actually
installed if i just type in tensorflow it says already installed but then it won't
be in blue for you because you might have not installed this right so click on
that install package on the left side and you're good to go how simple is it
guys so now that we're actually all set up and we're waiting in our scratch file
so let me quickly walk you through a tiny code snippet and we can check out
the advantages here as well so guys let me try to quickly import a package
here i'm not even going to type the entire thing right so i just basically typed
out the first three letters imp and it is actually prompting me to pick up the
entire thing right so this is basically how intellisense works in visual studio
and this is all the intelligence of pycharm guys so it is at this point of time
you can actually choose to type in the entire thing like ort or you can just
again come back imp and then you realize that you want to use import so all
you need to do is either hit enter or you can hit tab as well and it takes the
entire thing so this definitely helps reduce a lot of time by providing good
predictions right so this was just basically one line of codes so imagine if you
have to write hundreds and thousands of lines of code then this is definitely a
lifesaver in my opinion so next i'm gonna actually try importing a package
let's say pygame so import pygame come to the new line so as you can check
out everything is grayed out here right so we can actually change the color by
making sure we actually use something right so let me quickly go and buy
game dot init for example as you can see the color change right so this is
basically telling us that pi game is being used now simple as that and next
this is another actually good tip for you guys so let me quickly take an
example i equal to 10 i'm gonna print i so as you can already guess this is not
a very complex code right so it is going to print i so as soon as i run this piece
of code i'm supposed to get i printed to be like five times right so check this
out this was only five times so let's say you have a piece of code where you
have to change
something right so let me change this i to p quickly and now that this has
been changed to p since this is a small program i can probably go ahead and
change this manually right so i can go ahead and change this to vp again p
one more see again it took like almost 20 seconds to do this for five times
right so imagine if someone has to do this for thousands of lines of code so it
becomes really annoying right and this is where another useful feature of
pycharm helps us so let me quickly select this p as you can see if this is
selected every p here is highlighted right so let me quickly right click on it go
to refactor and then hit rename so let's say instead of p we want it to be test
and as soon as i hit refactor boom as you can check out right so once this got
changed everything else got changed in just one click and this is also a life
saver in my opinion guys so next up there are multiple keyboard shortcuts
you can use as well so basically it's the same we can use ctrl f to actually find
something and then use it right so this actually works even in scope as well so
let's say you're in the scope of a function or a user-defined function or
something and then you want to find something in that particular scope so
this particular search option actually works there as well so basically with
coding you would have done multiple changes right so you would have done
multiple changes with your program and in case you just want to check out
what are all the changes that you have done so we actually press alt shift and
c to actually give us a list of changes that we have actually done check this
out so these are all of the changes that we have actually done right so we
deleted something or created a new scratch file so this basically goes in the
reverse order guys so this is definitely useful in case you actually want to step
back or check out what are the changes that got done and then in case if you
just want to print the same thing over and over again you can do it as well so
let me quickly go ahead and type out print say edureka or something like this
guys these are all examples right so do not bother about the exact syntax right
now i'm just trying to show you how pycharm works here so basically in case
i have to just hit this print again so instead of typing it out or copying and
pasting it to something there is actually a shortcut because i'm going to place
the cursor here and i'm going to hit ctrl d so ctrl d basically duplicates this
entire line for us and how cool is that guys so guys the next feature i want to
show you guys is basically to select a current column so let me just quickly
select print here and then i'm going to use alt and actually scroll guys i am not
sure how you might actually use this but you can select the columnar output
of it and maybe this might help for your particular requirement is right so
basically you can use it for orientation of the code as well and then this
basically depends on your requirement but this is a very good feature
provided by python guys so basically to run this all you need to do is select it
or right click or run scratch or say you can even click the play icon here as
well to debug it there is a tiny bug icon on the right so basically you just
place the debugger wherever you want and you can actually stop execution at
this particular point of time and later move on from there as well so guys
there are n number of features that pycharm offers and to keep the session
simple so i basically just showed you all of the tips and tricks that you can
actually use with it so guys on the whole python is one of the most popular
ideas for python so the python programmers can make use of pycharm as
licensed software as well however jetbrains allows developers to choose
between three distinct editions of the ide guys community professional and
educational the developers can always curtail software development cost by
opting for the community edition of pycharm however the community edition
is free but it still lacks some of the advanced features provided by the
professional editions case so jetbrains have been updating both editions of the
python ide to make programmers more productive and simplify custom
software development as well let's say for instance the professional edition of
fight charm 2017.3 actually makes it easier for developers to test
functionalities of the api by providing a built-in rest client likewise it
accelerates web application development by allowing programmers to avail
new features provided by django 2.0 and also it allows developers to
visualize and analyze the data more efficiently through a data science model
as well guys so now that we checked out python in really good amount of
detail let me quickly conclude the session for you guys so we started out by
checking out what an ide is later we looked at why we need to make use in
ide followed by that we actually looked at the different ids you can make use
of to code with python and lastly we checked out python in a small amount of
detail guys so it is at this point of time i'd like to tell you that we have in-
depth tutorials and blogs on python and even a complete master's program
which will help you become a certified python expert guys so i highly
suggest you guys check it out

have you ever asked any programmer to explain the code he wrote a year ago
or have you ever tried reading your own previously written code it would
become a very time consuming and tiring task guys if you had to reanalyze
every block of code from scratch well the best thing to do is add a comment
so let's just quickly move ahead and look at what's in store under this topic
firstly we shall understand what exactly comments mean and when to use
them then i'll be showing you how to write comments in python and how
they're going to be interpreted following that we will be looking at the types
of comments that is single line and multi-line comments and a few shortcuts
related to them and finally we will be looking at docstring comments or to be
more precise dog strings as comments so i hope you're clear with this moving
on towards the first topic of the session what are comments no they are not
something there just to increase the size of your code but guys they are
indeed very meaningful comments are programmer coherent statements that
describe what a block of code means and they get very useful especially
when you're writing large blocks of code say for example you've developed
some software previously and now you're working on something that's new
and completely different at this point of time you find that your previous
software is throwing some error you would have completely forgotten what
you did and how so this is where comments come into picture a good code
actually consists of relevant comments these comments actually increase the
readability of the program not just to the programmer but to the others as well
now that you know what are comments let's move on and see when to use
them the best practice is to write comments as and how you proceed with
your code comments are very useful but only if they are implemented wisely
just keep the following points in mind when you're commenting your code
make sure your comments are very precise and clear and preferably short as
well they need to be as specific as possible to the block of code they are
included with please make sure you use decent language guys and do not
repeat your comments as they become redundant now that you know what are
comments and their importance let's see how to write them in python
comments in python are preceded by a hash character as you can see on the
screen over here i have a small example with some two lines of code my first
line is a comment and my second line is a print statement now let's move on
towards the jupiter notebook and see how this works now let's move on
towards the jupiter notebook and write some comments all i'm going to do
over here is i'll open a new python notebook and i will rename this notebook
to rename your notebook guys all you have to do is click on the title give
whatever title you want

and use rename like i've told you before comments start with a hash character
in python so here i'm going to write a comment preceded by a hash

as you can see my output there is nothing related to the comment line and
whatever i have printed in the print statement has been returned as my output
now this is how comments work they do not show up in your output now let's
get back to our presentation and see how they are interpreted which is exactly
what is our next topic whenever the interpreter encounters a hash symbol it
omits whatever is present after that the hash character actually tells the
interpreter to stop reading whatever is present after that until the end of that
line so when you're writing comments whatever is present after your hash
character is going to be omitted by your interpreter now what if the hash
character was present inside the string let's go to our jupyter notebook and see
what happens i am including a hash character within a string and i will run
this

as you can see when i run this the string is returned which means a hash
inside a string means a hash itself and nothing else so you cannot write
comments within a string okay so i hope you've understood how to write
comments now let us move ahead and see what are the types of comments
comments can either be single line or multi-line single line comments can
either appear individually or in line with some other code multi-line
comments have to be preceded by a hash character in every line they appear
now let's see a small example of single line comments like i've told you
before single line comments can appear either in an individual line or in line
with some other code now let's move on towards the jupiter notebook and
write some single line comments i'll just create a heading over here to create
a heading all you have to do is go to code select heading give whatever
heading you want as your heading and prefix it by a hash a single hash tells
that it's h1 level heading two hashes tell that it's h2 and so on you can use the
heading level of your choice here i prefixed my heading by a single hash
which means it's of level h1 now let's write some single line comments

as you can see over here my first line of code is a comment line i've prefixed
this line by a hash character and in my last line i have an inline comment this
inline comment is present with some part of the code as you can see in the
output none of the comments have been returned now let's get back to our
presentation and see how multi-line comments work like i've already told you
multi-line comments can appear anywhere in your code but each line needs to
be prefixed by a hash character for example as you can see on your screens i
have a hash character present in the first two lines of my code after that i have
some code followed by it you can see in the output that none of these lines
have been returned now let's go to our jupiter notebook and write some multi-
line comments
as you can see over here i have three initial comment lines and all three have
been prefixed by a hash after that i have some code and you can see in the
output that none of the comment lines have been returned and whatever code
is present after that an output is returned based on this code now typing a
hash everywhere might be a problem and many of us would not like to do so
let's look at some shortcut methods of how to comment multiple lines at once
all you have to do is type your multiline comments first

hold the ctrl key and left click wherever you want to insert a hash character
just like how i'm showing you all and then type it once and it appears
wherever i have inserted the cursor as you can see on the screens now in case
you want to remove multiple hash characters all at once do the same thing
hold the ctrl key click on wherever you want to remove the hash character
from and press the backspace key as you can see from two lines i removed a
hash character in a single go so these are some shortcut methods to comment
multiple lines many of us think that comments and docs strings are same now
let's move ahead and see what are doc strings and whether they are actually
comments or not doc strings are not actually comments but they are
documentation strings these strings are written within triple quotes they are
not assigned to any variable and many a times they are used as comments as
well now you'd be thinking what is the difference between docs strings and
comments docstrings are not omitted by the interpreter unlike comments
comments are omitted by your interpreter and nothing present after the hash
character is going to be read by it on the other hand doc strings are strings
that describe something about the code docstrings actually tell what some
function is going to do whereas the comments will tell how it is going to do
so this is the difference between doc strings and comments now let's go to our
jupiter notebook and see their functionality

like i've told you before doc strings are written within triple quotes as you can
see in the output when i execute this it returns the string itself whereas in case
of a comment when i execute a comment it does not return anything which
means the interpreter does not omit docs strings whereas it omits the
comment now these dog strings are efficiently used when you want to
describe something about a class or a function or something else now these
dog strings can either appear in your output or they can be omitted based on
where you're going to place them let's try to place a dock string initially
before the code starts

as you can see in my output the dock string has not been returned whereas
when i use the docstring individually without any code and i executed it you
could see that it had returned the string itself but when i include the docs
string before the code and after that i've included some code lines and i run
this you can see that only the output for my code is present and nothing
related to the docs string has been returned as my output now let's try to
include a doc string after some code

as you can see over here when i included the dock string after the code it has
returned the output for the code as well as the string itself so when you're
making use of docs strings just be specific of whether you want it to be
returned in your output or not many a times these strings are called rather
than writing it again and again so i hope you've understood what are
comments and doc strings as well

first of all we have to understand what a variable is a variable is like a


memory location where you store a value now this value you have stored you
may or may not change in the future now coming back to python to declare a
variable we just have to assign a value to it you don't have to give any
additional commands unlike any other programming languages like cec plus
java but you have to give additional commands for declaration and
assignment purposes let's take a look at an example here we have two
variables x and y and we have assigned values to each of them we have given
100 to x and edureka to y so this is actually how you create a variable in
python now when i print these variables i am going to get the output as
hundred and adura you can also perform operations on these variables using
the arithmetic operators you can perform addition multiplication subtraction
or division as well now let's try to understand this in the jupyter notebook as
well first of all what i'm going to do is i'm going to declare a variable without
assigning a value to it let's see what happens it is going to show an error the
error says name x is not defined so let's try again after giving it a value let's
say x is equal to 10 it does not give any errors now so we have successfully
declared a variable here let me declare one more variable okay i'll give it a
value 12. now let's try to perform a few operations on these variables first of
all let's just perform addition between x and y now let's try to do
multiplication there's one more thing i want to tell you about variable
declaration that is variables in python are case sensitive meaning an
uppercase letter here is not going to be the same as a lowercase letter they are
going to be two different variables let me show you it is showing another
error which is saying name y is not defined because we have not assigned a
value to a uppercase letter y let me give this another value here let me give it
20. so we have declared two variables here a lowercase value y and uppercase
value y which are going to be two different variables so we have understood
here the variable declaration how we declare a variable now let's quickly
move on to various variable data types that we have in python depending
upon the properties they possess there are mainly six data types in python
first one is the numbers or numerical data type the next one is the string then
we have a list after that we have a dictionary followed by a tuple and in the
last we have a set there is one more variable data type that is range we will
talk about that in the end because it is mainly used when we are iterating
through values or when we are using the for loop so let's try to understand all
these in detail numbers or numerical data types mainly have numerical values
and in numbers also we have four different data types that is integer float
complex and boolean so integer mainly takes the whole number values
without any decimal point values but if i add a decimal point value to a
number it is going to become float and for complex we just use j as an
imaginary part and add it to the number for boolean it only returns a true or a
false so we use boolean for only categorical output now let's try to understand
this in jupyter notebook first of all let me declare a variable x and give it an
integer value let's say 10. now to check the type of a variable i am going to
use the type function so it is going to show me the type of this variable let's
say x that is int now if i add a decimal point value to x let's say 10.25 and let's
check the type of this variable now we should get float as you can see we are
getting float here now to make a number complex i'm just going to add an
imaginary part that is j here let's check the type of this variable it is going to
show complex number to understand the boolean variable let me take another
variable now i am going to check if 10 is greater than 9 or not so when i
check the type of this variable here it is going to show me that it is a boolean
and when i print this value it is either going to show me true or false since 10
is greater than 9 it is showing true as output so this was all about numerical
data types now let's quickly move on to string data type string data type in
python is written in single or double quotes as you can see here in the
example that i have shown you i have two variables x and y and i have given
them the string values hello and world now to access the string values we use
the square brackets with the index number now you must be wondering what
an index number is so let's take a look at an example here i'll show you what
index numbers are in the jupyter notebook now let me declare a variable and
give it a string value let's say edureka now let me check the length of this
string let's say so it has a length of seven now what are index numbers so
index numbers basically start from zero so at the letter e here index number is
going to be zero and it is going to go until the end of the string so here at the
end is the letter a so index number at the letter a is going to be 6 since we
have the length of the string as 7 and the index numbers start from 0. now
let's try to access some values from the string using the index number so
when i write the index number as 2 i am going to get the value at the index
number that is 2 which is letter u now we can also perform several operations
on strings for example we can change the case of the string we can replace
the values in the string we are going to see if we can actually replace values
in the strings or not so let's try to update a value here at the index number 2
here so instead of u let's say i want d here it is going to show an error which
is a type error which says string object does not support item assignment
which means strings are immutable you cannot change them now to access a
series of letters from a string i can specify a starting index and with the colon
here i can specify the ending index as well let's say i write 8 but we only have
7 indexes here let's see what is going to happen here so it has actually started
from the index 2 that is u here and has gone to the end of the string but what
if i write ending index as 7 since we have the length of the string as 7 let's see
what it going to do it's going to show the same thing but what if i write 6 over
there it is not going to include the last letter because the ending index there is
not going to include when we are accessing the values from the string now
let's try to do one more thing here let's try to make all the letters here to
uppercase letters as you can see i've done that similarly i can make all the
letters lowercase as well so this was all about string data type okay one more
thing i want to tell you here is to access the values from the end of the string i
can specify the index number using the minus here so what i am going to get
here is starting from the end of the string i am going to get the two letters
there that is at the index number five that is k similarly if i write name specify
the index number two here it's going to give me the same value so we can
also access the values in the string like that also so this was all about string
data type now let's quickly move on to list data type a list is a collection of
arrays which is changeable and ordered which means they have indexes just
like strings so we use the square brackets to declare a list as you can see here
i have the list name fruits and inside the square brackets i have the list values
now we have to understand that we can declare different data types in the list
not just strings or not just integers we can merge integers and string as well or
we can also use other data types in the list as well so i'm going to show you
this in the jupyter notebook so let's declare a list first give it some integer
values first some duplicate values as well let's just see what happens and a
string value as well

as you can see we have successfully declared a list now when i print the list
let's see what all values i will get so i am getting all the values that i have
declared here now let me try to access the values using the index number just
like we did in the string as you can see we can access the values in the list
just like we did in the strings as well using the index number now we can also
update the values in the list using the index number as well so let's just try to
update the value at index number two so instead of 30 i want 35 over there so
let's just see what it does as you can see we have successfully updated our
value in the list now let's try to add a value using append so what append
does is it will add the value at the end of the list now let me show you so
there is a value at the end of the list that we have added using the upend
function now what if i want to add the value at the middle of the list using the
index number so what i'm going to do is i'm going to use the insert function
specify the index number and give it a value let's just say 100. now when i
print the list as you can see at the index number 5 i have added 100 as our
value so the difference between the insert and append is that using the append
you can only add the value at the end of the list but when you're using insert
you can add the value specifying the index number now let me do a few
operations here let me try to reverse the list here using the reverse function
now when i print this the list is reverse so this was all about list here let's
quickly move on to dictionary now a dictionary is a collection just like a list
but it is unordered changeable and indexed so we have a key value pair in a
dictionary and we can use the keys as indexes because they are unique but the
values in the keys can be duplicate as you can see in the example here i have
the dictionary name as animals and in the curly brackets i have declared the
key value pairs so let's try this in the jupyter notebook as well so i'll declare a
dictionary here let's just say courses is my dictionary inside the curly brackets
i will get key values let's just save one and give it a value comma key value
that is two and then i'll give another value let's just say data science i can give
string values in the key as well so i'm going to write here machine learning
now let's see if we have successfully declared our dictionary yes we have let's
try to print the dictionary now as you can see i am getting all these values
with key value pairs now i can access the values in the dictionary using the
keys as indexes i'll just write third over here as you can see i'm getting the
value at the key that is third now for the similar purpose i can use the get
function and specify the key value there it is going to show me the same
value now to update a value in the dictionary i am just going to write the
index number that is our key value here so instead of machine learning let's
just say hadoop alright so when i print the dictionary now it is going to show
me an updated value also i can add the key value pairs using the square
brackets i'll just specify the key value let's just say 4 here i'll add machine
learning again ok once again we have made a mistake here we wrote the
wrong name

now as you can see we have added another value to our dictionary so this was
all about dictionary guys let's quickly move on to tuple a tuple is an ordered
and unchangeable now what it means is it is immutable just like a string we
cannot make any changes in the tuple but we can have the duplicate values in
the tuple as well so let's try to understand this with an example so here i have
a tuple here which has a name animals and i have few values here so let's just
do this in jupyter notebook as well so i'll have my tuple as a name animals so
i'll give it a value in round brackets a few integer values first just to check of
course and then i'll add some values like tiger i'll just say lion and one more
i'll give let's say giraffe now let me give a duplicate value here to check if we
can actually add a duplicate value or not i'll say tiger once again so i have
successfully created a tuple here now let me access the values here using the
index number let's see if we can do that so this actually means the tuples are
indexed as well we can use the index values to access the values from the
tuple now since it is immutable or we cannot change it there are not many
operations that you can perform on a tuple but you can count the number of
duplicate values using the count function so you're just going to write the
value let's say tiger we have duplicate value over there so we will check how
many times tiger is there so it's going to give us the count here so this was all
about tuple guys so let's quickly move on to set now now a set is a collection
just like a list or a dictionary as well but it is unordered and there are no
duplicate entries present now let me show you this with an example in the
jupyter notebook so i'll give my set as the set name and inside the curly
brackets we can have values let's just say 10 20 30 40. i'll also give a few
duplicate values just to check if we can have duplicate values or not string
values let's just say dureca courses as you can see we have successfully
declared a set here now let me try to print this now as you can see there are
no duplicate values even though when we have declared the set it was there
now let me try to access the values using the index numbers it has shown us
an error which says set object does not support indexing which means a set
does not have any indexes and every time we print a set it is going to show us
a random value so this was all about set guys briefly talk about range now so
range is used whenever we are iterating through values suppose we want to
print numbers from 0 to 10 let me put it in a list to get the values so what i'm
going to do is i'll just write 11 over here and it is going to give me the values
in the list that is from 0 to 10 so this is all about range guys now let me take a
miscellaneous example now i'll have a dictionary with some values again
integer values now let me try to make a list and try to get the values from a
and b as well let's see if we can do that now when i print c here it is going to
show me that our list c has the list a and a dictionary as well so which shows
you can actually make a list with other data types for example you can
actually incorporate a dictionary over there you can also do that with a tuple
or a set and if you want some value that you don't want to change in the
future you can actually make it a tuple and declare it in a list so that you
cannot change that value in the future for example if you don't want to access
any value using the indexes you can make it with set so that it does not have
any indexes so that is all about data types guys so there is one more topic that
i want to talk about which is type conversion now suppose we have an integer
here that has 10 value and we have a string as well which says now when i try
to add these two variables name and x it is going to show me a type error
which says unsupported operand types now for this error i am going to do a
type conversion here so lets quickly talk about type conversion before
moving on to the example so type conversion is basically when you convert a
type of a variable to another data type so we have all these functions here
which will convert the data type into their respective counterparts now let's
try to look at the example now so we are getting an error here but what if i
change the data type of integer into string am i going to get the same error
again or not let's just see we're not going to get any errors so this is what is all
about type conversion let me show you one more example so we had a
dictionary over there that is with the name b what i'm going to do is i'm going
to use the list function and specify b over there so i have actually converted
our dictionary into a list so this is what is type conversion all about

collections in python before moving on let's take a look at the agenda for this
session so first of all i will be talking about what are collections in python
and then i will discuss what is the collections module in python and how we
can use it and finally i will sum up this session with various specialized data
structures that are present in the collections module i hope you guys are clear
with the agenda also i suggest you to subscribe to edureka channel for more
exciting tutorials and also press the bell icon to get the latest updates from
edureka now without wasting any more time let's understand what are
collections in python collections in python are basically container data types
namely list sets tuples and dictionary they have different characteristics based
on the declaration type and the usage as well so let's take a look at each of
them so talking about list a list is declared in square brackets guys it is
mutable which means you can actually change the values once you have
declared a list and it also stores duplicate values and the elements can be
accessed using the indexes now talking about tuple a tuple is ordered and
immutable in nature which means you cannot change a value inside a tuple
once you have declared it and a tuple can also have duplicate entries present
inside it now talking about a set a set is unordered and declared in curly
brackets it is not index which means you cannot access the elements inside a
set using the indexes also it does not have any duplicate entries present as
well now talking about the dictionary a dictionary has key value pairs and is
mutable in nature which means we can change the values inside our
dictionary and we use the curly brackets to declare a dictionary as well so
these are the python's general purpose built-in container data types but as we
all know python always has a little something extra to offer so it comes with
a python module named collections which has specialized data structures so
let's take a look at the python collections module guys what is it and how we
can use it so python programming language has four collection data types
that i have already told you which is list tuple sets and dictionary but python
also comes with a built-in module known as collections which has specialized
data structures which basically covers for the shortcomings of the four data
types now collections module in python implements specialized data
structures which provide alternative to python's built-in container data types
so let's take a look at those specialized data structures in collections module
also you don't have to install collections like other python modules guys it is
already there inside python you can just import it by writing this name
collections so i'll show you while we are working on the use case guys so
taking a look at the specialized collection data types guys so first of all we
have a name tuple then we have chain map deck there is counter order
dictionary default dictionary then we have user dictionary user list and user
string so we'll be taking a look at each of them one by one guys so let's take a
look at name tuple guys so what exactly is name tuple name tuple returns a
tuple with named entry which means there will be the name assigned to each
value inside a tuple now if you look at the tuple as in general it does not have
any named entries but with name tuple we can do that so it actually
overcomes the problem of accessing the elements using the index values with
name tuple it becomes easier to access these values since you do not have to
remember the index values to get the specific elements now here is an
example guys so this is what a name tuple looks like guys so let me take up to
pycharm guys we will try to implement a name tuple using the collections
module so we are inside the pycharm guys i hope this is visible to you so first
of all what we'll do is we'll import the collection module and from collections
now okay as you can see i have not installed it to anything you can just write
collections and it will appear there so from collections i want to import name
tuple guys done now what i'll do is i'll simply okay let me implement a name
tuple first so i'll just make it as a and use name tuple here and over here i will
just provide some values let's say the name of my name tuple will be courses
i have to put it in commas case now i have to give some names like i'll just
write course name and then let's say technology now what i'll do is i'll make
one more variable and i will pass this and provide some values over here for
my course name i'll write data science and for technology let's say python
now when i print s over here let's see what happens so as you can see i'm
getting the output as this course is which is the name of my tuple and over
here i'm getting the named entries for these values that i've put inside this
tuple guys so this is how you can implement a name double guys it's as easy
as it looks you just have to import it from collections and after that you have
to implement our name double and inside that i have provided the name and
the values that are going to be there from the tuple guys now i'll show you
one more thing guys how you can actually get the value or implement a tuple
using a list guys so let's take a look at that so what i'll do is i'll take one more
variable let's say s now what i'll do is i'll just specify using this variable over
here and i will use make and over here i can just make a list and i will
provide values like let's say artificial intelligence and technology is going to
be python guys so if you're wondering why am i making these courses these
courses are available at our edureka website guys you can check them out
anytime you want so now when i print this let's see what is going to happen
so i've actually used a list to get a name double guys to get the values inside a
name tuple so this is all about name double guys it's actually pretty easy and
you can get named entries for your values inside the tuple so let's take a look
at the next one that we have which is actually dead guys it is written as dq but
we can pronounce this as deck now talking about deck what actually it is
used for so dec pronounced as deck is an optimized list to perform insertion
and deletion easily so when i say optimize what it actually means is there is a
way where you can actually do it very precisely and very easily guys so let's
take it up to python again and we'll try to implement this so from collections
instead of name tuple what i'm going to do is i'm going to import deck guys
now what i do is so let me just specify a list over here so i'll just write a few
values here let's say eduraka guys

let's see what's happening here so now what i'm going to do is i'm going to
use a variable and inside this i will pass this list let's see what we get if i print
this variable guys so i'm getting a dq i have made a deck using the list guys so
let me show you the operations that we can perform in this so first of all let
me append the value or add a value guys so what i'll do is i'll just append a
value so let's say append and let's say python yeah so now when i print this
you will see the different guys so we have a deck over here and after that i
have appended a value or inserted a value using this append function guys so
which means i have added the value at the end of the day now if i want to add
it like before the deck guys like in the beginning of the deck what i have to do
is i'll just have to use this method which is append left so now you will see
what is going to happen guys so this value python is actually inserted in the
beginning of the deck similarly for removing a value what i can do is okay i'll
just now we have added this value let's say i want to actually remove this
value so what i'll do is i'll just write d dot pop and let's see what happens i'll
print it again so as you can see from the value from the end of the deck is
missing now we have actually removed it from the deck using the pop
function but let's see if i want to actually remove this value how am i going to
do it i'll just write pop left guys and as you can see the value python is also
missing here so this is an optimized version of insertion and deletion guys
using the deck so this is all about deck guys now let's talk about the next one
that we have which is a specialized data structure obviously and that is chain
map so chain map is a dictionary like class which is able to make single view
of multiple mappings so it basically returns a list of several other dictionaries
suppose you have two dictionaries suppose you have two dictionaries with
several key value pairs so in this case chain map will make a single list of
both the dictionaries in it so as you can see in this example we have two
dictionaries a and b and if i use the chain map it will return me a single view
of these two values or multiple mappings so let's take it up to pycharm guys
we'll try to implement this again so i'll remove this and instead of deck we are
going to use or we are going to import chain map guys so it's very simple so
let me declare two dictionaries guys so first of all i will give a value let's say
one and eureka then the second key value pair is going to be let's say python
and now let's take one more and inside this i'll give the value let's say ml and
the fourth one is going to be let's say ai now using the chain map i'm going to
specify these two dictionaries in this so let's print a1 let's see what happens so
as you can see i have made a chain map which has a single view for multiple
mappings which is a and b guys so this is what you can do using the chain
map guys i hope you understand this so this is a very basic example guys to
let you actually understand what is happening over here so we are using these
two dictionaries and we are able to get it inside a single view guys so let's
take a look at the next one that we have which is counter guys so counter is
also like a dictionary subclass which is used to count hashable objects now
what are hashable objects so let's take a look at this example so let's say we
have a list inside this we have different elements so what counter is going to
do is okay let's take it by charm to understand this better guys so i'll remove
this and instead of chain map let's say i have counter so let's take a list guys
so i'll specify some duplicate values because this is what it is used for to
count the hashable objects guys

now what i'll do is i'll make one variable and use the counter and pass a over
here so when i print c now let's see what happens so as you can see i'm
getting a dictionary inside which i have these values so which is saying the
number of times two has occurred is five number of time four has occurred is
three and then again one two and all so when i run this again i'm getting the
same value so this is how you can actually use counter guys to count the
hashable objects inside any iterable value so we have a list we can you do it
for any other iterable object guys like a topple or set so this is all about
counter i hope you understand this now in addition to the operation you can
perform on a dictionary counter has three more operations that we can
perform so which are basically an element function a most common function
and a subtract function as well so we'll talk about them in detail now so
talking about the element function guys so let's see what elements does so
we'll see elements now so over here we want the list so we will put it in the
list constructor guys and let's print this okay let's see what are we going to get
so it returns a list containing all the elements in the counter guys so as you
can see i'm getting all the values that i have inside the counter and this is the
counter that i have so two comes five times one comes two times and then we
have three two times four three times and so on so this is the function of
elements function which is returning a list containing all the elements inside
the counter now let's take a look at the next function that we have which is
the most common function so let's get on to it so we'll use the c which is our
counter guys so i'm going to use the most common here now so let's see what
i'll get here so i'm actually getting a sorted list with the count of each
elements inside the counter so we have two five times four three times and
one two times three two times five two times and six one time so this is
actually how you can use the most common function and then we have one
more function which is subtract guys so for subtract let me get one more
variable so i want to subtract let's say so i'm getting two five times so i'll just
subtract two one time and i'll subtract six one time so what i'll do now here is
i'll use the counter and let me use the subtract function guys here it is and i
will pass sub over here let's see what happens okay so now when i print my
counter okay i'll get the values the most common values again so now as you
can see 2 is coming 4 times here and 6 is coming 0 times because i have
subtracted using the subtract function so this is all about counter guys let's
talk about the next data structure which is order dictionary so order dictionary
is a dictionary subclass which remembers the order in which the entries were
added basically even if you change the value of the key the position will not
be changed because of the order in which it was inserted in the dictionary so
let's take it up to pycharm guys we'll implement the order dictionary over
there so i'll remove all this and instead of counter we will import order
dictionary now what i'll do is i will implement an order dictionary let's say d
and now i'll add a few values let's say okay the first one is going to be e and
then second one is

let's say

now let me print d over here which is our order dictionary let's see what the
output will be so we have our order dictionary which is saying on the first
value we have e and then so on we have edureka all the letters from edureka
guys so this is how you can actually implement an order dictionary guys so
let me take a look at what all functions do i have in this so i have pop update
pop item get items from key set default values clear copy keys so let me get
all the keys from this so when i run this okay let me print this

now as you can see i'm getting the order dictionary keys which is one two
three four five and seven and similarly i can get instead of keys let's see what
all we can get we can update pop item okay let's get items so the functions
are actually similar to what we have for dictionary guys

so this is all about order dictionary guys it remembers the order in which the
elements were put inside the dictionary guys okay let me do one thing guys
i'll change the value okay first let's print this so you'll understand it better so
now what i'll do is i will change the value at one so instead of e let's say i
want p over there and now when i print it let's say what happens so as you
can see i have replaced the value over there but since it was inserted in the
beginning like the first one was e the value is not changing over there so this
is the main reason why we use order dictionary because it remembers the
order in which the elements are being added inside the dictionary so now that
we are done with order dictionary let's talk about default dictionary guys so
what basically default dictionary does is it is a dictionary subclass which calls
a factory function to supply missing values so in general it does not throw
any errors when a missing key value is called in the dictionary so you'll
understand this better guys so let's take a look at this example we have a
default dictionary in which we have to specify our type as well so let's say we
have two values on the first value we have educa and then we have python
but instead we want to print java over there which is not actually inside the
dictionary because there is no value present over there but we will not get any
key value errors and it will instead give the output as zero so let's take it up to
pycharm guys we'll try to understand over there so let's remove all this now
instead of order dictionary we are going to import default dictionary guys so
let's make a default dictionary and inside this let's specify the type as well
now let's say we have the first value as python the second value let's say
eddie recap

now when i print this d over here i'm getting the value as it's showing me that
we have a default dictionary which has a class int that we have specified over
here and then we have a dictionary with the values one two which has python
and edureka respectively now let's say i want to get the value at the number
three which is not actually present there but i'm getting the output as zero so
i'll show you the different guys what actually happens if you do this in a
normal ordinary dictionary guys so i'll make one more dictionary let's say a
and i'll give it some value let's say python and edit now when i print this
which is not actually present inside the dictionary let's see what we are going
to get we are going to get the key error guys because 3 is not actually present
inside this ordinary dictionary but if you put it inside a default dictionary you
are not going to get this error guys so this is what is the function of default
dictionary guys it does not show you or throw any key error even if the value
is missing inside the dictionary guys so now that we are done with default
dictionary let's take a look at the next one that we have which is user
dictionary user list and user string so these three data structures are actually
same but different so let's talk about them one by one so talking about user
dictionary this class acts as a wrapper around dictionary objects now the need
for this class came from the necessity to subclass directly from the dictionary
it becomes easier to work with this class as the underlying dictionary
becomes an attribute now talking about the user list this class acts like a
wrapper around the list objects and it is useful base class for other list like
classes which can inherit from them and override the existing methods or
even add a few new ones as well and the need for this class came from the
necessity to subclass directly from list it becomes easier to work with this
class as the underlying list becomes an attribute as well now talking about
user string guys it is also a wrapper around string objects for easier string
subclassing now the need for this class has been partially supplanted by the
ability to subclass directly from string however this class can be easier to
work with because the underlying string is accessible as an attribute

in this session today guys i'll be covering the following topics first of all i'll
be explaining what exactly is an array and then i'll be differentiating between
python lists and arrays now this is a very common question that many of us
ask after that i'll be showing you how to create arrays in python following
which we will try to access array elements and then we will try to perform
some basic operations on arrays such as finding the length of an array adding
and removing elements from it array concatenation slicing and looping
through an array now let's move on towards the first topic our first topic for
this session is what exactly is an array an array is basically a data structure
guys with ordered series of elements any variable that is declared as an array
can hold more than one value at the same time all values in an array have a
particular address which is specified by its index number here as you can see
on the screen i've declared a variable a as an array and i've stored values from
1 to 100 in my array which is a also make a note of the index values indexing
always starts from 0 and not from 1. therefore a of 0 holds 1 a of 1 holds 2 a
of 2 holds 3 and similarly a of 99 holds 100 when the length of my array is n
the index value will be n minus 1 it is always one less than the length of the
array now let's move on towards our next topic for this session which is the
difference between python lists and arrays python lists and arrays have the
same way of storing data but there is a key difference that you all have to
note arrays can store only single data type values whereas lists can store any
data type values so for example if i have an array of integer values all values
present in that array will be integers and nothing else on the other hand if i
have a list then it can store integers together with float and cars and strings
etc now when you try to perform some operations like slicing or looping it
will be similar for both but when you try to perform different operations like
if you want to multiply your array values by 2 or you want to divide it by 2
you can do so easily when you have an array but if you try to do the same
with the list it will throw an error because naturally you cannot multiply cals
and strings or divide them so i hope you are clear with the difference between
these two so now let's move on towards the next topic how to create arrays in
python unlike other programming languages if you want to create arrays in
python you will have to import the array module now this module has all the
functions that are necessary for creating and performing various kinds of
operations on arrays to import the array module you can use three ways first
is to import the array module by its original name which is array the second
method is to use an alias name this is the most widely and commonly used
method as well in my demonstrations i'm going to be using this method the
third way is using star from array import star what this does is it's going to
import all that is present in your array module now let's go to our jupiter
notebook and try to do this please do it along with me guys i'll open a new
notebook and i will use the first method to import the array module

as you can see when i hit run no error has been returned which means this is
executed now let's try to create arrays using this method

as you can see over here i've created an array a using the first method so i
have used array dot array of integer values and i've specified some random
integer values here the first array is the name of the module the second array
is the array constructor and then i've given a type code this type code
specifies what type of elements my array will hold as you can see i've created
an array so i hope you are clear with how to create arrays using the first
method now let me open a new notebook and try the second method the
reason to open a new notebook is because i've already imported array module
in this notebook i'll rename this notebook because i'm going to be using this
method in further demonstrations as well

as you can see over here when i use import array as arr arr here is my alias
name when i use this and hit run it does not throw any error now let me try to
create arrays using this method

i'm using int as my data type you can use any data type of your choice

as you can see that an array has been created with some random integer
values in place of the module name array i've used arr now let's try the third
method i'll open a new notebook again

as you can see over here when i'm creating arrays using the third method i've
just specified the constructor name and then the type code and the value list
so now let's get back to our presentation our next topic for this session is
accessing array elements to access array elements you'll have to make use of
the index values each index value holds a unique element like i've told you
before indexing starts from 0 and not from 1 so therefore a of 0 holds 1 a of 1
holds 2 and so on this is the normal traversal order which starts from the left
hand side and moves towards the right hand side but here i want you all to
note this point as well that negative indexing also exists so negative indexing
will start from the right hand side and move towards the left hand side
therefore 100 will be at a of minus 1 99 will be at a of minus 2 and similarly
1 will be at a of minus 100 now let's go to our jupiter notebook and try to
access some array elements

as you can see over here i've created a heading to create a heading all you
have to do is go to code select heading and prefix your text with the number
of hashes based on the heading level you want so if i want h1 i will use one
hash if i want h2 i will use two and so on here i've created a heading of h1 so
i prefixed my text with one hash now let me try to access some array
elements you can see over here when i access a of 2 my output is 3. let's see
where 3 is present in my array 1 is present at a of 0 2 at a of 1 and 3 at a of 2.
so therefore when i access a of 2 3 has been returned our next topic of this
session is basic array operations here i just want to tell you all something
arrays are mutable which means they are changeable so in case you want to
add or remove elements from it you can do so easily now coming back to our
presentation our first operation under this section will be finding the length of
an array the second is adding or changing elements of an array and then we
will try to remove or delete elements of an array and then guys we will try to
perform array concatenation slicing and finally we will be looping through an
array now let's move on towards the first operation to find the length of an
array you will have to make use of the len function now this function returns
an integer value which is equal to the number of elements that are actually
present in your array the len function takes one parameter which is the name
of your array as you can see in the example over here i've created some
random array a and i've given some random values as you can see i have
three values over here and when i use the len function and i specify the name
of my array the output is 3 which is equal to the number of elements that are
present in my array now let's move towards the jupiter notebook and see how
this works

as you can see over here when i use the len function and i've given the array
name which is a an integer value is returned which is 6 6 is the number of
elements that are actually present in my array which is a okay so i hope you
are clear with this so our next operation is adding elements to an array in case
you want to add elements to an array you can do so using the append extend
or the insert function the append function is used when you want to add an
element to the end of your array the extend function is used when you want to
add more than one elements to the end of your array the insert function
specifically adds a new element to a particular position in the original array
let's have a look at a small example of these three as you can see on the
screen i've created some random array a and then i've used the append
function and i've given the value that i want to add to my array as you can see
in the output 3.4 which is the value i've specified to the pen function has been
added to the end of my array which is a and then i've used the extend function
please make a note over here that when you use the extend function you will
have to specify the values between square brackets if you don't use the square
brackets it will throw an error i've given three new values and all three values
have been added to the end of my array and then i've tried to use the insert
function over here i've specified the index number as 2 and the value to be
inserted at that position as 3.4 as you can see in the output 3.4 has been
inserted at c of 2. now let's go to our jupiter notebook and we'll do the same

i'll reprint my array which is a so that it's easy for us to refer to it

since my array a holds integer values i will give some new integer value to it

as you can see i have given 8 as the value that i want to insert in my array and
8 has been added to the end of my array now let me try to give some float
value to this array and see what happens

as you can see when i try to append some float value it gives me a type error
therefore i can add only those values which is specific to the type of elements
that are present in that array now let me try to use the extend function

like i've told you all when you're using the extend function you will have to
make use of the square brackets

as you can see in the output all the values that i've specified within the extend
function have been added to the end of my array now let me use the insert
function

i've used the insert function and the first parameter i've specified is the index
value and the second is the element to be inserted at this index position so at
index value a of 2 6 will be inserted as you can see in the output 6 has been
inserted at a of 2. so i hope you are clear with how to add elements to an
array now let's move on towards the next operation our next operation is
removing elements of an array in case you want to remove elements from an
array you can make use of the pop or the remove function the pop function
removes the element and returns it whereas the remove function will remove
it but it will not return it the pop function can either take no parameters or one
parameter the parameter it takes is the index value of the element to be
removed if you do not specify any parameter it will remove the last element
from the array the remove function takes one parameter which is the element
to be removed itself now let's have a look at a small example of this as you
can see on the screen i've created some random array a and then i've used the
pop function without specifying any parameter as you can see in the output
when i do not specify any parameter the last value present in my array has
been popped and returned as well second time i've used the pop function and
i've given some index value now this pop function will remove the element
that is present at this index position as you can see it has removed 3.1 and
returned it as well after that i've used the remove function like i've told you
before the remove function takes one parameter which is the element to be
removed and you can see in the output that the remove function has not
returned any value after that i've printed my array and you can see all the
values that are removed using these two functions are no more present in the
array a now let's go to our jupiter notebook and do the same

let me reprint my array which is a first i will use the pop function without
specifying any parameter to it

as you can see over here when i do not give any parameter it removes the last
element that is present in my array now let me give some index value to it

i'll reprint my array a because i've removed an element from it now let me
give some index value to the pop function

as you can see when i use a dot pop of 2 it removes the element which is
present at a of 2 which is 6 and it returns it as well let me try to use some
negative index value for the pop function a dot pop of minus 1 removes the
last element that is present in my array which is 5. now i'll use the remove
function let me reprint my array guys as you can see all the elements that
have been removed using the pop function are no more present in my array a

like i've told you before when using the remove function you will have to
specify the element that is to be removed here let me remove it because there
are two occurrences of 8 and let's see what the remove function does when i
hit run remove function does not return anything now let me print my array a
and see what is present as you can see the first occurrence of 8 has been
removed but the remove function did not return the value so i hope you are
clear with the remove and the pop functions now let's get back to our
presentation and perform the next operation our next operation is array
concatenation concatenation means joining so in case you want to join
different arrays you can make use of the plus symbol as you can see on the
screen i've created some random array a and b and then i've created some
random array c which is empty also make a note that all three arrays have the
same type code and then i've concatenated a and b into my empty array which
is c as you can see in the output all the elements present in a and b have been
concatenated into my array c now let's go to our jupiter notebook and perform
array concatenation

i am using int as my data type you can use any data type of your choice

to create an empty array all you have to do is specify the type code and leave
the value list empty here i've created an empty array d and i've concatenated b
and c into my array which is d now let me hit run when i hit run all elements
present in b and c have been concatenated into my new array which is d so i
hope you are clear with array concatenations let me just show you what
happens if i try to concatenate arrays of different data types i'll just change
one of my previously created arrays type code and i'll give it as float let's see
what happens when i change the type code and i try to concatenate these two
arrays you can see that i've encountered an error and it says type error which
means it cannot concatenate two arrays of different data types so just be
careful when you're concatenating arrays you cannot concatenate arrays
which hold different data type elements okay now let's move on towards our
presentation and see what is the next operation our next operation is slicing
an array slicing actually means fetching some particular values from your
array to do so you can make use of the colon symbol as you can see on the
screen i've created some random array a and i've sliced it from 0 to 3. 0
specifies from where fetching has to start and 3 specifies where it has to stop
so it will start from 0 it will go on till 3 but it will not include the value which
is present at 3. as you can see in the output i have a of 0 a of 1 and a of 2 that
is present in my output now let's go to our jupiter notebook and we will try to
slice our arrays

i'll reprint my array d over here and then i will try to slice it as you can see
i've sliced my array from 0 to 5 so it will start from index number 0 it will go
to 5 but it will not include the value which is present at index number 5. you
can also see the same in the output over here let me try to use some negative
index value

my output when i use 0 colon minus 2 contains all the values between 0 and
-2 but it will not include the value which is present at -2 okay so i hope you're
clear with this topic just give me a quick confirmation before i move on okay
anil says yes shashank has a question he asks what does colon colon minus
one mean shashank unlike what many of us think colon colon -1 does not
reverse my array but it prints a reversed copy of my array so let's try to do
this over here as you can see all the elements present in array d have been
reversed now let's print our array which is d the original array d is the same
but colon colon -1 has reprinted a reversed copy of my array which is d this
method is actually not preferred because it exhausts the memory so i hope
i've cleared your doubt shashank just give me a quick confirmation okay
shashank says yes now let's get back to our presentation and perform the last
operation of this session which is looping through an array you all might be
familiar with these two loops which is the for and the while loops the for loop
iterates over the items of an array specified number of times whereas the
while loop iterates until some condition is met or some condition is true when
you're using the while loop you will have to keep three things in mind one is
initializing your iterator second is to specify a condition third is to increment
your iterator remember that if you do not increment your iterator your while
loop will go on forever let's see a small example of this as you can see on the
screen i've created some random array a and then i've used the for loop to
loop through my array a i've used for x in a print x which means go to every
element that is present in a and print it let's try to do the same on our jupiter
notebook

let me reprint my array d now let me use the for loop to loop through this
array

for x in a print x which means go to every element in d and print it as you can
see all elements present in d have been returned one after the other now let
me try to slice this array and print specific elements

as you can see over here i've sliced my array from index number 0 to minus 3
and i've printed only those specific values using the for loop now let's go to
our presentation and have a look at the while loop like i've told you before
when you're using the while loop you will have to do three things one is
initializing your iterator second is to specify the condition and third is to
increment your iterator let's try to perform looping on our jupiter notebooks
please do it along with me guys let me reprint my array d here i'm using the
iterator as temp you can use any name of your choice

as you can see over here i've initialized my iterator to 0 and then i've
specified a condition wherein i have told whenever the value of my
temporary variable is less than d of 2 then print that value and then i have
iterated the value of temp i can also use temp plus equal to 1 which is same as
temp equal to 10 plus one now let's try to use the while loop using the len
function here i will use my array a so let me reprint it over here

as you can see over here when i use the len function my temporary variable
will go to all elements present in my array a and print them one after the other
so i hope you are clear with looping

data requires a number of ways in which it can be stored and accessed and
one of its most important implementations includes hash tables and hash
maps so before we begin just make sure you subscribe to our channel and hit
the bell icon to stay updated with all the latest edureka videos coming back
towards this session we shall first begin by understanding what exactly are
hash tables or hash maps in python and for that i'll be showing you guys how
to create dictionaries nested dictionaries and perform various
operations on hash tables such as accessing updating and deleting items from
them finally i'll be showing you guys how to convert a python dictionary into
a pandas data frame so without any further delays let's get started so what
exactly is a hash table or hash map in python in the field of computer science
a hash table or a hash map is a type of data structure that maps keys to its
value pairs it implements the abstract array data type so this basically makes
use of a function that computes an index value that in turn holds the elements
to be searched inserted removed etc this makes it easy and fast to access data
in general hash tables store key value pairs and the key is generated using a
hash function hash tables or hash maps in python are implemented through
the built-in dictionary data type the keys of a dictionary in python are
generated by a hashing function the elements of a dictionary are not ordered
and they can be changed so for example a dictionary can be a mapping of
employee names and their employee ids or the names of students along with
your student ids okay so moving ahead let's go on and see how to create
dictionaries in python dictionaries in python can be created in two ways one
is by using the curly braces and the second is to use the dict function so now
i'll jump onto my jupyter notebook and over here i'll be showing you guys
how to create dictionaries in both these methods so the first method is by
using the curly braces for that i'm just going to give some name to my
dictionary i'll say my dictionary and i'll just give some random key value
pairs to this so i'll just give a name say dave

and i'll specify the value of this as zero zero one so just consider this to be an
employee mapping with your id numbers so i'll give another key over here i'll
say deva and i'll specify the id to be zero zero two i'll specify another one i'll
say joe and i'll give the value as not not three okay so after this i'll print out
my dictionary

and also the type of my dictionary

and then i'll hit shift enter so as you can see over here my dictionary has been
printed out and the type of it is dictionary itself okay so now to show you
guys how to make use of the dict function all you can do is just specify some
name i'll say new dictionary and make use of the dict function i'm not giving
any parameters at first i'll just print out new dict

and the type of it as well

okay so as you can see over here an empty dictionary is created since no key
value pairs are supplied as a parameter to the dict function in case you want
to add the values all you have to do is specify parameters into that function so
what i'm going to do is copy this from here and i'll just paste it and within this
function i'll specify these values as a parameter to this so over here i'll just
use the key value as dave and i'll say this is equal to not not 1 and then ava
which is equal to not not 2. now i'll just print out new dict and i'll run this so
as you can see over here i've specified the key value pairs as parameter to this
function and therefore my dictionary has been created with those parameters
so i hope you're clear with this so now moving on towards our next topic
which is nested dictionaries nested dictionaries are basically dictionaries that
lie within other dictionaries so for example consider a project within which
there will be a number of teams such as the development team the marketing
team sales team etc all these are basically other dictionaries that are contained
within the project dictionary this project dictionary itself can be a part of the
organization that has a number of projects so i hope that gives you a clear
idea about what exactly is a nested dictionary so now i'll jump onto my
jupiter notebook to show you guys how to create them so all i'm going to do
over here is create a dictionary which contains the employee details a single
team can have a number of employees and these employees have different
salaries ids and designations i'll just create a variable over here i'll just say
emp details and then i'll use the curly braces within which i'll specify the
main element to be employee and this is going to contain various other
dictionaries so here the first employee name will be dave

and since each employee will have other details such as id salary designations
etc it is going to be another dictionary within this dictionary so i'll just open
another dictionary and over here i'll specify id to b001

the next detail that i'm going to specify for this employee is the salary so i'll
just specify the key as salary and i'll give some random value to this say 2000
and finally i'll specify the designation

okay so this was all the details for dave now i'll create another employee
name so i'll move out of this dictionary and here i'll specify eva so just like
dave ava is also going to have ids salaries and designations and for that i'll
create another dictionary within this and i'll specify the same key value pairs
the id is going to be 002 and salary i'll give some random value say 1000

the designation will be associate

okay so after this i'll just print out this dictionary


so as you can see over here i've created a nested dictionary so i hope you
guys are clear with this so now let's move on towards our next topic which is
performing operations on hash tables there are a number of operations that
can be performed on hash tables in python using dictionaries in this session
i'll be showing you how to access update and delete elements from
dictionaries or hash tables in python so accessing values the values of a
dictionary can be accessed in many ways such as using key value pairs using
functions or implementing the for loop now to show all this to you i'll jump
on to my jupiter notebook

i'll just give a heading over here say accessing values or rather i'll say items

so the first method that i'm going to show you is using the key values so for
that i'll just use the dictionary that i've created earlier which is my dict and
i'm going to say my underscore dict and the parameter that i'm going to
specify is dave and then i'll hit run so as you can see over here the key dave
contains the value as zero zero one python also provides a number of
functions using which you can access the key value pairs that are present
within dictionaries some of these functions are the keys function the values
function or the get function so what i'm going to do over here is first print out
my dictionary

now i'm doing this only because it's going to be easy for us to refer to it so
after this i'll be showing you guys how to use the keys the values and the get
functions so what i'm going to do is print my dict dot keys and then i'll hit run
okay so as you can see over here when i use the keys function all the keys
that are present in my dictionary have been returned now in case i want to
access all the values all i have to do is change this from keys to values and
then hit run okay so as you can see in contrast to the previous function the
values function has returned all the values that are present within my
dictionary now there's another function which i already told you which is get
and to use that function you'll have to specify some parameter whose value
you want to retrieve so what i'm going to do is print my dictionary dot get
and i'll specify the value as ava so as you can see over here the value that's
present for ava is not not two so i hope you guys are clear with this so there's
another way by which you can access the values that are present in a
dictionary and that is using the for loop so in case i want to retrieve all the
keys that are present in my dictionary all i'm going to do is use for x in my
dict i'll say print x so as you can see over here my for loop is iterating over all
the keys that are present in my dictionary and it has returned all of them one
after the other now in case i want to fetch only the values that are present in
my dictionary all i can do is use the same for loop and within that i can
specify mydict.values function

so as you can see all the values that are present within my dictionary have
been returned by the for loop now there's another function called as items that
will retrieve all the key value pairs that are present in my dictionary so to
show you guys i'll just type for x for x in my dictionary

dot items which is the name of the function

sorry guys this is supposed to be x comma y since i have to retrieve two


values at a time that is the key and the value and then i'll just print x comma y

so as you can see over here i have all the keys along with their value pairs
okay so i hope you're clear with this so now let's move on and see how you
can actually update the values of a dictionary dictionaries are mutable data
types and therefore you can update them as and when required so in case if
you want to change the id of some employee or if you want to add some new
key value pair to your dictionary you can do it easily so now to show that to
you guys i'll get back to my jupyter notebook i'll give a new heading

i'll say updating

so i've already created a dictionary over here and from that dictionary i'll just
change the value of dave from 001 to 004 for that i'll just specify my dict

and within this i'll specify the parameter as dave

and the value i'll change it from 0 0 1 to 0 0 4. now i want to add some new
value to my dictionary so for that all i'm going to do is specify my dict
and i'll specify a new parameter say chris

and the value i'll specify to this as 003 finally i'll just print out my dict

so as you can see over here the value of dave was initially zero zero one and
now i updated it from zero zero one to zero zero four you can also see over
here that i've added a new key value pair and the key is chris and the value is
not not three so i hope you guys are clear with this okay so now let's get back
to our presentation and see how you can actually delete items from a
dictionary there are a number of functions that allow you to delete items from
a dictionary such as the del function the pop function the pop item function
clear etc so to implement this i'll get back to my jupiter notebook and over
here i'll create a new heading

so the first thing that i'm going to do is use the pop function so i'll just copy
the name of my dictionary from here and i'll use the pop function with this so
the pop function will take one parameter and it's going to remove that key
value pair from my dictionary so i'll just specify ava and i'll hit run so as you
can see over here the pop function has removed and returned the item from
the dictionary so there's another function called as the pop item function
which will remove the last inserted element from my dictionary so for that all
i'm going to do is specify my dict dot pop item

and then i hit run okay so as you all know the last item that i had added to my
dictionary was chris having the value of not not three pop item has removed
that and returned it as well so to use the delete function all you have to do is
specify del followed by the name of the dictionary and to this you'll have to
specify the key whose value you want to remove from your dictionary so here
i'll just specify dave and i'll hit run finally i'll just print out my dictionary

so as you can see over here all that is left in my dictionary is just one key
value pair which is joe having the value of not not three okay so now let's
move on towards the last topic of this session which is converting a
dictionary into a data frame so before showing you guys how to convert this
let's first see what exactly is a data frame a data frame is a two-dimensional
data structure that consists of columns of various types it is very similar to
python dictionary and you can even convert a dictionary into a pandas data
frame so now to convert this i'll get back to my jupyter notebook

okay so as you all have seen previously i had created a nested dictionary
containing employee names and their details mapped to it now to make a
clear table out of that i'll make use of the pandas library in order to put
everything as a data frame so what i have to do over here is import pandas

and i'll take a new variable say df i'm going to import the pandas library as pd
guys sorry it's just an alias name so you don't have to worry about that so i'll
just use pd dot data frame

and over here i'll specify employee underscore details which was the nested
dictionary which i've created earlier

finally i'll just print out the data frame

so if i would have imported the pandas library as pandas and not as pd in


place of pd over here i should have written the complete name of the library
which is pandas okay so now i'll just hit run so as you all can see a clear table
has been created for the dictionary which i had created earlier

so here is a list of all the operators that we have in python so first of all we
have arithmetic operators then we have assignment operators comparison
operators logical operators then we have membership operators identity
operators and bitwise operators so we will be discussing all of these operators
in detail so let's talk about arithmetic operators arithmetic operators are
nothing but the operators that are used to perform arithmetic operations
between variables or two values so these are the arithmetic operator symbols
that we use in python so we have addition subtraction multiplication division
modulus exponentiation and flow division so let's take it up to jupiter
notebook to understand the concept of arithmetic operators so let's say i have
two variables x i'm going to give this value as 10 and then i have one more
variable let's say y i'll give it a value let's say 20. now to understand the
concept of arithmetic operators what i'm going to do is first of all i'll try to
perform addition between these two variables so i'll just write plus over here
and when i execute this i'm going to get the addition as my output now to
perform subtraction i'm going to use the subtraction operator and it is going
to give me the value as the subtraction over here similarly i can perform
multiplication then i can also perform exponentiation so i'll use two asterisks
instead of one for exponentiation it is that easy in python guys now we will
perform division over here so it is going to give me the value of the division
now when i do the flow division i'm going to get the value over here as well
one more operator is left that is the modulus so i'll try to perform modulus as
well so it is going to give me the value that is the remainder so this was all
about arithmetic operators guys so these are all the symbols that we can use
for various purposes like addition subtraction multiplication division etc i
hope you are clear with the concept of arithmetic operators now let's try to
understand the next operator that we have which is assignment operator so
you can imagine what an assignment operator is by the name itself that is
assignment so we use the assignment operators to assign values to a variable
or any value that we have in python right so we have assignment operators
like is equal to then we have plus is equal to so all these symbols we have
let's try to understand what all these are used for for example let's say we
have a variable x which has a value hundred now when i write this x plus is
equal to 10 it is going to mean the same as x is equal to x plus 10. similarly
we can write x minus is equal to multiplication is equal to division is equal to
or exponentiation is equal to now let's try to understand these operators or the
assignment operators in jupyter notebook so first of all we have is equal to as
our first assignment operator so i'll have one let's say i have x so i have not
assigned any value to this let's say what happens okay let's try one more
variable i'll write this so it is showing me a name error which is saying name
a is not defined because i have not assigned a value to it so in python until
you assign a value to a variable it is not going to be declared in python so
now when i give the value to this variable let's say i'll write 5 over here it is
not showing any error which means i have assigned a value to this variable
now let's try to understand other assignment operators let's see so what does
plus is equal to mean in python so when i write this what should be the output
guys so let's try to understand this so when i print a i get the value as 10 so
why i'm getting this value because i have assigned the value 5 over here then
i write one more assignment operator that is plus is equal to 5 so what is
going to happen over here is it is going to be same as a is equal to a plus 5 so
we have 5 over here and we have added 5 more to this statement which
means we are getting the result as 10 over here now let's try to understand
other assignment operators as well so let's say exponentiation is equal to 5 so
let's see what the output will be so when i print this i am getting the
exponentiation to the value of 5 since a is equal to 10 and we are doing the
exponentiation until 5 digits so we are getting the output as 100 000 so this
was all about assignment operators similarly we can do the division is equal
to then we have minus is equal to so these are all the assignment operators
that we have in python now let's talk about the next operator that we have
which is comparison operator so comparison operators are nothing but the
operators that we are using to compare two values or objects right so we have
comparison operators like equal not equal greater than less than greater than
or equal to and then we have less than or equal to as well so let's try to take
an example over here so when i use the equal operator i am going to write the
statement as just i have written over here x is equal to y so when i am using
the comparison operator i'm actually using double equal to so this is the basic
difference between assignment operator and comparison operator so let's take
it up to jupiter notebook to understand these comparison operators guys so
let's say i have two variables value is equal to 10 and number is equal to 20.
so to understand the comparison operators let me take one more variable i'll
say this will be our boolean variable so what i'm going to do is i'll write val is
equal to number one what i'm checking is or comparing these two values so
what exactly i'm doing is comparing these two variables or values that we
have that is val and number one so when i print this compare variable what i
am going to get is either true or false so it is going to be false because value
is not equal to number so i can do the similar thing i can check whether it is
greater than or i can check if it is less than so when i write 10 over here so i
can similarly check if it is greater than or equal to i can check if it is less than
or equal to so these are the comparison operators that we have in python
which we can use to compare two values or two objects now let's try to
understand the next operator that we have which is the logical operators so
logical operators are used to combine conditional statements so what are the
conditional statements that we have in python so let's briefly talk about
conditional statement guys so mainly we have three conditional statements in
python we have an is if statement then we have an else if statement and we
have an else statement so i'll give you an example for better understanding so
for these two variables only i'll write if well is equal to number one print
equal

else if well is greater than number one print greater else print smaller so what
happened here is guys first of all the execution will go to the if statement it
will check this condition if this statement is true it is going to print this value
if this is false it is going to move to the next statement that is the else if
statement that we have over here it is going to check this condition if it is true
it is going to print this statement or if this condition is false it is going to
jump to the next statement that is the else statement and i will give one more
condition so if all of these conditions are false it is going to jump to this
statement and it is going to print not there over here if all of these conditions
are false it is going to jump to the next statement that we are going to have in
the program but i have not written any other statements so it is going to end
the execution over here only so this is a basic example using the conditional
statements now that we are done discussing conditional statements let's talk
about logical operators so i have told you logical operators are used to
combine conditional statements so what exactly are the logical operators so
we have a logical and we have logical or or we have a logical not as well by
looking at the example let's say we have two conditions over here we have x
is greater than 5 and then we have x is greater than 10 so let's try to
understand these logical operators in jupyter notebook now let's say i have
two statements all right x is equal to 10 and what i'm going to do is i'm going
to check if x is greater than 10 i'll write and which is my logical and operator
and i'll write x is greater than 5. so what is going to happen if i use the logical
and operator if both of these statements are true it is going to give the result
as true but if one of these statements is false it is going to give me the value
or the output as false so let's see what happens if i execute this statement i am
getting false because one of these statements is false now when i write
instead of 10 if i write 8 over here let's see what happens since both of these
statements are true it is going to give me the output as true now instead of
and operator if i use the logical or operator let's see what is going to happen it
is showing me that it is true because when we are using the logical or
operator only one of these statements has to be true the output will be true but
what happens if both of these statements are false it is showing me the value
that is false but let's see what happens if both of these statements are true i'm
getting true as well so one of the statements has to be true when we are using
the or operator now talking about logical not operator what i'm going to do is
i'll write not in the beginning now i'll specify the condition let's say x is
greater than 10 and x is greater than 5. this is the same statement that we have
used before and for this we have got the output as false so let's see when we
use the logical not operator what is going to be the output i am getting true as
the output here because this statement is negated over here using the not
operator and we are getting the opposite value that we should be getting for
this statement so this is the purpose which fulfills by using the not operator or
the logical not operator that we have in python so now that we are done with
logical operators as well let's try to understand what are identity operators so
identity operators are used to compare objects now you must be wondering
what are objects here so everything in python is actually an object so we can
use the data types as objects as well so let's try to understand what are the
identity operators in python so we have is and we have is not so these are the
identity operators so what is does is it returns true if both the variables are
same object for example let's try to do this in jupyter notebook so what i'll do
is i'll take let's say a list i'll give it of some values let's say 10 20 and 30. i'll
take one more list give it the same values let's say 10 20 and 30 and i'll write
x is equal to list one so when i use the identity operators let's say if i write x is
list one let's see what is the output that i'm going to get i am getting true
because x is actually the same object as list one now let's try to write list one
is list two even though when we have used the same values in list one and list
two let's see what the output will be it is false because these are the not the
same objects right similarly i can use list one is not list two so here i'm going
to get the output as true because list one is not exactly list2 even though we
have the same values it is not going to be the same object so this is the
concept about the identity operators now let's talk about the next one that we
have is membership operators in python so membership operators are used to
check if a sequence is present in an object or not now to understand the
difference between an identity and a membership operator okay let's first
understand what are the operators in membership operator we have in and
then we have not in so it is going to return true if a sequence with the
specified value is present in the object and it will return true if the sequence is
not present so let's do this in jupyter notebook we have already specified
these objects so let's try to do if x in list one let's see what happens it is going
to show me that it is false because we have no values in x so when i do the
same thing with list one in list two now you see we have the same values
over here let's see what the output will be it is false again okay let me do one
thing now to check a particular value or a particular sequence what i'm going
to write is i'll check if 10 in list one so it is going to check if this is going to
be present over here or not it is showing me that it is true so what if i write
like this 10 20 30 in list 2 it is false so this is the basic difference between is
that is then identity operator and membership operators so when i write let's
say it is going to check if this is present in the sequence or not it is showing
false because it is not there but what if i add this value over here let's say

now when i execute the same statement i am getting true because this
sequence is actually present in the object now to understand the difference
between is equal to and the identity operator let's see what is going to happen
what if i write list one is equal to list two it is showing false i have made a
change over here so i'll do this once again so when i print this it is showing
that it is true but instead of is equal to if i write is over here it is going to
show me false because these are two different objects so this is the basic
concept of identity and membership operators guys now let's understand
bitwise operators so bitwise operators are used to compare binary values or
binary numbers so this is a rather difficult concept guys so i'll be telling you
about what are binary numbers first and then we'll be moving on to the
bitwise operators that we have in python so these are the bitwise operators
like bitwise and bitwise or so these are the symbols used for these operators
guys so this is actually what happens when we are using these operators so
let's try to understand bitwise and operator first in jupiter notebook so what
i'm going to do is i'll just write 10 and 12. so what is going to happen over
here let's say it is showing me the output as 8 but it is not clear why we are
getting this output right so let's understand what 10 is in binary numbers so
when i write 10 in binary numbers it is going to be 1 0 1 0 and similarly for
12 it is going to be 1 1 0 0. now when i use the logical and operator what it's
going to do is if both the bits are 1 it is going to be 1. so in this case only first
bit is 1 over here so the output will be 1 0 0 0 and if we convert this to
decimal it is going to be the number eight so this is the concept between the
binary numbers guys similarly i can use 10 or 12. so what is happening here
is i have these values let's say 1 0 1 0 for 10 and 1 1 0 0 for 12. now looking
at first bits here that is 0 0 it is going to be 1 so all of these bits in the output
will be 1 1 1 1 which is exactly is equal to 14 so this is the concept of using
the bitwise operators where we are using the values as binary numbers we are
comparing the binary numbers now let's talk about left shift and right shift
guys so this is what i write for doing the right shift so 10 in binary numbers is
one zero one zero so when i right shift these two bits i'm going to be left with
one zero and when i convert this to binary i'm going to get the value as two so
this is the concept of right shift guys now let's try to understand left shift so
when i write this i'm going to get the value as 40. now let's try to understand
how i am getting this value so 10 if i write it in binary is going to be 1 0 1 0.
so when i do the left shift what is going to happen is it is going to shift two
values and i'm going to get the value as one zero one zero zero zero so what
is happening here if i convert this binary number to decimal i'm going to get
the value as 40. so this is why i'm getting the value 40 over here so this is the
concept of bitwise operators guys i hope you are clear with the concept of
bitwise operators it is a bit complicated because we are using the binary
numbers even though i'm telling you these binary numbers you need not
mention them while using the operators for example for these bitwise
operators all these are written over here let's say if you are using the bitwise
and operator it will set each bit to 1 if both bits are 1. as i've shown you and
then before bitwise or operator it is going to be one if one of the bits is one so
similarly for xor it will set each bit to one if only one of the bits is one and
then we have bitwise not operator which is going to invert all bits let's say if
we have all bits that is one it is going to convert all those bits to zero and then
i have told you about left shift and right shift as well so this is about operators
in python guys

today's session will be focusing on various loops that are available in python
so without any further ado let us move forward and have a look at the agenda
for today so first we'll see why to use loops what are the reason of
introducing loops in the programming world then we'll see what exactly are
loops and then we'll focus on various types of loops that are there in python
namely while for and nested i'll be explaining you all these three loops with
examples after that i'll give you a brief summary of one of the things that we
have discussed in today's session so let us move forward and see why we
need loops now let us understand this with an example that is there in front of
your screen suppose you are a software developer and you are required to
create a software module for payroll processing of all the employees in your
office now what are the things you need you need the salary of those
employees the bonus and the total amount that they'll get after the end of the
month right so all these things for each employee you need to print so for
each of the employees you need to print all these three details now there are
two ways of executing this task so let us see what are those two ways so the
one way is you can actually write a logic to calculate the total salary of each
of the employees that includes all the fields like salary bonus in total and you
are going to write that logic for all the employees that are there in your office
there might be hundreds of employees that are there in your office you need
to write the logic or you need to write the code for all of those employees so
this process is actually pretty hectic you need to repeat the same logic for
total amount of employees are there in the office i'm just giving you an
example of three employees but what if you have like hundreds of employees
so at that time this particular process will not work this will not only increase
the size of the code it'll make it more complex and less efficient now another
way of approaching this task would be you write the logic to calculate the
salary you keep on iterating that logic for the total number of employees that
are there so when this loop runs once it'll print the salary of first employee
when the loop runs for the second time it will print the salary of the second
employee similarly it will keep on repeating so if you have 100 employees it
will repeat 400 times now what advantage we get here the major advantage
that we get here is we don't need to write the logic for each employee in order
to calculate the salary we can write one logic and keep on repeating it for all
the employees so this way the size of the code gets reduced the length of the
code is reduced at the same time it reduces the complexity makes it more
efficient and even increases the speed of execution so this is just one example
in order to show you why we need loops so there are hundreds and thousands
of examples that you can think of why we need loops right so this is just one
simple example that i've shown you in order to make you understand why we
need loops so let us move forward and see what exactly are loops let me
explain you this with the help of the flow chart that is there in front of your
screen now what are loops loops basically allows us to execute a statement or
a group of statement multiple times let me explain you this with the help of
an example that is present in front of your screen now over here what
happens the control comes here and checks the condition so if this condition
is true it will go on and execute the conditional code that is here this is
nothing but the statements that are present inside the loop so it will execute
that and again it will go back and check the condition so if the condition is
still true then again it will execute the conditional code of the statements
present inside the loop and it will keep on repeating until this condition
becomes false and the moment this condition becomes false the control will
move out of the loop and it will execute the statements that are present after
that loop now one thing to notice here guys is that there can be two kinds of
loops one is finite this is actually the flow chart for the finite loops and
another can be infinite now in infinite loops what happened the condition will
never be false so at that time the control will never come out of the loop so it
will keep on repeating and it will never stop that is what infinite loops are so
basically the condition will never be false and due to that the loop will be
executed infinite number of times now there's one more way in order to
categorize loops that is called post test and pre-test in post-test loops what
happens the control will first enter the loop and then in the end it will actually
check the condition but in pre-test loops the control will enter the loop only
when the condition is true so the condition is checked in the beginning of the
loop in pretest loops but in post loop the condition is checked at the end of
the loop now in python there are no post test loops present there are only pre
test loops so we'll focus on pre-test loops in today's session so we'll move
forward and we'll see various type of loops that are present in python so
python basically supports three kinds of loops one is vibe for and nested we'll
look at all these loops one by one and i'll explain you with examples as well
so first we'll have a look at while loop so while loop is basically used when
you don't know how many iterations are required so let me explain you this
with the help of the flow chart that is there in front of your screen now over
here what happens the control will move inside the loop only when this while
condition is true and when it is true it will execute the body of the loop and
then again it will go back and see whether the condition is still true or not if it
is still true then again it will execute the body of the loop and will keep on
doing that until the condition becomes false and the moment the condition
becomes false it will come out of the loop and execute the statements that are
present after the loop now this is the syntax for while loop first you need to
write while then you write the expression or the condition then you give a
colon and the statements or the body of the loop now why we use while loop
basically i've told you earlier as well while loop is used when you don't know
how many iterations are required so you don't know how many times you
need to execute the statements that are present inside your loop so that is the
reason why we use while loops now let me show you that with the help of an
example i'll open my pycharm and i'll give you a very basic example of using
while loop and after that i'm going to increase the complexity of the code so
first we'll see a very small introductory example of while loop in which am
going to print the integer values between 0 to 9 that won't include 9 so it will
print 0 1 2 3 till 9 but it won't include 9. so let me open my pie chart and
show you how to do that now this is my pie charm guys so over here as i've
told you earlier as well i'm going to print the integer values between 0 to 9
but that won't include 9. so for that what i need to do is i need to first define a
variable let me name it as count and i'm going to initialize value to it that is 0.
now after that i'm going to use a while loop and i'll write while and then i'm
going to give a condition which says that when count becomes greater than 9
it should come out of the loop all right so now what i'm going to do is i'm
going to just type in print let it be number colon comma print count right now
i'm going to increment the value of count count equal to count plus one yep
now when i come out of the loop i want to print say goodbye

yeah looks fine now let me tell you what i've done here i've defined a variable
and i've initialized the value 0 to it after that i have used a while loop in
which i've given a condition that says that count should always be less than 9
because i want to print values between 0 till 9 which won't include nine let
me tell you that so my condition says that the loop should be executed only
when the count value is less than nine the moment it becomes greater than
nine then the control should come out of the loop after that is just the same
general syntax i have given a colon and then i have written a print statement
that will print the count value and after that i have increased the value of my
count by one and finally when the control comes out of the loop i want to
print goodbye so let us see whether it works or not i'm going to run it and as
you can see that it works so we have 0 1 2 3 4 5 6 7 and 8 and finally when
the control went out of the loop it has printed good pi this is just a very small
example guys now let me go back to my slides now the example that we just
saw was a very simple example so i'll increase the complexity a bit and i'll
give you one more example so let us move forward with that so over here
what i'm trying to do is i'm trying to code a little guessing game all right so
what happens in this guessing game so there will be a random number that
will be generated between say 0 to 20. and you need to guess that number so
the number that you have guessed is less than that random number then it will
print number is too small if you have guessed the number that is greater than
the random number then it will print that number is too large and the moment
you get the right answer you'll exit the while loop and you have won the
game basically so it's just a pretty simple example but this is a perfect
example in order to show you why we use while loop because if you notice
here i don't know how many iterations are required in order to guess the
correct answer so at that time while loop is a perfect solution to this problem
so without wasting any time i'll actually open my pycharm and show you how
to execute this so this is the code here guys let me explain you each and every
line that is present here now what happens first i need to import a module that
is called random in order to generate a random number now over here i've
defined a variable n and i've given a value to it that is 20 because i want the
random number that is to be generated should be between the range 0 to 20.
now i have taken one more variable and i've named it as to be guest and over
here it should be an integer types i've written end and this logic will generate
the random number that i'm talking about and this will be generated between
the range 0 to 20. so how it'll be generated it'll be generated with the help of
random modules that we have imported so it'll be n random dot random plus
1 this will actually generate a random number between 0 to 20. so after that
what happens i have defined one more variable guess and i have assigned a
value to it or initialize the value to it 0. all right so now comes the while loop
now in while loop i have given a condition which says that the number that i
have guessed if it is not equal to the random number then enter the loop now
once you enter the loop you need to input the new number the number that
you want to guess again now if that guessed number or the number that you
are guessing is greater than zero then again there will be one more if
condition which says that the number that you have guessed is greater than
the number that has been generated or the random number that has been
generated then print number is too large and if the number that you have
guessed is actually smaller than the random number generated then print
number is too small now there's one more condition that is else which means
that when the number that you have guessed is less than or equal to zero then
that means you are giving up so it will break it will come out of the loop and
it'll print sorry that you are giving up that's when your game gets over and
you have lost it finally if you have guessed the correct number then it will
print congratulations you have made it so let us go ahead and execute this and
see what happens all right so it asks me for a new number so it has to be
between 0 to 20 so yep i'll type 10 and let's see what happens so it says
number is too small that means it is between 10 to 20. how about 13 all right
so i've guessed the correct number and it says congratulations you have made
it now over here as you can see that it took only two iterations for me in order
to guess the correct number but what if it would have taken more iterations i
mean i'm pretty unclear how many iterations it will take for me so that is the
reason why we use while loop because we don't know how many iterations
are required now we can run this program again and i can show it to you once
more ask a new number so i'll just type in say 14. it says number is too large
so i'll type in 11. again the number is too large that means it is between 0 to
11 so how about eight guys number is too small so now now as you can see
that already three iterations have occurred and uh for the fourth iteration
definitely the random number will be somewhere between 8 and 11 so how
about 10 so congratulations you have made it and the control came out of the
while loop and it has printed congratulations you made it so we'll move
forward and see for loops in python so for loop is basically used when you
know the number of iterations that are required unlike while loop where you
are not sure about the number of iterations that are required in for loop you
know how many times the statements that are present inside the loops need to
be executed so for loop provides you with a syntax that will include three
fields basically or you can say three informations so first will be the boolean
condition then comes the initial value of the accounting variable and then the
incrementation of the counting variable so as you can see from the syntax as
well first you write for name of the variable in the range then you specify the
range in which that variable should be or and then you specify the range that
means from which point till which point it should be executed so you know
the number of iterations required then only you use for loop now over here as
you can see from the flow diagram itself the control comes to this and it will
see the item from the sequence it will execute the statement go back again
and then from the range it'll pick up the next item again it'll execute the
statement again go back and then from the range it'll pick up the third item
and it'll keep on executing until the range becomes over or that is the last item
from the sequence so when there are no items in the sequence it will go on
and execute the statements that are present after the for loop so this is how for
loop works guys now let me just give you a very small example of how for
loop works i'll open my pycharm again and i'll start with a very small
example and then i'm going to increase the complexity of our code like i've
done that in while loop now over here what i'm going to do is i'm going to
first define a list and i'm going to name it as fruits so what all fruits you like
guys i'll first type in mango then i like grapes

and finally i'm going to write and say apple yep so this is my list which
contains three fruits mango grapes and apple now i'm going to define a for
loop and over here what i'll write i'll define a variable say fruit for fruit in
fruits give a colon print

current fruit

and type in fruit

now when you come out of the loop just print

again goodbye so i have declared a list and the name of that list is fruits now
that fruits list contains elements which are mango grapes and apple now after
that i have defined a for loop which says that for a variable name fruit in
fruits so this will give me the range fruits will give me the range as you know
that in the fruits list there are only three fruits so i know it'll iterate only thrice
first for mango then for grapes then for apple so this is the difference between
the while and for loop in for loop i know that will take only three iterations
after that print the current fruit that's all and when the control moves out of
the loop print goodbye it's pretty easy guys so go on execute this and see
what happens so yep the current fruit first is mango then comes grapes then
comes apple and then finally print goodbye so what i'm going to do is i'm
going to increase the complexity now as i've done that in while loop as well
so i'll show you an example first let me go back to my slides so what i'm
going to do in this example i'm going to calculate the factorial now one thing
to notice here guys again in factorial also i know how many iterations are
required because if you see if i'm calculating the factorial of five and i know
that i need multiplication five times first i need to multiply five with four then
four with three then three with two and then two with one so this way i
require only four iterations so i know the number of iterations required so it's
a very good example in order to show you where we should use while loop
and where we should use for loop so let me go back to my pycharm and
execute this practically so this is the code in order to find the factorial of a
number so over here what happens first i need to input the number that i want
to calculate the factorial of after that i've defined a variable factorial and i've
initialized the value to it which is 1. now i have defined a condition if the
number that i've entered is less than zero then print the number must be
positive because i can't calculate the factorial for negative numbers right and
again i have given one more condition which says that if number is equal to
equal to zero then factorial is equal to one and then else condition says that
when number is greater than zero then i've used a for loop it says that for i've
defined a variable i in range 1 to num plus 1. when i write num plus 1 the
range will be between 1 to num plus 1 but it won't include num plus 1 so it'll
only be including 1 till num all right so after that what i've written factorial is
equal to factorial into i so factorial was one earlier then it will multiply by i i
will also be one in the beginning and then again it'll go back and it'll become
two similarly it will keep on increasing until it becomes num so till that time
it'll keep on executing the loop and the moment it becomes equal to num it
will come out of the loop and it will print the factorial value so let me go
ahead and execute this and show you if it works or not so i need to enter the
number so let's say i want to calculate the factorial of 3 which is 6. so if i
want to enter one more number so what i can do is i can start it once more so
what i'll type i can type again 4 so it prints 24 which is absolutely correct so
we'll move forward and we'll see what our nested loops in python so python
basically allows us to use a loop inside another loop for example you can use
a for loop inside a for loop or you can use a while loop inside a while loop
and at the same time you can use a while loop inside a for loop as well and a
for loop inside a while loop as well so that is basically what is called nested
loops now we'll have a look at the example of nested loops as well don't
worry so let us move forward and see one example of nested loops now over
here what i'm going to do is i'm going to write a code in order to simulate a
bank atm all right so for that i'm going to use nested while loop and what will
happen first you need to enter the four digit pin and then you can perform the
following functions you can check the balance you can make a withdrawal
you can deposit some money and you can even if you don't want to do
anything you can tell the machine to return your card as well so let me show
you how it is done i'll open my pycharm once more so this is a code that i've
written in order to simulate a bank atm i'll explain you each and every line so
don't worry about that so first line is nothing but a print statement that says
welcome to iron bank of browse atm all right and then i have defined a
variable restart and i've assigned a value to it that is y similarly chances i've
assigned a value that is three and this is the balance that i'm going to initialize
that is 67.1 phone notice you over here you won't get more than three chances
in order to write the correct password now comes the while loop which says
that when chances are greater than or equal to zero at that time what it'll do
you need to enter the pin so you need to input the four digit pin that you have
and if that pin is one two three four then it will print that you have entered the
correct pin now comes one more while loop which says that while restart
should not be in this particular tuple that is the value of restart should not be
n capital n o small n o or capital n so it should not lie within this particular
sequence that is n capital n o no and n but we know that the restart value is y
so it will enter the while loop now over here what will happen it will give you
four options first option is in order to check your balance for that you need to
press one to make a withdrawal you need to press two in order to pay in some
cash or you need to deposit something you need to press three or you want
your card back you need to press four so these are the four options that will
be given to you so when you choose option one it will print the account
balance so over here as you can see that your account balance is and the
balance that is there in your account after that it will ask you for restart so
you need to input that value so that will say would you like to go back and if
your restart value lies in this particular tuple then it'll break and it'll print a
thank you statement but if you want to continue or you want to go back then
you can press anything else apart from small n n o or this no or capital n so if
you press any other button apart from these it'll actually go back and in the
while statement as you can see it says that it is not present here so it will give
you all these four options once more now after that what if you choose the
another option in which you need to make a withdrawal so for that what will
happen you need to enter the amount that you would write to withdraw which
can be a float number it cannot be an integer number so that's why i've used
float here so you need to enter that value and once you enter that value it'll
check whether it is in this particular list or not that is 10 20 40 60 80 or 100.
now by default it will give restart y because you need to enter the amount
once more so again it will go back and it will give you all four options so you
can choose that withdrawal option again and you can choose a number which
is present in this particular list now when you choose withdrawal equal to
equal to one at that time it'll again ask you please enter the desired amount so
this is for option two now when we talk about option 3 it is pretty much
similar to the couple of options that we have discussed before so it's pretty
much similar to that over here again whatever the amount is that you want to
pay in how much amount that you would like to pay and balance plus the
amount that you are depositing so it will print the balance that will be equal
to balance plus the amount that you are depositing again it will ask you for
restart if you press anything apart from this particular tuple then it will go
back to the while statement and it will give you all these four options
similarly for option four as well now what happens when you enter the
incorrect pin so there's one more condition in the end which says that if the
pin that you have entered is not equal to one two three four then it will print
that incorrect password and it will decrease the chances by one so earlier you
had three chances if you press the incorrect pin once it will decrease your
chance and it will make it as two again if you write the incorrect password
then again it will make it as chance it equals to chances -1 which will become
one and if the third time also you do the same thing then the chances will
become zero and the moment it becomes zero then it will print no more tries
break it'll come out of the loop that's all guys so let us go ahead and execute
this and see what happens so please enter your four digit pin so i'll just write
one two three four and give me four options which is one for balance two for
withdrawal three for pain four to return a card so if i want to check my
balance i'll put in one so it has printed my balance which is 67.14 and then
the restart value that i was talking about it is asking for that let me just make
it big for you yeah would you like to go back so if i press n here it'll come out
of the loop and it'll break and if i press anything apart from small n capital n o
small n o or capital n it'll actually go back and ask give me all the four
options that were there so if i press y it'll again give me all the four options
that are there you can see that press one so again if i want to make a
withdrawal i'll press two how much amount that i would like to withdraw say
i want to withdraw 10 so my balance has reduced from 67.14 to 57.14 so
would you like to go back so i'll again press y and it'll give me all four
options if i want to pay in something that is i want to deposit something i'll
press 3 how much amount that i would like to deposit i'll say 10 so my
balance became again 67.14 again it is asking me would you like to go back
no i don't want to go back so i can type in n so yep so it says thank you and
again asking me for four digit pin so let me show you what happens if i write
the incorrect pin say if i write one one one incorrect pin if i write that pin
again again incorrect again incorrect so we have no more tries it will come
out since i have exceeded the chances that i was given so i was given three
chances i couldn't write the correct pin in those three chances so it'll come out
of the loop and it'll stop so this is an example of nested while now let me go
back to my presentation and i'll show you an example of for loop as well so
this is an example of nested for loop so over here what i'm going to do is i'm
going to write a code in order to print the pythagorean number between a
particular range so what happens is suppose if i want to enter the number 20
that means i want the pythagorean numbers between 1 to 20. so pythagorean
numbers are nothing but the integers which satisfy a square plus b square is
equals to c square so at that time it will print all the pythagorean numbers that
are possible between 1 to 20 3 4 5. you can see that 3 square 4 square is
equals to 5 square 9 plus 16 is equals to 25 similarly it goes for 5 12 13 6 8
10 8 15 17 9 12 15 similarly for 12 16 and 20. don't worry guys i'll go back to
my pie chart and i'll explain you how you can do that so this is the example of
nested for so first over here i need to import certain modules in order to use
the square root function so from math module i am going to import the square
root function after that will ask me for the number in the example if you can
remember in the slides where i've written 20 so it has printed the pythagorean
numbers between 1 to 20 that same number it will ask me and it'll print the
pythagorean numbers between 1 to n so whatever the number n that i'm going
to put in or give an input after that it'll run a for loop and it'll say that for a
which is a variable in range 1 to n plus 1 that means 1 to n that means 1 to n
plus 1 but don't include n plus 1 after that there's one more variable b which
is in the range a comma n that will not include n it'll only include till n minus
1. so the square root c squared i have to find one more variable c squared is
equal to a exponent 2 or a to the power of 2 similarly b raised to the power of
2 all right and then what i'm going to do is i'm going to calculate the square
root and then what i'm going to do is i'm going to define one more variable c
and it'll be an integer that will be the square root of c square so if that c
square is minus c square is equal to equal to 0 then print a b c it's pretty
simple logic guys okay i'll explain it once more neil so this is an example of
nested for so over here what i'm going to do is i'm going to first import the
square root function from the math module after that i'm going to input a
number so if you can remember in the slides i have given it as 20 so it will
print the pythagorean numbers between 1 to 20. over here also it will print the
particular numbers between 1 to n so whatever the value of n you input that
will be depending upon it so the particular numbers will be depending upon
the values that you input so it will be printing the pythagorean numbers
present between 1 to n after that i'll run a for loop which says that for a
should be in the range 1 to n plus 1 that will not include n plus 1 guys it'll
only include n so 1 till n plus 1 but don't include n plus 1. after that i've
defined one more for loop which says that for b in range a comma n it would
include n it will be till only n minus 1. i've defined one more variable here
which is equal to c underscore square that is equal to a square plus b square
now after that i've defined one more variable c and this will be actually the
integer of the square root of the c underscore square all right so whatever
value that you will get here the square root of that value will be converted to
an integer value and will be assigned to c now one if condition i'll be using
here which says that if c underscore square minus c square is equal to equal
to zero then print abc that means that will be a pythagorean number so this is
a pretty simple logic guys all right so i hope you have understood the code
that i've explained you here now let us go ahead and execute this and see
what happens yeah so the first number that i'm going to type in say five and
it'll give me all the pythagorean numbers present between one to five so we
have only one pythagorean number that is three four five in that range now
i'll execute this once more and i'll type in ten here so we have two particular
numbers there are three four five and six eight ten similarly if i execute it
once more and i type in a big number say 25 yeah so we have these many
pythagorean numbers present between 1 to 25 we'll again go back to our
slides and we'll have a look at one more example now in this example i'll
actually be using a for loop inside a while loop so what is this example i want
the bulk reservation of train tickets so i have like group of people who are
traveling somewhere and i want to give their details such as name age and
sex i want that to happen in bulk i don't want to give it one by one i just want
it to happen in bulk so for that what i'm going to use is i'm going to use a for
loop inside a while loop as i've told you earlier as well you can even use a
while loop inside a for loop but for now i'll use a for loop inside of while loop
and see what happens so let me go back to my pycharm so this is the code in
which i'll be using a for loop inside a while loop so first i have defined a
variable traveling so in which you need to input whether yes or no so if you're
traveling you'll say yes obviously and then we'll have a while loop which
says that while the condition is traveling equal to equal to yes that means if
you're willing to travel enter the number of people who are traveling so you
need to enter the number of passengers that are traveling and that will be
assigned to a variable num now there will be a for loop which says that for
num in range 1 to num plus one but it won't include num plus one enter the
name enter age and finally whether the person is male or a female and then
print all those values now one more thing here is again it will ask you
whether you have missed someone or not so you need to input that oops
forgot someone so at that time you can write in yes if you have forgotten
someone that again it will execute the loop again it'll ask you the number of
people traveling in all these details if you type in anything apart from yes that
means you have not forgotten anyone and it will come out of the loop so it is
a very small example but a very good example to understand how a for loop
can be used inside the while loop so let me go ahead and execute this whether
you're traveling i would say yes i am traveling number of people traveling i
would say three name is saurabh ages 78 male all right so again it has asked
me for one more name so i'll say neil

age is 90

male or female mail yep so one more name i need to type in say i would type
in geography

ages 98 male or female female and yup it'll print all those details for me so
now it is asking have you forgotten someone so if i type in and say yes then
it'll again ask me the number of people traveling that means it's again
executing the while loop so if i would say the number of people traveling is
one and i would type in the name of the person that was traveling so i would
just say siddharth whose age is 77 and he's a male yep again it has asked me
so if i type in anything apart from yes say if i type n so yep it'll come out of
the loop and this is how you can actually use a for loop inside a while loop so
let me just open my slides and yep so this was an example of a for loop inside
a while loop so let us move forward and i'll give you a brief summary of what
all things we have discussed till now first we saw why we need loops we
actually use the example of software module for payroll processing in which i
showed you two methods the one is manual and the another one in which you
are using loops after that i told you what exactly are loops and we saw
various types of loops in python namely while foreign nested then we focus
on each of these loops we started with while loop and i explained you where
to use while loop i gave you two examples of while loop similarly for for
loop i explained what exactly is for loop how it works its syntax and two
examples again for for loop when you talk about nested loops again i've
explained you the syntax how to use it and i've given you three examples for
nested loop as well

take a look at the agenda for this session first of all i will start with star
pattern programs and the patterns include pyramid half pyramid hourglass
diamond shaped patterns etc moving further i will discuss pattern program
with numbers so instead of asterisk we'll be using the numerical values in the
patterns and finally i will explain a few pattern programs with characters or
alphabets in them i hope you are clear with the agenda also don't forget to
subscribe to edureka for more exciting tutorials and press the bell icon to get
the latest updates from edureka now without wasting any more time let's take
a look at the star pattern programs that i will explain in this session so i'm
going to start with star pattern programs in which i'm going to show you how
you can play with the concept and make other patterns like half pyramid
triangle hourglass pattern diamond pattern and inverted pyramid patterns as
well so let's take it up to jupiter notebook and i'll show you how you can
make star pattern programs and we are going to start with the simple pyramid
program first so now we are in the jupiter notebook guys i'm going to start
with the simple pyramid program so i'll write pyramid over here and in this
i'm going to take one function and i'll name it as pattern and inside this i'm
going to pass n because this is going to be our number of lines which i want
in the pattern and for blank spaces i'm going to take one variable that is k i'll
show you what it does and we're going to use a lot of for loops inside this so
if you're not familiar with loops in python i suggest you to check out other
tutorials on eddie raker for loops in python so that you will be able to
understand this better and i'm going to take one for loop here for i in this is
going to be the loop for our outer rows so i'm going to take this as range 0 to
n and i'm going to take one more loop which is for j in range and this is going
to be our loop for columns and i'm going to take this as k over here now i'm
going to print some blank spaces over here so for this i'm going to write this n
is equal to and after this i have to decrement the value of k and i'm going to
take one more for loop inside this i'm going to specify the range 0 to i plus 1

because we are going to move in the forward direction while printing the
pattern that we have so inside this i'm going to print the asterisks pattern
which is the saw pattern also and end is equal to this

now one more important point you have to print backslash r or backslash n in
order to get the pattern right i'll show you what happens if you don't do that
now we're done with the pattern function over here i'll just call pattern and
inside this i'll specify five and when i run this i'm getting a pattern which is a
pyramid pattern so instead of backslash and if i write backslash r the pattern
will look something like this and if i just comment this statement let's look at
the output that varies so we're getting the output somewhat like this if you
want to get your pattern right you're going to have to write it like this and this
is how you can make a simple pyramid pattern program in python so you can
see this this is the variable that i was talking about to specify the spaces so
what if i write it as let's say n minus 2 the output will move to the left side
and if i write it as n look at this so this is what happens when you play with
the spaces over here so i'll just write it as 2 into n minus 2 so we are getting
the pattern somewhat like this so instead of 5 if i write 10 over here i'll be
getting a much more bigger pattern with a pyramid shape and this is how we
can write a simple pyramid pattern so let's take a look at the next program
that we have which is the inverse pyramid

so by now i think you have got the idea of how we are doing this so for
printing the inverse pyramid we are going to go from back to the starting so
we will start with this one first and we will go in the backward direction so
that we'll get one in the end so we will get the inverse pyramid then so let's
take a look at how we're going to do that

i'll just take a function like i have done before and inside this i'm going to
specify the space as well which is 2 into n minus 2.

and now i'm going to take a for loop so for i in range this is where the magic
happens guys you have to specify n over here because we're going to the
backward direction and minus 1 and okay we'll take this step as -1 as well
and if you're not familiar with the range functions please do check out the
other tutorials on edureka for better understanding guys we have a full video
on range function as well and i'll take another for loop for columns as well so
in this i'm going to go with the backward direction as well step is going to be
-1 and now i have to print end is equal to this now i have to specify a
increment in the k variable because we're going to backward direction i'm
going to take one more for loop and for j in range this time we are going to
go with the normal flow which is i plus one

and in this i'm going to print my asterisk

and after this i have to just print the backslash r so that my output will not be
distorted and it will print a perfect pattern so when i call my function pattern
over here and let's just say i write it as 10 okay i have an invalid syntax over
here sorry guys we're getting an inverse pattern right here so in this you can
see the output is towards right so what i'll do is i'll just remove this and you'll
see the output is just like the other one the pyramid and we are getting the
inverse perimeter right now so the approach that i followed was i was starting
from the end which i got over here and i got back to the backward direction
and in the end i'm getting the one stop so this is how you write a simple
program for inverse pyramid let's take a look at the next pattern that we have
which is a write start pattern program so we are going to follow the same
approach right here let me just write right start pattern

so in this i'm going to follow the same approach i will specify a function
pattern inside this i'll specify n and now what i'll do is i'll just write for i in
range 0 to n for j in range 0 and i plus 1 that we have written before as well
now what i'll do is i'll print my asterisk can any of you guess right now which
pattern i'm going to make because i'm not sure if everybody's familiar with
the pattern right start pattern it's going to be looking like a triangle but
mentioned in the comments if you had guessed right i'll specify one more
outer rows function because we're going to get fairly unique pattern in there
so we need two outer loops for rows and two outer loops for columns as well
so i in range i'm going to specify the range as n 0 and -1 the step is going to
be -1 and inside this i'm going to specify for j in range 0 and we're going to
follow the same approach that is i plus 1 after this i'm going to print asterisk
again

and is equal to this print backslash r don't forget the backslash r guys so if
you have any problems in your pattern just look at the print statement where
you have specified backslash r now when i call my function pattern over here
i'll specify 10 again okay i'm getting the pattern somewhat like this okay
we're not getting the output as i had expected so i'll just do one thing instead
of zero over here i'll specify minus one so when i run it again i'm getting the
perfect right start pattern so this is how you write a program for a write start
pattern in python and let's take a look at the next program that we have which
is a left start pattern

so for this i'm going to take pattern again specify n and after this i am going
to take one variable for spaces because we're going towards the left side so
what i'll do is i'll just write k is equal to 2 into n minus 2

again i'll take a loop for outer rows inside this i'll specify the range as 0 and n
minus 1 for the columns i will take for j in range 0 to k

print end is equal to this because we want some blank spaces over there and i
will recommend the value of k by k minus 2

you can modify these values for k and all these range functions as well
according to your pattern whichever pattern you are making do experiment
with these values so that you will understand how it's working so i'll take one
more for loop for columns again so j in range this time the range is going to
be 0 and i plus 1 and can any of you guess right now i'm going to print the
asterisks over here which is going to be in my pattern again this is going to be
n is equal to this and over here i need to print backslash r so that my output
will not look distorted and again i have to get the value of k right so i'll write
k is equal to k minus 1

now i have to take one more outer loop for outer rows so for i in range just
like we did in the other program okay i'll show you why we are taking two
different outer rows so i'm printing a half pyramid until here and after this i'm
going in the backward direction like this so instead of doing this i'm going to
print some blank spaces as well so i'll be printing backspaces until here and
then my actual program will start so this is why i am taking two loops over
here so i'll just specify n minus 1 minus 1 and minus 1 for the step as well
and after this i'm going to take one more loop for columns and inside this i'll
specify minus 1 and step as minus 1 as well i'm going to print n is equal to
spaces decrement the value or increment the value because we are going to
go in the backward direction in this loop and again for j in range 0 i plus 1
and after this i am going to print asterisk

and is equal to this and print backslash r

now when i call my pattern again say 10 okay i have invalid syntax for j in
range okay i think i have made a mistake over here so i'll just check my code
again okay i'll make this as -1 and move it a little further so i'm getting my
pattern right there which is a left start pattern so this is how you can write a
program for left start pattern in python and now let's take a look at the next
program that we have which is our glass pattern program so for our class
pattern i'm going to print a pyramid pattern and on top of that i'm going to
print a inverse pyramid so that it will look like an hourglass so let's take a
look at how i'm going to write that so i'll take one pattern function again
specify n and i'll just go with the variables for spaces and then for outer rows
i have a loop in which i am taking the range as n minus 1 and step is -1 as
well okay i made a syntax error and now for columns for j in range i'm going
to take the range as k 0 and -1 okay we'll do one thing guys i know for sure
that we need an inverse pyramid so i'll just take this code copy this and over
here i'll just print this code so when i call pattern now say 5 i'm getting an
inverse pyramid so now i'm going to take the code for pyramid pattern over
here and i'm going to paste this after this

this goes here so this is my hourglass pattern guys okay we have a little
distorted our glass so in our inverse pyramid we're getting the six rows and in
this experiment we are getting only five rows so what i'm going to do is i'll
just specify this as 0 and n minus 1 let's see what happens so i'm going to take
it as n plus 1 so now we're getting a perfect hourglass pattern and this is how
you can write our glass pattern in python guys all you have to do is
understand how it works and after that you can just play with the numbers
and the spaces and you can make any pattern that you want so now that we
are done with our glass pattern let's take a look at a half pyramid pattern that
we have in python so it's very easy guys i'll just take one pattern function
specify n over here and in this i am going to just write for i in range whatever
number that you want so i'll just write 0 to n and for j in range the range is
going to be 0 and i plus 1 and i'm just going to print my number over here
and inside this my asterisk and is equal to this and again i have to specify a
backslash r now when i call my pattern function specific 10 okay we have a
syntax error again i'm sorry guys and this is my half pyramid pattern or we
can call it a right triangle pattern as well so this is how you can make a half
pyramid pattern in python guys so let me show you how you can make a left
pyramid pattern for that you have to just add a simple code in which you have
to specify the spaces like we have done in the other programs also so i'll just
copy the whole code paste it over here and for spaces okay i'll have to take a
variable k for spaces and inside this i'm just going to specify 2n minus 2 and
after this i have to take one more outer rows loop and inside this i'm going to
take the range as it's going to go in the direction 0 to n and for j in range now
this is where k comes into picture and i'm just going to print the spaces that i
want so i think we're done i have to decrement the value of k as well so when
i call my pattern now

just say five okay we are getting a different value here i think i made a
mistake guys let me check the code again okay i think i've got the error guys
so let me just comment this line and see if our output changes at all it doesn't
and this one as well so now we're getting the left half benefit pattern guys so i
had made a silly mistake so i was taking two loops for outer rows instead i
just have to take one so let me just make it as then so that it will be better
looking so this is how you can make a left half pyramid pattern in python
guys now let's take a look at the next program which is a downward half
pyramid

so we're going to go from this line to that line in a reverse order so that we'll
get a downward half pyramid so we'll follow the same thing we'll take a
function specify n over here and now what i'll do is i'll write for i in range
range is going to be downward direction so it's going to be minus 1 and
minus 1 again and for j in range this is going to be the same i plus 1 since we
are not getting any left pattern we're just going to print the aztecs over here
and is equal to this print backslash r now when i call my pattern function let's
see what pattern i'm getting over here i'm getting a downward half pyramid
pattern like this and if you want to make it a left downward pyramid pattern
you just have to follow this approach in which you have to specify range and
get this variable k and decrement the value and you'll get the same output as
you're getting over here now let's take a look at the next topic or the next
program which is diamond pattern

diamond pattern in python so for this i'm just going to take pattern again and
after this i'll specify the spaces 2 into n minus 2 again for i in range i'm going
to take the range as 0 to n and again i'm going to take the columns which is
going to be in the range 0 to k i'm going to print the spaces

and after this decrement the value of k now again i'll take one more group for
columns which is going to be in the range 0 and i plus 1. and i'm going to
print asterisk again for my pattern

and is equal to this and after this i'm just going to print the backslash r now
let me just call my pattern function and see what happens over here

i'm getting the pattern like this to make it a diamond shape pattern i'll have to
make a inverse pyramid on the downward direction so that it will look like a
diamond so i'll take one more for loop for that i have to specify the k value
again so for this i'm going to take n minus 2 because if i take 2 n minus 2 it
will look a little distorted i'll show you that as well so i'll take the for loop for
i in range now we're going to dive downward direction so it'll be n minus 1
and step is going to be minus 1 as well and for j in range it's going to be k 0
and step is going to be -1 now in this i'm going to print n is equal to this bring
the backslash r for j in range now it's going to be 0 and i plus 1

again i'll print my asterisk value over here

and is equal to this print the backslash r so now that we are done with the
function i'll just print this okay we are getting a very distorted image i'll take
a look at what we are doing wrong over here okay we have this one so for
this i have to specify k is equal to k plus 1 and

as you can see we are getting the diamond shape pattern over here and let me
show you if i take the value of k as 2 into n minus 1 or n minus 2 the pattern
looks somewhat like this to make it better i have to make it as 2n and minus 2
should be gone

or i'll have to make a few changes over here to make it align to the downward
pattern so what i'll do is i'll just remove two over here and it will look like a
diamond shaped pattern right now so now that we are done with this one also
i'll show you a diamond star pattern so there is a different approach to this a
diamond pattern that i'm going to show you right now

so first i'll write the code and then i'll explain how i've made this so for i in
range i'm going to specify the range as 5 and for j in range it's going to be 5
as well and what i'll do is if i plus j or or i minus j is equal to 2 or i plus j is
equal to 6 or j minus i is equal to 2 so this is my condition guys i have put it
all in the if statement i am going to print my asterisk and n is equal to this
else print and is equal to this

i think i made a mistake over here let me just take a look at the code again so
when i print this i'm going to get the value as this so this is a star diamond
star pattern so what i've done here is you have to look at the picture over here
so if you take a look at the rows and columns there's going to be 0 1 2 and 3
and you have to you know identify the pattern in which you can make a
statement like this so for all these values i'm printing this one so wherever we
have our astrix over here it's going to satisfy this statement over here only
then it's going to print this value so this is how you can make a diamond star
pattern in python guys so now that we are done with the star pattern programs
let's take a look at the number pattern program so instead of asterisk we will
have a numerical value in the patterns and we will start with a simple
numbers program

i'm just going to take one function that is pattern and again i'll just write for i
in range the range is going to be 0 to n and after this i'll have a variable but
before that i have to specify it over here so let's say x is equal to 0 and inside
this i'm going to increment this x by 1 now comes my program guys so for
columns for j in range i'm going to get the value as 0 and i plus 1 just like
before and inside this instead of asterisk i'm going to print x and is equal to
this or because we don't have spaces over here i'll just write space now i'll
have to specify a backslash r statement

and take okay we'll just call our function over here

so we're getting pattern somewhat like this i'll just make it as let's say seven
so we're getting the pattern with numbers which is one then there is two two
then there's three four five six and until seven this is a very simple pattern for
numbers let's take a look at a pascal's triangle pattern guys so i'm sure most of
you are familiar with pascal's triangle so i'll just write the code for pascal's
triangle and inside this specify n again i'll have to take for i in range 0 to n for
j in range 0 i plus 1 and inside this i'm going to print my function which is i nj
comma this and end is equal to this and after this i'll just print now i have to
take one more function guys so my function is function and inside this i have
n and k so my result is equal to 1 this is the logic for pascal's triangle guys so
i have made the function for my pattern now i'm just writing the code for
pascal's triangle logic so if k is greater than n minus k k is equal to n minus k
for i in range 0 to k

result is equal to result into n minus i and result is equal to so flow division i
plus 1
return result so now when i call my pattern function specify not 10 let's say 7
so this is my pascal's triangle guys so basically what happens in a pascal's
triangle if you take a look at this one so some of these two numbers is going
to be over here and similarly for later purposes some of these two numbers is
going to be here and these two numbers here so this is how the particles
triangle will go on and for let's say 10 it will look something like this and for
let's say 20 it will look something like this so this is how you can make a
pascal's triangle pattern in python guys it's a very simple pattern i've given
you the logic also to get the third summation over here in this position so this
is how you can make a pattern for pascal's triangle in python let's take a look
at a half pyramid pattern with numbers guys so i just showed you a half
pyramid pattern guys it's right here so i'll just copy this code again paste it
over here so we're getting

when i call my pattern function let's say 10 i'm getting a half pyramid so what
i'll do is i'll just write x is equal to let's say 0 and after this i'll just mention x
is equal to x plus 1 and instead of asterisk i'll print x into a space over here
and we're getting the values as one two two three three three four four four
like that but instead of that we can also make a diamond pattern with
numbers as well so we'll just copy the code again with this one okay i'll just
show you over here only so instead of asterisk i'm going to print x and i'll
specify x over here x is equal to 0 and over here x is equal to x plus one same
here i'll have to do x is equal to zero x is equal to x plus one okay we have
made a mistake guys

and we have to change x over here as well give it a space will not do this for
10 let's say do it for seven and this is how you get a diamond pattern with
numbers guys so you just have to change the values inside all these patterns
that i've shown you and you can play around with numbers and make
different patterns as well now let me show you one more program with
numbers so i'm going to show you how you can make a descending order
pattern so it's very easy guys i'll just make one function with same approach
and for i in range i'm going to take the range as n 0 and -1 and again for j in
range 1 and i'm going to take one i plus 1 again i'm going to print j and end it
with space print backslash r call my pattern function specify five over here
and you can look at this we're getting the descending order pattern so first of
all we have five numbers then we have four then we have 3 2 and 1. similarly
we can do this for 10 as well for any amount of numbers you can make it this
as a descending order pattern which is also a downward half pyramid pattern
as well so now that we are done with this one let's take a look at a binary
number pattern program guys out of all these numbers we are just going to
use 0 and 1. so what i'll do is i'll take one function pattern

and inside this i'll take the range as for i in range 0 to n okay i forgot to take
that variable k is equal to 2 into n minus 2 after this for j in range it's going to
be 0 to k and after this i'll print the blank spaces is equal to this k is equal to k
minus 1 for j in range 0 and i plus 1 i'm going to print 1 and 0. so instead of
asterisk i've just written 1 and 0 so it's going to print a binary number
program so basically what happens over here is we're just getting the output
as zero and one so you can use any characters instead of zero and one you
can use two and three and you can use just two or four or five or any number
that you want and we're getting the value somewhat like this so this is a
pyramid pattern with just binary number that is 0 1 and this is how you can
make number patterns in python and now that we are done with number
pattern programs let's take a look at character pattern programs instead of
numerical values we will have a character value inside the program and there
is a little more change you cannot just dimension x some variable or just like
that you have to make sure that you are changing it to a integer value the
character number so first of all let me show you the pattern for right
alphabetical triangle

so what i'll do is i'll take function name in that pattern take n over here so i'll
take the variable x as 65 now because 65 is the sky value for a so for i in
range 0 to n and i'm going to take one more variable ch and i'm going to
change this x into the character variable now x is equal to x plus 1 it's easy
for me now for j in range 0 i plus 1 i can just print ch

call pattern program okay let's just name it as 10. we have our invalid syntax
over here so this is how i'm getting my pattern so it's starting from a and
going until j because i have specified 10 over here let's say i want it as 25 so
we're going until y and if i do it like 26 we're getting the whole alphabetical
pattern with a to z in a triangle pattern so this is a very simple example guys
so i'm going to show you a character pyramid program as well so i'll take this
same approach specify a function pattern n over here and inside this i'll take
the value of 2 n minus 1 or n minus 2. for i in range 0 to n we have forgot to
take the x now over here for j in range 0 to k print the blank space

decrement the value for k and for j in range 0 and i plus 1 now comes the ch
or character variable in which i'm going to change the x into character

now i'm going to print ch n is equal to this and x plus is equal to 1 because we
have not done that after this i'll just print my backslash r again now when i
call my pattern function let's see what i'm getting so we're getting somewhat
like this okay so instead of 10 let's just take seven so we're getting a b c d e f
and this is how we're getting the values over here so i have changed a little
over here so i was incrementing the value of x on the outer rows but now i
have incremented the value in the columns as well so we're getting a b c d e f
like that otherwise we'll be getting like a b b c c c d and so on so this is a
simple change that i've done in this program so that you will be
understanding better so let's take a look at the next pattern that we have
which is a k shape character program so i'm going to print the pattern in the
shape of a k using the asterisk again so i've shown you that diamond star
pattern in which i have taken a if statement so if that statement is satisfied it's
going to print a k shape pattern which is going to look like a k shape with
aztecs in them so i'll just write the code for this so for i in range let's see 7 and
for j in range 7 again so this is where the code begins and i'm going to specify
if j is equal to 0 or i minus j is equal to 3 or i plus j is equal to 3 again i'm
going to print

asterisk or instead of asterisk i'm just going to print a over here and end is
equal to this else i'm going to print n is equal to this and now

print so we're getting the value somewhat like this so this character actually
looks like k shaped character so instead of a i'll just write s just again so that
you'll be understanding better so this looks like a k shaped character program
using python and this is how you can make a k-shaped character program in
python so let's take a look at one more pattern here which is a triangle pattern
program so i'll just specify a function again specify n over here take k is equal
to 2 into n minus

2 again x is equal to 65 for i in range 0 to n

and ch is equal to character x

x plus 0 is equal to 1 now for j in range 0 to k i am going to print blank


spaces and for j in range 0 to i plus 1 i am going to print ch and n is equal to
this print backslash r and when i call my pattern function i'm getting the value
like this so this is how i make a simple triangle pattern so let's take a look at
the last pattern that i have in the session which is a diamond shape pattern
with characters

so we'll just copy this code again and this is my diamond pattern so i'll just
copy this whole code and over here i'll just paste this when i run this i'm
getting the pattern somewhat like this so instead of numbers i want characters
so what i'll do is i already have x over here so i'll mention x as 65 and over
here i'll take ch is equal to character x and instead of x we'll write ch let's see
how the pattern unfolds so we're going to follow the same approach over here
as well so x is going to be 65 and we have ch is equal to character x and
instead of x we'll write ch now when i print my pattern so i'm going to take
this to another level so i'll just write 15. so this is my diamond shape pattern
using characters guys

let me quickly walk you through the agenda for this session we'll begin by
quickly understanding why we need file handling later we'll move on to
understanding the types of files and guys this is very interesting next i'll walk
you through all of the concepts of how files are handled using python we'll be
making use of the code first approach to ensure that we understand code at
every point of time we'll end the session by checking out how edureka is
helping learners across the globe so we can make sure you can get started as
soon as possible and make your learning fun so let's begin by quickly walking
you guys through why we require file handling well guys think about this
situation you have a server running and you need to give access to someone
who needs to access it remotely right or basically you need to work with
these files in general and say you need you need to have some import into
your program where you're actually configuring an input for it well if i had to
answer this personally how would i go about it i would be using files for a lot
of my deep learning models to import my data sets into the program at all the
time so basically by doing this i'll be making use of files a lot so coming back
to the basics again how can we input something into python the standard
input the usual keyboard input right so you can key in anything you want
well there's another case as well maybe even command line arguments to
input some parameters into the code correct but what if you had to read lots
and lots of data which is not practical to type in at every point of time or even
that it doesn't make sense at all to type it all the time the easiest way out of
this here is to actually store whatever input you want in one place and keep
using it as long as your requirement is met so what's the answer the answer is
files guys so guys this concept is actually very easy i'm sure everyone who's
joined will take away some really interesting stuff about python that you can
practically use working with files basically opens another door among
thousands and each door with python opens up to n number of opportunities
again so now that we're good with this and we started off on a really high roll
let's keep it going next we'll be taking a look at some of the types of files
available in python so we have images we have audio we have video we have
text we have script and so much more right there is a key difference here i
want you guys to note check this out windows supports all of these files that i
told and more well virtually unlimited to be honest but again i won't get
ahead of myself here because there are limitations here as well now check out
python there are two types of files binary and text so whatever is not text is
binary as simple as that so either a file gets to be a binary which contains
obviously zeros and ones or it can have some literal text well text as in strings
or anything valid for that matter text files are structured as a sequence of lines
where each line includes a sequence of characters and this is what we call as
code or syntax right and every line is terminated with a special character what
we call as the eol what is the eol guys it's the end of line character a binary
file is any type of file which is not a text file as i mentioned and because of
their nature binary files can only be processed by an application that knows
and understands this file's system structure in other words they must be
applications that can read and interpret binary right and now that we know
what are the types of files are so we can start looking into more of this guys
formally speaking i think it can be consolidated as the operations performed
on a file right so what all can we do check this out it's called as the crud
operations what is crud well create read update and delete guys these are the
operations which can be done with files well again there are many other
operations as well such as copying a file changing the properties of a file or
anything but for simplicity's sake i have planned to keep this session really
easy for all of the audience so let us dive into python now

so let us quickly see how we can go about understanding the file handling
capabilities of python check out this flow diagram to give you a quick picture
of what needs to be done first we create a file and later we open that file we
work on the file well working on it is basically reading or writing or anything
for that matter and lastly we close the file when we are done using it coming
to python now creation of a file can be done manually by the user or through
python for now let us consider that we will do it manually by going into the
location and creating a file say like a text file later in this session i'll show
you how easy it is to make python create the file for us so make sure you stay
tuned till the end

so now we concentrate on how we can open a file with python guys it is very
simple so we have an inbuilt function called as the open function which is
used for this exact purpose the open function takes in two parameters as seen
here one is the file name and other is the mode and this on your screen is the
syntax for the open function

so what do the two parameters mean one is the file name that you want to
open it can be anything at this point of time right so it has to contain the
extension of the file type as well so this is compulsory and important so make
sure you keep this in your mind and second we have the mode we know this
means something that has to do with opening the file right so check the check
the screen so basically these are various modes available to open a file we can
open it in the read mode the right mode the append mode and even the create
mode as well pretty straightforward but do note that the default mode is
always the read mode

and guys note that you can open a file in read mode only if it exists as well if
you try to read a file or something that doesn't exist then python will greet
you with a beautiful error message and in addition if you want to specify if
the file should be handled as a binary or text mode then along with the mode
as well we can actually push in two categories for it check this out so we
have t for text and b for binary t is the default value and b is for binary modes
so we can have something as wt so what does it mean so it basically says that
the fine needs to be opened in the right mode and the file that the python
opening is a text file so we're basically making the job of python to be really
easy in this case

so check out the example code i have here for you guys even if we do not
give a mode as i said the default is the read mode so these two tiny snippets i
have for you are one and the same and yet make sure something exists before
reading that guys or else you're sure to hit that error so check this out right so
i have f equal to open and the file name is demofile.txt i don't have a mod
here this is exactly equal to having the read mode in the next example and it
is as simple and straightforward as that

so now we know how we can actually create a file and open it right so let's
begin working on it let us start with creating on how we can actually do a
read operation using python

so the read operation is very easy guys so basically just like all the other
functions and handling files in python we make use of the read function for
this very purpose but then again there are so many ways to read a file too so
let me so let me break it down for you all right so we can do many things
here we can read an entire file or read a few characters or read a few lines or
any number of characters and lines together and so on check out this example
code here so we have a variable right it's we call it file and then we're
opening the file it's called textfile.txt and opening it in the read mode later we
are actually going to make use of the print function to read the contents of the
file and print the same on the python console now similar to the previous
code that i just showed you we have something slightly different here can you
notice that 5 on your screen what do you think the 5 indicates here guys

let me help you out so it basically tells the python interpreter to read the first
five characters from the file and nothing else now check the old syntax so
here we don't have the five so we are basically telling the interpreter to read
every single valid character present in our file and print it out for us so you
got a good picture of what is happening with the file now well let's quickly
take a tour into seeing this practically so i'll open up my pycharm now which
i use as the ide to work with python where i'll show you the code for all of
these guys you can basically make use of any ids that you're comfortable with
and even the console as well it is your call i am comfortable working with
pycharm so i'll go ahead with that so let me quickly open up the ide and we
can see the basic code to read the file so as you can check out i'm here in my
pycharm right now importing the os module is the first line this is currently
being unused right now but i'm going to talk about this in the future session
so basically we are opening a file right so we have a variable file we're going
to open it and we're providing the entire path to the file present so here the
file is demofile.txt this is the name of the file w is the right mode that i
already told you about let me quickly go ahead and run this that ran fine but
you cannot see anything on the output right that is because we just opened it
over wrote everything that is present in the file and we just closed it so we're
not seeing absolutely anything here check out example 2 importing the os
module file equal to open again we are providing the same file here we had
right mode and now we are having the read mode and here we are actually
printing it using the file.read again i'll be walking you through file.read in a
second but right now all you need to know is this will print the output on the
screen for us if i go ahead and actually run it nothing is going to be printed
why do you think this happened this happened because we actually use the
write mode and we actually blanked out the entire file quick fix is to actually
open the file as you can see nothing is present there so let me type in
something

so we love edureka let me save that quickly minimize it go back to my pie


chart now as soon as i run this it is supposed to give me that exact output
which says we love edureka perfect right so with absolutely three to two lines
of code you can actually print something on your screen how simple is this
guys well check out the next case so again it's the same thing opening the file
using the read mode and then you're printing file dot read of five guys file dot
read of five right so i actually explained this to you so let me just go ahead
and run it we'll check the output we got the first five character right so w e a
blank space l and o oh let us try to make it more nice to look at let me just
quickly open up the file

uh hello world this is a perfect candidate for our example oh yep the quick
typo uh save it exit back into the code now if i'm going to run this old code
right so you're gonna get the entire output here check it out hello world
perfect because we have read of blank now we're gonna actually run this
because we're telling the interpreter to read only the first five characters of
the first line for us it is just printing hello how simple is this guys

so now that we are actually done with this let's quickly jump back to the
presentation to see what's next well guys next i want you guys to check out
this syntax right so this is what i love about python amazing readability and
you can almost guess what it means and you can be certain of it say 90 of the
time so we saw how to read characters now let us look at how we can read
lines well read line will actually read each of the lines and give us a line by
line output readline of 3 will tell the python interpreter to read only the third
line and absolutely nothing else but what if you wanted to return every line in
the file which is properly separated and nice to look at well you can actually
use the same function only in a new form this is called as file.readlines
function again let's take a quick jump back into the code so we can see this in
action

so check out example4 on your screen i have the same file demo file or text
i'm opening it in the read mode and i'm using readline as soon as i go ahead
and run this i will have the same output as hello world ok let us step it up a
little let me just change this hello world we love python and we love ed
eureka so i have three lines here all good right so i'm gonna save it and close
it i'm going to come back here i'm going to run the read line again we're
reading only the first line cool check out example 5 now this is where things
get interesting import again it's it's all the same guys so basically instead of
the read line i have read lines over here so the s is extra and it's going to read
all of these lines and it's going to put it in a really beautiful way for us to see
check this out hello world as an entity we love python as an entity we love
edureka as another entity and that's nice to look at right so instead of just
getting a gibberish output of everything in the line separating it actually
makes a lot of sense so now that we're done with this another quick hop back
to our presentation so guys

next we need to check out a tiny concept on how we can actually loop over a
file object well this is another simple concept so let me teach you this we're
using the for loop for this very purpose as shown but why would we want to
do this when you want to read or return all the lines from a file in a more
memory efficient way and in a faster manner you need to use the loop over
method so the advantage of using this method is that the related code is both
really simple and easy to understand right so let me take another quick jump
into pycharm and check the single snippet out

so we are back into pycharm and check out this for loop example i have for
you so again we're sitting on the same file demo file.txt reading it in the mode
so for every line in our file object print read lines so it is going to print the
output for us containing all of the documents of our file as you can see we
love python and we love edureka that's really simple right and with this we
are actually done understanding how to open the files and read them in
multiple ways next we need to actually take a look at the right operation
which is again very simple and almost similar to the read method let's start

writing to a file is as simple as using the write function guys similar to the
read again so to write to an existing file we make use of two modes one is the
append and the other is write which we already checked out earlier by append
we actually add the contents of the write to a new existing content and with
write we just add it to the blank file now i am sure there is a question in your
mind right now so what if the file that i am trying to work on is not blank
what if it contains some previous data and we make use of w instead of
append guys this will basically delete everything in the file and overwrite it
with what we've just put and this is exactly the first example case that i
actually showed you make sure that you use the mode very wisely in every
situation right so here's a quick example before we dive right back into code
as you can see we open a file in the right mode and we write two lines into it
and we close it it is as simple as that right now again taking you back to
pycharm and let me walk you through the code so guys we're back into
pycharm right now so check out the first example i have for you import os i
already explained opening it in the mode of write so since we already have
some content all of that content will be overridden with hello world and hello
world again so we're opening it we're using file.right to write two content into
it and then we're gonna close it let me run this again no output because we are
not printing it to our console how do we check if everything is working open
the demo file hello world and hello world again right so this is exactly what
we wanted but then again this looks a bit gibberish as i told you right so we
use read lines to actually make it look nice for us

heading back to pycharm again check out the next example i have for you so
now this is to prove that we are actually overwriting it again which i've
already told you and it is simple but still let me walk you through this so
we're working on the same file we're using the w mode and then we're writing
it to it saying oops we have over return it run it it run no output but in the
sense the file is changed so it says oops over it and instead of hello world and
that old message that we printed let me get back to the pycharm again and
this is for creation and we'll be coming back to this in just a second so let's
quickly go back to our presentation and then we're going to be coming back
to pycharm again

so we're down to the last two concepts that we will check out in this session
the first one among that is for us to create a new file using python well guys
even for the creation of the file we need to make use of the open method we
already know that a is used for append and w is used for write and now we
have x which is used to create a file but do note that you cannot create two
files of the same name guys so basically it means that you cannot create a file
which already exists check out the example on your screen and you will
definitely get a bit better picture of it right there so you cannot have two files
with the same name testfile.txt this is not right so again python will give you
a beautiful error message and it won't be so beautiful at the end of it let me
dive back to python and we can check out the example over here uh let me
change this we have something else right so let me type edureka.txt i'm going
to print new file into edureka opening it we are opening it in the x mode so
we are actually creating this file physically write more to write something
into it and close it so let's run it no output check out the file where is the file
called eduraka it is your new file of edureka so it's perfect right

let me quickly head back to the presentation and we can check out what's
next and then the next simple concept i have for you guys is showing you on
how deletion operation works with respect to files using python guys deleting
a file is very simple and straightforward we'll require the os dot remove
function just for this purpose so yes importing the os module is a compulsion
here i have been using it all along because it is just a good programming habit
to use the os module when you're playing around with the file system the
biggest mistake i have seen people do is that they usually go on to delete a
file which doesn't exist again python pushes in an error message and that is
not good at the end of the day right so it is very vital to know for sure that the
file exists to do this we just check if the path exists and if it does cool remove
the file else print that the file doesn't exist so you cannot remove it what does
this say guys this is a very simple case of an exception handled by the user
and this is a really good programming habit too so all good but can we delete
a folder yes we definitely can a folder with all the content inside it can be
deleted using the rmdir command what does rmdir stand for it basically
stands for removing directory and the parameter here is basically the path and
by the path it includes the name of the folder which needs to be removed and
this is all of the operations you can do with python by making use of files let
me quickly conclude the session for you guys so we started by checking out
the different types of files and why we need to use files right so we also saw
the different types of files again and how we can work with each of these
types of files and all of the operations involved with this as well

let's take a look at the agenda for this session so first of all i will start with the
prerequisites that are python functions and then i will talk about python
decorators with a few examples and finally i will discuss a rather complex
concept that is fancy decorators with a few examples as well i hope you guys
are clear with the agenda also don't forget to subscribe to edureka for more
exciting tutorials and press the bell icon to get the latest updates from edureka
so without wasting any more time let's start our session i'm sure most of you
are familiar with functions in python so let's recall some of the important
concepts that are going to be useful while working with the decorators so the
concepts that i want to discuss are first class objects and inner functions so in
python literally everything is treated as an object including all the data types
and even functions so the functions can be passed around as arguments as
well so that is why it is called a first class object coming on to the inner
functions a function can be also declared in another function which is known
as an inner function it also resonates around the decorator so we'll get to that
later on in the session so let's take it up to pycharm and understand how inner
functions work and we will also try to return a function from a function
which is actually passing a function as an argument so let's take it up to
pycharm guys so now that we're in the pycharm let me go to the presentation
mode so that the clarity will be better so first of all let me talk about the first
class object so i'll just take a function name it as let's say function1 and inside
this i'm going to pass a variable name so now i just want to return let's say
hello so for this i'm going to use the string interpolation if you're not sure
about that please do check out the tutorial on strings on edureka so that you
will be familiar with what i'm doing here that is the string interpolation you'll
see what it does now let me define one more function let's say define function
number two and inside this i'm going to pass the same argument that is name
and now i'm going to return using the string interpolation again so after this i
actually want to ask how you doing

i have to give two lines over here this should do and now i want to take one
more function guys so i'll name it as function number three and inside this i'm
going to pass function as an argument so here i just want to return function
number four and inside this let's say i want to write deal honor

now when i print this i'm going to print function number three and inside this
i'm going to pass function that is function number one now again i'm going to
pass function number let's say three and inside this i'm going to pass the
function number two again let's see what the output is okay we have an error
guys function 2 is missing one required positional argument name so we have
made a mistake over here so when i print this now i'm getting the output as
hello dl honor and dlr now how you doing so i'm actually able to pass the
functions as arguments so that is actually how we use the first class object we
can use anything as an object in python now moving on to the next example
that i'm going to show you is for inner functions so how exactly do you use
inner functions so i'm going to take one function let's say func and inside this
i'm going to define one more function so first of all let me give it a statement
i'll say first function

and after this i am going to define one more function and this is going to be
function number two or i'll just write it as function number one and after this
i'm going to give one more statement over here let's say first child function

now i'm going to go define one more function let's say function number two
and inside this i am going to print let's say second child function

and let me take one more statement so function2 and function 1. now when i
print our function over here let's see what the output is so first of all we are
getting first function that is the base function and then we are getting the
child function and the first child function so this is how you can use inner
functions in python basically it's a nested function we are using multiple
functions inside a function so we have one function over here and inside this
we have two more child functions so this is a basic example of inner
functions and python decorators is going to revolve around this concept a lot
the first class objects and inner functions that is why i was telling you about
this i'm going to show you one more example so i'm going to return a
function from a function so basically what it means is i am taking a function
as an argument for another function so what i'll do is i'll just write function
and define one function over here i'll just write n and now i'm going to define
one more function let's say function number one so i'm going to return let's
say edureka yes and now i'm going to take one more function let's say
function number two and inside this function i am going to return let's say
python and now let me take a statement guys so if n is equal to let's say one
so i'm going to return function number one i'll not use this i'll tell you about
this later else i am going to return function2 so this is my function guys inside
this i have two more functions i'll show you what it does so i have a is equal
to function and inside this i'll write one and now again inside this i'll write
let's say two so now when i print a and let's say i want to print b as well you'll
see what the output is okay we have uh name b is not defined so actually i
had to take b over here

so the output is edireca and python so i'm successfully able to return a


function from a function guys so i've taken these two functions as arguments
and this is how we can return a function from a function so now that we are
through with the python prerequisites we'll talk about decorators in python a
decorator is a design pattern in python that allows a user to add new
functionality to an existing object without modifying its structure so
decorators are usually called before the definition of a function you want to
decorate let's take a simple example to understand how it works so we'll go to
pycharm again i'll clear this off and okay let me just put it right here now i'm
going to take a simple decorator example so i'll just define a function yes and
inside this let's say i want to pass a function as an argument i'll name it as
function1 now again i'm going to define a wrapper function this is my inner
function guys and this is basically the decorator that i'm going to use here

i'm going to pass function again so you'll see what it does and i'm going to
print one more statement of this so let's just say welcome to python edureka

tutorial now i'm going to return wrapper over here

and i'm going to define one more function and inside this function number
two i am going to use a print statement let's say pythonista and let's just call a
function now function number let's say 2 is equal to function 1 function 2. so
this is a very important statement guys now i'm just going to call the function
number 2. let's see what the output is

so my output is hello pythonista welcome to python editorica tutorial so as


you can see inside the wrapper function over here first of all we are getting
hello after the function which we have right here this one function number
two which we have passed in function number one so this is my wrap
statement guys there is another approach to this using a pi syntax or we can
call it a syntactic sugar as well so it basically makes it easier to use decorators
in python guys what i'm going to do is i'm going to make a few changes in
this code and you will understand what i have done so after this statement
that is returned wrapper okay let me clear all this i can just write at again now
i'm going to define my wrapper function inside which i will have arguments
so earlier i didn't have arguments over here but now i'm going to have
arguments inside this decorator so i'm going to print hello again like i did in
the last program and i'm going to call the function again so inside this i'm
going to use arguments as well

and after this i am going to print the same statement that was welcome to edit
python tutorial

and i will return wrapper after this i will use the syntactic sugar function
number one i'll write and after this i'll define my function number two

and over here i'll write the print statement let's say all right we can use our
argument over here as well and we'll use the string interpolation again yeah
when i print function number 2 i'm going to specify a name as well let's say
the scene now my output is okay we have a error which is function1 is not
defined so basically this we have made a mistake over here now it should
work fine

so we have hello vasim welcome to edureka python tutorial so this is a very


simple example guys so we have actually used arguments in our decorator
let's take a look at the next function that we have so i'm going to use a
function in which i'm going to return values from a decorated function

so i'll just define a function function number one and inside this i'll pass
function again and now i'll define a wrapper function with the few arguments
let's say and after this it's going to work the same way like we did so i'm
going to write print let's say it worked so it will show us that it worked i'll
return wrapper

and after this i will have that same syntactic sugar function one and i'll define
my function number two here

pass name over here and i'll write print string integration get name and now
when i print let's say function number two with name let's say python so what
is the output that we are getting it's showing it work so now that we are
through with the decorative examples let's talk about fancy decorators in
python they're nothing but the complex features of decorators in python and
to explain this i'm going to take a few examples like class decorator and let's
talk about them one by one so we're making a reference here so that we can
use it for various purposes in the future as well so we're not using the
parentheses over here because we're making a reference to this function so i'll
clear this up and we'll talk about the class decorators now so there are two
ways to decorate a class in python the first one is where you can decorate the
methods inside a class and there are built-in decorators like class method
static method and property in python so class method and static method
define methods inside a class that is not connected to any other instance of a
class and property is normally used to customize the getters and setters of a
class attribute so let's take an example to understand this so i'll take a class i'll
make it a more relatable so i'll not use functions instead i'll use let's say
square and for my class over here i'm going to define few functions so first of
all i'm going to define an inner function and inside of self i'm using one more
variable that is side now self dot side is equal to side and i'm going to add a
property over here so this is going to be my decorator guys so this is going to
be my decorator it's a built-in operator guys i'll show you what it does so i'm
going to define one more function named as let's say side and inside this i'm
going to pass self and now again i'm going to return self side and i'm going to
use one more so this is my setup function guys and now inside this i'm going
to use the side function and after this i'm going to use the value so if value is
greater than equal to 0 i am going to get the side is equal to value else i'm
going to print that there is one arrow over here and now again i'm going to
use property and over here i'm going to define area self again and inside this
i'm going to return the area so i'm going to use self dot side and i'm sure
everyone must be familiar with what is the area of square that is side square
so i'm using a double exponentiation operator over there which is used to
calculate the square so if i make it as 3 it's going to be a cube but we don't
need that so i'm just going to leave it at 2. now i'm going to define a class
method and it is going to have one more function let's say unit square and
inside this let's have one more variable cls and now i'm going to return one
we are done with the so we are done with the class which has all these
functions and built-in class decorators like property class method and setter
and get all those so i'm going to have square over here i'm going to specify
the side as five now let's say what my side is yes and i'm going to print the
area as well so when i do this my output is 5 and 25 now sometimes it's
useful to have a decorator that can keep a track of state so let's take a few
more examples to explain decorators in python in detail so i'm going to make
a singleton class using class decorators so first of all i'll import font tools and
after this i'm going to define a singleton class so name is as singleton

now after that i am going to use the function tools dot wraps inside this cls
now comes the wrapper function and inside this i'm going to have a few
arguments as well

and after this i'm going to get the instance is equal to cls args and chaos i'm
going to return wrapper again making a reference to the function and not
calling it but i'm going to use this to make an

rapper dot instance okay we're making a small arrow here

now i'll just write wrap dot instance is equal to none and now i'm going to
return wrapper again after this i have a single ton and after this i'll have class
one i'm going to pass and let's say first is equal to one and let's say second is
equal to one as well

and i'm going to print first a second so let's see if we get true or false i'm
getting a error guys

all right i have made a mistake over here i had to add a if statement

that's why we're getting this error guys and after this it should work fine now
so it is actually true and we know that our singleton class only has one
instance and there are plenty of singletons in python including true none etc
so now that we are done with making a singleton class i want to talk about
nesting decorators so in a function you can actually use nested decorators as
well so i'll show you the syntax for that so basically what you can do is you'll
just write function1 and you can write function2 but you have to define all
those before that you use after that you can just define a function name and
print whatever you want you can use multiple decorators by stacking them on
top of each other and now let's take an example in which i am going to take
arguments in a decorator so for that i am going to import function tools and
after this i will define a function let's say repeat and inside this i'll write
number now again i'll write one more function let's say decorator

repeat and after this i will pass a function inside this and now i will make one
decorator let's say fung tools not wraps inside this i will pass function and i'll
define one more wrap function over here and inside this i will pass a few
arguments

now for ein range number value is equal to

i'm going to return value after this and return wrapper making not using the
parentheses again and after this i'm going to return deco rate or repeat and
again not using the parenthesis now we make our decorator let's say repeat
inside this i'll specify the number itself let's say 5 after this i'll define a
function and inside this i'll pass name using the string interpolation we will
have a name again so let's just say i want to print my name again or i can use
python as well so i'll just write python over here now when i run this there
should not be any errors so i'm getting it as python as four times so instead i
can use four over here i get it four times so this is my repeat function so i'm
using it as an argument two times also we can use it for 20 times as well so it
is always useful to pass an argument in a decorator

everything in the world of programming requires a name but still there are a
few anonymous mysteries lambda functions or lambda expressions are one of
these kind of entities that are in fact nameless so before we begin just make
sure guys that you subscribe to our channel and hit the bell icon to stay
updated with all the latest edureka videos coming back towards the session
we shall first begin with understanding what our lambda functions or lambda
expressions and why they're used following that i'll be showing you how to
write these lambda functions along with some user defined functions as well
as some predefined functions such as filter map and reduce finally we'll be
using these lambda functions to solve some algebraic expressions okay so
without any further dues let's move on towards the first topic of the session
which is understanding what exactly are lambda functions python lambda
functions are functions that do not have any name they are also known as
anonymous or nameless functions the word lambda is a keyword that
specifies what followers is anonymous now that you are aware of what these
lambda functions are let's move on further to see why they are actually used
the main purpose of anonymous functions comes into picture when you need
some function just once they are created wherever they are needed due to this
reason python lambda functions are known as throw away functions they are
also used within higher order functions which take a function as an input or
return it as an output another very good advantage of using these lambda
functions is reducing the size of code and i'm going to be showing you all in
this session how to do this so now let's move on towards our next topic which
is to see how to write anonymous functions lambda functions are created
using the lambda operator and its syntax is as follows the first thing that you
need to specify is the lambda keyword and following that you'll have to
specify the arguments or the inputs and finally after the colon symbol you'll
have to specify the expression that needs to be solved lambda expressions can
take any number of arguments so as you can see over here my first example
is a lambda expression without any arguments in the second example i've
taken a lambda expression which just has one argument a1 finally i'm
demonstrating a lambda expression which has inputs from a1 to a n just
remember that all your arguments or inputs need to be separated by a comma
so now let's move on towards our jupyter notebook and see how we can
actually write these lambda functions i'll just create a new notebook over here
guys

i'll just open a new notebook over here guys and i'll rename it as lambda
functions so guys now just let me write the syntax as a comment over here
this is going to be good for a referral purpose so first is the lambda keyword
like i already told y'all sorry guys for the spelling mistake lambda and the
arguments

followed by the expression okay so the first thing i'll have to write down is
the lambda keyword following that i'll have to specify the arguments so let
me just give one argument to this and after that i'll just say i want to multiply
this a with itself so this is my lambda function but before executing this i'll
require some variable that can hold the value of this so i'll just specify that x
is equal to this lambda function and after this i'll say x of 3 and i'll hit run so
as you can see over here when i used x of 3 it's returned the output to be 9. so
guys if i had to solve the same expression using a normal function then i
would have had to write a larger piece of code than this let me just
demonstrate this to you guys over here so i'll just define a function say new
and i'll pass the parameter as a now i'll be using return to return the value of a
star a to call this function i'll have to use the name of the function and specify
some value to the argument that i've already passed so in place of a i'll pass
the value as 4 or let me take it as 3 itself like the previous function and i'll hit
run as you can see over here using lambda functions i just required two lines
of code whereas while using the normal function i had to make use of three
lines of code along with this return statement over here okay so guys i hope
you all have understood how to write these lambda functions so guys as you
all have just seen i've used lambda expressions in the example along with
some other variable x now i did this because these functions are nameless and
require some name to be called but doesn't it seem confusing as to why assign
a name to a nameless function and what is the need of it it's a legitimate
question guys but the point is this is not the right way of using anonymous
functions anonymous functions like i've already told you all are best used
within higher order functions these functions either take a function as an
input or return it as an output to demonstrate this let me just move on towards
our next topic of this session the first thing that we are going to study is
anonymous functions within user-defined functions so as you all can see on
the screen i have a user-defined function that takes the lambda function as an
input in this example over here the normal python function which in my case
is new func takes one argument x this argument is then added to some
unknown argument which is supplied through the lambda function let me just
jump on to my jupiter notebook to explain this in detail let me just first create
a heading over here guys just remember the number of prefixed hashes tells
which heading it is so if it is h1 it will have one hash prefixed to it if it has
two then it's h2 and so on so i'll just create a heading over here of h1 level
and i'll give the name as user defined functions or lambda within user defined
functions lambda within user defined

so i hope you guys know what are user defined functions okay so as you all
know when you have to create a function in python you'll have to use the def
keyword followed by the name of the function i'll just name the function as a
and i'll pass one parameter to it say x after that i'll be using the return
statement and within this i'll specify a lambda function i'll pass y as the
argument to this lambda function and i'll use x plus y as my expression now
let me just give some value to the variable x and store it in another variable t
so a of 4 and i'll i'll print the value of t of 9 or sorry 8 and i'll hit run so as you
all can see on the screen the lambda function that is used within the function
a is called whenever i call this higher order function and the first thing that
i'm doing over here is passing a value to the variable x and then i'm printing
the value of x plus y so i hope everyone's understood this part okay now let
me just copy this function and pass a few other values to this as well

i'll just store a new value in the variable u and i'll pass the value for x as say
seven and i'll print two of five and i hit run okay so i hope everyone's clear
with this if you have any doubts please do let me know in the chat box and
my team is here to help you

now let's move on towards the next topic which is using lambda functions
within filter map and reduce functions the filter method is used to filter the
given iterables which can either be lists sets etc now this is done with the help
of another function which is passed as an argument to test all the elements to
be either true or false after applying the function to the set of iterables if the
value is true then that value is returned in the output now let me just jump on
to my jupiter notebook and use the lambda function within the filter method
i'll just give a new heading over here again

just for your reference guys i'll create a heading of h2 level by prefixing it by
two hash characters so i'll just use lambda within

filter and since it's a method like i already told you all the filter function
needs iterables now here i'll just create a list i'll say my list and i'll specify
some elements to this

the filter method is going to check for all the elements to either be true or
false in accordance to the expression that is passed within the lambda
function like i already told you all the filter method is going to check if the
expression that is specified within the lambda function is either true or false
for all the elements that are present within my list and it returns all the
elements that satisfies the expression so as a result i'll have a new list so i'll
just name it as a new list and i'll use the filter function and within this i'll be
using the lambda function like i already told you all let me just specify the
input as a and we'll give an expression over here say a i just want to check if
any of these values when divided by 3 will equate to 2 and i'll pass my list
and i'll pass my list as an argument to this

and since the output is going to be a list i'll just use the list method over here
and one more point i want you guys to note is the syntax of the filter function
and since i forgot to specify this before beginning the demonstration let me
just specify the syntax of this function over here i'll say syntax

you'll have to use the filter keyword along with some function followed by
the iterables okay so as you can see over here i have the filter keyword i have
the function which is lambda and then i've passed my list as the iterables to
this function

now let me just print the new list

and i'll hit run oh sorry guys i've made a spelling mistake over here so it's f-i-
l-t-e-r

so as you can see over here i've passed the elements one two three four five
and six to this filter method and after checking if this expression is true for all
the iterables it has returned 6 as the output now let me just cross check over
here so if i divide 1 by 3 i will not get a result which is equal to 2. similarly if
i divide 2 by 3 i'm not going to get the result as 2 again finally as we all know
if i divide all these elements by 3 only for 6 i'll get the output as 2. so i hope
everyone's clear with how to use the lambda function within the filter
function

so now let's get back to our presentation and see how we can use the lambda
function within the map function guys the map function in python is a
function that applies a given function to all the iterables and returns a new list
so i hope you are understanding what exactly it does it takes a function as the
input and some iterables as well and then it applies this function to the set of
iterables that are passed and it returns a new list so now let's get back to
jupiter and do the same i'll create a new heading of course

and it's going to be lambda within map and i hit run so before moving on
towards the demonstration i'll just write the syntax for the map function so it
has to have the map keyword of course and the parameters that are passed to
it is a function and the iterables now let me just make use of the same list
which i was using previously and i'll copy that over here and then i'll just
store the output in a new list p and i'll use the list function since i want the
output to be a list within this i'll use the map function and to that map
function i'll pass a lambda function as the input i'll just pass one argument to
this as a and the condition i'm going to specify is to check if any element
present within my list divided by 3 is not equal to 2 and i'll pass my list as the
set of iterables and then finally i'll be printing this now let me hit run so as
you all can see over here it has returned a list with some boolean values the
expression that i wanted to check is a by 3 not equal to 2. now let me just
move on to my list and see what happens when i divide 1 by 3 of course i'm
not going to get 2 so i have true as the output now when i divide 2 by 3 again
i'm not going to have the output as 2 and therefore i have true as the boolean
value for this similarly all the elements present in my list are divided by 3 and
it's going to check if the condition is true therefore only for six it's going to be
false and i have the output as false okay so i hope you guys have understood
how to use the lambda function within the map function if you have any
doubts please do let me know the chat box guys and my team will revert to
you

okay now let me just jump on towards our next topic which is using lambda
function within the reduce function so guys the reduce function is used to
apply some other function that is passed as a parameter to it to a list of
iterables and finally it returns a single value and to demonstrate this i'll just
jump onto my jupiter notebook again and i'll create a heading

this is going to be lambda within reduce and i hit run so first let me just write
the syntax of this function it is the reduced keyword

and it takes a function as a parameter the first parameter is a function and


second is a sequence now to make use of the radios function you'll have to
import the func tools library or from that library you'll have to import the
reduce function to do this i'll be using from func tools

import reduce you can also directly import the func tools library as import

func tools or you can also use from func tools import star these are just the
alternate ways that you can also use over here

okay so now i'll be using the reduce function and within this i'll specify a
lambda function

and i'll pass two parameters say a and b and let me just print the sum of a and
b and finally it has to have a sequence as its input so i'll just specify a list
over here i'll say the list of values to be 23 56 43 98 and 1. okay so now let
me hit run and see what it returns so as you can see over here guys i have 221
as my output so what this reduce function is actually doing is it first adds 23
to 56 so guys the first thing that the reduce function does is add 23 and 56

and the output of this is going to be 79

now after adding these two values to this output it will add 43 so to 79 it's
going to add 43 and it will produce a new output

after finding the output of 79 and 48 it's going to add the result to 98 and
finally it's going to add that result with 1 and returns the final output which is
221 so i hope you guys have understood how this function is recursively
adding each value to the next value that's present in the sequence guys if you
have any doubts please do let me know in the chat box

okay now let's move on to see how you can actually use these lambda
expressions or lambda functions to solve some algebraic expressions for this
i'll just go back to my jupiter notebook and i'll create a heading over here

oh sorry guys i'll just delete these two kernels

and i'll create a heading


i'll just say lambda for algebra

so guys first we'll be taking some linear equations so i'll just create a heading
as linear equations

so as we all know algebraic linear equations consists of variables of degree 1


which means they'll have the power as 1. so now let's just use the lambda
function to solve some linear equations i'll just say s is equal to lambda

and i'll pass the argument or the input as a and the expression i'll specify as a
star a and i'll use s of 4 and i hit run so as you all can see over here 4 cross 4
is 16. now let me take a different linear equation so let me just write the
linear equation over here as a comment so i just want say 3x plus 4y okay so
if i want 3x plus 4y so i'll have to specify some name to this say d is equal to
lambda and x and y as the inputs and since i want 3 star x plus 4 star y okay i
have 3 into x plus 4 into y okay and then i'll pass the values as 4 comma 7
and i'll hit run as you all can see 40 has been returned as the output when i
pass the value of x as 4 and the value of y as 7 now let me take some
quadratic equation

so i hope you all know what is a quadratic equation it's an algebraic equation
with the degree two let me just give the heading as quadratic equation

okay so now let me just try to solve the very famous a plus b the whole
square

a plus b the whole square so i'll just say part two okay

now let me write a lambda function that's going to return the value of a plus b
the whole square i'll just save it within a new variable x and i'll use the
lambda function and the arguments or the inputs are a and b

the expression that i'm going to use is a plus b and like we all know we'll
have to use double star when we use powers and then i'll print this x i'll pass
the values of a and b as three comma four and i hit run okay so as you all can
see i found the value of a plus b the whole square using the lambda
expressions

we love shortcuts in everything and with python's built-in functions it just


gets more exciting and in this session you will be learning about three very
important built-in functions namely map filter and reduce so before we begin
just make sure you subscribe to our channel and hit the bell icon to stay
updated with all the latest edureka videos coming back towards this session
we shall first begin with a small introduction to map filter and reduce
functions after which we shall take a deep look at each of these and see how
you can actually use these functions along with user-defined as well as
lambda functions finally we shall try to put these functions within each other
and see how it works so i hope everyone's ready to start with this so let's
move on towards the first topic of this session which will be a small
introduction to map filter and reduce functions okay so let's move on the map
filter and reduce functions are inbuilt functions of python these functions
enable the functional programming aspect of python in functional
programming the arguments passed are the only factors that decide upon the
output these functions can take any other function as a parameter and can be
supplied to other functions as parameter as well the map function takes
another function as a parameter along with the sequence of iterables and
returns an output after applying the function to each of the iterable that's
present in the sequence the filter function as the name says is used to create
an output list consisting of values for which the function returns true the
reduced function on the other hand applies a given function to the iterables
and returns a single value okay so now let's move on and take a deeper look
at each of these functions and how you can actually write them in python like
i've already mentioned before the map function will take a function and a
sequence as a parameter and it applies that function to the iterables that are
supplied to it as you all can see on the screen i have a map function to which
i've supplied a lambda function as a parameter and a list of iterables all i want
to do over here is add three to each of the iterables that are present in this list
as you all can see i'll have an output list with three added to each iterable
that's present in the original list so now let's move on towards the jupiter
notebook and see how this works okay so i'll just create a heading over here
okay so before i begin writing this function let me just write the syntax first
i'll just write it as a comment so basically the map function takes a function
and a set of iterables as a parameter now these iterables can be either a set
tuple or anything here the function defines an expression that is in turn
applied to the iterables the map function can take user-defined as well as
lambda functions as a parameter let us first take a user-defined function as a
parameter to the map function so i'll just create a function over here so i'll use
the keyword def okay so i'll just name my function as new and i'll pass a
parameter as a to this and i just want to return a star a now i'll take a variable
as x and then i'll use the bump function i'll take a variable x which will be my
map object and then i'll write the map function to which i'll pass the new
function as a parameter and a list of iterables

all i'm going to do after this is print x just to show you all that this is a map
object and then i'll print the list of x so as you all can see on the screen x is
basically the map object and the list of x consists of all values multiplied to
itself so i hope everyone's clear with this instead of using the list function you
can also use other functions such as tuple sets etc let me show you what
happens when i use tuple as a function over here so as you can see previously
i had an output list and now i have an output tuple similarly for the input
iterables you can supply anything such as lists tuples sets etc okay now let's
try to take a lambda function along with the map function map function can
take more than one list of parameters as well let's see what happens when we
try to do that so i'll just copy this over here and i'll paste it and i'll pass
another list as a parameter and i'll make a small change to the function over
here so i'll pass two parameters so i'll say a comma b and i'll say a star b now
i'll hit run okay so as you all can see on the screen these values present in the
iterables have been multiplied and i have a resultant tuple so i hope
everyone's clear till here if you have any doubts please do let me know in the
chat box and my team is here to help you so now let's see how to use lambda
functions along with the map function lambda functions as we all know are
functions that do not have any name they are also known as anonymous or
nameless functions these functions are generally provided as an input to other
functions so now let's move on and see how to use lambda functions along
with the map function okay so i'll just take a list over here say lst and then i'll
pass some random values to it i'll take a new variable say y and then i just
want to print the list off and then i'll use the map function along with the
lambda function lambda functions are single line functions so we have to
provide the expression along with the function itself so i'll just say x plus 3
and then i'll pass the parameter as lsd which is my list and then i'll just print
this

okay so as you all can see on the screen 3 has been added to all the elements
that are present within this list over here now let's get back to our
presentation and see how the filter function works like i've already mentioned
before the filter function is used to create an output list consisting of values
for which the function returns true so as you all can see on the screen i have a
small example with a condition where i want to print the values which are
greater than or equal to 3 where i want to print the values which are greater
than or equal to 3 within this list present over here so now let's jump on to our
jupiter notebook and see how the filter function works i'll just create a new
heading over here

the syntax of this function is similar to the map function so basically it takes a
function and a set of iterables as a parameter okay just like the map function
filter function can be used along with user defined as well as lambda
functions so first let us take a user-defined function as a parameter to this so
i'll just define a function over here so i'll say new one and i'll pass a parameter
say i now if i is greater than or equal to three i want to print the value now i'll
take another variable j which is going to be my filter object and then i'll use
the filter function and i'll pass nu1 as the parameter and i'll supply a tuple of
random iterables to this and then i'll just print out what is j okay so as you all
can see over here i just printed j to which the output says that this is a filter
object now if i want to return the values that are present within j i just have to
use print tuple of j okay as you all can see all the values that return true for
this condition has been returned as the output of this function so now let's try
to use the filter function along with lambda functions i'll take a new variable
say z and then i'll use the filter function to which i'll supply a lambda function
as a parameter so i'll say lambda x where x is greater than or equal to 3 sorry i
have to put this within brackets and then i'll pass the same tuple as a
parameter i'll just copy this
this time i'll print out the list of c okay as you all can see the output has been
returned just make a note over here guys that last time i wanted my output to
be a tuple and this time i just said print list of c so i have a list as the output of
here okay so i hope everyone's clear to this now let's get back to our
presentation and take a look at the reduce function the reduce function as the
name describes applies a given function to the iterables and returns a single
value so here i have a small example wherein i want to add all the values of
these iterables and return one single final value so in the first iteration i'll
have 1 as x and 2 as y and then i'm going to add x plus y which is 1 plus 2
and it gives me 3. after the first step this output 3 becomes x and this input 3
over here becomes y and then i get an output as 6. this process will go on till
all the values present in the iterables have been reduced to a single value now
let's jump on to our jupiter notebook and see how this works so i'll just create
a heading

just like before i'll write the syntax first so reduce it takes the function as a
parameter and a set of iterables

now one thing you'll have to note over here is to import the reduce function
from the func tools module so all i'm going to do is say from func tools
import reduce sorry i've just made a spelling mistake over here just like filter
and map you can use reduce functions also with user defined as well as
lambda functions so first we'll take a user defined function say a to which i'll
pass the parameters as x and y within this i'll just say return x plus y now i'll
just take a new variable say s and i'll use the reduce function to which i'll pass
a as the parameter and i'll pass a list of values

and then i'll just print s

sorry guys i've added an extra comma over here and now i'll hit run as you all
can see all the values have been added to each other and i have the output as
49. now let's try to use the reduced function with lambda functions i'll use the
radius function directly over here and then i'll use the lambda function within
this i'll pass parameters and x and y or this time i'll change the names i'll say
q and p and then i'll just use q star p and i'll pass a list of values to this
and then i'll hit run okay so as you all can see all the values that are present in
this list have been multiplied to each other and i have the corresponding
output okay i hope everyone's clear till here if you have any doubts please do
let me know in the chat box and my team is here to help you now let's get
back to our presentation and see how you can use these functions along with
each other so first we'll be using the filter function within the map function
when i use the filter function along with a map function it filters out the
values that satisfy the condition which is present within the filter function and
it supplies that output list as a parameter to the map function so as you all can
see on the screen i have a filter function which says i want to filter out the
values that are greater than or equal to 3 from the tuple of values that are
supplied as a parameter to this i'll have 3 and 4 as the output of this function
which will be supplied as the input to the map function okay so now let's
move on to our jupiter notebook and see how this actually works

so i'll just take a variable say c and then i'll use the map function to which i'll
supply a lambda function first as a parameter so i'll say lambda x i'll just say
x plus x you can specify any expression of your choice and then i'll use the
filter function to which i'll supply another lambda function as a parameter

and as a condition i'll just say x greater than or equal to 4. i'll pass a list of
values to this say 2 3 4 5 and then i'll just print the tuple of c

so as you all can see the first thing that happened was filtering out the values
that are greater than or equal to 4 present within this list after that 4 and 5
which is the output of the filter function will be supplied as an input to the
map function and then using the map function i'll add 4 plus 4 and 5 plus 5
which is 8 and 10 respectively okay now we've used the filter function within
the map function so now let's move on and see how you can actually use the
map function within the filter function so when we use the map function
within the filter function the set of iterables that are supplied as an input will
be operated upon first by the map function and the output of this map
function will be supplied as the input list to this filter function so now let's get
back to our jupyter notebook and see how this works so i'll just take a new
variable say d and then i'll use the filter function i'll use the same condition
again so i'll just copy this
and then i'll use the map function within the filter function and i'll use lambda
within this map function

so i'll just say x plus x and i'll pass a list of values

then i'll just print the tuple of d or this time i'll just say set of d so as you all
can see on the screen i have an output set which is a resultant of applying
map function to the given set of iterables and then applying this condition
within the filter function to the output of the map function so now let's move
on towards the final topic of this session wherein we'll be using map and
filter within the reduce function okay so as you all can see on the screen i
have a small example wherein i have a reduce function to which i've supplied
map and filter as the input functions now the innermost function is the filter
function which says i want all the values that are greater than or equal to 3
from the list of iterables that are supplied to it so as an output of the filter
function i'll have 3 and 4. to this output list of the filter function the map
function produces a new list of iterables which is 6 and 8 which are obtained
after adding each of these values to itself and finally 6 and 8 will be supplied
to the reduce function as a parameter so now let's get back to our jupyter
notebook and do the same

so i'll just say map and filter within reduce

okay so i'll just take a new variable say r and then i'll use the reduced function
to which i'm going to supply a lambda function as a parameter so i'll just say
lambda x comma y and then i'll just say x plus y

now i'll take the map function to which i'll supply another lambda function as
a parameter and then i'll just say x plus x after this i'll be using the filter
function and again i'll use a lambda function within this filter function i'll say
x i want to return all the values that are less than or equal to 4. to this i'll pass
a list of iterables say one two three four five six seven and then i'll just print
out r oh sorry guys i've made a small mistake over here okay so now let me
hit run
okay as you all can see on the screen first my filter function will filter out all
the values that are less than or equal to 4. the output of this is supplied to the
map function and all the values are added to each other finally the output list
of the map function will be supplied as an input to the reduce function and all
the integers will be added to each other and i'll have one output which is 20.

generating iterables is considered to be a painful task but with generators in


python this task becomes very simple before we begin just make sure you
subscribe to our channel and hit the bell icon to stay updated with all the
latest edureka videos coming back towards the session we shall first begin
with understanding what are generators and their advantages then we shall be
differentiating between normal functions and the generator functions
following which i'll be showing you all how to create generators in python
then we shall take a look at generator expressions and finally a few use cases
which will be generating the fibonacci series generating a stream of numbers
and generating the sine wave using c bond along with generators in python so
let's move on towards the first topic which is what are generators generators
are basically functions that return traversable objects or items these functions
do not produce all the items at once rather they produce one at a time and
only when required also whenever a for statement is included to iterate over a
set of items a generator function is run generators have a number of
advantages as well without generators in python producing iterables is
extremely difficult and lengthy generators make our task very simple this is
because they implement the iter next and stop iteration methods automatically
generators also help save memory as the items are produced only when
required unlike normal python functions this fact becomes very important
when you need to create a huge number of iterators this is also considered as
the biggest advantage of generators along with this generators can be used to
produce infinite number of items and to pipeline a number of operations so i
hope everyone's understood what are generators and their advantages okay so
now let's move on to see the difference between normal functions and
generators generators in python are created just like how you create normal
functions using the def keyword but generator functions make use of the
yield keyword instead of return this is done to notify the interpreter that this
is an iterator not just this generator functions are run when the next function
is called and not by the name as in case of the normal functions and like i've
already mentioned before generator functions produce items one at a time and
only when required whereas the normal functions produce all the items in a
single go now that you have a brief idea about generator functions let's move
on to see how to write generators in python so as you can see on the screen i
have a small example wherein i've defined the function and then i've used the
yield keyword instead of return so now let me jump onto my jupiter notebook
and show you all how to write generators in python i've already opened a new
notebook over here

i'll just rename the notebook as generators in python and then like i've already
told you all before i'll have to use the def keyword to define a generator
function so i'll just name the function as new and i'll pass the parameter as a
dictionary after this i'll use the for statement and i'll use for x comma y in i'll
use for x comma y in my dictionary and i want the items as well yield

x comma y okay after this i'll have to specify a dictionary so i'll say a is my
dictionary and i'll specify 1 as high and 2 as welcome

you can give any values of your choice now after this i'll have to create a
generator object for my function so i'll name that object as b and i'll specify b
is equal to nu of a just to show you all what is b i'll print b and like i've
already told you all before instead of the name of the function you'll have to
use the next keyword to return values from generators so i'll say next of b and
i'll hit run so as you can see over here the first output over here specifies that
b is a generator object and the second output is generated by this next
function now let me just copy this function again and i'll paste it over here
and i'll hit run so as you can see over here the first time i use the next
function it returns the first key value pair of my dictionary and when i used it
again it has returned the second key value pair of my dictionary if i try to use
the next method again it says that stop iteration has been called okay now let
me take another example wherein i'll specify some condition i want to return
iterables that satisfy that particular condition okay so here i'll just define
another function so i'll say define my func and i'll pass the parameter as a or
i'll use some other name since i've used a last time i'll use i now while the
value of i is less than or equal to 3 yield of i sorry i've made a spelling
mistake over here it's y i e l d okay so yield i now for this i'll have to create a
generator object again i'll say the generator object is j which is equal to the
name of my function

and i'll have to specify a value for i so i'll just specify the value as 2. after this
i'll just print next of j since you all know that j is the generator object i'm not
going to print it again okay so as you can see over here the first time i use
next of j it has returned 2 as the value now i'll just copy this and i'll rerun it
uh oh sorry guys i've forgotten to increment the value of i please keep in
mind that when you're using while loops you'll have to increment the value of
the variable that you're using as an iterator so now let me hit run so as you
can see over here without incrementing the value of i when i use the next
method it has returned 2. now that i've incremented the value of i i'll hit next
of j again and as you can see over here i've got three as my output now if i
use next of j again it has called the stop iteration method so i hope everyone's
clear with this now let me take another example when i'll have two parts in
my function so i'll just define a new function i'll name the function as ex and
within this i'll just specify some variable n equal to 3 and then i'll yield the
value of this

after this i'll make some changes to the value of n i'll say n is equal to n star n
and then i'll yield n again

i'll have to create a generator object so i'll just say v is equal to

and then i'll use the next method so as you can see over here when i use next
of v it has returned only the first value of my function now in case i use the
next function again it will return the second value which is present in my
function and after this if i do it again it has to call stop iteration in case you
want to execute the same function at once you can make use of the for loop
this loop helps iterate over the objects and after all implementations it
executes stop iteration let me just jump onto my jupyter notebook and show
you all how to do this okay so i'll use the same function which i've used
previously

and after this i'll use the for loop so for x in v print x
so as you can see over here after using the for loop i have both the values that
are returned one after the other the for loop has not returned them
simultaneously but using the for loop i'm getting into the function printing the
first value first and after that i'm printing the second value so i hope
everyone's clear till here in case you have any doubts please do let me know
in the chat box and my team is here to help you

now let's move on and see how to use generator expressions generator
expressions can be used along with for loops to produce iterators this usually
makes the generation of iterables much easier generator expressions resemble
list comprehensions and like lambda functions generator expressions create
anonymous generator functions let me just jump onto my jupyter notebook
and explain this in detail i'll use some variable f and i'll specify the values of
this to be in the range of 6. after this i'll just print

list comprehension and i'll end this with a colon

i'll use another variable q when i'm going to store the values of list
comprehensions so to specify the list comprehension i'll be using the square
brackets so i'll say x plus 2 for x in f and then i'll print q after this i'll just
copy these two lines and create a generator expression so i'll just change the
name over here i'll say generator expression and make a note you'll have to
change the braces to regular braces and then i'll print q again i'll change the
name to r and then i'll print r as you can see over here when i used list
comprehension it has returned a list of values corresponding to the values of f
and when i used a generator expression and after that when i said print r it has
just returned that r is a generator object to print the values using the generator
expressions i'll be using the for loop so for x in our

print x so as you can see over here using the for loop i've generated the values
one after the other whereas using the list comprehension all the values were
generated at once generator functions like lambda functions can be used
within other functions as well so in case you want to find the minimum value
of r i'll just copy this and i'll paste it over here and then i'll say print minimum
of r
so as you can see over here it has returned the minimum value which is
present in r and that is 2. so i hope everyone's clear till here okay so now let's
move on and look at the use cases that we'll be discussing in this session
today like i mentioned before i'll be taking three use case examples which is
generating the fibonacci series generating a number stream and generating the
sine wave using generators in python okay so let's move on towards the first
one which is the fibonacci series fibonacci series as we all know is a series of
numbers wherein each number is the sum of preceding two numbers the first
two numbers of this series are assumed to be as zero and one so for example
as you can see on the screen i have values 0 1 1 3 etc okay so now let's get
back to our jupiter notebook and see how you can use generator functions to
produce fibonacci numbers okay so i'll just give a heading over here guys

i'll just give the heading as fib

okay and i'll define a function i'll name the function as fib and within this i'll
just specify the first variable and the second variable as 0 and 1. after this

while true i want to yield the value of f which is the first number of my series
after this i'll have to increment the values the second number becomes the
first number and the third number is the sum of the first and second number
so i'll just use f comma s will become s and f plus s

in case you have any doubts please do let me know in the chat box guys okay
so after this i'll use the for loop

so for x in fib

now i'll specify some condition over here so that the iterators that i'm
producing satisfy some limit so i'll just use if if the value of x is greater than
50 then i want it to stop so i'll say break after this i'll just print i'll just print x
and i'll end this with a space

now let me hit run so as you can see over here i have all the values of the
fibonacci series that are less than 50. so i hope everyone's clear with this okay
so now let's move on and see how you can generate a stream of numbers the
stream of numbers can be anything from zero to any number or even numbers
or odd numbers okay so let me jump onto my jupiter notebook and see how
you can actually generate a stream of numbers so i'll just create a new
heading over here

i'll name it as number stream and i hit run okay i'll just take a variable a and
i'll specify the range of this to be hundred after this i'll use a generator
expression so i'll say b is equal to x for x in a i want to print all the values of a
within the range of hundred so after this i'll just print b

and i'll have to use the for loop so for y in b print y

so as you can see over here i have all the hundred values of a

now in case you want to generate only odd or even values you just have to
make a change to the range function so i'll just copy this and i'll paste it over
here and to print even numbers i'll just say start from 2 go until 100 and in the
range of two so as you can see over here i've generated a stream of even
numbers in case you want to generate odd numbers all you have to do is
change the values over here i'll just say one so as you can see over here by
just changing the first value from 2 to 1 i've generated a stream of odd
numbers so what this range function actually does is it starts from 1 it will go
until 100 excluding 100 in the intervals of two so i hope everyone's
understood this okay now let's move on towards our third use case example
which is generating the sine wave using c bond and generators in python so
as you can see on the screen using the normal function my sine wave is going
to produce all the waves at once but using the generator function i can
produce one wave at a time okay i'll just move on to my jupiter notebook

i've already written a function for that so i'll just paste it over here and i hit
run it's going to take a few minutes since i've imported the numpy matplotlib
and the cbond library

as you can see over here using the normal function i've generated all the sine
waves at once now let me show you what happens when i use the generator
function since i already have my function i'll just copy paste it over here and
then i'll hit run so as you can see over here i've produced just one wave
among all the waves that are present in my output now if i want to print
another wave i'll just copy this next function again so i'll say ctrl c and i'll
copy it and i'll hit run so as you can see over here when i use the print
statement for the next function again it has returned another sine wave okay
so i hope you're clear with this let me just print the sine wave again

as you can see on the screen the third sine wave has been returned and then
when i print it again it will return the fourth sine wave

oops which basically stands for object-oriented programming system or


object-oriented programming as its most popularly known is one of the most
popular programming paradigm now although python is not completely an
object-oriented programming language but still it uses major concepts of
object-oriented programming style as part of this now in this session what
we'll majorly be talking about are classes and objects classes in python and
object oriented concepts in python as well now let's first start about classes
and objects now to those of you who are not familiar with the different
programming paradigm two of the most programming paradigm is object
oriented programming and procedure oriented programming now when you
look at older programming languages like c or you can see visual basic as
well these followed procedural oriented programming language style wherein
what used to happen was that the entire program was divided into smaller
parts as known as functions and the importance was not given to the data but
the sequence of actions which were performed also what used to happen there
was that the entire process took a top-down approach as such but what
happened is when newer programming languages came up they realized the
value of the data and they came up with the opportunity of creating
something known as objects now objects are quite similar to what you can
relate to in real world entity as well now anything that we see around
anything that has different properties can be called as an object and here how
it differs from the older style that is the program uh procedure oriented
programming style is that it goes from a bottom up approach as well as
there's more data security as and you can use various operations like data
accessing data overloading data expansion and so forth now some of the
examples of object oriented programming languages is c sharp java visual
basic.net and so forth now let's first address the question of what exactly is a
class and object now to help you understand this better let's actually look at
an example here now to give you a simple one-line definition a class
basically is a logical grouping which helps us reuse and rebuild our data as
part of the code now to put it quite simply it basically is similar to a template
or a blueprint that we use once i have defined a specific requirement of mine
then what i can do is that i can go on variating with respect to that now let's
look at the example here now if you look here i have created a class called
employees wherein i have defined some of the most common parameter each
of my employees will be having there would be his name there would be their
age and there would be their salary now i have defined a blueprint but it come
there comes a time where i need to implement this so an instance which is
basically a entity of the class is referred to as an object here now if you look
here there are basically three different objects i have object one which is
referring to sarah whose age is 37 as well as salary is 10 000. my object 2 is
john whose age is 43 and salary is 21 000. similarly is jessica as well whose
age is 26 and the salary is 24 000. now how does python implement classes
now again to go back to the definition a class basically is a blueprint for
which objects are created now coming to the basic syntax for how to write a
class in python it's quite easy because you just need to define the keyword
class following which you need to specify the name of the class now let's go
if you take the previous example the name of that class would be employees
and each of the objects would be created from that same class now what i'm
going to be writing inside the class would be three major aspects i would
have my class variables i would have instance variables and i would have
data members okay now these are the three major aspects to any class as such
now if i need a variable which is going to be shared by all the instances of the
class now do not get confused when i say instance it basically is referring to a
object itself so here we refer to an object as instance now each if i want each
of the instance to share a common variable then i would make it a class
variable but let's say i want each of the instances to have a specific variable
okay then i would be using an instance variable as such then comes the third
part which basically is your data member this basically is a class variable or
an instance variable as such that actually holds the data associated with
respect to the class and objects now without confusing you any further let me
actually switch to my pycharm okay and let me show you this by writing by
defining a class here itself so let's start by creating a simple classic now let
me use the first keyword for defining any class that is class then comes name
of the class now for today's example what i'll do is i'll create a class called
cars okay so i've created a class called cars okay can you guys see this okay

and here what i'm going to do is that right now i'm not going to write
anything

so i'm just going to use the keyword pass then comes the time for me to
create objects for this class so what i'll do is let me call an object let's take
honda for it okay so this is the name of my object and then i'm going to
specify to which class it belongs to so it belongs to the class car and this is
how you create an object in python quite easy right

similarly let me create another one let me call it starter okay tata is also going
to be of car

okay so basically what i've done here is that i've created two objects that
belong to a specific class now time now comes the time when you actually
assign values to these instances or objects as such now let's say i want to add
the name or the model number for the honda car so i'm going to say honda
which is my object following which use a dot operator and then specify what
instance variable you want to use now let's say i want to specify model name

okay model name is equal to i'd say city because i like honda city

okay now i'll also add another variable which is

year of manufacture so i'll say year m okay and this basically is going to be
equal to let's say 2017. now i'll also add price

okay

i'd say about 10 lakhs does that sound fine

now let me just copy the same and let me create an object for tata car as well
now here let me just change it to data

and let's say this is

bold okay so let's keep the year the same or let me reduce it to 2016. and let's
say the price is

let me reduce it i'll make it six

okay does that sound fine now what i have done here is that i've created
instances of the class or objects to that class and each of these instances
themselves have a specific variable assigned to them as well so in this case
what you see here is the model name what you see is the year and what you
see is the price so these are basically variables associated to each of these
instances as well now if i say just print and i say

honda dot model name

okay let me take the price itself

let's try running this

okay it's with respect to the definition of the class now if you go back to if we
go back to our slides here can you see there's a small semicolon here that we
have missed out so this is how it is a single semicolon can make a lot of
difference okay now let's just save this let's run it

ah okay i can see the price of my honda car here now this is a lot of pain for
me when i'm working with multiple instances which have unique variables to
them but let's say if i have common values that needs to be created for all of
these if i was using other programming languages we had a concept known as
constructors but don't worry that same is present here as well with python so
to create a constructor use the following command which is def which is
basically defining a function and use init now init is basically a constructor
here and what it is representing is that it is going to initialize the value of the
variables now if you notice here there's a keyword that is already added here
that is self self basically is a reference to the object which is going to be
calling this function now those of you who are not familiar with functions can
check out our video on python tutorials where we have talked about functions
and also check out our python function video as well okay now what happens
is to this let me pass a model name i'll also pass the year manufacturer

and let's see the price as well okay now i need to assign the values for these
variables for all the object now if i need to do that then what i need to do is
that i need to first reference the object so that's self dot

model name equal to the model name that it's getting so

then self

dot year of manufacturing

and finally self.price

okay now what i'm basically doing is that for my constructor i would be
passing these three parameters so for the object or the instance which is going
to be created please add these values for that okay now let me show you how
to change this as well now i don't need this so i'll remove all this

okay so here what i'll do is i'll pass honda i'll pass city

okay

i'll also pass the year of manufacturing is 2017 and let me pass the price again

same for tata

so what i've basically done is that i have generalized the requirement that i
want now again if i run the same what you can see here is i'm getting the
same output that i had gotten earlier as well so this basically is a constructor
that is going to be used when i have to assign specific values to my objects or
instances at the time that they are creating apart from this if you want to
create or you want to add any specific value you're free to do that now let's
say i want to add a new value let's say i want to create honda dot let's say i
want to add the cc as well the cc of honda city which is equal to 1500 okay so
this is also very simple now what happens here is that i've created an instance
variable for the honda object okay now same thing let me just say if i want to
see the complete values that are associated to an object then what do i do is
that i check the name space for it now how do i check the name space for it is
that i use the dictionary option sorry i use a dictionary function okay so if i
use dict function and if i run this then what you see here is that i have a
model name which is city i have a year of manufacturing 2017 i have a price
and i have the cc associated asset to it as well okay now what basically it tells
me is if i use this object and request any of these values then this is the output
that i would be getting same if i change for tata

and i run this

then what you see here is that cc is not present so i hope you understand the
difference between both can i have a quick confirmation in the chat box

okay that's great good to see that all of you are following it now if i have a
class then if i don't perform any operations in it then i'm basically not
optimizing or using the complete capability of that class as well now what i'll
be doing is that i'll be creating a function here so this function what it
basically does is that it's going to increase the price of my car so what i'm
going to do is that for defining any function use the keyword def okay
following which the name of the function so let's say

price underscore increase okay now this is a function but it's going to be
performing on itself as well so use self here okay and i'm going to start
defining this function what do i need to do is that i basically just need to
update the value of price okay so what i'm going to do is that i'm going to use
self dot price equal to then i'm going to do a simple computation let's say the
present self.price

i'm sorry about the typo


into okay how much do you think the annual price range would be let's take a
guess let's maybe a 15 percent rise in that case i'll go with 1.15 okay now i
have defined a function here but what you need to understand is that it's not
exactly in the scope of the class so

oh sorry about that

now how do you identify if it's in scope or not it's basically one of the easiest
with respect to pai cha if i expand it then i know what is part of the class and
what is not so this is one of the major reasons that we recommend you use
pycharm as an ide as such okay now i need to increase the price so what i'll
do is let me go back let's say i want to check the price of the honda first

okay then what i'm going to do is that i'm going to call the function with
respect to the class now it's defined to that class so what i'll do is that i'll send
this function i'll use the honda object to call that function now to use any of
the functions associated to a class make sure you're using the instance or
object of that class so honda dot now you can already see here the different
suggestions that comes to it now price increase is the function that i want
okay and again let me copy this and paste it

okay so again see the major issue here is it's considering this so if you just
double indent it it's going to set back okay just save this and let me rerun this

ah okay now it's giving me the output so it's converting it let me just add int
here just to convert it to integer type

okay so the output should be converted to integer type for me so it's


incremented the value to 1.15 times okay so these are basic function
operations that you can perform with respect to python now let me go back to
my presentation and here let's talk about the various object oriented concepts
in python now in this session what we'll be talking about are the three major
concepts which is inheritance encapsulation and abstraction now when we
come down to inheritance inheritance basically is the ability or the
opportunity for any class to inherit the attributes and behaviors from the
parent classes now when i talk about a parent class it refers to a super class as
such okay so let's take cars itself for an example but before that let's look at
the example here now your parent becomes a base class and sun becomes the
derived class as such this is same that we'll be implementing in our program
as well so in our python what i'll do is that i'm going to create a new class and
let me call it

supercar

but if it has to inherited the properties that are present in the car class then
what i need to do is that i need to specify car here okay that means it becomes
the parent for the supercars okay so here i'm not going to define anything i'm
just going to say pass and let me remove this from here and let me add it here
okay now rather than making honda as a instance of car class let me let me
make it of the supercar class

okay now i have not defined an init operation on nor i have i initiated the
values for these variables as well okay so what i'm going to do is that let me
just try running this okay let me remove this

okay and let me just print the namespace for honda which is honda dot

before that let me just show you uh let me just print one of the values itself
first before i show you the name space completely let's say honda dot

here

okay so year of manufacturing is defined here i have not explicitly defined in


the child class but let me make sure let me just run this and let's see the
output

okay so here basically it's just passing it ah spelling mistake

let's read on this now here what is happening is that it is referencing to its
parent okay now to get a better understanding of what exactly is happening
here okay we're going to use something interesting what we're basically
going to do is that we're going to use the help function print
help and here what i'm going to do is that i'm going to pass honda

let me just comment this

now this is something that i really want to show you guys

okay now if you see here what is happening is that it's showing me the
method resolution order so basically it's showing me how it is going to follow
the sequence of operations first it is going to check in supercar for init
method but i have not defined it here so what it's going to do is that it's going
to refer the car class if it is not defined there as well then it will go back to the
parent class for all objects which is built-in dot objects this is the parent class
that is going to be inherited by all the classes used in this language as such so
it's found the init method present in cars okay and it's shown methods
inherited from class is the initiate in init method and it has initialized itself
okay now this is basically the sequence of operations that happen as well now
when i create define any function with respect to the child class it's going to
check the child class if it is not present then it's going to check the parent
class as such now it can be anything as such it can also be the price increase
as well

and

okay

okay let me just comment this section out

so here again it has inherited this method as well now let's say if you do want
to define an init method as part of the class then what you basically do is that
you follow the same sequence you write define okay following which you
use in it then you specify the parameters it has to take

okay and then what you basically do is that you shouldn't actually copy this
entire code and replace it here what you can do is that you can use the
keyword super
dot

init okay so what i'm referring to is that it should call the init function present
in the super class okay in that case what i'm going to do is that i need to pass
the parameters here as well so i'm going to pass the model name i'm going to
pass the year of manufacturing as well as i'm going to pass the price as well
now this is basically to reduce the code that you're going to be writing as such
now apart from this let's say there are a few other variables that you're going
to be taking let's say i'm going to include cc as part of my super class then
what i can do is that i can write here self

dot cc is equal to cc so i'm basically building on what is already present and


this is one of the major aspects that you can use inheritance for this in turn
reduces a lot of code dependency as well and is one of the most popular and
major factor for any programming language that uses object-oriented
programming systems okay now coming back to the next concept that is
associated to python okay you have encapsulation now encapsulation
basically is the method through which you bind your data and your code
together now it also helps you in hiding your data from people whom you
don't want to do it don't want to give visibility to so this is one of the major
key factors for any programming language as such now there are two major
ways through which you can i access or achieve encapsulation one is by
using the getter and setup method and the next is by using at project okay
now we'll be talking more about that in our next session but let me give you a
simple understanding what happens is that you want to change a specific
value as on when in the go itself let's say my year of development or my year
model year just keeps changing continuously in that case what i need to
should do is that i need to update these values on regular interval but let's say
if there's a specific dependency on these variables ahead as well then it
becomes an issue same can be said with respect to price now price is going to
be increased continuously through getter setup method i can ensure that this
is going to be implemented every time there's going to be a change as well
apart from that one of the major concepts with respect to object oriented
programming is abstraction now with respect to abstraction what basically it
means is that it hides the implementation details and only provides the
functionalities to the user now if you look at the image here now a
mechanical engineer or an automobile engineer who works with your car is
aware of the inside and out of your car as well now if i need to drive a car i
don't need to know that i just need to know how to turn on my car how to
change the gears and how to move forward as well so that is what abstraction
helps me achieve i don't need to understand what exactly happens when a
gear shifts from second to third but i just need to know that a gear shift from
second to third is going to make it easier for me to move ahead as well okay
so this can be achieved by using abstract classes and an abstract class is quite
similar to an actual class itself but how is it different from an actual class is
that an abstract class cannot have an object of itself you need to inherit the
abstract class and you need to create an object of that abstract class as well
now let me go back to the same example let's change it here okay now what
i'll do is that i'm going to add a few additional lines of code okay let me just
copy this here let's say i'm going to say from abc

abc and create abstract method

okay now what i'm going to say is that my car class abc is also

inheriting this abstract now i'm going to remove all this and

okay here i'm going to make this an abstract method where i'm not going to
define the logic here okay for now what i'll just do is that i'll call it

okay

and in my superclass what i'll do is that i'm going to create the same function

but here i'm not going to define any logic

okay so what i'm basically doing is that in my abstract class i'm defining the
method to increase the price but based on my requirement now let's say i
don't want my supercars to have an increase of just 1.15 so what i'm going to
do is that i'm going to increase this let's say the annual increase is going to be
two percentage so this is one of the major uses through which i can perform
or i can use abstract classes i can just define the basic logic which is needed
to be implemented in all the classes going ahead and then what i can do is
that i can implement or variate these functions as per my requirement okay
now with this let me go back to our slide and let me just summarize so we
started with classes and objects we talked about classes in python and then
we talked about the various object oriented programming concepts in python

let's talk about the init function in python so what exactly is init function init
function automatically gets called each time an object is created for a class
now when we add a init function to a parent class a child class will not be
able to access the parent class method so to overcome this the child class init
function overrides the parent class init function so now let's take a look at an
example to understand this now to show how init function works let me first
clear this

we'll write our init function over here yes and instead of self i will add one
more variable let's say f name and f h now what i'll do is i'll just write self dot
is equal to fname and self.h is equal to fh now i'll take one more function
guys so i'll just name it as let's say view and for view i want to print the value
of f name self dot name and self dot age so this is my parent function guys
and for the definition in the child class i will also make one in function so i'll
just write it as init self and again i have to add f name and fh and let's say
self. name is equal to fname and self.h is equal to fh now this init function is
going to overwrite the parent in function guys so let's make one more
function so this is going to be view as well and in this let's say i want to print
okay before we move on we have to specify the variant function with the init
function as well

and we don't have to mention these variables instead i'm going to add one
more let's say i want to add last name as well

and i'm going to add it as let's say eduraka now i'm gonna print over here self
dot h self dot last name and self dot let's say name all right i have to remove
these let's make one more object and give it the value let's say i want the age
to be 23 and last name is going to be python in the inverted commas name we
have already specified so we don't have to give it again and i'm going to just
call the function and let's see what happens what is the output will be so as
you can see i'm getting the output as python and eureka and 23 so this is how
you can overwrite the parent class init method using the child class guys so
this is all about doing it function now let's talk about the next topic that we
have which is the types of inheritance so depending upon how many types of
parent class and child class are going to be there inside the program following
other types of inheritance python guys so there is single inheritance there is
multiple inheritance then there is multi-level inheritance hierarchical
inheritance and there is hybrid inheritance as well so we are going to talk
about each of them in detail guys so first of all let's talk about what is single
inheritance so when the inheritance involves one child class and one parent
class only it's going to be a single inheritance the example that i showed you
before is the example of single inheritance guys and talking about multiple
inheritance it is going to involve more than one parent class which means we
are going to have at least two parent classes and the child class is going to
derive properties from both of them and this is called multiple inheritance not
talking about multi-level inheritance let's say we have a single inheritance
going on we have a parent class and we have a child class but the child class
also act as a parent class for another child class that is going to be a multi-
level inheritance guys and talking about hierarchical inheritance hierarchical
inheritance actually involves multiple inheritance from the same parent class
and talking about hybrid inheritance if a program has more than one types of
inheritance let's say we have a single and multiple inheritance going on
simultaneously it's going to be a hybrid inheritance guys so let's take a look at
examples for each of them so let's go to pycharm guys and i'll remove all this
so i'll start with single inheritance guys so i'll just take a parent class

and give it a function let's say function one and give it a statement let's say
this is function one

now let's take another class guys class child and give it the value of the parent
class and after that we can move for another function let's say function
number two and give it a statement let's say print this is function2 now make
a child class object

and call the function so we can call both of these functions so just call
function1 give it the output and we are getting the output as this is function
one so this is a basic example of single inheritance guys now talking about
multiple inheritance what i'm going to do is i'm going to make one more class
over here let's say class parent to now what happens is let's say give it a
function number three let's say and print statement this is function three and
in the declaration over here i'm going to just specify two classes and when i
call the functions i can call function number one and i can call function
number three as well guys so let's see what is happening here in the output
i'm able to call the function number one and function number three as well
from the child class object so this is the example of multiple inheritance guys
now talking about multi-level inheritance so what i'm going to do is i'm just
going to specify parent over here and from this let's say it doesn't have any
declaration of parent one which is this class so it is not able to inherit any
properties from that but what i'm going to do is i'll just specify parent two
over here and i can still call these functions because there is an inheritance
going on between them which is multi-level inheritance which basically
means this class the parent one class is actually giving properties to parent
two class and parent two class is giving properties to the child class so this is
example of multi-level inheritance guys now talking about hierarchical
inheritance guys what i'm going to do is instead of parent two over here i'll
just specify parent so for these two child classes i have the same parent class
and now let's see if i can have the same output or not i'm not going to get the
properties from the parent two because i have not specified it in the
inheritance so i'll just remove this and let's see what happens i'm getting the
output this is function one okay let's make the object for parent two as well

all right give it one and ob1 dot let's see what functions we can have i can
have the function number three and i can have the function number one as
well so i'll just print function number one and from both the child classes i'm
able to print the function number one so this is the example of hierarchical
inheritance guys i'm using the same parent class to give the properties to both
parent two and child class as well and now talking about hybrid inheritance
hybrid inheritance actually involves more than one inheritance going on in
the single program so we have a single inheritance over here so let's say i
want to have multiple inheritance as well so i'll just specify parent two now
and this is the example of hybrid inheritance guys because we have a single
inheritance going on over here and in the child class i'm inheriting both the
parent one and parent two and this is the example of multiple inheritance so
this is a hybrid inheritance example guys okay we are getting a type error
which is saying cannot create a consistent method resolution order for base
parents parent one and parent two okay let's say instead of this i'll make one
more class over here give it a value let's say pairing number three give it a
function function let's say four and print statement this is function four now
instead of period number two what i'm going to do is i'll just take parent
number three guys and with the child class operator let's see if i can actually
get the function number one and let's say i want function four as well i'm able
to do that so in the output let's say what i get i'm getting the function 1 and
function 4. so this is a simple example of hybrid inheritance guys now that
we are done with the type of inheritances let's take a look at what all we have
now so we're going to talk about the super function guys super function
actually calls the parent class method directly so let's take a look at a simple
example guys how it works so i'll just remove all this

now what i'll do is i'll make a let's say parent class and give it a function
function one

again the print statement

now what i can do is instead of calling the parent function from the object i
can just use the super function and over here i can just call the function1 now
i'll just print this is function2 let's make a child class object

now let me see if i can call the function2 or function1 i can do that so i'm
going to call the function two guys let's see what the output will be so i'm
actually able to call the function one directly from the super function over
here so this is the function of super function guys it can directly call the
parent method and now that we are done with the super function let's take a
look at the next topic that we have which is method overriding in python so
method adding can also be achieved to change the functionality of the parent
class function so let's take a look at an example to understand how we can
actually achieve method overriding in python guys so instead of naming them
separately i'll just name them as same so when i create the child class
constructor and if i call the function now okay function1 which is so when
i'm calling this function technically it should call the parent function but what
happens is it overrides the parent method okay to specify this run it again
now i'm getting the output as this is function2 even though i'm calling this
function 1 which should be ideally calling the parent function but it is
printing out the function which i have specified in the child class so this is
how i have overridden this parent class method and this is how we can
perform method overriding in python guys

in this session let me walk you through on how you can learn and make use
of exceptions in python guys this session is intended to be useful for anyone
considering to kickstart their learning about python and need some insight on
how you can go about making use of exceptions to make coding very easy for
you so the focus is basically on approaching the language in the easiest way
possible and to find out what it has to offer to the community and all of the
learning enthusiasts out here so let's begin by checking out the agenda for the
session we'll start by checking out why we need exception handling first later
we'll check out what an exception actually means followed by that we'll be
walking through the entire process of how we can handle an exception and
lastly we look at how easy it is to code with python where we'll take a
programming approach and learn the concepts through code now that we're
done with the agenda without further ado let's begin by checking out why we
need exception handling well to understand the concept let me quickly walk
you through a very simple scenario consider the case where you're dividing
any number by zero what will happen can you divide a number by zero you
cannot correct but how would a kid approach this problem the kid would
think that you can actually use regular division to divide something by zero
so you're dividing something by nothing so it stays the same something like
this right little does the kid know that this is wrong now check out how a
programmer would approach the same concept well it is established that
dividing by zero is not possible mathematically so as programmers we know
it is not correct so this basically leads to two cases either an exception or an
error so a python program terminates as soon as it encounters an error well in
python an error can be either a syntax error or an exception and it is as simple
as that well let us actually divide by zero for fun guys so this is what happens
in python python presents us with this beautiful error message saying that it
cannot divide something by zero well in fact let us head to pycharm which is
my ide for coding in python so we can actually walk through this practically
so guys here i am in my pycharm so let me quickly go ahead and type out
some simple code for you guys so let us start with y equal to 10 we can
actually print y by zero now so let me quickly go ahead and run this in the
console so as you can check out it's a zero division error division by zero is
not possible so you cannot divide anything by zero so let's establish that at
this point guys that was good enough right so let's get started then let us
quickly check out what exception handling actually is well guys to get a clear
picture of what that is we need to start with understanding the definition for
both exception and exception handling well what is an exception guys an
exception is an event which occurs normally during the execution of a
program that disrupts the normal flow of the program's instruction so instead
of the program actually executing evenly and nicely there is actually a
disruption in between the core so this we basically call as an exception so
next what is exception handling guys this is the process of actually
responding to an occurrence of an exception as simple as that so basically the
process of responding to the occurrence during compilation of exceptional
statements which require special processing is actually what is exception
handling guys so this is basically done because of the change in the normal
flow of the program execution well it is a very simple concept and i am sure
at the end of this session you guys will agree well at this point what do you
think of exception handling in python guys head to the comment section and
let me know what you think so we can interact there and now that we know
what exception handling is we need to understand how the entire process of
exception handling works so let us check it out first let us walk through what
happens in python so let's say the user makes an error what happens next
guys when you think about it it is either the user that finds out the error or
python will actually tell you what the error is correct so once you know what
the error is and you know where it is you can basically start analyzing it to
know if it is fixable or not well if it is fixable how can you go about doing
that well if it isn't nothing to worry guys python is so good that no matter on
what level you mess up there is always a way out of it guys so now if it's
fixable how can we handle the exception check out the image on the right
side so we need to first find the error if we cannot do it python will find out
for us well next is to make sure you take caution while coding if you think
that there is going to be an error in that particular piece of code well
remember the word try at this point all right and later we'll actually fix the
error and we call this as catch just remember the keywords for now and we'll
be walking through these in detail in the following slides in fact let us begin
by checking it out right now so guys these are some of the important terms
that you need to take a note of before starting to code and understanding
exceptions so first we have try well try is basically the keyword which is used
to keep the code segment under check so whatever code you put under try is
actually the code under scrutiny guys and next we have accept well except is
a segment which is actually used to handle the exception guys so how do we
know that the exception is occurred if our piece of code in the try block has
actually caused an exception then we can handle it in the except block and
how do we use else well else is basically run when no exceptions exist guys
and lastly we have finally finally we'll run even if there is an exception
finally we'll run if there is not an exception as well so i want you guys to note
this at this point of time and this will help you a lot in the coming slides guys
so now coming back to python this is what it visually looks like we first have
the try block where we run a piece of code and next we have the except
where the code actually runs only when there is an exception in the try block
and if there are no exceptions then we run the else block guys and lastly no
matter what exception or no exception we run the finally block always guys
sounds simple right well it actually is and now that we are familiar with the
process of exception handling let us check out how we can go about
understanding this using python practically guys well syntax errors occur
when the parser detects an incorrect statement well check out the tiny arrow
on the left side here well this is basically to indicate where the parser ran into
the syntax error well in this particular example there were too many brackets
right so there was an extra closing bracket well if you actually remove it and
run it you will actually get a different error this time we'll check on the right
side part of the code well this time you actually ran into an exception error
well this type of code occurs whenever syntactically correct python code
results in an error guys so the last line of the message indicated is what type
of an exception error that you actually ran into well in this particular case it is
zero division error and it says that the integer division or modulo by zero is
not possible so this is basically the same case that i showed you in python a
while ago but instead of showing the message exception error python details
what type of exception error was encountered well as i mentioned in this case
it was a zero division error right well python comes with various built-in
exceptions as well as the possibility to create self-defined exceptions as well
and now that we are clear with that let us check out how we can go about
raising an exception on our own so we can basically make use of race to
throw an exception if a condition occurs the statement can be complemented
with a custom exception well if you want to throw an error when a certain
condition occurs using race you can actually go about it like the following
piece of code you actually see on the screen and when you run this piece of
code you'll be greeted with the following output guys so it says exception x
should not exceed 5 and the value of x was 10. so let me quickly jump back
to pytham and we can execute this there so guys i'm in my pycharm right now
so and i quickly typed out the code for you guys so let me quickly go ahead
and run it and we can check out the error as you can see it says exception x
should not exceed 5 and the value of x was 10. perfect right so let's quickly
jump back to the presentation to check what's next so the program basically
comes to a halt and displays our exception to screen right so this basically
offers clues about what went wrong and now that we're clear with that we can
actually proceed to checking out the assertion error guys so instead of waiting
for a program to crash midway you can actually start by making an assertion
in python well we assert that a certain statement is actually met and if this
condition turns out to be true then excellent the program can continue but if
the condition turns out to be false you can have the program to throw an
assertion error exception for you guys we'll have a look at the following
example on your screen well this is basically where it is asserted that the code
can be executed in a linux system guys so if you run this code on a linux
machine the assertion passes if you were to run this code on a windows
machine the outcome of the assertion would be false and what would happen
well definitely the result would be something like this right so it would
basically present us with an assertion error and says that this code runs only
on linux right so i'm using a windows desktop in this particular case so let me
quickly open up my pycharm and then we can actually run this piece of code
to check out our exception guys so i'm back in my pycharm and i've typed out
the code guys so let me quickly go ahead and run this as you can check out
since this is a windows machine it says this code can run on linux only but
this particular case this assertion would be true if you are actually running
this on a linux machine base so if any of you guys are using linux machine
make sure to try it out and on that note let's quickly come back to the
presentation guys well in this particular example throwing an assertion error
is the last thing that the program will do the program will definitely come to a
halt and it will not continue guys but what if that is not what you want what if
you want something different from this or that you want the program to
continue while displaying an exception for you guys well now that we
actually have a fair idea about how we can go about understanding
exceptions let us dive right into the heart of exceptions now yes i'm talking
about the try and accept block guys so basically the try and except block in
python is used to catch and handle exceptions well python basically executes
code following the try statement as a normal part of the program the code that
follows the accept statement is the program's response to any exception in the
preceding try clause guys well as you saw in the earlier example that i
actually showed you when syntactically correct code runs into an error
python will throw an exception error and this exception error will actually
crash the program if it is unhandled guys so the accept clause determines how
your program responds to these exception guys so instead of actually
crashing our program we can actually tell python what to do when this
particular exception occurs we'll check out the following function guys so
this function can basically help us understand the try and the except block
well the linux interaction function can only run on a linux system the assert in
this function will actually throw an assertion error exception if you're using it
on any other operation system apart from linux well we can actually give this
a try in pycharm so let me quickly open up that so guys i'm quickly here in
my pycharm so let me quickly go ahead and select this and run it well this
won't say anything right now because well if it was actually a linux platform
the message would have been printed right so let's quickly jump back to the
presentation so basically if we run the tiny piece of code you see on the
bottom the way we actually handle the error in this particular case is because
we gave out a pass right well if you were to actually run this code on a
windows machine you would get the following output which is already on
your screen right so it is a blank output you get nothing well the good thing
here is that the program actually did not crash but it would be nice to see if
some sort of exception occurred when you actually ran your code well to this
end you can actually change the pass into something that would generate an
informative message like this check it out so let me quickly go ahead and run
this in pycharm well as you can check it out it says the linux function was not
executed right so basically this happened because i am on a windows
machine guys so let's quickly go back to the presentation and guys when an
exception occurs in a program running this particular function the program
will continue as well as inform you about the fact that the function call was
not successful well what you did not get to see was the type of error that was
actually thrown as a result of this function call guys so in order to see what
exactly went wrong you would need to catch the error that the function
through well check out this particular piece of code i have for you guys so
here is basically where we actually capture the assertion error and we print
the output message to the screen so we have a try block we have the same
function and we have accept as error right so we're going to print what type
of an error it is followed by a message for us right so running this particular
case on a windows machine will actually give us this following output guys
so it says function can only run on linux system and whatever you have
chosen in the print block is actually being printed for us so let me run this in
pycharm so as i can check it out we have the message printed right so it was
the same as i told you so it was the same message as i told you before
heading back to the presentation well in the previous example we actually
called a function that we wrote ourselves right and after that when we
actually executed the function we caught the particular assertion error
exception and then we printed it on the screen well i have for you another
example where you actually open a file and use a built-in exception guys in
fact let us dive into python and we can actually run this and we can come
back and take a look at the output so guys i actually came into pycharm and i
actually ran that particular piece of code why does it say could not open file
log well guys basically if the file.log does not exist the block will give you
this output right so it says the file could not be opened well this is an
informative message and our python program is actually still able to continue
to run it has not crashed right well actually in the python documentation you
can see that there are a lot of built-in exceptions that you can make use of and
here is one exception that i have for you guys that you can check it out so it's
an exception file not found error right so basically this is raised when a filer
directory is requested but that doesn't actually exist and this is just one among
many that python offers to us guys well to catch this type of an exception and
to print it on the screen we would actually use this following piece of code
guys so in the try block we actually going to open it as file and we're going to
read something present in it guys we're going to accept it by pushing a file
not found error as an object and later we actually end up printing that object
right so let me quickly go into pycharm and we can check it out well as you
can check it out we have error number two which says no file or directory
right so it's perfect well you can have more than one function call in your try
clause actually guys and anticipate catching various exceptions as well well a
thing to note here is that the code in the try clause will actually stop as soon
as an exception is encountered but there is one important thing that i want
you guys to note down is that while catching an exception it basically hides
all of the errors guys well definitely there are some unexpected errors in your
program right when you're catching an exception and even these are
completely hidden from you well this is why basically you should avoid
using bare accept statement clauses in your python programs guys so instead
basically what you can do is you can refer to the specific exception class that
you want to catch and then handle those particular exceptions guys so look at
this following piece of code i have for you so here basically you first call the
linux interaction function and then later actually try to open a file guys so let
us quickly jump into python and we can actually check it out so as you can
see i actually executed the program guys again if the file doesn't exist running
this code on a windows machine will give you that output right so it basically
says that the function can run only on a linux machine and then we have
actually printed something guys well what we actually did here is inside the
try clause we directly ran into an exception immediately and we did not get to
the part where we'll actually try to open our file.log right now basically when
you actually run it on the linux machine it's gonna says no file or directory
phone check it out here guys so this is the windows output that you get and
this is the linux output guys well at this point let's take a quick break and
check out what are the key takeaways of this particular module guys so
basically a try class is executed up until the point where the first exception is
encountered and inside the accept clause or the exception handle of what we
basically call it we can actually determine how the program actually should
respond to that particular exception and we can actually manipulate multiple
exceptions and differentiate how the program should respond to each of them
right and lastly we actually learned why we should avoid using bear except
clauses guys and now that you're clear with this next up i have for you is the
else class guys so basically in python using the else statement you can
instruct a program to execute a certain set of code only in the absence of
exceptions guys we'll check out this following diagram on your screen so
basically in the tripod we have the code except when we actually want to
handle the exception or else in case there is no exception we're going to run
the piece of code that comes in under else guys so let me quickly walk you
through the code guys so here is basically the same linux interaction function
and we have an assertion error here and we actually are going to print the
error right so else if there is no assertion error so we're going to have an else
clause and we're going to print saying executing the else clause right so let
me quickly open up my python and we can run this piece of code guys so as
soon as i go ahead and run this it says function can only run on a particular
linux system right

so as you can check out the output it says the function can run only on linux
systems right so in this case i have a windows machine so we are actually not
printing the accept class here but if you are running this on a particular linux
machine this is the output that you would get guys so it says doing something
and executing the else class correct this happened because the program did
not run into exceptions any exceptions right so else clause was actually
executed well you can actually try to run the code inside the else class and
catch possible exceptions there as well well again we have the same linux
interaction here we're going to print it right so the linux output says doing
something and no such file directory found well this is basically for the else
clause and we're using the same file example here but then we're actually
trying to catch an exception in the else block as well so the output is pretty
much straightforward as well right well from the output you can actually tell
that the linux interaction function actually ran well because no exceptions
were encountered an attempt to open file.log was actually made and that file
did not exist and instead of opening the file you actually caught the exception
which is the file not found exception pretty simple right and i hope you guys
are clear with all of the concepts that we discussed until now and next up we
need to check out how we can actually use the finally clause guys well to
begin with imagine that you always had to implement some sort of action to
clean up executing your code guys well python basically enables you to do so
using the final e clause have a look at the following example guys check out
the workflow on your screen i'm pretty sure we're all familiar with try except
and else at this point of time right so this is the chronological order that you
need to go into first we have the try to check for an exception then we
actually handle if there is an exception using the accept or else if there is no
exception we're gonna print whatever is there in the else block and lastly we
have something called as finally guys so no matter what we're gonna execute
this in case if there's an exception the finally block is going to run in case
there is no exception finally block is going to run there as well so let us
quickly check out a coding example guys so basically this is the particular
code i have for you guys and let me jump back into my pycharm and we can
actually execute this so guys i'm back into my pie charm so let me quickly go
ahead and run this well as you can check it out it says that the function can
only run on linux machines this is because i'm on a windows machine right
now and no matter what right so exception or no exception we have this
message which is cleaning up irrespective of any exception guys so this is
basically the use of finally guys and that is as simple as it gets so it's pretty
much simple right well try except else finally all of this is a really simple
concept and once you understand what it actually does you can go about
doing a lot using python guys well no matter what the python application is
there is a very good chance that you'll actually make use of exceptions guys
well on that note let me quickly summarize the entire session for you guys
well in this session we covered the following topics well basically we started
out with introduction to exception handling and later we looked at why we
actually need it right and then we checked out the following concepts in the
screen so we checked out race we checked out azert we checked out try we
checked out except else and finally guys well guys i would suggest you
actually take a screenshot of this right now or take a note of all of the
keywords and how you can use them in python guys so this will actually take
you a really long way in your python career and knowing exceptions in
python is always an upper hand when you're coding guys

so let's begin with our session and talk about the agenda for this session first
of all i'll be starting with what exactly is a python module and after that we
will learn how we can create a module in python moving further we will learn
to use that module we have just made inside a program and we will also learn
about the built-in modules in python and finally i will sum up this session
with a little demo using the python modules also i suggest you subscribe to
the eduraka channel to kickstart your learning and also press the bell icon to
get the notifications for the latest update on the channel so let's try to
understand what exactly is a python module so before talking about python
module let me talk about modular programming so what exactly is modular
programming it is a design technique to break your code into separate parts
now these parts that we are breaking the code into are actually called the
modules now we will talk about them in detail so the basic focus for breaking
down the code is to have the modules with no or minimal dependencies on
each other the benefits include you have to write lesser line of codes first of
all and then a single procedure can be developed for reuse as well and also
you are eliminating the need to write the same code again and again we can
write programs that can be designed easily because the whole team is going
to be working on just a part of the whole code now coming back to the
python modules they are simply a program logic or a python script that can
be used for variety of applications and functions let's try to understand this
with a basic example let's suppose we have a calculator app or a calculator
program so what all operations can you think of right now there'll be addition
subtraction multiplication and division so let's stick to these four for now so
the basic concept of modules is to break down the code into separate parts so
what we are going to do here is we are going to break down the code into
four different modules and we are going to save that code into different files
we can do that in a single file also but the purpose of doing that is actually
minimizing the line of codes so when we are making these four modules for
different operations such as addition subtraction multiplication and division
we can use them in the main file that we will make for the calculator app so
now that we have understood what exactly is a python module also i have to
tell you guys that if you have made a module it is not necessary that it will be
used for that particular program only if you're making a custom module there
are ways you can save that file inside site packages where you can actually
use the module for different programs as well so now that we are done
understanding what exactly is a python module let's try to understand how we
can create one in python we can declare various functions classes and
variables in the module it's as simple as writing a simple python script with a
dot py extension to our file once we have created a python script we can use
it in the program using the import keyword so we are going to do that later
guys so for the example that i was talking about this is a python file or a
python script which has these four different functions which has the logic for
the operations for addition subtraction multiplication and division so i'm
going to save this file so let's take it up to pycharm guys we will try to
understand this better so this is our file guys where i have actually defined
four functions let's actually get into the presentation mode so as you can see i
have these four functions this is the logic for addition then this is the logic for
subtraction multiplication and division so i have saved this file with the name
mod1 so this is going to be my module for my calculator app so this is
actually how you can create a module inside python so it is as easy as writing
a script so instead of functions also i can use classes i can use any variables i
want data types etc so now that we have learned how we can create a module
in python so let's try to understand how we can actually use that module we
have just made we use the import keyword which will incorporate the module
into our program and there are different ways where you can import all of the
functions and classes using the asterisk or you can just write an alias when
you are importing the module using the as keyword you can use the from
keyword to only import a few parts of your module as well so this is actually
the procedure of using the module that we have just created now let's take it
up to pycharm to understand how we are going to use that module we have
just created so we'll exit the presentation mode

okay so i have my main file over here so i'll just write it from the beginning
so what i'm going to do is i'll write the import keyword and then i'll import
the file that i have created over here that is the mod one okay let's take it up
to the presentation mode again so i'll write mod one as you can see i'm
getting the module over there and i will use the alias let's say i'll use md over
here so for addition let's say i want to perform addition this will be my
variable and to add i'll use the alias and then i will call the functions that are
there in the module so i'll use the add function and then in here i'll specify
two variables let's say 10 and 15 so when i use the print statement i'll print
addition here so when i run this

i'm getting the output as 25 so as you can see this is how you can actually
import a module into your program now for similarly i can do the subtraction
okay instead of addition i'll just put it as result

now instead of addition let's say i want to perform subtraction so here i'll just
do 20 and when i get the output it will be 5 that is the subtraction between the
two numbers and similarly multiplication as you can see in the output we are
getting the multiplication as well and we will get the division now there's a
division as well so right now i've shown you how you can actually do the
these operations using the module you have just created now instead of using
the alias i want to show you another approach so i'll just write from mod 1
import let's say i want to import just divide so i'll write that now instead i
haven't used this alias over here so i'll just remove it and if i run this now i'll
get the output as i was getting before so this is how you can actually import
your module in another way so instead of just divide if i want to actually
import all the functions and everything in what is there in my module i'll just
write asterisks now instead of divide i can write sum i can write subtraction i
can write multiplication and i'll get the results as i was getting before so this
is a basic example guys where i have created a module for where i have
actually specified four functions with the operations for addition subtraction
multiplication and division so i have also created one more module which is
actually with the name of sample guys i'll show you the file later so i'll just
import sample over here and give it a alias and let's say s now what i'll do is
i'll just write print s dot so we'll see what all operations are there that i have
created in the sample module so as you can see there are two functions that is
fact and palindo so these are the two functions i've created to check if the
number is palindrome or not and then i have one more which is actually used
to find out the factorial of a number so i'll just write 1 5 1 over here and now
one more statement i'll just write s dot fact and we will find out the factorial
of the number five so i'm sure you guys must be knowing what is the factorial
of number five which is actually 120 so let's see if we are getting the output
as same or not so 151 is actually a palindrome and then there is the factorial
of this number so now i'll show you guys what the file i had made for the
sample module

so this is the file or the module that i had made for the sample module and i
have two functions over here which has the logic for actually finding out or
calculating the factorial of a number and then there is finding out if a number
is palindrome or not so this is a very basic example of how you can actually
make a module and use that same module inside your program guys now that
we are done with how we can create a module and how you are going to call
that module in your program let's talk about built-in modules in python guys
so what exactly are built-in modules built-in modules are written in c and
integrated with the python interpreter each built-in module contains the logic
or the resources for certain system specific functionalities such as os
management disk input output etc the standard library also contains many
python script with the dot py extension containing useful utilities now there
are several built-in modules in python at our disposal that we can use
whenever we want so to get the list of all the built-in modules in python you
can just write okay i'll just show you in the pycharm only so we'll exit the
presentation mode

so i'll open the python console guys i hope this is visible to you guys

so what we'll do in the python console i'll just write help and i'll write
modules over here what this statement is going to do for us is get the sorted
list of all the functions or all the built-in modules that we have in python we'll
wait for it for a while

so now as you can see this is the list of all the available modules that we have
in python as you can see there is pip and then there is traceback turtle types
typing p stats so these are all the like there is random there'll be math as well
so let's talk about a few modules few built-in modules so i'll just talk about
math over here so let me take a quick so i'll just try one thing okay before
talking about any built-in module let me talk about directory function guys so
what this directory function does is we'll go to the presentation mode now so
what this directory built-in function will do is it will return a sorted list of
strings containing the names defined by a module so the list will contain the
names of all the modules the variables and the functions that are defined
inside a module so when i run this we'll get the list of all these things that we
have in pipelot as you can see there are so many things that you can use
inside this pipelot module i'll be showing you the demo for using the pipelot
module guys don't worry now let's check it for the module that we have just
made guys
so i'll just write import all right sample that is our module guys so i'll just use
the directory function again and now i'll write sample over here and i run this
i'm getting all these files and names of all the functions and everything so i
have two functions over here that i mentioned that was factorial and
palindrome which are actually here so this is what it is about directory
function guys so we can check it for module mod one as well that we have
created so we'll check it for mod one as well so instead of just sample i'll
write mod one so as you can see i'm getting all these files and names of
variables and everything and the functions as well so i'll be having addition
yes i have addition divide multiply and subtract so to actually get the list of
all the values or the functions variables everything you want in a module you
can just write directly function and you will get the sorted list of everything
so now that we are done discussing how we can get a list of all the built-in
modules in python let me talk about python module search path so what
exactly is a python module search path so whenever we are importing a
module python is going to look for it inside the built-in module directory but
if it does not find it over there suppose you are making a custom module how
it is going to search is another story guys so what it is going to do is it is
going to search through the list in the sys dot path so first of all it will search
in the current directory then it will go to the python path and then it will go to
the default directory so i'll just show you guys if you import

says and then you write says dot path print this

and when i get the output over here it is going to show me the path and in
here you can make the changes to actually get your module to work for all the
programs that you're going to need so this was all about python search path
guys so let me talk about a few built-in modules that we have in python so
first of all let me talk about the math module so i'll import math over here so
we have imported the math module over here so let's see what all functions or
what all properties that math have that we can perform so we have factorial a
cos a cos h a sine a sine h tan so there are so many functions that are already
mentioned so let's check the factorial first so factorial of a number let's say 10
okay just write 5 so we are getting 120 as the output when we were
mentioning it in our custom module let's see if the math module does the
same okay we are getting the same output as we were getting before actually
the advantage of using the modules is similar to not writing the logic for
everything else because this is already mentioned inside a module that is
created inside the python already so as you can see i don't have to write the
logic for factorial like i have done in the sample module guys i can already
find it inside the math module so these are the functions that are already there
inside the math module exponent is also there floor f mod there are so many
functions guys we have pi as well we have power radiance reminder sine sine
h square root also let's find out the square root of 164 guys i'm sure you must
be knowing the square root of 164 guys if you're not just check it up on
google and you'll get the output as 12.80624

so this is all about math module guys if you want more practice you can just
make a program using the math module and you will be through with it in no
time so next one is the random module i will import the random module guys
so we'll see what all random offers

so we'll just write rand range all right 50 over here so what it does it is going
to give me the values from okay i'll write 0 to 50 so it is going to show me the
values from 0 until 50 randomly so each time i get the output i'm going to get
the different value see i'm getting 13 now i'll be getting some other value
from 0 to 50 i'll write 0 to 5 over here to understand this better so i'm getting
0 now i'll be adding 4 so there's no telling what value you're going to get so
there's one more inbuilt module i want to talk about that is the date time
module guys so when i import date time what i can do is i'll get the date time
so using the date time i can get the date of today let's see what it does for us
so i'm getting the date for today which is 2019 and 15th of may so this is
what you can do using the daytime module guys so we'll exit the presentation
mode now

so now i'll be showing you a little demo where i'll be using the pi plot module
that we have in matplotlib guys so this is a very basic example of using the
matplotlib module guys so i have imported matplotlib and inside that i have
imported piplot and given it the alias as plt so i have values such as you know
i'm using values of bmw and rd so this is my data guys this is inside a list so
i'll be actually plotting a graph here which is going to be a bar graph so these
are all the operations that you can actually get from using the plt ideas and
which is exactly using the functions defined inside the pi plot so i'll show you
what all are there inside the pipeline that you can use so as you can see these
are all the functions that you can actually use inside a pipeline there are so
many i'll show you the output guys then you will understand how it is going
to make our life easier as a developer so the next code is actually for pie chart
guys so you have we have the values like day sleeping eating working
playing and then we have specifications like what all activities we'll be
having like four columns we'll have in the pi plot so let's run this and we'll get
a graph guys okay there's a mistake over here i have forgot to write the color
over here so i'll run it again

so as you can see we are getting a bar graph with the information which has
the values that we have specified in the data given over here so as you can
see using the pipeline module data visualization becomes very easy and the
code for this bar graph that you're getting is actually completed in 11 line of
codes so that should make you realize the importance of using the python
modules guys because if you were to write the logic for getting the bar graph
by yourself imagine the horror guys so i'll just stick to the main part so i'll get
the pipe loud over here so as you can see we are getting the pipelord likely i
mentioned over here the data and everything using pipeline module will
actually make your life easier when you're working on a data analysis or
you're analyzing a data or anything like that so now that we are done with the
demo over here we'll exit the presentation mode i hope you guys are clear
with the concept of modules guys so we had created two modules the custom
modules so these are a very basic custom module guys that i have just created
when we are working on a big company our product based company there'll
be a lot more complex modules that we will be working on but to get the
hindsight this is how you actually make a module in python and we have
made sample eye as well and we have shown you a demo for using the
pipeline module inside matplotlib

time is definitely the most impactful factor for life and therefore it becomes
equally important to access set and modify it so before we begin just make
sure you subscribe to our channel and hit the bell icon to stay updated with all
the latest edureka videos coming back towards the session we shall be
dealing with two modules namely time and the date time module to
manipulate our clocks and calendars using some of the built-in functions and
format codes i'll be showing you all what these format codes are but before
that let's move on and take a quick look at the time module and its built-in
methods the time module consists of all time related functions that are
required to perform various operations using time it also allows you to access
several types of clocks required for various purposes the time module begins
recording time from the epoch epoch literally means a time in history and it
begins on first january 1970. as you can see on the screen i've listed down
some of the most important functions that are available in this module so
talking about the first function which is time it returns the number of seconds
that have passed since the epoch the c time method returns the current date
and time by taking the elapsed seconds as its parameter sleep stops the
execution of a thread for a given period of time the local time method returns
the date and time in the struct time format by taking the number of seconds
past since the epoch as the parameter gm time on the other hand returns the
current date and time in the utc format the mk time method is inverse of local
time it can take a tuple of maximum nine parameters and returns the seconds
past since the epoch and finally the asc time method which can also take up
to nine parameters and returns a string representing the same okay so now i'll
jump onto my jupiter notebook and show y'all how this works so the first
thing that you have to do is import the time module so i'll say import time and
i'll hit run okay so first i'll be making use of the time method present in the
time module so i'll just say time.time and i'll hit run so like i've already told
you all this method returns the number of seconds that have passed since the
epoch so i'll hit run okay so here is the number of seconds that have passed
since the ebook now if i want to convert it to the current date and time i can
make use of the c type method so i'll just have to use dot c time now if i want
to convert this into the current date and time i can make use of the c time
method to do this i'll just use time dot c time and i'll have to pass the number
of seconds as a parameter to this

so as you all can see on the screen i've passed the number of seconds which
was returned by the time method to the c time method and i've got the current
date and time if you want more information about these functions and
methods all you can do is use the help method so i'll just say help time and if
i want to fetch data about the time method i'll just say time.time and i'll hit
run so as you all can see it says that this method returns the current time in
seconds since the epoch similarly if you use help on any method or function
it will return the corresponding information about that function okay so
moving on i'll be making use of the local time method and see what it returns
so i'll just say time dot local time

and i'll hit run so as you can see on the screen i've got the current date and
time in the struct time format now to make you all understand what the struct
time class is let me get back to my presentation okay so as you all can see the
struct time class basically has nine attributes starting from the year whose
value starts from zero and goes up to nine thousand nine hundred and ninety
nine the second attribute is month whose value will be anything from one to
twelve after that is m day which means the day of the month and the values
can range anything from 1 to 31. similarly our minutes and seconds have the
values 0 to 23 0 to 59 and 0 to 61. the weekday value can be from 0 to 6
where 0 is monday y day or your day can be anything between 1 to 366 and
the final attribute is daylight saving time it's 1 if it's summer 0 if not and
minus 1 if unknown okay now that you're aware of what this struck time
format is let's come back and see what our output actually means year is 2019
month is 8th or august the date today is 8 as well and so on so i hope you're
clear with this okay so now in case you want to fetch the number of seconds
that have passed since the epoch so to do this you can make use of the mk
time method okay so all i'm going to do over here is first store the local time
in a variable say a and after that i'll take another variable b wherein i'll be
using the mk time method and i'll pass the parameter to it as a finally i'll just
print out b so as you can see on the screen the mk time method has returned
the number of seconds that have passed since the epoch till now so now in
case you want to fetch the current date and time from the struct time format
and return it in local format you can make use of the asc time method so like
i've already told you all before the local time method returns the current time
in the struct time format i'll be using the variable a which stores the struct
time format of the current date and time to convert it to the local format and
to do this i'll create some new variables ac and then i'll use asc time method
so time dot asc time and i'll pass the parameter to it as a
and then i'll just print out c okay so as you all can see over here it has taken
the struct format and has returned the local format of date and time python
also allows you to format and pass strings using the strf time method and the
strp time method the sdrf time method can take a tuple containing nine
parameters and returns a string representing the same depending on the
format code used the strp method passes a string and returns it in the struct
time format to show you all what these format codes are i'll just use the help
method and i'll pass time dot strf time as a parameter to this and i'll hit run oh
i've made a spelling mistake over here sorry guys it's strf time so as you all
can see over here i have a number of format codes which i can use to format
my date time strings okay so first let's make use of the sdrf time method so as
we all have seen i've created a variable a in which i stored the current time in
the struct time format so let me just print this out again

okay so now i want to format this output in a manner which is convenient for
me so to do this i'll use the strf method so i'll just say time i'll take another
variable say x is equal to time dot strf time i'll use the strf time method within
which i'll be using the format codes to format the date as per my choice so
first i want to print out the month so i'll use the format code mod m it's small
m guys please be careful because this is case sensitive and then between this i
just want to see a slash after this i'll just print the date i'll use mod d and then
the year so i'll use mod y sorry for the spelling mistake

i'll just print x

so as you can see on the screen i've returned the current date in the month day
year format similarly you can also pass a string and return it in the struct time
format to do this you can make use of the strp time method to do this i'll take
another variable say y and i'll pass a string to this i'll say 8th august

2019 and then i'll make use of the strp method to pass this string so i'll just
say sdr p time

and i'll pass y as a parameter to this and the format of it which is day month
and year capital b means the full name of the month and now i hit run
okay so as you all can see over here i've passed a string using the strp method
and returned it in the struct time format so now let's get back to our
presentation and take a look at the date time module the date time module is
similar to the time module consisting of all the required methods that are
essential for working with date and time some of the important methods
present in this module are the date time method which is a constructor and it
consists of two methods which is today and now that will return the current
date and time the date method will help you create a date and the time
method will help you create time which includes r minutes seconds micro
seconds and the time zone information the date time module also consists of a
from stamp method which converts the seconds to return the corresponding
date and time another very important function that's present in this module is
time delta time delta basically returns a duration which will be the difference
between two different times okay so now let's get back to our jupiter
notebook and see how this module actually works i'll just create a heading
over here

say date and i hit run the first thing that i'll have to do is import this module
so i'll say import date time after this i'll be making use of the date time
constructor to create some date so i'll say date time

and then i'll pass some values to this starting with the year which is 2019 and
the month as 6 date as 7 time as 4 minutes seconds and milliseconds and then
i'll just print this out

so as you can see on the screen i've created some random date using the
datetime constructor now in case you want to fetch the current date and time
all you can do is use the today and the now methods like i've already told you
previously so i'll say date time so i'll just copy this

and then i'll use the today method

so as you can see over here it has returned the current date and time along
with milliseconds which is very precise i can also use the now method instead
of today method over here so i'll just say now and i hit run so as you can see
both these methods return the current date and time now in case you want to
access some particular value from this date all you can do is use the attribute
name to access that particular value so in case i want to access the year and
the month all i can do is save this into a variable say v and then i can use v
dot year to access the year

so as you can see i've accessed just the year from the current date similarly
you can access anything of your choice so if i say print v dot month and then
i'll say print v dot r

and i'll hit run so as you can see the month and the r have been returned
similarly you can access any values of your choice using these attributes now
in case you want to set only date without time you can use the date method so
you just say date time dot date and then pass the date as a parameter

the time method can be used to create time without date so i'll just say it's 3
hours 45 minutes and 23 seconds so now moving on towards time delta
which is a very important method that's present in this module like i've
already told you all this method represents a duration which can either be the
sum or the difference between two different dates now to make use of this
method i'll just take some variables say b1 and i'll say date time dot time delta

and i'll pass the number of days as 20 to this you can also pass other
parameters like microseconds minutes etc okay i'll take another variable say
b2 and i'll use the same method again

and to this i'll pass the number of days as 30. now i'll take another variable
say b3 within which i'll just store the difference of b1 and b2 so i'll say b1
minus b2 and then i'll print what is b3 and the type of b3

so as you can see over here the difference between b1 and b2 is minus 10
days and the time since i've not specified anything is 0 and the type of b3
comes under the time delta class

in today's session we are going to focus on num py module available in


python so let us move forward and have a look at the agenda for today first
we'll see what is numpy then we are going to compare it with list and we'll
see why it is better than list then we are going to see various operations that
we can perform with numpy arrays and there are certain special functions as
well that we are going to focus on later in the session so let us move forward
and understand what exactly is numpy so what is numpy numpa is basically a
module or you can say a library that is available in python for scientific
computing now it contains a lot of things it contains a powerful n-
dimensional array object then tools for integrating with cc plus plus it is also
very useful in linear algebra fourier transform and random number
capabilities now let me tell you guys numpy can also be used as an efficient
multi-dimensional container for data for generic data now let me tell you
what exactly is multi-dimensional array now over here this picture actually
depicts multi-dimensional array so we have various elements that are stored
in their respective memory locations so we have one two three in their own
memory locations now why is it two dimensional it is two dimensional
because it has rows as well as columns so you can see we have three columns
and we have four rows available so that is the reason why it becomes a two-
dimensional array so if i would have had only one row then i would have said
that it is a one-dimensional array but since it contains rows as well as
columns that is it is represented in a matrix form that is why we call this as a
two-dimensional array so i hope we are clear with what exactly two-
dimensional error is so let me open my pycharm and i'll tell you practically
how to actually create a numpy array

so this is my python guys over here the first thing that you need to do is first
installed the numpy module and how you're going to do that click on file go
to settings tab and you'll see the project interpreter option and on the right
hand side you'll see a plus symbol just go on and type the module that you
want to install so i'm going to install num py just go there click on it and
install package i've already done that so i'm not going to repeat it so this is
my pie chart so first thing that i need to do is import numpy as np now after
that i need to create a numpy array so for that i'm going to define a variable
let it be a and i'm going to type in here np dot array and certain elements
inside it so i'm going to put in 1 2 3 and print it that's all

so this will actually print a single dimensional array so 1 2 3 has appeared


now if i want to convert this to a 2d array so for that i'll keep this in
parenthesis

and after a comma i'll add one more element and i'm going to give certain
values inside that so i can give say four five and six

now go ahead and print this so as you can see that it is now a two
dimensional array so this is how you actually create arrays using num py
module so now i'm going to open my slides and we'll move forward and see
what is our next topic now let us see why are we using numpy instead of a list

all right so many of you might be thinking why are we using numpy when we
have list all right so basically we use numpy because of three main reasons
the first thing is it occupies less memory when compared to lists then it is
actually pretty fast when you compare it with list and at the same time it is
very convenient to work with num py so these are the three major advantages
that num py has over lists and that is the reason why we use num py instead
of list now don't worry i'm actually going to prove it to you practically by
opening my pycharm so guys this is my pycharm again so first thing that i
need to do is import

numpy as mp and now what i'm going to do is i'm going to import a couple of
more modules i'm going to import time and i'm going to import sis all right
done so our first step is to actually define a list and the name that i'm going to
give to my list is say s and i'll type in here range thousand so what this will
actually do it will actually take all the integer values between 0 to 1000 and it
will give it to a variable s so this list will contain the integer values between 0
to 1000 but it would include 1000 it will be only there till triple nine that is
999 and now i'm going to print the space occupied by this particular list so for
that what i need to do is i need to type in print says dot get size of any one
element okay so you can give three four five anything i'm going to give it as
five any one element and multiply that with the length of my list that's all so
this will actually give me the space that has been occupied by the list because
cis dot get size off will actually give me the memory occupied by one
element and when i multiply that with length of my list i get the entire
memory that has been occupied by my list now the same i'm going to do with
my numpy array as well let me give a name to that i'm going to type in d np
dot a range

and the range will be thousand now a range function is pretty much similar to
the range which is there so the same thing will happen here the integer value
is between zero to thousand but it won't include thousand will be present in
my variable d so we have created a numpy array now let us print the space
occupied by it so the first thing is i'm going to type in here d dot size so this
will actually give me the space occupied by one single element and when i
multiply that with the length of my numpy array i get the entire memory that
is occupied by the numpy array so i'm going to type in here d dot item size
that's all now go ahead and print this so this actually shows the memory that
has been occupied by my list and this shows the memory that has been
occupied by my numpy array so as you can see there is a quite a lot of
difference between both of them so we have proved the first point that it
actually occupies less memory now when i talk about numpy array is faster
and more convenient than the list so the next step is i'm going to prove it to
you that numpy array is actually faster and more convenient than list so i'll
remove all of this and so now i'm going to show you that numpy arrays are
faster than list and at the same time it is easier and more convenient in order
to work with numpy arrays when compared to list let me show you
practically so first what i'm going to do is i'm going to define a variable say
size which is equal to say 1000 and then i'm going to define two lists now
what i'm going to do is i'm going to add those two lists as well as i'm going to
add two numpy arrays which i'm going to define now and then i'm going to
compare the time taken in order to find the sum for list and the sum for
numpy rs so first let me define two lists and two arrays so my first list will be
equal to range size same goes for my second list as well just change the name
to l2 and now i'm going to define two numpy virus a1 equal to np dot a range
size go ahead and do the same for the second numpy array as well and change
the name as a2 so we have two lists and two arrays and we need to compute
the sum of both of these list as well as arrays now before that i'm going to
define a variable say start which is equals to time dot time and now i'm going
to calculate the sum so i'm going to save that in result and first i'm going to
calculate the sum of list that is l1 and l2 so for that what i need to do is i need
to run a for loop because if i directly write l1 plus l2 it is going to give me a
result which is nothing but the concatenation of both the lists so in order to
calculate the sum i need to use for loop let me show you how to do that first
i'm going to type in x comma y and we have already studied loops in detail
for x comma y in zip and the name of the two list that is l1 comma l2 that's all
so what will happen here it will first take the first element of list cell 1 and
then it will take the first element of list l2 it will go in it will calculate sum
and store in result and it will keep on repeating until the range has been
exceeded now this is how you calculate sum in list but when you talk about
rh what you need to do is you need to just write in a1 plus a2 that's all that's
why i'm saying that it is more convenient in order to work with numpy arrays
when compared to lists now our next step is now our next step is to define the
same variable start and initialize it with time.time

and now i'm going to find the sum of my two numpy arrays which is nothing
but a1 plus a2 that's all and now print the time taken so print time dot time
minus start and then multiply it with thousand because by default it will take
it in seconds and i need to convert it into milliseconds now i forgot to actually
print the same thing for my list so i'm going to do it over here so this will
actually give me the time taken by my list in order to compute the sum and
this statement will give me the time taken by my numpy array in order to
compute the sum so let us go ahead and execute this and still see what
happens so it gives me 0 milliseconds because the size is small let me just
start a couple more zeros let's make it a million now go ahead and execute
this now you can notice the difference that there's a significant change lists
took 208 milliseconds whereas numpy array took almost 67 milliseconds so
there's a huge difference between the compute time of a list as well as numpy
array that's why i say that num py array are faster convenient and at the same
time they occupy less space when compared to list so that is the reason why
we choose numpy arrays over list so let us go ahead and move forward
towards the next topic that is numpy operations so let me go back to my
slides so now is the time to see various operations that you can perform with
the numpy arrays

so you can find the dimension of your array whether it is a two dimensional
or a single dimensional array then you can even calculate the byte size of
each element it is pretty easy i'm going to tell you that practically you don't
need to worry about that and you can even find the data types of the elements
that are stored in your array so if you want to know what is the data type of
the elements you can do that as well so let me show you these three
operations first and then we'll move forward to the other operations i'm going
to open my pycharm once more guys let me remove all of this

so we have imported the numpy module now what i'm going to do is i'm
going to define a numpy array i'm going to name it as a and i'll write here np
dot array

one comma two comma three put that in parenthesis now add one more
element say two comma three comma four all right so it's a two dimensional
array now if i want to know whether it's a two dimensional or a single
dimensional array so i'm just going to type in print a dot endem and it'll give
me the dimension so let me show you that and i'm going to run this so it says
2 that means it is a two dimensional array so what if i move this part and
make it as a single dimensional array it should give us the result as one let's
see if it does that or not and yup it gives us one as a result so this is how you
actually calculate the dimension of your array now if you want to find the
byte size of each of the elements so what you need to do is instead of ndm
you can call a function called item size go ahead execute this and you'll get so
each element occupies four bytes after that if you want to know the data type
that is stored in the array so you can just type in here d type go ahead execute
this it should give us integers integers 32-bit all right so this is how you can
actually perform these three functions that i've told you in my slides now let
us move forward and see what are the other operations that you can perform
with numpy module so by using numpy array you can actually find the size
of your array how you can do that i'll show you practically you don't need to
worry about that so when i say size of the array that means the total number
of elements that are present in the array so if this is an array so the total
number of elements become four one two three and four now you can even
find the shape of your array now what do you mean by shape so basically the
total number of columns and rows now over here we have three columns and
four rows so our shape is actually three columns and four rows now let me
show you practically how you can do that again i'm going to open my pie
chart and show you let me remove this print statement from here now if i
want to find the size of my numpy array i just need to type in print a dot size
that's all you have to do and it'll give the size of your array so there are three
elements so if i go on and add some more elements say four five six seven
then if i execute this you'll see that seven elements have appeared that means
the total number of elements in my array is seven then comes the shape part
that i was talking about so in order to find the shape what you can do is you
can just type in here a dot shape and it'll give you the shape so let us see what
happens so it has seven columns but there are no rows so it has given seven
comma blank so what i can do is i can close this in parenthesis and i can
define one more element say 8 9 10 11 12 13 14. go ahead and execute this
and you can see two comma seven because we have two rows and seven
columns available with us so this is how you can actually find the size of
your array as well as you can find the shape of your array now let us move
forward and see what are the other operations that you can perform with num
py module so we saw how to find the size and the shape of an array so we
can perform reshape as well as slicing operation using num py array now
when i talk about reshape what do you actually mean by reship when you
change the number of rows and columns that is called reshaping now over
here there is an example so we have three columns and two rows which we
have converted to two columns and three rows now let me show you that
practically how you can do it in a variable and i'm going to start a numpy
array and i'll have two elements in that my first element will be 1 comma 2
comma 3 comma 4 and my other element will be say three comma four
comma five comma six so i have a two dimensional array that contains two
rows and four columns now i can convert that to four rows and two columns
let me show you how to do that you're just going to type in a is equal to a dot
reshape and i want to convert it to say four rows and two columns go ahead
and print this

so it has converted that to four rows and two columns as you can see in front
of your screen now let me show you that earlier this is not the case i'm going
to type in a print statement here as well in order to show you that how it has
reshaped so earlier we had four columns as well as two rows but now we
have two columns and four rows so this is how you can perform the reshape
operation now let us talk about slicing so slicing is basically extracting
particular set of elements from your array and the slicing operation that
happens here is pretty much similar to the one which is there in list as well so
suppose if i want only this particular element that is three so for that what i
need to print i'll show you print a and the index value of 3 which is present at
0 comma and the index is 2. let me tell you how indexing happened so this
element will be zero this element will be one now if i want three from here to
from the zeroth element i want the index two indexing starts from zero one
and two so that's why i've written zero comma two and it should print three
for me let us see if it does that or not and yep it prints three now say if i want
to print four and six now for that what i need to do is i need to remove this
two here and i'm going to put a colon that says all the rules including zero
and in that row i want only index three so we have only two rows so if i ever
have written zero colon one then it wouldn't have included this particular row
so if i have one more element here so i can actually write here two so that
would actually include the element which is present at the second index so
when i say zero colon this actually means all the rows that includes zero as
well so we have only two rows it will include both the rows and at the same
time it'll actually going to print the third index from both of these rows so let
me show you if that happens or not and yep it happens we have four and six
available with us now just to remove confusion what i'm going to do is i'm
going to add one more element and i'm going to give values to it say 7 8 9
and 10. so now if i want 4 and 6 i can't just write 0 colon because if i do that
it'll print 10 as well let me show you that yup it has printed 10. now in order
to avoid that what i can do is i can write in here two so as i've told you this is
the zeroth element first element and the second element so when i write zero
colon two it won't include the second element it'll only include zeroth as well
as the first element now inside that we have index three from both of these
rows that is why we'll actually get four and six let us see if that happens or
not and you can see four and six is now available so this is how you can
perform slicing when we in numpy arrays now what i'm going to do is i'm
going to type in a equal to np dot line space and now over here first i write
one comma say three and i want say five values between one comma three
what this will do is it will actually print the five values which are equally
spaced between one two three so let me print this first i'm going to type in
print a and go ahead execute this and you can see that we have one then we
have 1.5 then we have 2 2.5 as well as 3. so if i would have written here 10 it
will actually give me 10 values between 1 to 3. and yup you can see we have
the 10 values between 1 to 3 so this is how you can perform line spacing as
well let me open my slides and we'll see what the other operations that you
can perform with num py so we saw how to perform reshaping and slicing
now let us see what are the other operations so we are now going to find out
the minimum maximum as well as the sum of our numpy arrays so let us go
ahead and execute that practically let me remove all of this and now i'm
going to define one more numpy array np dot array and i want elements and
let's say one two three now if i want to find the element which has the
maximum value so what i can do is i can just type in here print a dot max
that's all and it'll give me the maximum value in my a numpy array which is
three obviously if i want to find minimum values so i'm just going to type in
here min and it'll print the same for me which is one now if i want to
calculate sum it is pretty easy just go on and type sum and it'll give you the
sum that's all guys it's that simple i pretty sure there won't be any doubts here
if there are you can just ask me fine so there are no doubts so janice has a
question she's asking me is it that simple to work with numpy all right janice
so let me tell you that whatever i'm telling you these are all the basics that
you require after that whatever your requirement is there on that basis you
need to use those basic knowledge that you have and implement it now the
best way to do that now the best way to understand any programming
language is to play around with it so you know the basics with the help of
those basics just install pycharm first then try out new things like how should
i get that how should i get this and if i'm not getting it what is the reason
behind it so go on and try to discover new new things so the conclusion is
you need to actually perform things practically you need to make sure that
you're not only getting the theoretical knowledge you need to perform it
practically that's why i always say that side by side when i'm executing these
practicals you need to do that as well although you might find it pretty basic
but with the help of this knowledge you can perform a lot bigger task as well
all right so janice looks happy now so let's move forward with our slides so
now comes the access concept here guys it is pretty similar we have a numpy
array which looks like this and the rows are called axis one and columns are
called axis zero now you must be thinking what is the use of this axis suppose
if you want to calculate the sum of all the rows then you can actually use
these axis and you can do that now let me show you practically how it
happens i'm going to open my pycharm again and i'm going to show it to you
let me remove this and let me add one more element here three comma four
comma five all right so if i want to find the sum of x is zero it's very very
easy just go on and type print a dot sum and type in axis equal to zero go
ahead and print this and you can see four six and eight one plus three is four
two plus four is six similarly 3 plus 5 is 8. if i make this as axis 1 and print
this so it gives me 6 and 12 because 3 plus 2 plus 1 is 6. similarly 4 plus 5
plus 3 is 12. so this is pretty easy i know now let's go back to our slides and
see what are the other operations so there are many mathematical functions
that you can perform with numpy that is to find the square root of each
element you can even find the standard deviation so these two operations can
be performed with the help of an mpy you can find the square root you can
find the standard deviation now let me show you that how you can do it this
is my pie charm again so now i'm going to remove this print statement here
and i want to print the square root of each of the elements that are there in my
numpy array which is actually assigned to a variable a so i'm going to type in
here print

np dot sqrt that is square root of my numpy array a go ahead and execute this
and it is actually printed the square root of each of the elements the square
root of 1 is 1 for 2 it is 1.414 for 3 it is 1.73 again for 3 it is 1.73 then for 4 it
is 2 then for 5 it is 2.23 this is how you can find the square root of each of the
element now when i talk about standard deviation so you can find that by
typing here so now if i want to find the standard deviation what i need to do
is instead of sqrt i'll just type in here std and it'll give me the standard
deviation that is how much each element varies from the mean value of my
numpy array and this is the standard deviation guys it's that simple so this is
how you find standard deviation now let us go back to our slides and see
what are the other operations that are still left now these are the basic
mathematical functions that you can perform with numpy arrays like addition
multiplication subtraction and division and that will actually happen element
wise so basically you are performing matrix addition matrix multiplication
matrix division as well as matrix subtraction let me go ahead and show it to
you practically it is very very simple guys so similarly i'm going to define
one more array and let me name it as b let me remove this print statement
now if i want to calculate the sum so what i need to do is i need to type in
print a plus b that's all you need to do but when i talk about list again i'm
telling you that when i talk about list if i do that it will concatenate both the
list so if i want to print list that is the addition of two lists i need to use for
loop so that is where num py array stands apart and it is pretty convenient go
ahead and execute this and you'll see that element wise addition has happened
1 plus 1 is 2 2 plus 2 is 4 3 plus 3 is 6. similarly 3 plus 3 is 6 then 4 plus 4 is
8. 5 plus 5 is 10. all right so this is how you can perform addition you can
perform subtraction by using the subtraction operator go ahead execute this
and you'll find all zeros because one minus one two minus two three minus
three three minus three four minus four five minus five will be zero only right
no rocket science now go ahead and multiply it as well and see what happens
so you have one into one is one two into two is four three into three is nine
again three into three is nine four into four is sixteen five into five is twenty
five if i go ahead and divide this it'll give me all once and yup it does so this
is how you can actually perform addition subtraction multiplication and
division using a numpy arrays now let me go back to my slides and see what
are the other operations present so now guys let me tell you one more thing if
i actually want to concatenate two arrays i don't just wanna add those two
arrays you can say that if my one array is a box then i want another array on
top of it so let me show you how you can do that actually there are two ways
to do that one is called vertical stacking and another is called horizontal
stacking let me show it to you one by one first i'm going to show you vertical
stacking for that what i need to do is print np dot v stack and a comma b let
us see what happens when i run this so we have one two three three four five
then again we have one two three and three four five so this is called vertical
stacking if i want that horizontally i'll just write in here h stack and i'm going
to run this now and you can see that we have one two three then again one
two three that means these two are present added horizontally and we have
three four five again we have three four five so this is how you can perform
stacking as well now there's one more thing that i want to show you if i
actually want to convert this particular numpy array that is a to say a single
column so how i can do that just type in here print a dot revel that's all you
have to do go ahead and execute this so allow one two three three four five so
you have one two three three four five let me go back to my slides and see
what are the other topics that we are going to cover now come certain numpy
special functions now i'm going to talk about sine function and cosine
function first now i hope all of us know what is a sine function and what is a
cosine function so what i'm going to do is i'm going to use this cosine and
sine function and i'm going to plot sine and a cosine graph so for that i'm
going to import a module called matplotlib so you don't need to worry about
that module because i'm going to discuss about matplotlib in the upcoming
sessions so there'll be a detailed session especially on matplotlib so you don't
need to worry about what exactly matplotlib is and how it works and all those
things because that'll be covered in the upcoming session for now what we
are going to do we are just going to use sine and cosine function in order to
print their graph so for that i'll open my pycharm and let me remove this and
import my plot lip dot pie plot as plt

now we are going to define two coordinates that is x and y first x is equal to
np dot a range 0 comma 3 into np dot pi

comma 0.1 ah now i'm going to find y so for that i'll type y np dot sine x now
i'm going to use plt in order to plot the graph x comma y now finally show
the plot for that i'll type plot dot show where you must plot dot show to make
a graphics appear so plot dot show and here we go go ahead and execute this
and you might be able to see a graph and yep it is here similarly what if i
change the sign to cos and should give me the cosine graph go ahead and run
this and you can see we have a cosine graph as well similarly if i write in here
tan that is any other trigonometric function and i print this so i get the graph
for tan as well so any doubt still here guys no doubts fine so i'll open my
presentation once more and we are going to see what are the other special
functions that we can use with numpy now numpy comes with two very good
functionalities i would say that is called exponential function and logarithmic
functions now exponential this e value is somewhere equal 2.7 and we all
know log so when i talk about log it is actually log base 10 and when i'm
talking about natural log that is log base e i will write it as ln so instead of
that i've written log that means log base 10. so you can perform these
operations with the help of numpy let me show you how you can do that so
i'll open my pycharm let me remove this and i'm going to define a numpy
array let it be ar equal to np dot array one comma two comma three now i
wanna calculate the exponential value i'm going to throw in a print statement
and i'm going to write in here np dot exp ar and this will calculate the
exponential value for me and let us see if it does that or not so yep as i've told
you earlier as well value of e is 2.71 so e to the power of 1 is actually equal to
e so it has returned the e value but e to the power of 2 will be somewhere
equal to 7.38 e to the power of 3 will be somewhere equal to 20.0855 now in
order to calculate log what you can do is you can just type in here log now
this will give you natural log so when i talk about natural log it is nothing but
ln or you can say log base e but if i want to calculate log base 10 so i need to
type in here 10. first let me show you how you can find the natural log just go
ahead and execute this all right so when i talk about 1 so e to the power of 0
will be equal to 1 right so log or ln r equals to 0 similarly the other values as
well now if i want log base 10 instead of ln or you can say natural log i can
just write in 10 and go ahead execute this and you'll find log base 10 values
so obviously when answer is 1 that means anything to the power of 0 is equal
to 1. so the answer will be 0 here and similarly we have other answers as well
if you're unsure about it you can open your calculators and do that

mathematics and scientific research are definitely the ruling domains in every
era and to solve all the problems contained in them is scipy and in this
session you'll be learning how to use the scipy library of python so if you
have love for numbers this is where you have to be before we begin just make
sure you subscribe to our channel and hit the bell icon to stay updated with all
the latest edureka videos coming back towards the session we shall first begin
with a small introduction to scipy and the difference between numpy and
scipy following that we shall take a look at the sub packages present in scipy
and then take a deeper look at each of them starting with basic functions
followed by special functions integration functions fourier transforms linear
algebra and interpolation functions so let's move on towards the first topic
which is what exactly is scipy scipy is an open source python library which is
used to solve scientific and mathematical problems it is built on numpy
extension and allows users to manipulate and visualize data with a wide
range of high level commands as mentioned earlier sci-fi builds on numpy
and therefore if you have to import scipy there is no need to import numpy so
now you'd be wondering what is the difference between numpy and scipy
both numpy and scipy are python libraries used for mathematical and
numerical analysis numpy contains array data and basic operations such as
sorting indexing etc whereas scipy contains all the numerical code though
numpy provides a number of functions that can help resolve linear algebra for
your transforms etc scipy is the actual library that contains full featured
versions of these functions however if you're doing scientific analysis using
python you'll have to import both the numpy and the scipy libraries okay so
now let's move on and take a look at the sub packages present in scipy scipy
has a number of sub packages for various scientific computations as you can
see on the screen the cluster sub package is available for clustering
algorithms constants deals with physical and mathematical constants
similarly fftpack is for fast fourier transform routines integrate for integration
and ordinary differential equations interpolate for interpolation and
smoothing sp lines etc for a detailed description on each of these you can
follow the official documentation so now let's move on and take a look at the
basic functions that you can use over here since scipy builds on numpy you
can make use of numpy functions itself to handle arrays to know in depth
about these functions you can simply make use of help info or source
functions the help function returns information about any function or a
keyword or class etc now this function can be used in two ways one is
without using any parameter and the second is using a parameter i'll be
showing both these methods to you in a while similar to the help function is
the info function this function also returns information about any function or
a keyword class etc the source function on the other hand returns the source
code only for objects written in python this function does not return useful
information in case the methods or objects are written in any other language
so now let's move on towards the jupiter notebook and see how you can make
use of these functions okay so first let's take a look at the help function like
i've already told you all before the help function can be used in two ways one
is by supplying a parameter and the second is to use it without any
parameters i'll be showing you all both these methods one thing i want you all
to note is that all sub packages present in scipy need to be imported
exclusively prior to using them so in case i have to use the cluster package i'll
have to import it exclusively from the scipy library so for that i'll have to type
from scipy import cluster

and then i'll hit run okay so now making use of the help function to retrieve
information about this sub package all i have to do is type help and within
that type cluster

and hit run so as you can see all the necessary information about this sub
package has been returned by the help function so now if i want to use the
help function without passing any parameters all i have to do is type help and
hit run so as you can see it's asking me to enter the name of any module or a
keyword of which i want to retrieve information so here i'll just type
scipy.cluster

so as you can see on the screen it has returned all the necessary information
about this sub package now in case you want to stop this function from
execution all you have to do is type quit and hit enter so now if i want to use
the info function all i'm going to do is import scifi

and then type scipy dot info and pass the name of the package as cluster now
i'll hit run so as you can see this function has also returned the necessary
information about this sub package

same is the case with the source function all i have to type is scipy dot source
and pass the parameter as cluster please make a note that every time i'm using
the cluster keyword only because i've imported this package if i use the name
of any other package without importing it it's going to throw an error so now
i'll hit run okay so i hope you have understood how these three functions
work okay so now let's move on towards the next topic which are special
functions scipy provides a number of special functions that are used in
mathematical physics these functions can be anything such as convenience
functions gamma functions beta functions etc in today's session we'll take a
look at the exponential and trigonometric functions which are present within
the convenience functions sci-fi provides two functions using which you can
compute 10 power x or 2 power x where x can be any integer okay so now
let's jump on to our jupiter notebook and see how these functions work so the
first thing i'm going to do is create a heading over here

and i'll name this as special functions or i'll just say special

now i'll have to import this package from the scipy library so i'll use from
scipy import special

after this i'll take any variable say a and i'll type special dot exp of 10 which
is to compute 10 power x and for the value of x i'll write 2 and then i'll just
print a

sorry guys i had to type special.exp of 10. so as you all can see on the screen
this function has returned the value for 10 part 2 which is 100. similarly if i
have to calculate the values of 2 par x i can make use of the exp2 function so
all i'm going to do over here is take another variable say b and then i'll type
special dot exp of 2 and the value i'll pass as 3 then i'll just print b

and hit run so as you can see i've got the output for 2 part 3 which is 8. scipy
provides a number of functions that deal with trigonometry using these
functions you can calculate anything such as sine cos tan etc so now let's get
back to our jupiter notebook and see how this works okay so i'll take another
variable say c and then i'll use the sine theta function over here i'll take
another variable say c and then i'll calculate the sine value of 90 degrees i'll
use the sine dg function and i'll pass the value as 90. after this i'll just print c

as you can see the sine value of 90 degrees is 1. similarly you can also use the
cos dg function so i'll just change the name from sine to cos over here and
then hit run

okay so as you can see it has returned the value for cost 90. so i hope
everyone's clear to here in case you have any doubts please do let me know in
the chat box and my team is here to help you so now let's move on and take a
look at some of the integration functions that are present in scipy integration
is a way of adding slices to find the whole it can be used to find areas
volumes central points etc in today's session we'll be seeing how to solve
general and double integration problems sci-fi provides a function named
quad that can calculate the integral of a function which has just one variable
the limits can range anywhere between plus and minus infinity so now let me
jump onto my jupiter notebook and see how this function works i'll just create
a heading over here

so before i make use of the quad function i'll have to import the integrate sub
module from the scipy library and to do this i'll type from scipy
import integrate

after this i'll use the help function to retrieve information about the quad
function present in the integrate module

as you can see over here it has returned all the necessary information about
this function the quad function basically takes another function as a
parameter and a and b which are the lower and upper limits all the other
parameters are optional and you can try them out by yourself okay so here i'll
take a variable say i and then i'll type scifi dot integrate

dot quad the name of the function and the first thing i'll have to do is pass a
function as a parameter so i'll just use a lambda function so i'll just type
lambda of x and i'll compute the exponent of 10 for this x so i'll type special
dot exp of 10 which is the name of the function and the parameter of this will
be x so this was our first parameter and now i'll have to pass the lower and
upper limits so i'll just say 0 comma 1 and then i'll just print i

okay so i hope you all are clear to here now let's get back and see how we can
solve double integration problems a double integral as many of us know
consists of two real variables to compute this you can make use of the dbl
quad function which will take the function to be integrated as its parameter
along with four other variables which define the limits and the functions dy
and dx so to make use of this function all i'm going to do is take some
variables say e and to this i'll just assign a lambda function

and i'll pass any expression of my choice so i'll just say x star y part two now
i'll take another variable say f within which i'll store another lambda function
and to this lambda function i'll just take one argument now i have to define
another variable i'll name it as g and then a lambda function again

now i'll just make use of the double integral function so integrate dot dbl dbl
quad

and i'll have to pass the parameters starting with e and then the limits i'll just
say 0 comma 2 and then the functions f and g
okay so as you all can see this function has returned the value of the double
integral i hope everyone's clear till here so now let's get back to our
presentation and take a look at some of the fourier transform functions
present in scipy fourier analysis is a method that deals with expressing a
function as a sum of periodic components and recovering the signal from
those components to calculate this you can make use of the fft function and
the ifft function which return the discrete fourier transform and the inverse
fourier transform of a real and complex sequence so now let's move on and
see how this works

the scipy sub package that contains these functions is the fft pack so from
scipy.fftpack

i'll import fft and ifft function and now i'll just import the numpy library as np

sorry i made a spelling mistake over here it's numpy

and then i'll just take a variable x within which i'll store a numpy array with
some random values i'll take another variable say y within which i'll store the
fourier transform of x so i'll just say fft of x and then print x

sorry guys i wanted to print y and i printed x by mistake okay so as you can
see i've got a list containing the fourier transform of x in case you want to
find the inverse of it all you have to do is use the ifft function and hit run
okay so as you can see the ifft function has returned the inverse fourier
transform of x so i hope everyone's clear till here in case you have any doubts
please do let me know in the chat box and my team is here to help you so the
next topic that we'll be covering in this session is linear algebra linear algebra
deals with linear equations and their representations using vector spaces and
matrices scipy is built on atlas lapak and b last libraries and is extremely fast
in solving problems related to linear algebra in addition to all the functions
present in the numpy library scipy also provides a number of other advanced
functions also if numpy is not used along with atlas lapak and bilar support
scipy is much faster compared to numpy so now let's move on towards the
jupiter notebook and see how to solve linear algebra problems
okay the example that i am taking over here is finding the inverse of a matrix
mathematically the inverse of a matrix a is a matrix b such that a star b is
equal to an identity matrix an identity matrix is a matrix consisting of ones
down the main diagonal to compute this you can make use of the inv function
present in scipy to do this i'll just take a variable say a and within this i'll just
store a numpy array and this time i'm going to create a two-dimensional array
i'll just pass some random values

and i'll store the inverse of a in b

finally i'll just print b

oh one thing i forgot to do over here is import the sub module so i'll just type
from scipy from scipy import lin edge and then i'll hit run okay as you all can
see i've computed the inverse of a using the inv function so now let's get back
to our presentation and take a look at the final topic of this session wherein
we'll take a look at the interpolate sub package of scipy in the field of
numerical analysis interpolation refers to constructing new data points within
a set of known data points the scipy library consists of a sub package named
scipy.interpolate that consists of sp line functions and classes one-
dimensional and multi-dimensional interpolation classes etc in today's session
i'll be showing you all how you can solve univariate interpolation problems
univariate interpolation is basically an area of curve fitting which finds the
curve that provides an exact fit to the series of two dimensional data points to
do this you can make use of the interp 1d function present in scipy

so i already have a code for this i'll just copy it i'll paste it over here so as you
can see i'm making use of the interp 1d function to find x1 and y1 which
range between x and y so all i'm going to do is hit run so as you all can see x1
and y1 have been computed for between x and y

in today's session we'll be focusing on data analysis with python so let us


move forward and have a look at the agenda for today so first we'll see
various applications of python after that we'll understand the data life cycle
starting from data warehousing till data visualization then we'll focus on data
analysis and we'll see how we can use python for that purpose we'll also look
at what is pandas library and we'll also understand a bit about numpy and
scipy then we'll focus on various pandas operations merging joining all those
things and we'll see after that python for statistics and python for hadoop so
we'll move forward and we'll see what are the various applications of python
so these are the applications of python i have listed only four of those
although there are many more so you can perform web scraping with python
that is you can extract certain contents from a particular web page you can
perform a web development you can perform testing as well as you can
perform data analysis so for today's session we'll be focusing on a data
analysis part of python so guys let us move forward and see what exactly is
data lifecycle

so this is the data lifecycle guys over here what happened data is stored in
different formats we have a csv file we can have an excel file or an html file
so data is basically stored in different formats now what you do you actually
convert that data or transform that data into a single format and you store it
somewhere that's where data warehousing comes into picture now once you
have stored your data you can perform certain analysis on it you can perform
predictive modeling you can join merge data so various other things that we
are going to see in today's session now once you have done the analysis you
can even plot it in the form of a graph and that stage is called a data
visualization so this is just a general overview about data lifecycle and in
today's session let me tell you guys we'll be focusing on only data analysis
here so let's move forward and understand what exactly is data analysis so
what is data analysis so let us understand data analysis with the help of an
example that is there in front of your screen over here what happens we have
a data set in which we have data about the unemployed youth across the
globe so country wise from 2010 to 2014 the percentage of youth that is
unemployed within that particular country we have data about that now what
if i want to find only for a particular country say afghanistan in this example
and in that particular country i want to find the unemployed youth between
2010 to 2011 or you can say percentage increase in the unemployed youth in
afghanistan between 2010 to 2011. now what should i do so basically what i
need to do is in this particular data set i need to perform certain analysis that
analysis should give me the percentage increase in unemployed youth in
afghanistan between 2010 to 2011. so this basically explains what is data
analysis and why we use it so let us move forward and understand how you
can actually perform data analysis with python so basically to perform data
analysis with python you need to import a particular module which is called
pandas so let us discuss about pandas in the upcoming slides what is pandas
pandas is a software module written for python programming language which
is used for data manipulation and data analysis now it can perform that at a
fairly high performance rate when it is compared to other python procedures
now we can say that pandas is actually built on top of numpy scipy and
matplotlib matplotlib is basically a data visualization module that we use in
python now when we talk about numpy and scifi numpy is actually a
fundamental package for scientific computing in python so it contains a
powerful n-dimensional array object it has tools for integrating with cc plus
plus and it is very useful in performing linear algebra fourier transform
random number capabilities etc when i talk about scipy scipy is again an open
source python module used for scientific computing and technical computing
scipy contains module for optimization linear algebra integration
interpolation special functions fourier transforms all those things right we'll
actually focus on numpy and scipy in the next session for this session we'll be
only focusing on pandas and we have a separate session on matplotlib as well
where i'll teach you exactly how to perform a data visualization using
matplotlib so i'll open my pycharm and i'll actually tell you how to import
this pandas library and how to actually create a data frame so for that i'll open
my pycharm once

so this is my pycharm guys so over here what i need to do is i need to first


import the pandavas module so for that i'll type import pandas as pd that's
what they usually keep so yeah let's follow the protocols and now what i'm
going to do is i'm going to define a dictionary say that contains the data about
say my website so we can have columns like day visitors bounce rate all right
so let's go ahead with that i'm going to name my dictionary say as x y z
underscore web so over here my first key will be day day and it'll actually
include the day so it'll have a list of days one two three four five and six yeah
now my next key value pair will be actually about visitors so i'll write in
visitors
so visitors in day one say we had around 000 visitors then we had 700 then
we had say 6 000 then we had around 1k again then 400 and then say 350 yep
so the next key value pair that i'm going to add is a bounce rate bounce rate is
nothing but the number of people who have visited your website but have left
your website immediately so yeah which is not good for any website bounce
underscore rate so bounce rate will be around say 20 again 20 second day
also make it 23 then say 15 10 and 34 yep so now what i'm going to do is i'm
going to close this dictionary and now what i'm going to do is i'm going to
convert this dictionary into a pandas data frame now how we do that let me
first declare a variable say df and over here what i'm going to type in i'm
going to type in as pd for pandas pd dot data frame and the name of my
dictionary which is x y z web now go ahead and print this data frame and
we'll see what exactly happens

so yep it has converted our dictionary into a data frame so what all columns
we have we have bounce rate we have day and we have visitors so this is a
very basic introductory example for you all guys in order to show you how to
make data frames using pandas library so i'll open my slides and we'll move
forward and have a look at various operations that you can perform on pandas
data frame so these are the operations that you can perform with pandas data
frame you can slice the data frame that is if you want only a particular part of
that data frame you can do that you can change the index value you can
convert the data into a different format you can actually change the column
headers you can perform concatenation of multiple data frames and you can
even perform joining and merging of two or more data frames these are all
the basic operations that you can perform with pandas so we'll move forward
and have a look at these operations one by one first we'll look at slicing so
over here we have a data in which there is an index value which is nothing
but the year 2001 2 3 and 4. here we have interest rate and here we have us
gtp in thousands now i want to slice a particular column from this particular
data frame so what will happen if i do that it should only give me so when i
slice only the starting two rows it will give me only till 2002 but when i slice
the last two rows it will give me only for 2003 and 2004 so this is how you
can perform slicing so let me show you guys practically how to do that so this
is our data frame guys and over here if i only want say the starting two rows
so for that what i can do is
instead of print df i can do it as print df dot head and i want only the starting
two rows so i'll keep two here and we'll see what happens when i execute this
so yep there are only two rows that are present so this is how you can actually
print only a part of the data and if i want only the last part of the data that is
the last two rows so what i can do is i can convert this to tail instead and we
can do that as well go ahead and execute this and yep you can see that it has
printed the last two rows so this is how you can perform slicing so i'll move
forward and we'll look at the other operations that you can perform with
pandas after slicing we are going to talk about merging so what is merging let
me explain you that with the help of an example that is there in front of your
screen so over here we have two data frames and in one data frame we have
index values from 2001 to 2004 and in another data frame we have index
values from 2005 to 2008 now what happens when i merge both of these data
frames let us see what happens now these two data frames can be merged
together to form a single data frame and we can actually make sure what all
columns that we need to keep common so over here we have common
columns as hpi interest rate and index but when i talk about gdp we have two
us gdps one is x and another is y so this is how actually you can perform
merging you can actually make sure what all columns you want in your final
merged data frame so i'll open my pycharm once again so this is my pycharm
again guys i'm going to show you the merge operation so for that what i need
to do is i need to import this pandora's module so for that i'll type and import
pandas as pd and now what i'm going to do is i'm going to define a three data
frames let me name it as df one and over here what i'll type in i'll type in pd
dot data frame and i'm going to use a tuple and inside the tuple i'm going to
define a dictionary and i'll be using multiple lists inside that dictionary so the
first key that i'll use is hpi house pricing index and the value that i'll assign it
to hpi is a list and in that list i'll play certain values so let it be 80 comma 90
comma 70 comma 60 all right so now i'm going to define one more key and
i'm going to name it as interest underscore rate and the value that is assigned
to this is a list which contains the interest rate so i'll type in 2 comma 1
comma 2 comma 3. now i'm going to define one more key and i'm going to
name it as say ind underscore gdp and now i'm going to define a list here so
for that i'll type in the values 50 comma 45 comma 45 comma 67. all right so
what i'm going to do now is i'm going to close this dictionary and i'm going to
define the index values so for that i'll type in as index equal to whatever the
values that i want in my index so i just want the year so i'll type in 2001
comma 2002 comma 2003 comma 2004 so this is our first data frame in our
second data frame also we'll do something like similar to this i'll type in pd
dot data frame open and close parenthesis and over here i'm going to define
the same key value pair that is hpi let me copy it

all right so we have hpi now i'll define one more key value pair and that is
interest rate so again i'm going to copy this whole thing and i'm going to
paste it here and the same india's gdp also i'm going to copy in and i'm going
to paste it here now as in i've done in the previous data frame as well i'm
going to define the index values for that i'll type in index equal to a list and
my index values will start from 2005 so i'll type in 2005 comma 2006 comma
2007 comma 2008 i forgot the comma here so yeah comma and now we have
two data frames so now what i can do is i can go on and merge these two data
frames so for that what i'll type in i'll define one variable say merge equal to
pd dot merge and the data frames that is df1 comma df2 now go ahead and
print merge and we'll see what happens print merge go on and print this so as
you can see that we have merged the two data frame that is df1 and df2 and
we have got one single data frame now what if i don't want to keep certain
columns as common when i perform the merge operation so what i can do is i
can write in the columns that i want to keep as common so suppose if i want
only the hpi column to be common so i'll just type in here on hpi and when i
go ahead and print this so as you can see only this particular column is
common that is hpi rest everything we have two different columns for that
that is india's gdp that is x and y again we have interest rate as x and y what
i'll do i'll again open my slides and we'll see the other operations that you can
perform with pandas so we saw merging operation right now let us move
forward and have a look at the next operation that is joining so in joining
what happens the two data frames are joined on the basis of their index
values so let me show you that so we have two data frames one is this and
another one is this so over here what happens when we join both of these data
frames so let us see what happens as you can see that by joining these two
data frames we get this one single data frame now one thing to notice here
guys as i've told you earlier as well joining happens with the index values so
over here you can see that we don't have any index called 2005 over here as
you can see that we have no index that is 2005 but after joining the 2005
index appears in the data frame but there is no interest rate or usgdp
thousands associated with it similarly when i talk about the data frame two
that is the second data frame over here we don't have any 2002 index value so
the value with respect to 2002 will be nan and for unemployment also it will
remain as nan now you must be wondering what is n a n so when there is no
value attached to a particular index it writes this as n a n that means not a
number so let me practically show you how to perform a joining i'll again
open my pycharm and we are going to perform join operation in that so this is
my pycharm guys and over here i have two data frames df1 and df2 which i
actually use in order to show you the merge operation now for join operation
what i'm going to do is i'm going to remove this hpi key value pair from the
dictionary and same i'm going to do it for the second data frame as well and
instead of interest rate i'm going to write in here as low tier hpi low
underscore tier underscore hpi and certain values to it so yep i'm going to
type in here as 50 comma 45 comma 67 comma 34 and instead of india gdp i
am going to type in here as an employment and certain values to it so i'm
going to name it as one three seven six five six one three five six sorry all
right express it anything doesn't matter now let me just change these index
values so i'm going to type in here as 2001 2003 2004 and yeah let this be
2004 only and now what i'm going to do is i'm going to type in joined equal
to df1 dot join df2 and print joined let's go ahead and execute this and see
what happens so over here what happens in in 2002 we have no values that is
attached to lower tier hpi and unemployment so it has actually printed nan
that is not a number and in 2004 we actually have both the values available so
it has printed that so i'll again open my slides and we'll see the other
operations that we can perform with pandas so we saw exactly how to join
two data frames and let us move forward and see what is the other operation
now we are going to change the index and column headers now let us see
what how this actually happens so we have two data frames here so one
contains index interest rate and us gdp in thousands another has index as the
year and we have only usgdp thousands there is no interest rate here so what
happens when i change the column headers or i change the index so over here
as you can see i've changed the index value as the interest rate and i've
changed the column header as gdp instead of usgdp in thousands so don't
worry guys i'll actually open my pie chart and show you practically how to do
this

now first what i'm going to do is i'm going to remove all of this and i'm going
to define one data frame let it be df and now over here i'm going to type in
key value pairs in a dictionary so first of all i'll write in say day and inside
that i'll type in 1 comma 2 comma 3 comma five or four now one more key
value pair so i'll type in here as visitors so in day one we had around 200
visitors then we had 100 visitors then 230 and then we had 300 visitors 230
and then we had 300 visitors and i'll give a one more comma and i'm going to
define one more key value pair so for that i'm going to use the key as bounce
rate and and i've already explained you what exactly bounce rate is so i'm just
going to type in the values 20 45 comma 60 comma 10. all right so we have
this particular dictionary so in that dictionary let me convert this to a pandas
data frame for that i'll type in pd dot data frame and it'll convert this to a data
frame let me open and close parentheses as i forgot i'll convert this o to a
lowercase o and yeah i have made a mistake in the syntax so it actually has
open and close parenthesis

i need to add e also here now go ahead and print this so we have got this
particular data frame now i want to change this index value say i want day
here to be my index value so for that what i can do is i can type in here as df
dot set underscore index and i want my index to be day and that's it now go
ahead and print this and we'll see what happens

and over here i need to type in here as in place equals to true now when i go
ahead and print this as you can see day has become my index value so this is
pretty easy guys so you just need to set your index value whatever you want
and you can get that data frame with it now my next task is to convert one of
the column headers so say instead of day i want to convert it to date so let me
first remove this so now i want to convert one of the column headers so for
that what i can do is df

so as you can see we have successfully changed the index value to day so i
can even plot this so for that what i need to do is i need to just import one
more library which is matplotlib i'll have a separate session on matplotlib so
you don't need to worry much about it
now plot tip dot pi plot

plt now import from matplotlib import style

import style all right and now what i'm going to type in here i'm going to type
in style dot use 538 yep i'll keep it as 538

and now i'll remove this print statement now what i'm going to do is i'm
going to type in df dot plot

plt dot show go ahead and execute this

so we have got a graph in which the bounce rate is represented by the blue
color line and the red color line represents visitors so these are our index
value or you can say the day and these are the values corresponding to that
particular day so this is how you can actually plot it now our next task is to
actually change one of the column headers so for that how what i can do is
first let me remove all of this now suppose if i want to change the column
header from visitors to users so how am i going to approach this task now
what i'm going to do is i'm going to type in here as df equals to df dot rename
columns equal to i want to replace visitors with with what i want to replace it
i can replace it with users now go ahead and print df and you can see that
column header has been changed instead of visitors we have users now so
this is how you can actually change the column errors and index values so i'll
open my slides again and we'll see what are the other operations with pandas

concatenation so you have a student data in which you have name age sex
and phone number now you want to add email address to this particular data
so you can perform concatenation and add the email address field at the end
of this particular data don't worry guys i'll actually show you practically how
to perform concatenation

so this is my pycharm guys so in order to show you concatenation i'm going


to paste the two data frames that i have created earlier i don't want to type it
again because it's going to take a lot of time so i'm just pasting it now in order
to perform concatenation i'm going to declare a variable say concat equal to
pd.concat

df1 comma df2 go ahead and print this and we'll see what happens

so yep as you can see that we have concatenated the two data frames so the
index values are from 2004 for the first data frame and then it starts from
2005 to 2008 for the second data frame so as you can see that concatenation
has been successfully performed so we have index values from 2001 to 2008
and for the first data frame it is still 2004 and for the second data frame it
starts from 2005 till 2008. so this is how you can perform concatenation so i'll
again go back to my slides and see what is the next operation that we are
going to see now comes data munching so data munching basically means
that you can actually convert a particular format of data into a different
format so if you have a data which is in say csv file you can convert that to an
html similarly you can perform that operation with the other data formats as
well so let me actually show you that i'll again open my pycharm so this is
my pycharm guys let me first remove all of this and i'm going to actually read
a csc file which is there in my system locally it is present in my system so i'm
going to read that file so for that what i'm going to do is i'm going to type in
this this is nothing but i have defined a variable country and in that country
what i'm doing is i'm using the partners module in order to read the csv file
which is present at this particular location and finally this index underscore
call equals to zero actually make sure that i have no index present in that
particular data frame that's all so now what is the operation that we are going
to see here we are going to convert the csv file into an html file so for that
what i'm going to type in country dot to underscore html

open close parenthesis and i can say edu dot html now go ahead and execute
this and we'll see what happens and i'm going to open my projects folder as
you can see that edu.html is added when i click over there it gives me the
html code for that now what i can do i can copy this path and i'm going to
open my browser and i'm going to paste that path and we'll see what happens
yep so we have got this particular html table so it was in csc format we
converted this to an html format so this is how you perform data munching
with pandas so we'll be more specific and we'll see a use case in which we
have the data about the global youth unemployment and let me show you
how it looks i'll open my slides again

so we have a data set in which we have the percentage of unemployed youth


globally so for every country we have the data of the percentage of
unemployed youth from 2010 till 2014. so what is the problem statement for
this particular case study let us move forward and see that so basically i want
to find the change in the percentage of unemployed youth for every country
from 2010 to 2011. so what i want i want to see how the trend is what is the
percentage change between 2010 to 2011 for every country so we'll see that
first let me show you how the data set looks like so it looks something like
this we have the country name then we have country code but then 2010 the
percentage of unemployed youth same goes for 11 12 13 and 14. so this is
how our data set actually looks like so this is our data set looks like we have
the country name then we have the country code and then over here we have
in 2010 the percentage of unemployed youth for similarly for 11 12 13 and
14 as well so let us move forward and actually perform this data analysis in
which we are going to find out the percentage change in the unemployed
youth between 2010 to 2011. so for that again i'll open my pie charm so let
me first remove all this so now i already have the code in order to do that so
what i'm going to do is i'm going to paste it and i'm going to explain you what
exactly i'm doing so this is the code guys over here first i've imported a
couple of libraries i've wanted pandas i've imported pandas matplotlib for
visualization and the style is 538. let me tell you guys you don't need to
worry a lot about visualization because i'm going to teach you visualization in
detail in the upcoming sessions so for now just focus on pandas and the
various operations that we can perform with it now i've defined one data
frame that is country and this is pde read that csv which is present in this
particular path so i have my data set which is present in this particular path
and then what i've done i've made the index value as zero that means i don't
want any index that's all after that i've defined one more data set df in which
there will be only the top five values of the particular data set that means it
will contain only the first five rows of the data frame country after that what i
have done i have defined an index value that is country code i only wanted
country code to be my index value and after that i have defined one more data
frames sd in which i want to re-index the columns that is i want only 2010
and 2011 to be my columns that's all so let me first show you how this sd data
frame looks like let me comment this first

and i'll show you how sd looks like

so yep as you can see we have the index value as country code and we have
only 2010 and 2011 column headers that is only for the five rows all right so
this is how my sd data frame looks like now let me uncomment these lines
and i'll remove this print statement now after that what i've done i've defined
one more data frame db which is nothing but the difference of index
difference between the two columns that is 2010 and 2011. so that will
actually give me the percentage change in each and every country between
2010 to 2011 in the percentage of unemployed youth so after that i'm using a
bar plot so finally i've just shown it with the help of a graph let me show you
how this looks like i'm going to run this and we'll see what happens so yep
this is a graph over here as you can notice in afghanistan between 2010 to
2011 there has been almost a rise of 0.25 percent of unemployed youth and
when i talk about ago that is angola in that there is a negative trend that
means the percentage of unemployed youth in angola has been reduced when
i talk about albania in albania it has increased that is from 2010 to 2011 there
is an increase of around 1.25 percentage of unemployed use in the country
when i talk about arab world almost 3.1 percent of increase is there in terms
respect to a percentage of unemployed youth between 2010 to 2011. and for a
re that is united arab emirates there has been no change that means in 2010
and 2011 there were exactly the same percentage of youth that was
unemployed now over here i can perform multiple operations as well say if i
want to find out this for 2011 and 2012. so i can just keep it that way and i
can just go on and run this so as you can see here in afghanistan between
2011 to 2012 the percentage of unemployed youth has went down by almost
1.25 percent when i talk about angola there's no change for albania it has
increased around 1.5 percent and it has increased to one percent for a united
arab emirates there has been no change this so this is one example that i've
shown you where we have performed an analysis on global youth
unemployment data this is just an introductory example pretty basic example
that i've shown you there are a lot more things that you can perform with
pandas so we are going to discuss all those things in the upcoming sessions
but for now this is what partners is and this is how you can perform data
analysis i'll open my slides and we'll see what it has to offer us now we are
going to see how we can use python for statistics so i've shown you four basic
operations that are mean mode median and variance let me explain you all
these terms so what do you mean by mean mean is nothing but the automatic
mean or the average value of a particular list or any particular sequence when
we talk about median median is what the median the middle value so they
can be high median and low median then we have a sequence in which there
are odd number of elements so that time median will be the center most value
but when we have even number of elements in a particular sequence at that
time we have high median and low medium in high median what happens the
two center values the higher value is taken as the median and in low median
amongst the two center values the lower values taken as the median when we
only calculate the period for even number of elements then the two centre
most values the average of those values will be taken as median so i hope you
are clear with what exactly median is there's no rocket science behind it it's
pretty easy now when we talk about mode mode means nothing but a value
that has been repeated the most so over here we can see that one has been
repeated four times three ones four four four tries five ones and two as also
once now when we talk about variance variance is nothing but what is the
variation of each and every element in the sequence from the arithmetic mean
i am going to open my pycharm and perform these things practically so this is
my pycharm guys so over here what i'm going to do is i'm going to import
certain modules so i'll type in from statistics import mean and i'll type in print
mean and the sequence so i can type in one two two two one three four one
five one five now go ahead and execute this and yep it has given us the mean
value or the automatic mean of the sequence that we have given so now from
median i'm again going to import the statistics module and from that import
median print median and the sequence so let it be one comma one comma
one comma two comma two all right let's give it us five elements so it'll print
the center most element that is one as you can see here one is here that is at
the third position we have two elements here and two elements here so it has
printed the center most element or the middle element now instead of median
if i want to find in mode here so for that i just type in mode and i'll change
this to mode go ahead execute this and yep as you can see one has been
repeated thrice whereas two has been repeated only twice so one has been
repeated the most so it becomes the mode now you can even find variance
here variance as i've told you earlier as well it gives you the variation in the
elements from the arithmetic mean go ahead execute this and yep you can see
the variation is 0.3 so this is how you can actually use it for statistics as well
so we'll move forward and understand how you can use python with hadoop
so i'll open my slides once more so guys you can use python for hadoop as
well now what happens you need to import a library called pi do and you can
write a mapreduce program in python and process data that is present in hdfs
cluster now let me explain you with the help of flow diagram that is there in
front of your screen so you have some input data which is stored in your hdfs
cluster across various theta nodes now what happens you write a logic in
python in order to process that data on the respective node managers where
data is stored now this stage is basically called map phase and it will produce
some intermediate output so how much of a node manages you have you'll
have that many outputs and that will be given to our reducer now what
happens in the reduced space so this reduced phase happens in the node
managers what will happen whatever the output that comes from the map
phase will be provided as the input to this reduced phase and it will aggregate
that and provide us with the output now i know you might not understand
node managers you might not understand data nodes all those things so we
are actually going to discuss about this later in the upcoming sessions so you
don't need to worry about it right now but i'm just giving a general overview
and i'm just basically telling you that you can use python in order to process
big data across the hdfs cluster which is present across the hdfs cluster

in today's session we'll be focusing on matplotlib module president python so


let us move forward and have a look at the agenda for today first we'll see
why we need data visualization and what exactly is data visualization after
that we'll understand matplotlib and various types of plots like bar plot
histograms all those things then we'll get started with it and i'll tell you how
to plot each of these graphs using python so we'll move forward and we'll
understand why we need data visualization so why we need data visualization
now let us take an example suppose you work in an organization as an
analyst and you have made certain analysis now you need to show that
analysis to your boss or your ceo whatever now now you can understand it by
just looking at the excel sheet and the numbers but the other person is not an
analyst he's not that technically sound as you are so what do you need to do
you need to present your analysis or your data in such a way that the other
person can understand and how you can do that you can do that by
representing it in the form of a graph and it is a well-known fact that human
brain can process information easily when it is in pictorial or graphical form
so that is one of the key reasons why we use a data visualization in order to
understand the trend better and make better decisions so let us move forward
and understand one more reason why we need data visualization now
basically it allows us to quickly interpret the data like whatever the trend the
data is showing us now basically it allows us to quickly interpret the data so
just by looking at the graph we can understand what the data is about and
what is the trend but if you are not from an analytics background and you see
just the excel sheet then it is very tough for you to understand it so if it is
there in the graphical form you will quickly understand it and you can
experiment as well now what happens if you want to change certain variables
and see what will be the outcome so with the help of the graphical
representation of your data that will give you a very good idea as to what all
variables are useful for you and what all variables are useless you don't need
to include in your analysis in order to perform that experiment in an efficient
and a quick way you need data visualization so guys these are the two key
reasons why we need a data visualization so we'll move forward and
understand what exactly is data visualization so what is data visualization so
data visualization is nothing but the presentation of your data in a pictorial or
a graphical format now why we do that we do that in order to enable the
decision makers of an organization to see the analytics presented visually so
that they can grasp some difficult concepts or identify new patents you can
use it to identify the areas that need attention or improvement in the
organization you can even use it in order to clarify which factors influence
customer behavior now it might depend on the season or anything else
basically now you can even use it to understand which products to place
where now this is very important guys obviously you won't be selling jackets
or sweaters in summers right you and you won't be selling shaving cream to
kids so you should know what are your target audience and where you yours
where you are selling your product and to whom are you selling your product
so that is one very important uh field where we need data visualization and
you can even use it to predict sales volume as well fine guys so we have
looked at a lot of examples for data visualization now let us understand the
diagram that is there in front of your screen so it basically tells you about
how to find insights from your data now for that we need data visualization it
plays a very very important role and it is one of the major applications of data
visualization in order to find insights in data now there's a process that has to
be followed in order to do that so it starts with visualize the first step is
visualize so basically you understand what your data is you visualize it in a
form of a graph and you understand what that data is actually talking about
now we'll take an example suppose you have a data set that tells you about
the youth percentage of unemployed youth country-wise from 2010 to 2014.
all right so you have that data then you visualize it the moment you visualize
it you'll get to know that okay it's fine this country has a lot of unemployed
youth whereas this country is doing pretty good so accordingly you just you
just grasp it pretty easily when you visualize it after that you make certain
analysis now what sort of analysis suppose if i take the same example
forward if i want to find out the change in the percentage of unemployed use
between 2011 to 2010 so that will come under analysis phase so i'll analyze it
after that what comes is document insight now you have done that analysis
but what is the outcome of that analysis now i'll see what all countries are
doing good i mean the percentage of unemployed youth have gone up and
which country it has gone down and from what all countries it is stable there's
no change so we'll see that and make a document after that we transform our
data set now there might be certain fields in my data that i don't need so at
that time what i'll do i'll transform my data set i'll remove those fields or there
might be certain feeds that i need and which is not there so i'll add those
fields so accordingly i'll transform my data set and once i've done that i'll
again visualize it in order to understand what my data is now talking about
and this process will keep on repeating so this is how you find insights and
data where visualization plays a very very important role guys so we'll move
forward and understand what exactly is matplotlib now it is very important
for us to understand as to how matplotlib works fundamentally now it is
pretty easy and pretty basic you have some data then your computer will
draw that data to a canvas of some sort but it is only in the computer's
memory now once your computer has drawn that data you can show that data
so this is so the computer can first draw everything and then perform the
more laborious task of showing it on the screen very basic i know you might
find it pretty lame but it is very important for us to understand how
fundamentally matplotlib works so you have an example in front of your
screen so again we have the data in which we have country-wise percentage
of unemployed youth and i've done some analysis and i've shown it
graphically the percentage change in the unemployed youth country-wise
between 2010 to 2011. so this is how that plot looks like it is nothing but a
bar plot now there are various types of plots available we'll have a look at few
of those in the next slide so we'll move forward and see what are the various
types of plots so i've listed down six types of plots first is the bar graph then
histograms scatter plot pi plot hexagonal bin plot and area plot we are going
to plot all these things in today's session with the help of matplotlib module
so we'll move forward and we'll get started with it we'll write our first
matplotlib code so here's the most basic code in order to generate one of the
most simple graph so let me explain you this code first of all what i've done i
have imported pi plot from matplotlib as plt then i'll use this pi plot in order
to plot the graph in the canvas and then finally i'll use this plt which is
nothing but pi plot in order to show what we have got all right so pretty basic
guys so what i'll do i'll open my pycharm and execute this practically so this
is my pycharm guys so over here i'll first create a python file with dot py
extension and i'm going to name it as first code now over here i'll first import
pi plot from matplotlib so for that i'll type from matplotlib import pi plot as
plt now this plt is pretty much similar to np that we were using in numpy
array if you can recall so it is not mandatory to use plt only you can use
whatever you want but a lot of people use it as plt and i'll keep it that way
now our next step is to plot our graph to the canvas so for that what i'll do i'll
type in plt dot plot and i'll write in here my x and y axis values so for x axis
i'll keep it as one comma two comma three and then for y-axis i'm gonna add
values such as four five and one so this will plot our graph in the canvas now
final step is to show that plot how we'll do that i'll just type in here plt dot
show and we'll execute this and see what happens run first code and yup this
is how our first basic graph looks like so with three lines of code you have
got this graph so we'll move forward and we'll see how to actually add title
labels to our graph for that i'll open my slides once more so now of course
there are some problems with our graph first off we have actually learned in
school that we are supposed to put labels on each axis and we need to also
add a title to our graph it actually doesn't make sense our graph doesn't make
sense if there are no x and y axis labels and a title so you don't know what is
axis you don't know what is x axis you don't know what is y axis and what is
the graph about plus in terms of programming it is very unlikely that you'll be
actually filling in data to the plt dot plot function now over here you can
notice that we are actually filling in data like 1 2 3 4 5 1. instead you will be
passing variables into it all right so it should be something like plt.plot and
you can say x comma y if you have defined variables x comma y all right so
now let us show plotting variables as well as adding some descriptive labels
and a good title so we'll move forward and see how to add title labels and
plotting variables now the code is pretty much similar to the previous one but
it has few extra fields let me explain you that so of course i've imported the pi
plot from matplotlib after that what i've done i've defined two variables x and
y and i have certain values in it like 5 8 10 and 12 16 6. you can put whatever
values you want and this can even contain a data frame a pandas data frame
that has a data set after that what i've done i've defined plt.plot function in
which i have x and y instead of filling the data i'm putting in variables that
actually contain data after that i've added a title which is info then y label
which is nothing but y axis and x label which is nothing but x-axis after that i
need to show my plot so for that i've done plt dot show and the result is there
in front of your screen we have a title we have labels for x-axis and y-axis
now let me open my pycharm and execute this practically this is my pycharm
again guys so i'll remove till here and obviously i need pi plot function from
matplotlib so now i will define x and y variable so in x it'll have a list of
numbers say 5 8 and 10. and now i'll define one more variable y which again
has list of numbers 12 16 and 6 12 16 and 6. yep now what is that next step
guys can anyone answer me all right so i've got a correct answer from theon
he's saying a plt dot plot function which is absolutely correct so i'll write in
here plt dot plot and instead of filling in data i'll be passing variables all right
and now our next step is to add title and x label as well as y label so in order
to add title i will write here plt dot title and the title of my graph so i can just
write here info and now i'm going to define x and y labels for that i'll type in
plt dot y label and i'm going to name it as y-axis similarly for x label i'm
going to do the same thing x axis all right now finally i'll type in plt dot show
now go ahead and run this so you can see that we have a graph that contains
the title info y-axis is a y label as well as x-axis as the x-label now i'll again
open my slides and we'll see what next are we going to see now this graph is
pretty much incomplete or ugly i would say because what if i want to change
the width of this particular line what if i want to add some grid lines what if i
want to change the color so all those things how will i do that don't worry the
next slide will actually tell you the same how to add style to your graph so
how to add style to your graph for that first thing that you need to do is
import the style function from matplotlib module after that you need to call it
style.use ggplot so whatever plot that you want to use i'm using jgplot right
now then again i've defined four variables x y x2 and y2 and all of these
contains list of numbers again i'm telling you it can be a data frame as well
which contains a data set then what i've done again i have used plt.plot
function but over here apart from x and y there are many other fields so don't
get confused i'll explain it to you it's very very easy so this thing g actually
tells me that the color of my line should be green then this is label so this
label is not for your x-axis or y-axis it is for your curve which is line one you
can give whatever name you want then we have line width i want the width
of my line to be five so i've put in here five similarly i've done for the next
plot as well then i've added title which you know how to do that similarly y
label and x label now after that i'm using this legend function in in order to
add a legend to my graph over here you can notice that we have it present in
our graph where i'm pointing with my highlighter right now so we have line
one and line two after that what i've done i have added grid lines to my graph
which is of the color k which is nothing but black so you can see it in my
graph as well we have grid lines available and finally plt dot show so i'll open
my pycharm again and i'll show you how you can do that practically so this is
my pycharm again guys let me first remove all of this and i need to import
the style function so for that i'll type from matplotlib import style that's it
style.use

ggplot now define the variables first will be x add certain values to it alarm 5
8 10 5 8 10 then y i'm going to add a list of numbers 12 16 6.

now one more variable x 2 again it'll have list of numbers which will be 6 9
11.

then i'm going to use y2 variable and i'll add some numbers to it 6 15 and 7.
all right so now i'm going to use plt.plot function

and over here first i write x comma y

then now given a color to it i'm going to give it as green next label

line one now line width

is equal to five now again for x2 and y2 i'm going to type in plt.plot x2
comma y2 comma the color then label

so i'm going to type in line 2 then comes line width

all right so now our next step is to add title to our plot so plot plt dot title and
the title that i'm going to give is info again then x and y labels plt dot y label

y axis then plt dot x label x axis tlt dot show now go ahead and run this so
over here i have not added any grid lines i can do that as well so for that let
me first close it fine so i've defined title x label as well as y label now our last
task is to actually add grid lines so for that i'll type plt dot grid and just write
in here true comma give a color i want it black so i'll keep it that way finally
show your plot so plt dot show that's all go ahead and run this so you can see
that this is our graph so we have changed the default line width we have
added grid lines we have added labels titles plus we can add legend as well so
let me show you how you can add a legend so for that i'll go back to my code
once more just write in here plt dot legend go ahead and run this again and
you'll see that legend has been added so here we have line 1 and line 2 as our
legend and we have changed the default line width title y-axis x-axis labels
plus we have grid lines so this is how you can customize and add style to
your graph so what i'll do i'll open my slides again and we are going to look
at how to plot various types of graphs for example a bar graph or a histogram
all those things fine so first we'll look at how to plot a bar graph so these are
all the linear graphs that we have seen till now now we'll see how to plot a
bar graph so before i tell you how to plot a bar graph using matplotlib let us
understand why we actually use a bar graph so bar graphs are basically used
to compare things between different groups and when we are trying to
measure changes over time bar graphs are very well suited when changes are
larger so this is why we use bar graph now let us understand how we can do
that using matplotlib now since we know why we use bar graph let me
explain you the code and how you can do that using matplotlib so first import
pipeline like we do every time after that instead of plt.plot i'll use plt.par and i
have filled in data here you can fill in variables as well that contains data then
i have defined a label example one after that i have one more plot in which i
have filled in data plus a label and i've given a color as well i don't want the
default color i want some change so i've written it as a green after that i have
plotted the legend after that comes legend and then x label and y label that
you have seen in the previous graphs as well then i've added a title and then
finally show it don't worry guys i'll execute this practically in my pycharm
now so this is my pie charm guys so over here what i've done first of all i
have imported the pi plot function then instead of plt.plot i'm using plt.bar
and inside that i have data filled in instead of that i can even have variables
that contains data then comes label in which i am using example one then
comes label for this instance it is example one then again for one more plot i
have plt dot bar inside that i have data filled in then label and then in order to
differentiate between both of them i'm using a color green for this particular
paragraph then comes legend and then after that and then after that i've
defined x label as well as y label after that i have title and then finally show it
now go ahead and run this and see if it works or not and yes it does so we
have legend here we have x x lab we have y label as well as x label and we
have a title for our graph all right so let us move forward and focus on the
code that you have in front of your screen so let me explain you this code so
over here we have population ages so we have defined a list in which we
have multiple numbers after that we have defined one more list or a variable
bins in which we have multiple numbers again now instead of using plt.bar
for bar plot for histogram we use hist plt.hist then comes population ages
instead of data i am filling in here variables that contains data then bins then
his type i want it to be a bar type now when i talk about his type i want it to
be bar and then the width should be 0.8 that's all just all you can understand it
is x label y label title legend and finally show the plot now i'll go ahead and
execute this practically in my pie chart so this is my pycharm guys and just to
save time what i have done i've actually copied it already so over here you
can see we have imported the matplotlib module then we have a variable
population ages and bins now instead of using plt or bar i'm using plt.hist for
histograms then comes the two variables and then his type is equals to bar
and then i've defined width similarly i've defined x label y label and title like
the previous examples then comes legend and then finally show the plot so let
us go ahead and execute this and see if it works or not yep it does so we'll
move forward and understand scatter plot as well now before we understand
how to plot a scatter graph we need to understand why we actually use scatter
plots usually we use scatter plots in order to compare two variables or three if
you're plotting in three dimensions looking for a correlation or groups so
basically you try to find out how much two or three variables related to each
other so over here as you can see there is one point here and there's another
point here so these two are pretty much dissimilar to each other right now
when i talk about these two points are pretty close to each other so you can
say that these two are pretty much similar and basically what we are doing
here we are trying to find the relationship between the two variables and that
and that is actually called your uh correlation now let us understand the code
now let me explain you the code so first of all we have imported the pi plot
function from the matplotlib module then we have two variables x and y
which contains a certain set of values now instead of calling
plt.plot.pld.plt.hist i'm using scatter because i'm doing it for a scatter plot
right now inside the parentheses i have x and y variables these variables
contain data and i can even write the data instead of just writing the variables
as well now i've defined a label and then color then rest of the things you
know we have x label y label the title then legend and then show that's all
now let's go ahead and execute this practically in my pie chart now this is my
pycharm and over here i've already pasted the code so i'll just go and run this
and we'll see what happens so this is how a scatter plot looks like so here we
have our legend then we have the title then we have our y-axis then x-axis
these two are the labels for that so let me close it and see what is the other
plot that we are going to focus on now once scatter plot is done we'll have a
look at the area plot or you can even call it as a stack plot so basically these
area graphs are very similar to the line graphs okay they can be used to track
changes over time for one or more groups area graphs are good to use when
you are tracking the changes in two or more related groups that make up one
whole category you can take an example of say public and private groups
okay so before i explain you the code let me tell you one thing guys the
problem here is with polygons we cannot actually have labels for our data in
order to solve that problem all we did here was plot some empty lines giving
them the same color and the correct labels in accordance with our stack plot
we also gave them a line width of five as you can notice here to make the
lines a bit thicker in the legend now we can easily see that we are spending
our days sleeping eating working and play so this is how the code works now
let me execute that practically in my pycharm so i've copied the code already
just to save time again now this is our code over here i've already explained
you why are we defining these empty lines just to add labels now let us go
ahead and execute this and see what happens so this is our graph guys and
again we have legends title to our graph and y label as well as x label so we'll
move forward and look at various other plots this is called a pi plot so let me
tell you about pie charts a bit so pie charts are pretty much similar to stack
plots only they are for a certain point in time typically a pie chart is used to
show parts to the whole and often a percentage share you can consider the
example of percentage of market share and things like that right now let me
tell you guys matplotlib handles the sizes of the slices and everything so all
we need to do is just feed it the numbers that's what we have done here so let
me explain you the code here so over here we have so over here we use
plt.pie ins to plot a pie chart we have slices we have specified slices now
slices which are nothing but the relevant sizes for each part then we specify
the labels and then the colors list color list for the corresponding slices next
we can optionally specify the start angle for the graph this lets you start the
line where you want in our case we chose a 90 degree angle for the pie chart
which means the first division will be a vertical line next we can optionally
add a shadow as well and after that we can even use explode to pull out a
slice a bit so we have explored that say zero comma zero point one comma
zero comma zero so because of that you can see that eating has been pulled
out a bit now basically we have four total slices so with explode if we didn't
want to pull out any slice at all we would have just written here zero zero
zero zero now if we want to pull out the first slice a bit we would do zero
point one comma zero comma zero comma zero and if we want to pull out
the second slice a bit what we can do is zero comma zero point one comma
zero comma zero like in our case now finally we do an auto part now this
auto part overlay the percentages on the graph itself so you can see that we
have eight point three twenty nine point two percent fifty four point two
percent all those things written on the graph itself and finally add a title and
then show it now let me execute this practically guys

now just to save time i've already written the code so i'm just going to go
ahead and execute this and we'll see if it comes not yep here is our pie chart
so we have seen multiple types of plots we have seen pie plot power plot
histograms area plot now what we need to understand is how to handle
multiple plots so at that time what will you do let me open my slides again
and we'll move forward with that so this slide actually tells you how to deal
with multiple plots now you can notice in the figure as well we have two
plots available now let me help you out with the code that is there in front of
your screen so in the beginning we are importing a couple of modules one is
matplotlib.pyplot which you are already familiar with after that there is a
numpy module as well now after that you might find this part confusing if
you're not familiar with numpy now let me just tell you what it does it will
create a numpy array that'll have elements between 0 till 5 in the steps of 0.1
now similarly t2 will also be a numpy array that'll have elements ranging
from 0 to 5 and in the steps of 0.02 now after that the code is pretty much
similar to the previous examples that we have seen but there is one new
concept that is called subplot now let me tell you what this subplot does it
helps us to plot multiple plots all right so when we write subplot 2 1 1 this
means that we have two plots horizontally we have only one plot present and
vertically we have two plots and in that vertical position this plot will be our
first graph now you can notice that we have one more subplot that is two one
two so so vertically we have two plots horizontally we have one and this is
the second plot so what i'll do i'll open my pycharm and i'll play around with
it a bit so that you'll be able to understand it better so now this is the code
guys first i'll go ahead and execute this and we'll see the result so we have a
graph something which is like this right we have two plots which are aligned
vertically now what i'm going to do is i'm going to just minimize this and i'm
going to change the subplot values so that you'll be able to understand better
how we are dealing with multiple plots now over here if i make this as 2 and
this one as well as 2 so let us see what we get so we have got the same graph
but it is aligned horizontally if you can notice this is our another graph and
this is our first graph so you can notice the difference between both of these
graphs right so this is why we use subplot
data visualization is known to be a challenging task but cbon just makes it so
simple before we move on just make sure you subscribe to our channel and
hit the bell icon to stay updated with all the latest edureka videos coming
back towards this session we shall first begin with a small introduction to
seaborn and the advantages of seaborn over matplotlib then i'll be showing
you all the installation of seaborn along with its dependencies following that
we shall take a look at the various plotting functions in c bond and how you
can create multiplied grids and finally we shall be studying the various plot
aesthetics available in c bond so let's get started c cbon as we all know is a
data visualization library available in python it's based on matplotlib and
allows creation of statistical graphics it also has a number of functionalities
such as an api that is based on datasets allowing comparison between
multiple variables it also supports multi-plot grids that in turn ease building
complex visualizations it has univariate as well as bivariate visualizations
available to compare between subsets of data the availability of different
color palettes to reveal various kinds of patterns it also estimates and plots
linear regression automatically so now if you were wondering why you see
born when you already have matplotlib here is the answer to it michael
vascom who's the creator of seaborn says if matplotlib tries to make easy
things easy and hard things possible seaborn tries to make a well-defined set
of hot things easy too factually matplotlib is good but seaborn is better there
are basically two shortcomings of matplotlib that cbone fixes matplotlib can
be personalized but it's difficult to figure out what settings are required to
make plots more attractive on the other hand cbond comes with numerous
customized themes and high level interfaces to solve this issue when working
with pandas matplotlib doesn't serve well when it comes to dealing with data
frames while c-bond functions actually work on data frames now that you
have an idea about c-bond let's move on to see how you can actually install
this library to install c-bond you can use the simple pip install c1 command or
if you are using an anaconda platform you can just go to the anaconda prompt
and type conda install seaborn

since i already have it installed over here i'm not going to redo it again now
let's get back to our presentation and take a look at the dependencies of cbon
cbon basically has four mandatory dependencies which is numpy scipy
matplotlib and the pandas library it also has a recommended dependency
which is the stats models library of python so just like we've installed cbon
we'll have to install numpy scipy matplotlib and the pandas library to install
these libraries you can use the same commands which i showed earlier with
the name of that particular library okay so i hope everyone's clear till here if
you have any doubts please do let me know in the chat box and my team is
here to help you so now let's move on and take a look at the various plotting
functions in cbon c1 has a number of functions that are available for
visualizing statistical relationships plotting with categorical data visualizing
the distribution of a data set let's begin with visualizing statistical
relationships the process of understanding relationships between variables of
data set and how these relationships in turn depend on other variables is
known as statistical analysis in today's session i'll be using the rel plot
function to plot various statistical relationships rel plot is a figure level
function that makes use of two other access functions for visualizing
statistical relationships these access level functions are scatter plot and line
plot which can be specified using the kind parameter of the rel plot to explain
this in detail let me jump onto my jupiter notebook from here i'll just open a
new python notebook

i hope everyone's familiar with jupiter okay i'll just rename this to python
cbon tutorial

i'll just say python cbon and i'll rename this before we begin data
visualization with c bond we'll have to import c bond along with its
dependencies so the first thing i'm going to import is numpy

import numpy as np then i'll import pandas as pd

import matplotlib dot p y plot as plt and then i'll import c bond import c bond
sorry for the spelling mistake guys this is import cbon import c1 as sns and
i'll just execute this like i've already told you all before you can load any data
set present on the github and make use of it with cbon cbon also allows you
to load any data set from git using the load data set function so let me just
load the flights data set so i'll just say sns dot load underscore data set and i'll
specify the name which is flights
okay so now let me just go to the github website

and open the flights data set over here

as you can see there are a number of data sets that are available which you
can use along with cbon so let me just open the flights data set and scroll
down so as you can see over here there are three columns for the year month
and the number of passengers so i'll just come back to my jupiter notebook
and i'll use sns.rel plot and i'll specify what i want my x-axis to be so i'll just
give x-axis as the number of passengers

and to the y-axis i'll give month as the parameter and for the data i'll use a
which is the variable wherein i'm loading the data set and i'll execute this
okay so i hope you're clear with this so as you can see over here the y-axis
has month and the x-axis has the number of passengers these points are
plotted in two dimensions to add another dimension you can add the hue
semantic so i'll just copy this ctrl c and i'll paste it over here and i'll give
another parameter over here which is hue and i'll say that is here to be the hue
semantic and i'll hit run

so i hope you see the difference over here the year has been marked as the
hue semantic month which is in the y axis and the number of passengers
which is on the x-axis so as you can see on the screen this is nothing but the
scatter plot so in case you want a line plot all you have to do is specify the
kind parameter of rel plot with the keyword line so let me just load another
data set over here so i'll say b is equal to sns dot load underscore data set and
i'll load the tips data set this time after this i'll use sns.rel plot i'll specify the
x-axis to be the time and y-axis to be the tip data is nothing but b and kind is
line now let me hit run okay so i hope you're clear with this if you have any
doubts please do let me know in the chat box and my team is here to help you

now let's get back to our presentation and see how you can plot categorical
data in c1 this approach basically comes into picture when our main variable
is divided into discrete groups to achieve this we'll be using the cat plot
function available in cbon like rel plot cat plot is also a figure level function
characterized by three families of access level functions which are scatter
plots distribution plots or estimate plots okay now let me jump onto my
jupiter notebook and show all a few examples regarding this okay so here i'll
use the same tips data set and since i've already stored it in the variable b i'll
just use sns dot cat plot

and i'll specify the x axis to be the day

y axis as the total bill

and data is b now let me hit run okay as you can see over here this is the
scatter plot that we've got using the cat plot function scatter plot is basically
the default type of cad plot however you can change the kind of plot you
want by specifying the kind parameter like we've done previously you can
choose between any options which is strip plot swarm plot box plot while in
plot etc let me just show you what happens when i change the kind parameter
of this cat plot so i'll just copy this and i'll paste it over here and i'll specify
kind to be as violent plot so i'll specify the keyword violin and i'll hit run
okay so i hope you see the difference this is our scatter plot and this is our
violin plot so if i change the kind parameter our plot will change
correspondingly let me just give the type as box in now

okay so i hope you're seeing the difference guys so now let's get back to our
presentation and see how to visualize the distribution of a data set visualizing
data set basically deals with understanding data sets with context to being
univariate or bivariate okay so now let's get back to our jupyter notebook and
see how you can actually plot univariate and bivariate distributions so before
doing this i'll just import stats from the scipy library so from scipy import
stats and i'll hit run okay so first let us plot univariate distributions to plot
univariate distributions you can use the dist plot function so let me just take
an example c is equal to np dot random

i'll just use random.normal functions to draw random samples from a normal
distribution so i'll just give the corresponding parameters to it you can give
any parameters of your choice let's say size equal to 100 and scale i'll specify
the scale to be s2 and i'll hit run i did not specify the dist plot function so i'll
use sns.dist plot and i'll pass the data to it as c okay so this is how the dist plot
function works so this is an example of a univariate distribution so now let's
move on and see how a bivariate graph is going to look to plot bivariate
distributions you can make use of the joint plot function i already have a
small example typed over here so i'll just copy paste that and i'll show you all
how it actually looks

okay so this is basically a bivariate distribution so i hope you see the


difference this was our univariate distribution and this is our bivariate
distribution okay if you have any doubts please do let me know in the chat
box and my team is here to help you moving on python cbon also allows you
to plot multiple grids side by side these are basically plots or graphs that are
plotted using the same scale and access to it comparison between them this in
turn helps the programmer to differentiate between the plots and obtain large
amounts of information to plot multiple graphs you can either use the facet
grid function or the pair grid function of c bond let me jump on to my jupiter
notebook and show y'all an example of each of these so first i'll be using the
facet plot function okay so here i'll load another data set so i'll just say a is
equal to sns dot load data set and this time i'll load the iris data set and i'll say
b is equal to sns dot facet grid which is the name of our function and i'll
specify a variant wherein our data is present and i'll specify the column to be
the species

i'll specify the column as the species of flaws and then i'll just use the map
function

and i'll specify all of them to be as histograms and i'll give the parameter as
sepal length

now let me hit run oh sorry i made a spelling mistake over here it's capital f
okay so i hope you're clear with this i basically have three graphs that are
available for the three species of flowers which is setosa versicolor and
virginica as you all can see it becomes very easy to differentiate between
them you can also make use of the pear grid function when you have a pair of
variables to compare let me show you a small example of that as well so here
i'll just say a is equal to load underscore data set and i'll load the flights data
set

and then i'll specify b as sns dot pair plot pair grid sorry and i'll specify the
data to this as a and i'll use the map function again to plot them this time i'll
use scatter plot so plt dot scatter sorry guys i forgot to specify sns over here
sns dot load underscore data set okay so i hope you're clear with this so as
you can see the output clearly compares between the year and the number of
passengers in different ways seabond also allows you to make your plots
more attractive and delightful so till now as you've been seeing i've just had a
white background for all my plots so in case i want to change this or if i want
to change the color palettes that are available in my graph i can do so easily
let me just jump on to my jupiter notebook to show you all how to do this so
here i'll just copy paste the previous example i'll just copy this and i'll paste it
over here and to this i'll just use another function which is the set function
and i'll specify the style the style of my plot to be dark grid

and i'll hit run i hope you see the difference between the two here i have a
white background whereas when i specify dark grid i have a different
background with dark grids that are seen clearly you can change the style
parameter to any of the available themes which is dark grid dark white etc so
if i just specify dark and i hit run you can see that the grids have vanished but
the background is dark

not just this guys you can make many of the changes to your graphs such as
adding or removing access the colors that are available etc now let me just
show you all how you can remove the access lines that are present in your
graphs i'll take another example over here so sns dot set i'll set the
background this time as white i'll say style equal to white and i'll specify the
color color code parameter to be true

i'll load the tips data set again sns dot load data set and i'll load the tips data
set

then i'll use a box and plot

or i've used the box and plot so this time i'll use the box plot function and i'll
specify x-axis to be the days and sorry it's day not days and the y-axis to be
the total bill

and data is nothing but a oh sorry guys i've made a spelling mistake over here
it's color codes okay so here as you can see my plot has access all around it
now if i want to remove any of these access all i can do is use the display
function so i'll just copy paste this and i'll use the display function

i'll specify the offset parameter to be 10 and i'll specify trim parameter as true
and i hit run okay so i hope you see the difference so as you can see over here
i've specified the offset to be 10 i do not have the access that are present
before that seabond also provides a number of color palettes and to check the
color palettes that are available in seaborne you can just use the color palette
function so i'll just use c is equal to sns dot color palette

and this time i'll use the pal plot function

and the data is c

okay so as you can see these are the color palettes that are currently available
in seaborne for deeper variations you can use other functions such as the hls
palette husl palette etc

once in every four years the world celebrates a festival called fifa world cup
and with that everything seems to change priorities switch to football and
predictions switch to the teams and players that would perform in the
tournament as everybody must be knowing that world cup has already started
in russia and people are going crazy about it so keeping that in mind i have
come up with an use case wherein i'll be analyzing the world's best playing
11 in fifa 2018 so for all the football lovers out there i hope that excites you
so let's make this fun and let us see our problem statement first but guys let
me make it very clear that this list is based on my opinion only and you are
entitled to have a completely different opinion so if you do have a different
opinion let me know about your list in the comment section below now as i
told you that i'll be predicting the world's best and strongest 11 players taking
part in this fifa world cup and i would be using python for the analytical
implementation so i start this analysis by first analyzing the world's best
goalkeeper then 4 best defenders three best midfielders and three best
attackers so if you notice over here i am following a 433 lineup well it's often
said that 433 is the best lineup but obviously it is not fixed so based on my
players availability i have choose this lineup as 43c so guys it's totally up to
you you can choose any position you want now as i've said guys that i'll be
using a 433 position so here i have four defenders red marked as three
midfielders blue marked as three attackers and mustard orange for a
goalkeeper so i hope you guys are clear with this 433 position so if you notice
over here i have a question mark on all these positions now why because this
exactly my problem statement is that is i need to find out the players who will
play the best in these respective positions so this sounds pretty interesting
right so let's begin our analysis so here i'll be following five steps wherein i'll
first load my data set and then import the required libraries now i'll be using
fifa data set from kavel so don't worry about the data set guys i'll be
mentioning the link of kaggle website in the description below so once you
have loaded the data set and imported all the required libraries will then
analyze it explore the data set and then we figure out the best goalkeeper the
best defender best midfielders and best attackers so let us go through all these
steps one by one now my very first step is to collect or you can say load the
data set and then analyze it so if you notice over here i have a screenshot
which displays the data set so over here i have the name of the player i have
the nationality that is the country he belongs to then i have the national
position in which the player plays at the national level then we have the
national kit we have club we have club position club kit and we have so many
others like that so this is a data set which is provided by kaggle so i just
mentioned this in my description box and you can just download the data set
from there now i'll be using different libraries as well so over here i'll be
using pandas for data analysis manipulation cleaning and all those stuff then
i'll be using numpy for the scientific computation part and matplotlib and c
bond for visualizing plots so in this step i'll be just loading my data set and
then importing the required libraries so let me just go to my jupyter notebook
and let us implement all these steps one by one so guys this is my jupiter
notebook now as you can see we need to figure out the world's best playing
eleven so over here i have first imported all my libraries that is import pandas
as pd then c bond as sns numpy as np and then i've imported matplotlib and
then i've just written percentage matplotlib inline that is to visualize the plots
in the jupiter notebook itself then what i've done i have just read my data set
so the name of my data set is full data now using pandas i have read the csv
and then displayed the top seven rows so over here i have already discussed
that the set contains the columns such as names nationality national positions
and we have so many like that so here i have just printed seven rows and if
you notice that we have 53 columns over here so you can just go through it
explore do experiment with them and gain insights out of them so here if you
see you have characteristics of all the players and their score so you can just
go ahead download this data set and explore as much as you can now
analyzing this huge data set is a tedious task as it involves quite a few pre-
processing steps as well now there might be a lot of redundant and unwanted
columns which you may want to remove therefore you can delete certain
columns if needed so let me show you that as well so here what i have done i
have deleted one column that is national kit so i don't require the column as
national kit so what i'll do i'll say delete so i'll just write d e l d f is the name
where i have stored my data set and then i've just mentioned the column
name over here i don't want the national kit columns so i've just write this and
then i just printed the head of it so once i run this you'll see that the national
git column no longer exists and if you notice i just have 5 rows and 52
columns whereas in totality we were having 53 columns similarly you can
delete as many columns as you want you can actually do a lot of
transformation you can remove the null values that is nothing but the
cleaning of data so you can do the analysis on your data set as well so i'll just
leave this part on you so you can just go ahead and analyze as much as you
can now once you have simplified this data you can then start with the
analysis part so to explore you can analyze your data the best thing you can
do is to visualize the data in the form of plots so what happens with that is
you can easily read out your conclusions you don't have to calculate a lot of
things you don't have to play with numbers in fact you can simply see that
okay this has the highest peak means this is the most likely outcome to be
happen so that is how we can visualize everything using matplotlib and c-
bond libraries so here what i have done i have plotted a simple count plot
which basically gives me the number of players representing a particular
country so over here i have count plot and on the y-axis i have the nationality
and on the x-axis i have the count that is the players count so as you can see
here from the graph you can easily conclude that most of the players are from
england then from argentina spain france brazil and the list goes on now these
graphs are best used to gain statistical insights so you can just go ahead plot
with different columns and analyze your data set now in this case the graph
won't add a lot of value because we would be picking the best 11 and the
results may vary accordingly so these graphs are just for analysis part so over
here the results that we got is purely dependent on your data set so right now
i'm getting the maximum count from england and then from the argentina so
guys don't take it personally it's just displaying what my data set contains
now moving ahead with the analysis you can try out different visualization
let's say with the player's age with the preferred position he plays then the
rating of it then the club he is and you have a lot more columns like that so let
me show you one more visualization and then we'll switch to our analysis of
fetching the best playing 11 for the world cup so here i have again plotted a
count plot wherein i have the player's age on the x axis and the count on the y
axis so here it is quite evident that the majority of players are between the age
20 to 29 and it has the largest peak at 25 years so that is how you can
conclude a lot of other things by just going through your data set and taking
up different columns and plotting different graphs with them so now is the
time we try and find answer to the question we put forth in the problem
statement that is who will be the world's best playing eleven let us begin our
analysis so as discussed earlier as well i'll be using a 433 lineup which means
we need to find four best defenders three best midfielders and three best
attackers and we'll be having one goalkeeper as well so let us start our quest
by finding a goalkeeper first now over here as you can see i have assigned
some weights to these variables so if you notice over here i have given the
minimum weight of 0.5 to the variable a then i have given b as 1 c as 2 and
the maximum weight is 3 to the variable d now i'll be telling you why we
have assigned these weights and then we will be using these as well now in
order to find the best goalkeeper what i'll be doing i'll be analyzing the data
for the two parameters that is the short stopper and the sweeper so a short
stopper is a goalkeeper who is strong in stopping the shots taken by the
opponents whereas the sweeper is the player who is quite strong in playing
with his feet and making the passes so that is why i have taken these two
characteristics and then assigned all the weightage to the characteristics now
in my data set i have various features such as we have reactions we have a
column of composure we have the column of speed strength and we have
many other features like that now that is why i've assigned weights to it now
in short stopper what i'll be doing i'll be giving weightage to all these
characteristics so let's say i'm giving the weightage of a to the speed now a is
the minimum weightage and similarly if you see for sweeper i am giving a bit
higher value to the sweeper now why because sweeper is the one who sweeps
up the ball if an opponent manages to breach the defensive line so that is why
i have given b weightage to him similarly for jumping i have given c
weightage for shortstopper and i have given lesser weightage for sweeper
then moving ahead i have given the d weightage which is the maximum
weightage to the reflexes so both the characteristics either it is short stopper
or a sweeper both must be having very good reflexes so that is why i have
given the weightage d to both of them so that is how you can assign weights
to all of them and then what you can do you can simply plot them and then
pick the best one so what i'll be doing i'll be first plotting my short stopper
now over here what i have done i have simply plotted a bar plot wherein i'll
be passing the variable that is gk short stopper and then using the function
sort values we have arranged them in the descending order and then i just
want the top five of them then on my x-axis i have the name of the players
and on the y-axis i have the short stopper score so based on these parameters
you'll get a graph somewhat like this now it is quite evident from this graph
that manuel neuer is the best goalkeeper as you can see he tops this chart now
let us plot the other parameter that was sweeper so i'll just copy the same
code i'll just pass in the value that is gk sweeper and then pass the same in my
sort values function and then arrange them in the descending order for the
first top five so over here again we have the player's name on the x-axis and
we have the sweeper score on the y-axis so as you can see over here manuel
neuer tops the chart here as well so based on these two parameters we
conclude that manuel neuer would be the best choice goalkeeper for this
world cup so by going through the two characteristics that was shortstopper
and sweeper which came to a conclusion that manuel neuer is my best choice
for a goalkeeper let me just go back to my presentation and let's see what all
we have covered so we have seen this we have collected the data and we have
imported the required libraries then what we have done we have analyzed the
data we explored the data set variant we have plotted two count plot one with
the nationality and the other one with the age so by plotting these two graphs
you basically find out a relationship between one variable or you can say one
column and another column and then you can predict better results so
analysis exploring your data set and visualizing them brings you a lot of
insight so you should definitely do that now i've already told you that you can
go through the data set you will find a lot of columns you can just pick up the
ones which are relevant for you and then you can start your analysis on that
next my second step was to analyze the best goalkeeper so over here i have
plotted two graphs one with a short stopping score and the other with the
sweeping score so as i told you guys that a short stopper who is quite strong
in stopping the shots taken by the opponents whereas the sweeper is the one
who is strong in playing with his feet and making the passes now when we
plot these two graphs we come to a conclusion that manuel neuer is the best
goalkeeper for this fifa world cup and hence we chose him now next in a
quest to find the world's best playing 11 it's time we choose some defenders
as well now in order to find the best defenders i'll be using these attributes to
fetch the best defenders so as for my position i am using 433 so i need to
fetch four defenders so here i'll be fetching two center backs and two wing
bags so in center backs we need two center backs that is one who plays from
the left and the one who plays from the right so here we have lcb and we have
rcb just the positioning is different then we have wing back so again we need
two wingbacks one who plays on the left hand side and the other who plays
on the right and based on these parameters i'll be predicting the four best
defenders so let me go back to my jupiter notebook and let us plot each one
of them and find out who are my best defenders so as discussed guys i have
taken df center back that is defenders in the back and defender wing bags
now i'll be using the same characteristics for left center back and for right
center back and i'll just change the positioning let's say i want to know the
left side who is my best left center back so i'll give the position as lcb and if i
want to know the right center back i'll give the position as rcb that is right
center back so that is how we can sort the players by assigning the positions
to them now if i have to calculate the center back i should know that they
should be having a higher defending capabilities so the interception the
tackling power the jumping then your stamina marking all these things should
be high so if you see over here i have my sliding tackle and standing tackle as
d which is the highest weightage so that is why i've assigned the weight d to
them similarly i have given d to marking as well then to heading as well so
that is how you can give weights to all of the parameters now for wingbacks
as well you must be having high defending capabilities so the interception
should be higher the tackling power should be higher so here also i've given
the standing tackle and sliding tackle as the weightage of d then i've given
acceleration to d and let's say finishing to a because a wing back is not that
involved in finishing so that is why i have given the lowest weight that is a so
now is the time we plot the center backs so here first we'll plot this left
central back so over here if you see i've given the position as lcb and then it's
the same code guys i've just passed in the values of center back and using the
sort value function i have arranged them in descending values and i need to
print only top five values then on my x-axis i have the name and on the y-axis
i have the score of this also notice guys that i have given a position lcb that is
the club position so if you have explored the data set you can actually take
any other column let's say you also have a column of national position so you
can take up that position and then you can find out the results but for now i
have used the club position because the player plays the best in the club so
that is why i have taken club position now you can go ahead with the national
position as well and then you can perform the analysis so do let me know
what is your result or what is your take on the national position and then we
can see the results as in how different our results come out so do let us know
about your result or your list that comes up after taking different parameters
and different weightage and everything so guys this is my list based on these
parameters so you can just go ahead analyze the set and you can actually do
wonders with the data set now if i see the result of this particular graph i have
sergio ramos as my best left central back now let me plot the right center
back as well so over here i'll be giving the club position as rcp and then the
whole code is same so let me just see the result so my best right central back
is cesar equilibreta so now next let's move ahead and plot the wing backs as
well so over here let me plot the left wing back so here i'll be giving the
position as left lwb or you can say lb so lwb stands for left wing back and or
you can say left back and then it's the same exact code over here my left
finger or you can say left being back is david alaba since david alaba's team
does not qualify in this world cup 2018 so i'll be picking up alexandro as the
best left finger defender then it's time to plot the right wing back as well so
over here i have given the position as rwb or you can say right back so as per
this analysis it is evident that kyle walker is the best right bring back for the
world cup so that is how we have calculated the four best defenders that is
two central backs and two wing backs having said that i got a list of my four
best defender so let me just go back to my presentation and show you them as
well so over here i got the result as left wing back as alexandra then we have
central back as sergio ramos then we have right central back as cesar
espiliqueta and we have the right ping back as kyle walker so moving ahead
with the world's best playing 11 it's time we chose some midfielders as well
so as per the game formation that was 433 i have to choose three midfielders
now in order to find these i'll be analyzing the data for these parameters so
over here i have a controller a playmaker and a beast let me explain you these
terms now a controller is the person who is orchestrating your midfield
engine by either sitting back or going forward based on the dynamic need
secondly we have a playmaker so a playmaker is someone who will move the
ball to the attacking from defense or you can say midfield then we have a
beast so a beast is a typical box-to-box player with loads of energy and who
can basically boss the midfield so that is how i have categorized the
midfielder in terms of controller playmaker and a beast so let me just go back
to my jupiter notebook and let us implement and give weightage to all the
characteristics so as discussed we have a controller a playmaker and a beast
now when i talk about controller i have given the position of controller as lcm
or you can say left midfielder the controller must be good in passing the ball
then you have dribbling so basically the characteristics that involves the
highest weightage is ball control then you have composure you have short
pass long pass and all those things so if you see over here in controller i have
given d weightage to the ball control then we have short pass long pass so we
have given that weightage then we have a playmaker so a playmaker is
someone who will move the ball to the attacking from the defense or midfield
so a playmate must be having good dribbling the agility should be very high
then the ball control then you can say short pass in long pass everything
should be high so over here i have given d weightage to the ball control then
d for the dribbling then for the short pass long pass and similarly you can
assign betas to all the relevant characteristics then we have a beast so a beast
is basically a box to box player with lots of energy and basically who can
boss the midfield so he is the one who will be playing from the position that
is rcm or you can say rm so he'll be becoming a right central midfielder now
in order to find the best beast what should be his plus point so i want that
beast to be strong in defending as well as physical so in defending you have
interception strength tackling power then in physical you have the speed
stamina agility and all those characteristics so i have given here deviation to
the agility then it must be having good stamina so i have given d weightage
again and similarly i have assigned the weightage for the relevant
characteristics so over here i have just assigned the weightage of all these
three and now is the time you need to plot them so the very first plot is to plot
a controller now when i talk about controller i told you that i'll be giving the
position of lcm that is the left control midfielder or you can say lm so over
here i've just added one column that is club position lcm or lm and then i just
sort the values so as per this analysis i'm getting the best controller or the best
left controller midfielder is in esl next what i'll do i'll be plotting playmaker
as well so in playmaker i want the position as cam that is center attacking
midfield or lm that is left attacking midfield so over here let us see the results
so the best playmaker or you can see the best center attacking midfielder is
meset ozil so we have already come to two best midfielders that was iniesta
and ozil next we need to plot the beast so over here i have given the position
as rcm or rm and then we have just plotted it so let me just see the results so
over here as per the analysis i'm getting kante as the best beast or you can say
the right central midfielder so here we have completed a hunt of finding the
best three midfielders so let me just go back to the presentation and let me
show you them as well so here i have the controller or you can say the left
midfielder as iniesta then i have the playmaker as ozil and we have the beast
or you can say the right central midfielder as kante so now we are done with
the best goalkeeper we are done with the best defenders and we are done with
the best midfielders so now is the time we find some attackers as well now in
order to find the best attacker i'll be plotting the three graphs which is for left
wing attacker then for right wing attacker and one for the striker so a left
wing attacker is a player who attacks from the left flank then a right wing is
the player who attacks from the right flank and a striker is the one who
attacks from the center let me just go to my jupiter notebook and let us assign
weightage and then let's see the results so over here i have three positions that
is left wing right wing and a striker so in order to have a best left ping he
must be having strong pace then you should also be good in shooting or you
can say passing so basically the attributes that contribute same is acceleration
speed then the finishing of it then crossing so all these things are
characteristics so here i have given the acceleration d then i'm also giving the
finishing as d because attackers must be having high finishing and also the
shooting capabilities now i have allocated both these characteristics are same
because a left wing and the right thing both have the same capabilities is just
the positioning difference over here if you notice i have given the same
weightage to each one of them and then when i'll be going to plot i'll be just
specifying the position to left wing and to right wing then comes my striker
so a striker is the one who should be good in dribbling he should be good in
ball control reactions then the finishing also should be high the balance
should be high so all these things are the characteristics of a striker so here
we have ball control then we have the balance so here we have given the
weight is d then we have high finishing so again the weight is d for heading
also we have given d and we have similarly assigned betas to all the other
characteristics so now let us go ahead and plot each one of them so here we
have very first graph which basically plots the left wing so here i have given
the position as lw lm or ls so on the x-axis i have the player's name and on the
y i have the score so now let me just see the results so it's quite evident that
the best left wing is ronaldo and now let me just plot the right wing as well so
over here i've given the position as rw rm and rs so i'll go to the results alright
so i'm getting messy as the best right-wing attacker so here we have the left
best attacker as ronaldo and we have the right wing as messi now comes the
striker so here i have just given the position striker to st or you can say left
striker or right striker so let me just plot this as well so as for analysis we are
getting robert lewandowski as the best striker so that is how we have
calculated the best three attackers that was ronaldo messi and lemondos so let
me just go back to my presentation and let me show you there as well so on
my left hand side we have left wing as cristiano ronaldo then on the right
wing we have messi and striker as lewandowski so guys this brings us to the
end of this use case we now have the best goalkeeper for best defenders three
best midfielders and three best attackers so let me just show you the complete
picture of my analysis so these are the world's best playing 11 for the fifa
world cup in the 433 position so here i started from choosing the best
goalkeeper that comes out to manual lawyer then we have picked up four best
defenders so my left wing was alex sandro then it was ramos cezar and kyle
walker then we have gone ahead with analysis and then we chose the best
three midfielders so the midfielders that came out were iniesta ozil and kante
and finally towards the end we have analyzed the best attackers as well so on
the left hand side we have ronaldo on the right hand side we have messi and
on the striking we have levandos so i hope you guys like these results so i'll
repeat it one more time guys that this list of players and the formation is
totally based on my opinion and you are entitled to have a completely
different opinion so if you do have a different opinion do let me know about
your list in the comment section below so here i'll just wrap it up and i hope
you guys like the coverage of python in this fifa tournament so guys this is
just one use case on fifa data set you can actually achieve a lot more by
applying various machine learning theorems then you can go through
statistics and you can do wonders with the data set so this was just the
beginning and this was quite a basic use case for the fifa data set you can just
go ahead with the data set and you can actually apply machine learning and
predict a lot of things also in order to learn more about python and data
science or machine learning you can let us know in the comment section and
we will reply you back with the detailed code content now if you're investing
in learning something be sure guys that this is something which is not going
out of the date anytime soon so python is totally worth the effort guys so
don't just learn it master it with edureka

today's session is all about computer vision using opencv in python for now
let us move forward and have a look at the agenda for today so guys this is
what we'll be discussing today we'll begin by understanding what exactly is
the meaning of computer vision and how a computer reads an image then i'll
tell you what is opencv and how it works after that we'll see how to create an
image detector as well as a motion detector using opencv so i hope you guys
are clear with the agenda let us move forward and we will understand what
exactly is the meaning of computer vision so before i explain you anything
guys i believe all of you are on facebook and the moment you upload any
picture on facebook there's a feature called auto tag right to facebook will
give you suggestions to tag people who are there in the image right so how do
you think that happens that happens all because of computer vision so
computer vision is an interdisciplinary field that deals with how computers
can be made to gain high level understanding from digital images or videos
so the idea is to automate tasks that the human visual systems can do so a
computer should be able to recognize that this is a face of a human being this
is what a lamppost looks like this is basically a statue so things like that right
so i hope i'm clear what is the meaning of computer vision and i don't think
so i need to explain you what are the applications of computer version right
so uh let's move forward guys and we're going to see how a computer reads
an image now this is very interesting so notice the image that is there in front
of your screen right so a normal human can easily tell that there is a new york
skyline in this image but can computers really see this well the answer is no
computers see a matrix of numbers between 0 to 25 0 to 255 right so for a
colored image there will be firstly three channels red green and blue and
there'll be a matrix associated with each of these channels right and each
element of this matrix represents the intensity of brightness of that pixel all of
these channels will have their separate matrices and these will be stacked
onto each other to create a three-dimensional matrix so a computer will
interpret a colored image as a 3d matrix i hope i'm clear so when i say that the
size of an image is 700 cross 700 and it is a colored image that means there
are 700 rows 700 columns and there are three channels because it's a colored
image similarly if i say 300 cross 700 that means there are 300 rows in 700
columns and if it's a colored image there'll be three channels now in the
example which is there in front of your screen we have an image which has a
size of b cross a and since it is a colored image there'll be three channels one
thing to note here guys for a grayscale or a black and white image there's only
one channel so if there's a black and white image and i say that the size of the
image is 700 cross 700 it means there are 700 rows and 700 columns in one
single channel right so i hope i'm clear for a black and white image there's
only one channel for a colored image there are three channels popularly
called as rgb and each element of the matrix represents the intensity of the
brightness of the pixel so this is how basically a computer reads an image it
will read an image in the form of matrix it depends if it's a colored image
then it'll be a 3d matrix and if it is a grayscale or a black and white image
then it will be a 2d matrix similarly if i want to calculate the number of pixels
all i have to do is multiply the number of rows number of columns and the
number of channels so if i say that the size of the image is 700 cross 700
cross 3 because it's a colored image then you can go ahead and multiply these
numbers and you'll find the number of total pixels so i hope you have
understood this let us move forward and we are going to focus on what
exactly is opencv now first of all opencv is a library which is used for
computer vision it was first developed in the year 1999 at intel by gary
bradsky and the first release came out in 2000. let me tell you that opencv
supports a wide variety of programming languages such as c plus plus python
java etc and also supports different platforms including windows linux etc etc
now opencv python is nothing but a python wrapper for the original opencvc
plus plus implementation and in opencv all the images are converted from or
to numpy rs right so if there's any image then opencv will first convert it into
a numpy array right and this makes it easier to integrate it with other libraries
that uses numpy for example scipy and matplotlib but for now understand
that all the images will be first converted to a numpy array right so that's how
opencv works since we saw that computer will first convert the image to a
matrix in this case it will convert it into a numpy matrix or a numpy array
you can say now we'll directly jump into certain basics of opencv so what i'll
first teach is how you can read an image how you can perform basic
operations for example resizing the image or displaying the image and things
like that so that that's what i'm going to first focus on so for that what i'll do is
i'll open my python i'll execute the code there but let me just first explain you
what i'm going to show you so first of all i'm going to teach you how we can
read a particular image the first thing you need to do is obviously import the
opencv module then we are going to read the image with the help of this im
rate function so this one represents that it will be a colored image if it is a
colored image and if we put zero here then it'll convert it into a black and
white or a grayscale image right and let me tell you that opencv will read it as
a numpy array so basically python stores the images as numpy arrays or
matrix of numbers so if it's a colored image it will be a 3d matrix and if it's a
grayscale image it will be a 2d matrix so what i'll do i'll just quickly open my
pycharm and i'll show you certain basic operations here itself so guys this is
my pycharm so what i've done here is i've imported the cv2 module and what
i'm doing here is i'm using this imread function and i've given the path to the
image so you can see the name of my image is frank.jpg which is present in
this particular path and one basically tells it to keep it as a colored image
itself right so since i was telling you that all the images are converted to
numpy arrays so it is a colored image it will convert it into a 3d matrix let us
see if that happens or not so i'm just going to print this and let me go ahead
and execute it and you will obviously see a 3d array here right similarly if i
go ahead and convert this to a grayscale image if just all i have to do is put 0
here and we have a grayscale image here so let me just go ahead and run this
and you will notice a 2d array notice the difference guys right and if you want
to see what kind of a matrix this is all you have to do is type in here type and
it will show you the type which is a numpy n-dimensional array all right so
i've told you earlier as well that opencv will convert all the images to a
numpy array now what if i want to know the size of my image for that all i
have to do is use the shape function and you will know the size of the image
since it's a numpy array all i have to do is img dot shape and let us see what is
the shape of our image so it is 600 cross 800 because we have converted this
colored image to a grayscale image that means we have 600 rows 800
columns and one single channel because it's a black and white image now if i
convert this to a colored image you will notice the difference in the shape and
you can see that three is added here which basically means there are three
channels rgb so there are 600 rows 800 columns and there are three channels
so i hope you guys are clear how opencv reads an image uh how to know the
shape or size of the image how do we know that whether it's a colored image
or a black and white image what is the difference what do you mean by rgb
channel so we saw how to read an image we saw how to print an image how
to print the n-dimensional array then we also saw how to print the shape of
the image and what will happen if we convert it into a colored image then we
saw that three was added in the end which basically means three channels
right now what we are going to do is we are going to display the image how
we are going to do that we are going to use this weight key function in which
if we don't specify any parameter and we keep it as 0 it means that the
moment user presses a key the window will be closed and if we specify a
time frame for example 2000 milliseconds then the window will wait for
2000 milliseconds and then it will be destroyed so this destroy all windows
basically closes the windows based on my wait for key parameter so if it is
zero the moment any person presses any key then all the windows will be
destroyed and if i've given certain parameters like two thousand milliseconds
then it will wait for two thousand milliseconds and it'll automatically close
the window so i hope you have understood this let me just go ahead and open
my pycharm and i will show you there as well so guys this is the pycharm all
i will do here is i basically want to print it or i want to display my image so
i'll use this i am show function uh to give a name to this image so let it be a
legend and we're gonna type in here the name of the image here this is my
file name and this is the image name right so i have given the path here if you
can see now what i'm going to do is i'm going to add the wait for key
parameter so for that all i have to type here is cv2 dot weight key and for now
i'll just keep it 0 which means that the user has to press any key to close the
window right now what i'm going to do is destroy all windows function and
let us go ahead and execute this and we will see the image and the moment i
press any key it is gone similarly if i type in here two thousand milliseconds
right so it will appear for 2000 milliseconds and will automatically go away
right so i hope you have understood how we can you know display the image
and how we can close the windows by using weight key and destroy all
windows function so this is pretty easy guys i hope you have no doubts here
and still if you have any doubts again i'm telling mention it in the comment
section i will reply you asap so now we saw how to basically read an image
how to perform basic operations how to show the image how to close the
windows and things like that now i'm going to tell you how we can resize a
particular image so let me just go back and what i'll do is i'm going to resize
this image i'll go back to my pycharm again and let me just create one more
variable let it be resized which is equal to cv2 dot resize the name of my
image and the shape that i want so probably i want 600 cross 600 right let me
just go ahead and run this i want 600 across 600 so instead of img i'll type in
here resized and let us see what happens once i do this so you see that i have
a resized image here right now obviously that is not symmetrical right so
what can i do to make it symmetrical i can just go ahead and divide it by two
or three the way i want to reduce the size so for now i'm just going to divide
it by two and uh let us see what happened so basically if you see the code
here as well what i'm doing here i'm reducing it by two right so image shape
divided by two and i'm converting it into an integer because even if it turns
out to be a float value i will convert it into an integer so new image shape is
equals to all image here by 2 that's what i'm doing basically right so again i'm
going to use the resize function for that i'll open my pie chart so all i have to
do here is type in here n to convert it into an integer img dot shape function
i'm going to use 1 divided by 2 and i'm going to close the parenthesis
similarly here as well end open the parenthesis img dot shape 0 divided by 2
and close the parenthesis and i think we are good to go so the size of the new
image will become half of the old image let us go ahead and run this so yes
we can see that we have reduced the size let me just keep it a zero so that if i
press any key then only the window will be closed now similarly i can
increase the size as well so let me just go ahead and multiply it by two and
increase the size so my new image will be twice the size of the old image let
us see if that happens or not we'll run this and yep it's a pretty huge image let
me just close it for now alrighty then fine so we have learned how to
basically resize an image let me go back to my slides and we are going to
focus on what we are going to discuss next so we saw how to resize the
image next up we are going to see how we can detect a face in a particular
image so it's pretty easy guys what you need is an image obviously you need
to create a cascade classifier and it will contain the features of the face right
so that your code can determine okay where is the face then we will what
we'll use we'll use opencv that will read the image and the feature file and
we'll convert the image into numpy rs so it will search for the row and
column values of the face right so numpy and dimensional array the face
coordinates and it will display the image with the rectangular phase box let
me repeat it again for you guys what we need for face detection we need an
image then what we are going to do is we have a cascade classifier which
contains the features of the face then we will use opencv that will read the
images and the features so it will convert that image into a number array and
it will search for the row and column values of the faces of the face numpy
and dimensional array basically the face rectangle coordinates and then what
we'll do is basically we'll display the image with the rectangular face box
right so what we are basically doing here is we are going to first read this
cascade classifier uh we'll give the paths to it then what we are doing is we
are reading the image that we are talking about we'll give the path to it as
well we're converting it into a grayscale image cv2.color bg2 bgr2 gray is
basically going to convert it into a black and white image or a grayscale
image then what we are going to do is search for the coordinates of the image
right so we have this gray image we are going to search for the coordinates
with the help of detect multiscale this is basically to figure out where is the
face right let me just drill it down a bit so this will create a cascade classifier
object right and this is the path to the xml file which contains the face feature
then we are converting the colored image to the grayscale image after that
what we are doing we are using a method to search for the face rectangle
coordinates so this detect multi-scale is basically a method which will help us
to search for the face rectangle coordinates and scale factor basically
decreases the shape value by five percent and until the face is found so
smaller this value the greater is accuracy so scale factor is something i don't
want you to focus too much right now this decreases the shape value by five
person until the face is found it keeps on decreasing it right the smaller this
value the greater is your accuracy right and after that we are just printing the
type and the face and how we are going to add the rectangular face box for
that we are going to use a for loop and a method to create the face rectangle
this is nothing but a method to create that rectangle this is our image object
right and this is nothing but the rgb value of the rectangle outline so i'm going
i've given it as some color you can give it whatever color that you want now
this is the width of the rectangular phase box and these are nothing but the
coordinates x comma y then we have x plus width and y plus h so this is
nothing but x plus w plus comma y plus h right so i hope you guys are clear
with it and let me just quickly open my pycharm and i will execute the code
there i've already written the code so let me just take you through it it's very
easy guys i have a cascade a classifier object here that i've created which will
contain the face features then i'm reading the image which i want to create a
rectangular facebox around or detect the face i'm converting it into a
grayscale image then what i'm going to do is i'm going to determine the
coordinates of the face for that i'm going to use this detect multi-scale method
then i'm going to add a rectangular face box around it for that i'm going to use
this for loop and this rectangle is nothing but a method to create that
rectangular face box after that i'm resizing my image and that's all i'm doing
so what i can do is i can divide it by two so that it becomes easier for you to
see but i don't think so i need to resize this image what i'll do is i'll just keep it
the way it is and we're gonna see that particular image itself i don't think so i
need to resize it so i'll just type in here img and we have our code ready that
will determine that'll detect the face in the image yep it successfully did that
so i hope you guys have understood how we can detect faces in a particular
image using opencv so guys this is nothing but the type right so we have a
numpy and dimensional array so this is nothing but the coordinates of the
face now if i go back to my slides you can see here these are nothing but the
coordinates which i have displayed here right it's that easy guys now let me
go back to my slides again and we are going to see how we can capture
videos using opencv interesting right let's see how to use opencv to capture
video with computer webcam now before i move forward guys let me just tell
you a few things so what we'll be doing we'll be using opencv for reading
frames or images one by one so what basically a video is video is nothing but
multiple images or multiple frames which are displayed very quickly so that
it looks like a video so what we'll be doing we'll be using loops to build a
window where images will appear really fast so that you can see it as a video
something like this guy he's basically smoking a cigarette it is nothing but
two images but since i'm doing it pretty fast you can see it as a video like he's
smoking although i don't want you guys to smoke now let us see how we can
capture video using opencv the first thing we need to do is import opencv
obviously then what we are going to do is create a video capture object and
this number basically tells the computer to use our built-in camera right if i
want to use an external camera for example i have an external cam and i can
put one to use that similarly if i have two external cameras and i want to use
the third cam i can put two here apart from that even if i have a video file i
can give the path to that video file as well then this will basically release the
camera in some milliseconds right so let me just quickly execute this and you
will see what happens there right i'll quickly open my pie chart let me just go
to the basics of py file and i'll just type in here video equal to cv2 dot video
capture and i'm typing in here 0 to use my built-in camera and after that i'm
going to release this so i'm just going to type in here video dot release that's
all i have to do go ahead and execute this run it again notice that the camera
light will be on for split seconds again and i can execute it'll be on for split
seconds right so let me go back to my slides and i'll explain you there what
i'm talking about so basically when you execute the code you will notice that
your cam light switch is on for split seconds and then it turns off so what we
need to do is we need to add a time delay and for that what we need is a time
module right so what i'm going to do is i'm just going to type in here time dot
sleep 3 which will stop the script for 3 seconds for 3 seconds your camera
will be on right so when you execute the code the webcam will be on for
three seconds let us see if that happens or not i'm going to execute this now
so for that i'll open my pycharm again so this is my pycharm again guys i
need to first add time module here and now i'll add that time delay time dot
sleep for three seconds keep my webcam on and here we go so we have
successfully added the time delay it was that easy guys now let's add a
window that shows the video till now we didn't see the video we didn't see
what's happening right so how can i add that window it's very very easy guys
i hope you guys know this this is basically a video capture object now this
check is a bool data type that returns true if python is able to read the video
capture object this is just basically a true and false kind of a variable that will
return true if python is able to read the reader capture object otherwise it will
return false frame is a numpy array it represents the first image that video
captures right since we saw that video is nothing but multiple images which
appears really fast and it looks like a video right so the first image of the first
frame is basically what we will store in this particular frame the numpy array
of that particular image so it is a numpy array it represents the first image that
video captures we are going to print both check and frame and we are going
to add a time delay as well so let us just quickly open uh the pie charm and
we're going to execute this code there let me just open it for now what we are
doing here is uh check comma frame equal to video dot read let me just print
check and i will also print frame and let us go ahead and execute this we'll
see what happens all right so what happened here python was able to read the
video capture object that's why we have got the output as true basically our
check has returned true because python was able to read that particular video
capture object apart from that this is nothing but the numpy array for my
frame right which is pretty visible i don't think so i need to explain you why it
is a numpy array why it is three-dimensional i think we have discussed quite
a lot about numpy rs in the previous slide so for now i think you have
understood this what check-in frame is check is basically a bool data type it
will return true if python is able to read the video capture object and frame is
nothing but the n-dimensional array so guys now we'll see how we can
actually create a window right so what we need to do is we need to create a
frame object which will read the images of the video capture object and we
will recessively show each frame of the video being captured so all i'm doing
here is using this i am show function again right and i'm going to give a name
to it and i'm going to show all the frames which are going to come till i close
the window all right so it's pretty easy guys for three seconds you're gonna
see a video being displayed on a window and for that i'm just quickly going
to open my pie charm and i just need to add this i am show function there and
let us go ahead and do that cv2 dot im show i'm going to give a name says let
us call it as capture i'm going to type in here frame now uh we need to use
this wait for key function weight key uh let us keep it as zero so that
whenever i press any button it will close the window and finally i'm gonna
type in here cv2 destroy all windows so now let's go ahead and execute it so
we'll see a window that will capture our first frame and let's see if that
happens or not here we go

so yes the moment i press any key the window will disappear all right so this
is how we can display the video on the window right uh let me just go back
now how to capture the video instead of the first frame right for till now what
we did we just captured the first frame that appeared in front of the camera
right because that is basically what video is basically what it is nothing but
multiple frames which appear really quickly and that comes out as a video so
what we need is now we need to capture the entire video so for that what
we'll do we'll use a loop because i've told you earlier as well that is what
we're going to use uh in order to capture the video we will be using a while
loop right and the condition will be such that unless check is true python will
display the frame because what is check check will basically return true if
python is able to read the video capture object and if it is not able to read it
then it becomes false so our condition will be such that if check is equals to
true then python will display the frames right it will display the frame on a
window so let me just take you through the code that i have written here
video is equal to video capture equal to zero which is basically a video
capture object i'm not going to repeat that i have a variable a which is equal
to one while true while python is able to read the video capture object it'll
enter the loop a is equal to a plus one which will keep on increasing check
comma frame so it will print the frame basically the numpy array object and
what i'm doing here is converting the frame the image into a grayscale image
then i'm going to show that grayscale image and i've given it a time frame
that is one millisecond so it will be the this will generate a new frame after
every one millisecond so this will basically generate a new frame after every
one millisecond right so it is nothing but a weight key and after every
millisecond the frame will change all right guys and the moment i press q this
break statement will come out of the loop and the window will close right
print a this will print the number of frames that we have captured right and uh
video dot release you know destroy all windows you know right so let me
just take you through the code again we are importing cv2 and time module
then what we are doing we are creating a video capture object after that we
have a variable a equal to 1 which is nothing but it will tell us the number of
frames that we have captured while true which means that while python is
able to read the video capture object increase the a value by one then you
know these two statements we are printing nothing but the frame the n-
dimensional array object then we are converting that frame to a grayscale
image then we are showing it and after that we are generating a new frame
after every one millisecond that's what it is doing here then once we press q
we are out of the loop and console will print the number of frames and all
those things right so let me just quickly open my pycharm and i will execute
it there all right so for that let me just remove these things for now right so
after this i have a video capture object that you can see below this i have a
variable a equal to one now i'm going to use while loop while true enter the
loop a equals a plus one now over here i'm just going to print the frame and
now i'm going to convert this to a grayscale image gray is equals to cv2 dot
cvt color frame comma now i'm going to type in here cv2 dot bgr underscore

cv2.color underscore b g r to gray all right next up we are going to use this i
am show function uh let me just show you what i'm gonna do here i'll just
type in here cv2 dot i am show let it be capture again and i'm going to show
you the grayscale image and then finally i want a new frame after every one
milliseconds for that i'll type in here cv2 dot wait for weight key and after
every one millisecond and over here i'm just going to use a conditional
statement which says that if key is equal to equal to order q and then a colon
break the loop right and now i'm going to type in here print a which is
basically the number of frames now video dot release and then finally cv2 dot
destroy all windows right so i hope you guys have understood the code i'll
just quickly take you through it import couple of modules cv2 and time then
we are creating a video capture object we're defining a variable a equals to
one and while the condition is true that is my python is able to read the video
capture object we are going to create two variables check and frame where
check is a bool type variable frame is nothing but an n dimensional array
which will read the video right after that we are printing it printing the n-
dimensional object converting it into a grayscale image we are showing it we
are also mentioning that after every one millisecond the new frame should
appear and then once a user press q then the window will disappear and the
control will come out of the loop right and then we are printing this number
of frames video dot release we know we know what is destroy all windows so
let us see what will happen once we execute this and here we go oops so so
there is an error so all i have to do is define this variable key and here we go
so let me go ahead and execute this

so yup you can see the frame that is behind me and you can see my hand as
well so let me just quickly press q and you'll see that window will disappear
all right so i hope guys you have understood that how we can actually you
know capture the video and how we can display it on the window and then
things like that so i hope it was clear to you all guys so let me go back to my
slides again and now we're going to talk about a motion detector right so this
is our use case guys and i know all of you must be waiting for it right so let
me just take you through the problem statement why we are executing this
use case right everything exists for a reason so let us understand what are the
problems that this motion detector will help us to solve so you have been
approached by an organization that is studying human behavior now your
task is to give them a camera that can detect any motion in front of it and it
should return a graph which should contain for how long the object of the
human was in front of the camera so this is how the graph should look like
this should be the starting time right the moment object appeared in front of
the camera for how long it stayed in front of the camera then it went off then
again it appeared at this particular time then again it went off so this is how it
should look time at which object appears in front of the camera and the time
at which the object moves away from the camera so how we are going to
execute it so this is the flow diagram for that guys and first of all we need to
save the initial frame so what will happen since i've told you earlier as well
video is nothing but fast moving images all right so what we'll do the moment
we switch on the camera the first frame the first image that will appear we
will save it right then we'll convert that image to a gaussian blur image you
don't need to worry about it i'll explain you what is gaussian blur image then
we'll take the frames with the object and convert it into gaussian blur image
so basically this is done to give us the accurate results right the gaussian blur
image is something like that you don't have to go into too much detail here to
execute it but just understand it just to increase the efficiency we are
converting our images to gaussian blur so we are converting our first image
also to gaussian blur and the subsequent frames as well that will appear will
also be converted to gaussian blur image then what we'll do will calculate the
difference the difference between the first frame and the frames that will
appear after the first frame since the first frame is stored already we are going
to subtract that with the frames that will appear after that right then what we
need is now because of this we'll know okay there's a change in the frame the
initial image looks like this but now since there's some movement or some
motion we can see that there's a difference in the subsequent frames right so
we know that there is some motion or there is some object but that object
might be too small that we don't want to capture that for that what we do we
define a threshold that will remove the shadows and then two small objects or
other noises so basically we will define a threshold or the size of the pixel
that should appear as and it will be considered as an object right i don't want
a flying house fly to be considered as an object there just an example now
define the borders of the object right so we need to give a border or a box
there right basically a rectangular box around the object and then we are
going to calculate the time when object appears and exits the frame i hope
you guys are clear again guys i'm repeating the logic what happens you first
save the initial image in a frame what happens the moment you switch on the
camera the first image that will appear that will be saved that will be
converted to a gaussian blur image similarly whatever frames that appear
after that initial image will also be converted to gaussian blur image now the
difference between the first frame and the subsequent frames will be
calculated now that difference will tell us whether there is an object in front
of the camera or not because if there's a change from first frame then there is
definitely some object but that object might be too small and i might not want
it for that we will define a threshold all right so this should be the size of the
object in order to consider it as an object or any motion in front of the camera
then we are going to define the borders around that object we'll add a
rectangular box and then finally we are going to calculate the time when
object appears and exits the frame right we'll save that in a data frame and
after that we are going to visualize the data frame that's it we are going to
create a partner's data frame for that now the question is how i'm going to
execute it right so guys this is pretty much from what we did last time as well
so what we have here is we are going to create a video capture object then we
are converting the frame color to grayscale then we are converting the
grayscale image to gaussian blur image and this if statement will basically
store my first frame or my first image the moment i switch on the camera
whatever image comes first it will be stored in this particular first frame
variable right so the statement says that if first frame is none when there is
nothing in the first frame it will enter the root the first image that will appear
will be stored in the first frame and after that continue means it will come out
of the loop right let's see what we are going to do next after that what we are
going to do is we are going to calculate the difference since i have told you
earlier as well we are going to calculate the difference between a first frame
and the subsequent frames which i have stored in gray right so this will
calculate the difference after that i have defined a threshold now it provides a
threshold value such that it will convert the difference value with less than 30
to black if the difference is greater than 30 it will convert those pixels to
white so basically whatever object is there in front of the screen it will
convert that to white right whatever the difference is so that's why i've given
the color as well and this is basically uh the difference value that i've defined
a threshold here similarly i've defined one more threshold right you can see it
over here as well thresh delta that i'm using here after that what i'm doing is
i'm defining the contours or you can say the borders so basically the borders
around that object which appears now i'm adding one more threshold guys
this will remove noises and shadows or even a house fly which i don't want to
detect right so basically it will keep only that part white which has area
greater than 1000 pixels so if my object has area great smaller than thousand
pixels it won't be detected because i don't want to detect it right so you can
change it the way you want you can keep it five thousand you can keep it ten
thousand you can keep it two hundred that totally depends on you right and
this is basically to create a rectangular box around the object in the frame so i
hope you guys are clear with it and finally we are just displaying all the
things and uh yeah you can see it over here as well and you know what it is
basically frame will change after every one millisecond this will basically
close the window and this will close all the windows now what we need to do
is we need to calculate the time for which the object was in front of the
camera for that we will create a pandas data frame right so pandas.dataframe
is what we are going to use here that will have two columns start and end
basically when object appears in front of the camera and when it went off and
we are going to tweak a couple of things we are going to define this variable
called status status at the beginning of the recording is zero and as the object
is not visible right so if there is no movement then it will be zero because
there is no object that is there in front of the screen right but it will change the
status when the object is being detected the status will become one right
similarly we were going to append the status list of status for every frame for
every frame we are going to append it so this basically tells us the second last
status list value all right these two condition statements will basically record
date time in a list when change occurs let me tell you how so if my state is
underscored list the last value of this list is actually equal to equal to one
which means there is a object but my second last value says that there was no
object before in the previous frame that means there is an object which has
appeared right so that basically the time at which the object has appeared will
be stored here again which will be stored here after that if you notice the
second conditional statement which says that my last frame does not have
anything uh i mean there's no object in front of it in front of the camera but in
my second last frame there was an object that means the object went off right
so it will note that time as well when the object was not there in front of the
screen that simple guys so this will basically create a pandas data frame that
will have two columns start and end which will tell us when the object
appeared in front of the camera and when the object went off from the camera
right so this is how it is and then what we are going to do is we are going to
create a use this for loop in which we are storing the time values in a data
frame right i think you guys are aware of pandas if you aren't aware of
partners i'll leave a link in the description box below which is nothing but a
detailed tutorial about pandas and data analysis using it so go through it if
you are not aware of pandas it's very important library i think every python
should know about it and then we are going to store it in a times dot csv file
so it will be a csv file right so time i n time is equals to i plus one ignore
index so they basically we don't have any index values here right we don't
want to display the index so there is no index value here this for loop is pretty
self-explanatory so let me just go ahead and execute this first and then i'll tell
you how we have visualized it so here is our motion detector guys i've
explained you the code in detail and if you want the code you can go ahead
and you know mention your email id and we will reply you back we'll
basically provide you with the code so if you're looking to execute it on your
own go ahead and mention that right so what i'll do is i'll first you know won't
come in front of the camera i'll go away because it has to first capture the first
frame then only it can identify the difference between the subsequent frames
right so guys i'll execute it now and what will happen it will first capture the
first image which is there in front of the camera and any movement that will
happen it will capture that right so the first frame will be stored then the
difference between the first layer and the subsequent frame will be calculated
in order to determine if there is a object in front of the camera or not let me
go ahead and execute this so guys you see a plain background there's nothing
right so this will be saved the first frame and then let's see uh what will
happen if i bring in my hand so there's a rectangular box around my hand you
can see right so it is basically uh capturing the motion around the camera and
all of these things are saved in my pandas zeta frame right so you can notice
my hand is coming and then it is going off so all the the time at which the
hand appears in front of the camera and the time at which it went off will be
stored in my pandas data frame because i have two columns start and end
right so if i just minimize this let me show you the gaussian blur image as
well right so yeah in that gaussian blur image i have defined that you know to
keep the object white if it is greater than thousand pixels right so this is what
comes up right yes this is gaussian blur image this is gaussian blur yeah and
this is a gray frame which you can see over here let me press q it'll close all
the windows now let me show you this times.csv file so yep this is how it
looks now let me go back to my slides again now basically what we are doing
is we are going to plot it on the browser using the bokeh library now guys to
explain bokeh it will take a lot of time right i've just written the code here to
show you how the graph will look like i'll be coming up with a separate
tutorial on bokeh if you guys want so if you really want a tutorial on bokeh
which is nothing but a library that helps us to visualize the data on the
browser you can go ahead and mention that in the comments section that we
want a tutorial on bokeh as well right for now i'll just go and uh open my
pycharm and i'll execute the code there so this is my code that will help us to
visualize the graph right so it is basically using the motion detector which i
have here right from this file it will take df the data frame which we have
created so let me just go ahead and run this

right so again uh i'm just going to put my hand couple of times and gonna put
my other hand as well yes so yes i think it's a good enough size of the data
frame and it should appear in the browser the moment i press q you'll see that
there'll be a graph that will appear on our screen and here we go guys so this
is the graph that i was talking about end time start time so let me just increase
the size for you guys so yeah this is how the graph will look like start time
end time so we have everything here so guys so i hope you have understood
this and it was an interesting session for you

top five frameworks in python so without wasting any more time let's look at
the agenda for this session so first of all i'll be starting with what exactly are
frameworks in python moving further we will discuss why we are using
frameworks and then i will list out the top five frameworks that we have in
python namely django web 2 pi flask bottle and cherry pie i hope you guys
are clear with the agenda so let's quickly try to understand what are
frameworks in python python is a general purpose programming language it
is one of the most popular programming language nowadays we can use it for
so many applications including web development now a framework is a
collection of modules or packages which helps in writing web applications or
it helps in web development now we don't have to worry about the low level
details such as protocol sockets or thread management when we are working
with the framework frameworks make the developers life easier by giving
them a structure for app development they automate the implementation of
common solutions which gives the flexibility to the developer to focus only
on the application logic instead of the routine processes they provide
common patterns for faster reliable scalable and easily maintainable web
applications now let's take a look at a few operations that i use to run web
applications using frameworks so i have listed down all the operations here
so first of all we will talk about url routing so url routing is the mechanism of
mapping the url directly to the code that creates the web page the next one is
the input form handling and validation coming on to the next operation is
output formats with templating engine now you must be wondering what a
templating engine is a template engine allow developers to generate a desired
content types for example html xml or json we also have the data connection
configuration and persistent data manipulation through an orm orm is also
known as object relational mapper now you must be wondering what is the
function of an orm an object relational mapper or an orm is a code library that
automates the transfer of data stored in a relational database table into the
objects that are most commonly used in an application code we also have the
web security against cross sites request forgery also known as csrf sql
injection cross-site scripting and other common malicious attacks as well the
last but not the least is the session storage and retrieval so these are only a
few operations we can perform using the frameworks in python now let's try
to look at a few advantages of python frameworks first of all python
frameworks are open source which means you don't have to spend any money
while working on a python framework the next one is it has a very good
documentation all the frameworks in python have a very good documentation
which means you can learn easily the functionalities and the key features of
any framework using the good documentation that it has the next one is the
security where it provides security against the malicious attacks and then
there is integration and efficiency as well so these are the advantages of using
a python framework for web development also there are a few limitations
when we are working on a python framework which is it is open source so
the code is going to be public so that is one issue here also there are a few
limitations when we are using a framework because the difference between a
library and a framework is it adds to a few rules and regulations when it
comes to a framework now let's try to understand why we are using a
framework now we know that frameworks make it easier to reuse the code
for common http operations and to structure projects so other developers with
the knowledge of the framework can easily build and quickly maintain the
application so these are the advantages which is why we are using a python
framework that is easier implementation we have the maintenance and the
readability is pretty good and then there is code reusability as well so these
are the reasons why we are using python framework instead of a library right
so now that we have understood what our frameworks and why we are using
them in python and also we have discussed the key features and advantages
of python frameworks now let's try to look at the top five frameworks that we
have in python so first of all let me talk about django guys django is a free
open source and a full stack python framework which includes all the
necessary features by default it follows the drive principle which says don't
repeat yourselves also django uses orm to map objects to the database tables
some of the exemplary features of django are authentication url routing
template engine and the orm also there is database schema migrations as well
now the main databases that django works with are post gre sql mysql sqlite
and oracle also it follows the mvc mvt architecture so let's try to understand
what is an mvc mvt architecture the model view template or mvt is slightly
different from mvc which is the model view controller in fact the main
difference between the two is that django takes care of the controller part
itself the controller part is basically the software code that controls the
interactions between the model and the view leaving us with the template
now the template is a html file mixed with the django template language now
looking at the diagram we can understand that the developer provides the
model the view and the template and then just maps it to a url and django
does the magic to serve it to the user so this is the mvc mvt architecture guys
and this is all about django now let's try to understand the next framework
that we have which is actually web 2 pi web 2 is a scalable open source and a
full stack python framework however you should know that it does not
support python 3. now what is so great about web 2pi right it comes with its
own web-based ide and among other things includes a separate code editor a
debugger and one-click deployment as well now looking at the other valuable
web to pi features it includes no requirement for installation and
configuration it has the ability to run on different platforms it has the ability
to read multiple protocols it also provides us with data security that prevents
such vulnerabilities like cross site scripting injection flaws and malicious file
execution it also has an error tracking system through error logging and
ticketing systems also it has the ability for role-based access control and last
but not the least it has a backward compatibility that ensures user oriented
advancement without the need to lose the ties with earlier versions so this is
all about web 2 pi guys these are all the features that we have in web 2 pi
framework now let's talk about the next framework that we have which is
flask framework so talking about flask flask is a micro framework guys now
the difference between the full stack framework and a micro framework is the
full stack framework does the heavy lifting for the application that we are
making but the micro framework is small and very easy to use also when we
are using the micro framework the url routing is going to be restful for many
of the occasions so this is the basic difference between a full stack and a
micro framework guys now let's try to look at the features of the flask
framework so i've already told you it is a micro framework it is lightweight
and it has a modular design which makes it easily adaptable to developers
needs it also includes a number of useful out-of-the-box features which
include a built-in development server and a fast debugger it also has an
integrated support for unit testing and the restful request dispatching one
more thing guys first suppose the jinja 2 templating now you must be
wondering what is the jinja 2 templating right so jinja 2 templating is nothing
but a modern day templating language made after the django's template
language coming on to the next features we have a flask it has secure cookie
support that is the client-side sessions then we have wsgi compliance as well
which is the web server gateway interface now you must be wondering what
is whdi guys it actually implements the web server side of the wsgi interface
for running the python applications that we are making now flask is also
unicode based and also has the ability to plug in any orm last but not the least
we have the http request handling as well so these are all the key features of
flash framework guys now that we are done with flask now let's move on to
the next framework that we have which is bottle talking about bottle bottle is
also a micro framework guys originally it was meant for building apis portal
implements everything in a single source file it has no dependencies apart
from the python standard library now its default features include routing
templating utilities and a basic abstraction over the wsgi standard bottle is a
perfect solution for prototyping learning the organization of web frameworks
and building simple personal apps so these are the features of bottle
framework which is also a micro framework guys just like flask so now that
we are done with the key features of bottle let's take a look at the next
framework that we have which is cherry pie cherry pie is an open source
minimalist web framework it makes building python web applications no
different than building any other object oriented program it allows you to use
any type of technology for templating data access and so on however it's still
able to handle sessions statics cookies file uploads and everything else that of
web framework typically can now let's try to take a look at some default
features of cherry pie it has an http compliant whgi thread pool web server it
has the simplicity of running multiple http servers at once it also has a
powerful configuration system a flexible plugin system it also has out of the
box tools for caching encoding sessions authentication static content etc now
cherry pie also has a built-in support for profiling coverage and testing and
last but not the least it also has the ability to run on different platforms so this
is all about cherry pie guys now that we are done with the top five
frameworks and we have discussed the key features of all these frameworks
let me take you to pycharm guys where i have a sample project that i made on
django and flask so this is actually where my project is saved guys so i'll go
to my project and this manage.py file is actually the file which helps with the
management of the site and we can start a web server without installing
anything else so i'll copy this path guys and i'll go to the project that i made
over here and if you want to know how you can make a project or install
django on your system and then make a web app you can simply go to the
edireca youtube channel where we have the detailed tutorial about django in
which we have a detailed tutorial about django web development and where
you can actually learn to build a simple app from scratch so what i'll do is i'll
just write the path that i have copied so now that i'm in my directory where i
want to run my server i'll just write python dot manage dot py to run my
server i'll just write run server now you have to pay a little attention to these
files that you get while creating your project in django so these files are there
so settings dot py file actually has the configuration of your website and url
dot pi have the list of patterns that will be used by the url solver and then you
have the database the time zones and everything else that you can actually
edit in your settings dot py file so i'm not going to go line by line explaining
everything so i'll just explain you that i have one more directory polls over
here which is actually my app and in this i have migrations and the template
inside the template i have the html file where i have actually written the code
of my survey form that i have made that i will show you guys so when i run
this server what is going to happen is i'll get address wait let it run so i'm
getting this address guys so when i go on this address and write polls that is
the name of my app i will get this survey form that i have made and stored
inside the template that i had made so this is actually a very basic survey
form that you can make from using the django app so let me show you guys
what the same thing you can do using flask so i have also made a project
using flask as well so in this we have the main file main dot py when you
install flask you can simply import it and there is no i'll show you guys in the
project interpreter so inside in project interpreter you can just add flask over
here if you don't have install it in your system you will find it over here you
can install the package and you are good to go so now that i have told you
about the main dot py then we have a render template in which we are going
to store the html file the template that we have inside this i have also written
the same code for the survey form and to run this server we are just going to
run this main file and you will get an address see over here and when you go
over here and type the name of your app that is profile you will get the same
survey form that i had got so this is a sample project guys that you can make
for practice although it is a very basic thing that you can do you can connect
it to your database and there are so many things that you can do while using
these projects so this is only a very basic project that i have done using this

let's move on and see why python is used for web development guys python
allows you to build web applications dynamically it's a very stable language
it also grants you ease to build multi-protocol network applications the fact of
python being flexible easy to use and its quick processing are just a few
reasons to mention for its worth in web development now that i've explained
about the features of python let's take a walk through some of the libraries
that python provides for web development guys python provides a number of
libraries for web development some of the important ones are cherry pie
django web to pi pyramid turbo gears and flask among these in today's
session i'll be using the django framework so now you all might be
wondering why django and why not any other library django is truly the best
python library for web development it's written purely in python and it's fast
you can create websites within a matter of few hours it's fully loaded with all
the required tools to create websites and it's very secure be it youtube your
dropbox google or instagram all these internet giants rely on django so with
this i think i've given you enough for why i've chosen django over the other
libraries so as you can see over here web project has been created within the
current directory so after this i'll just open up the terminal and over here i'll
use the command pip install django

it's going to take a while to install django guys so when you're installing
django along with django the sql parse database and the pytz module also
gets installed sql powers is actually a non-validating sql parser for python it
provides support for parsing splitting and formatting sql statements now this
is actually compatible with versions of python from 2.7 the pyth module is
actually a third party module that brings the olsen tz database into python tz
actually stands for time zone guys this library allows accurate and cross
platform time zone calculations using python 2.4 or higher it also solves the
issue of ambiguous times

ok so once django has been installed it will throw a message saying


successfully install django with its version and the version of the pytz module
and the sql parts now to cross check the installation of django go to your
command prompt

and use the command python hyphen m django

hyphen hyphen version

now when you use this command it should return the version of django that's
been installed so i hope everyone's getting the same okay so now let's close
this i hope everyone's clear with this for any doubts guys please do let me
know in the chat box because my team is always here to help you so now to
create a django project within this project i'll use the command django
hyphen admin

start project

and i'll give a name to my project let me give the name as demo project

okay so now a demo project has been created within the web project directory
let me open this directory and here it shows the web project that's been
created let me just go to the presentation mode and show y'all i'll go to view
and i'll select the files that i want and the terminal as you can see over here
within the demo project directory there's another directory with the same
name as my project and there is a file created by django called as the
manage.py file the manage.py file is actually a command line utility that lets
you interact with the django project don't worry guys we'll be using this many
a times so you'll get familiar with this now let me just open this directory and
see what's present within it the first file that's created within this directory is
the init.py now the init.py is actually an empty directory which is considered
to be a package after that there is something called as the settings.py this
actually consists of all the settings that are necessary for the current project
after that its urls.py urls.py consists of all the url declarations for this project
and finally the wsgi.py file where wsgi stands for web server gateway
interface now this is actually a calling convention guys for web servers to
forward requests to web applications or other servers so i hope everyone's
clear until here if you have any doubts do let me know in the chat box okay
so now to check if i'm able to connect from my project to the web server i'll
just get into my project using the cd command

and after this i'll use python manage dot py

run server like i told you the manage dot py file will help me connect to the
server so this will return an ip address so when you click on that address you
will see a screen with a rocket which is ready to take off so congratulations
guys your rocket is ready to move on which means you're all set to create
your own websites so i know that after this everyone would be excited to
create their own websites to do so i'll just get back to my pycharm and show
you guys what exactly you must do to create your own websites okay so to
create my website all i'm going to do is create an app within my demo project
i'll just return the control to my terminal using control c and over here i'll
create a new app within my project please make a note guys that one project
can have n number of apps which means you can include any number of apps
within your project to create an app i'll use the same command which is
python manage dot py and instead of run server i'll use the start app
command and i'll give a name to my app let me just give the name as demo
app so now an app has been created within my project let me just open this
up to show you all what's present within this demo app so just like how
django had created files for us within our project when we created a new app
django has created the necessary files for us so this is what django does it
writes all the necessary code and all you have to do is write your website
specific codes and just modify the files that are present and add your own
files as per your choice the first file that i'm going to open over here is
views.py and as you can see over here django has already imported render for
me now i want to use the http response function so i'll use from django.http

import http response please be careful with your spellings guys

now within this file i'll create a new function using the def keyword and i'll
give the name of the function as hi to this function i'll pass one parameter
which is request
within this function i'll just write one return statement

using the http response function i actually want this function to return a
message saying that this is the home page of my website i'll just put it as a
string and i'll use the h1 tag for this this is my home page

and i'll close the h1 tag slash h1 so as you can see over here pycharm has
highlighted this line because i'm using the http response function the first line
of my code is not highlighted because i'm not using the render function
anywhere as of now i'll not be using the render function however i'll be
showing you how to use this later on okay now i've created views for my
project but i will not be able to connect this file to the urls.py which is present
in the demo app to connect views.py to this urls.py i'll have to create another
urls.py within the demo app directory and connect that urls.py to the urls.py
which is present in the demo project don't get confused guys i'll be doing it
over here and the video will be available after this in case you have any
doubts you can go through it again so i'll just create a new file within this app
it's going to be a python file i'll give the name as urls.py

and i'll say ok this url start py is actually very similar to the urls.py which is
present in the demo project so i'll open the urls.py present in the demo project
directory and i'll copy the from statement which is from django.urls import
path and the url pattern list i'll just copy this and i'll go to urls.py present in
my app and i'll paste it over here now over here since i want to map the
views.py into this urls.py

what i'm going to do is use from dot which means from the current directory
import views and within the urls pattern i do not want this admin path so i'll
just remove this and i'll leave the name as blank

because i want this to be mapped to my home page and over here i'll use
views.hi which is the name of my function and i'll give a name to this path
you can give any name of your choice let me just give the name as home
page home hyphen page okay so after this what i have to do is map this
urls.py to the urls.py which is present in the demo app so i'll open the urls.py
present in the demo app and over here i'll create new path and i'll give an
empty string because i want it to be mapped to my homepage like i already
told you all oh sorry guys i'll have to import the include function also so from
django.urls i'll import the include function

and over here i'm going to use the include function i'll map the urls.py present
in my demo app

and i'll close this so after this let me just go to my terminal and use python
manage dot py run server i've just made a name mistake this is demo app

okay so as you can see over here it has returned the ip address again i'll click
on this ip address congratulations guys instead of that rocket which we were
seeing previously which was the default page my website is displaying
whatever i want it to display so this was the message i wanted to display on
my home page and it shows that this is my home page so now i'll get back to
my pycharm and i'll see how i can modify this page to create a website i'll
return the control back to my terminal using ctrl c so to write html code
within this project all you have to do is create a new directory within your
app directory

and that will be the templates directory now these will be the templates that
are specific to this project and instead of looking elsewhere django will look
into this directory for the necessary templates

within the templates directory i'll create a new directory with the same name
as my app don't get confused with this guys this is actually the django
convention which helps you write project specific code so within this demo
app i want to write the html code so i'll create a new html file to write all the
html code that i want i'll just give the name as high.html and i'll say ok so as
you can see over here django has already written the minimum html code for
me i'll just change the title to edureka guys you can give any title of your
choice and within the body i'll just write hi and after this i'll open the apps.py
file i'll copy the name of this class

and then go to settings.py present in my demo project and over here i'll look
for installed apps
remember that whenever you create new apps you'll have to add it over here
then within a string give the name of the app which is demo app please be
very careful with the spellings because if you make any mistakes it's going to
throw a lot of errors and you'll not be able to understand why it's throwing
such errors and for beginners it sometimes gets very confusing to debug these
errors so just be careful over there so let me get back to this name of my app
which is demo app dot apps dot the name of the class that we've copied from
there i'll just paste it over here and i'll specify a comma after this now from
here i'll go back to my views.py file and instead of this http response i'll be
using the render function so i'll just remove this

i'll return render

and i'll specify the request function and then within a string i'll specify the
html file which is present in the demo app so demo app slash hi dot html
which is the name of my file guys please write the same name which you
have given to your file i'll run my server again after this so python manage
dot py run server let's go back to our server and see what happens so as you
can see over here guys the title has changed from the default address to
edureka and my home page now shows a message saying hi so i hope
everyone's clear with everything until now now all i'm going to do is go back
to my html file and do some modifications to create my own website

so now to create my own website i'm just going to modify this html page
guys if you're done till here you've been successful in creating a website now
all you have to do after this is specify your project specific html code let me
just show you a few basic things that you can do using html over here so i
hope everyone knows some basics of html let me just change the message
from hi to welcome to edureka

okay i'll just specify the second line of my page to be some h2 tag and a new
message saying that this is my website

let me save this and rerun my server i'll just go back to my server and i'll
reload the page so as you can see over here the h1 tag says welcome to
edureka and the second h2 tag says this is my website so this is how you can
write your own html code to your program guys so now let me create some
list over here to create a list i can either specify it to be an ordered list or an
unordered list for ordered list i'll have to use ol tag and for unordered list i'll
have to use the ul tag over here i'll be using the unordered list and within this
list i'll specify the list elements

first element is python and the second element i'll give as java or something
okay let me save this go back to my server and reload this page so as you can
see over here guys it has created an unordered list over here so now let me
show you all how to create a table over here so to create a table for your
website you can use the table tag and specify whatever style you want for
your table in my case i'll just give the width to be 30 and i'll close this so
within the table you can have the tr the th and the td tags the tr tag is actually
for the table rows th is for table headings and td is for the table columns i'll
just write a dr tag over here and within this tr tag i'll specify the th tags

let me just give the heading as python and i'll give another heading

as java so after this i'll create another row using the tr tag and within this i'll
specify the columns so for that i'll use the td tag and i'll just specify which ide
you can use for python and java so for python you can use pycharm let me
just copy this

and for java you can use eclipse so i'll change the name from pycharm to
eclipse over here

i'll save this

so as you can see over here a table has been created but guys my table over
here does not have any borders to add borders to my table i'll go back to my
html page and over here within head i'm going to use the style tag

and within this tag i'll specify what border i want for my table

let me save this and reload my page so as you can see over here guys i
included the style tag and specified what kind of border i want so the same
way on my server over here a table has been created with a specified style to
know more about html and learn how to create beautiful websites you can
just go to the bootstrap website

and from here you can take any code that you want for your website so i'll
just show you what happens when you use this so let me just use the style
from the bootstrap and it should be present within the head so i'll just paste it
over here let me save this i'll go back to my server and i'll reload this page as
you can see over here guys using the small bit of code that was present on the
bootstrap website my website looks so much more better than what it was
looking before this you can use this bootstrap website to create your own
beautiful websites

web scraping using python now without wasting any more time let me
quickly tell you what all we are going to cover in this session so these are
topics that i'll be covering in this session so i start the session by first
discussing the need what is the need of web scraping or why do people
actually scrape a website and then we'll understand what exactly is web
scraping now once we get an idea of scraping we'll then understand the
different libraries which are used to scrape a website and towards the end
we'll be doing a demo where i'll be scraping a website from the scratch so in
this demo i'll be fetching some details from flipkart so i hope you guys are
clear with the agenda

now let me begin with the very first topic that is the need of scraping or why
do people actually scrape a website

so scraping is basically extracting data from various websites now there are
many ways to collect data online but let's say i just want to collect data for
comparison so here let me take an example of my smart price which is known
for best price comparison so what they do they collect data directly from
merchants now the larger stores generally provide the feeds which are listed
on their stores but what about the smaller stores now one way of doing it is to
either copy the prices from different websites and then paste it to your local
system which will in turn be a very tedious job and it will consume a lot of
time as well so what you can do you can simply scrape the prices from
different websites now apart from these there are many use cases or you can
say real life examples where people do scraping so here first is your e-
commerce portals now here what you can do you can build your own website
and then scrape products from retailer or you can say manufacturing websites
so basically you can skip prices ratings images or any other specifications as
well then you have market research so here scraping can help you in
providing important information to identify to analyze the market to analyze
the need its size and the competition of market as well now it can be any kind
of industry it can be your travel areas where you can scrape reviews or you
can scrape products or any places hotels restaurant or it can be anything then
you have social media so here people scrape business profiles from social
networks and track their online presence and reputation and hence the list
goes on so people generally use web scraping to build the best marketing
strategies monitor them and hence upgrade their business so in a way web
scraping provides them a way to get information whether it can be your
website prices it can be images it can be data for any for any analyzing
purpose as well so also you do scraping because many websites do not
provide an api unlike facebook twitter and all but in many cases you will find
that web scraping is the only alternative to get data out of them so we have
discussed the various real-life use cases which uses web scraping but here the
question is is it actually legal well maybe scraping is fine till you are not
causing any considerable damage to the target website and you are doing it
responsibly so website is legal as long as there is no attempt to change the
article or block or anything you should not try to override the restricted
access of the website or play around with the security mechanism now let me
tell you the companies who have faced problems while web scraping

so you all must have heard about linkedin so in 2014 there was a case where
they sue a group of dependents in california now this case was based on
digital millennium copyright act where they used a series of bots and fake
profiles to scrape the data from other member profiles so that is why you
should always know the difference and respect the fine line between
collecting information versus stealing it so now let's understand what exactly
is whip scraping now as i've already explained you the need it will be very
easy for you to understand this concept so web scraping is a method where
you pull data from different web pages extract the useful information and
then store the same data to your local storage now this local storage can be in
any form it can be an xml form it can be csv or it can be any database as well
so web scraping is a technique where you automate the procedure within a
fraction of seconds instead of manually copying the data from websites now
we know scraping is when you extract any information now if you want to
extract through a browser or a website or web page so that process is known
as a web scripting so let us see the basic steps which are involved while
scraping so the very first step is document load now in in our case we are
doing web scraping so we have to load the entire document which is your
html page next is your parsing so parsing is basically where you interpret
your document to make your searching possible so in html there is a dom by
which you interpret all the html code next is your extraction so here you
simply extract anything like the name like the price or any specification of
the product and the last is your transformation so here it basically converts
the data into useful formats like for example you can change the type here
now if you have a date string and you want to output as date so you can
transform it in any form so these are the steps which are involved to do
simple scripting

now let us see what are the different packages that are used for web scraping
although i would recommend python because a lot of people use it for web
scraping well the good part about python is that it has libraries for everything
now this is why it is the go to language for many developers now as you can
see here there are a lot of libraries which are used for web scripting such as
patterns scrapey mechanized beautiful soup and request so i have only used
scraping i have also i've only used python for scraping because what i like
about python is that it makes a string manipulation very easy so string
manipulation basically is the key where you pass any information from a
page along with this it is also compatible with various databases such as your
nosql databases like mongodb and mongodb is what we mostly prefer to use
for data storage in web scripting now as you can see there are different
python packages now these are not enough we also have some other python
libraries such as xpath you have pdf you have miner and many more but here
if you see beautiful soup and request are the most popular libraries in this lot
and later in the demo we'll be implementing them as well
so beautiful soap is a python library which is used for pulling data out of your
html and xml files now it provides you simple in fact very simple ways of
navigating searching and modifying the html and many more things like that
next is your request so request is a library which is widely used for sending
and receiving information over http

well that's all for the theory part so now let me move on to a demo part where
i'll be scraping a website from the scratch

excuse me so here we'll be scraping flipkart now let's see what all we can
scrape from it so we all know flipkart is an e-commerce company so what i'll
do first

so what i'll do first i'll simply search a product on flipkart let's say an iphone
so here as you can see the list of all the iphones will be displayed now what i
do i have to fetch the name of the iphone what are the configurations what are
the ratings and what is the price of the iphone so fetching all these details i
need to first view the html page now how will i do it i have to simply right
click it and go to the inspect so this will basically open up my html code now
this is my html code so to understand this html let me open my pycharm and
let's understand each component one by one

so this is my pyjama community guys and as you can see this is the code for
scraping flipkart well it is not that big code because python makes it very
easy it has a very it has small syntaxes and it is very much similar to your
english language as well so what i have done in the beginning i have simply
imported two libraries which are beautiful soup and requests so these libraries
i've already discussed so how you can import them you can simply go to file
then go to your settings open your project integrator and here all your
packages will be present now here as you can see we have beautiful soup for
so we just click on that and just click ok so these packages will be imported
automatically

now i have named my beautiful soup as soup and request as you request
because i don't want to use beautiful soup and request again and again next
also i have used url lib which is a package now if you're using python 2 you
have a different package you will be having url too since i am using python 3
so this will work for me and then i have it and then i have a function which is
url open so this function will basically import all the dependencies next what
i've done i have simply specified the url which i have to script so let me just
copy this url and let me show you what does this explain

or in fact if you don't want to copy it just simply type in flipkart.com

you can search the product now in my case it's iphone

so as you can see there is a list of iphones are displayed so here we have all
the necessary details of it we have the title we have the ratings we have the
reviews we have the price as well so this is what the flip card page now let
me go back to python and let's understand the code

so here what i have done i have i have my u request which basically opens up
the connection and this will grab the web page or the flip card page in our
case and then it will directly load it and then what i have done i have simply
saved it to a variable which is you client after that what i have done i have
passed the same variable to the read function so this read function will dump
all your data which is gathered and then store the same in the variable which
is h page underscore html and then i have closed the connection then what
next i have to do i have to parse my html because it's a large html file so let
me show you the html

now to see html you just have to right click go on inspect so here on the right
hand side you see your html code now if you move your cursor you will see
the left side the pointer will be changing so here if you want to see which part
it is showing you have you have this title then if you go down you have the
reviews and the ratings and then if you have you'll go down you have the
content or you can say the description and after that you have the price so
what i have to do i have to first search for the main class in which all these ah
all these features are present so if i go up so this is my main class or you can
see the main div class which covers all the element it has title also it has price
also it has ratings reviews and everything so i'll just copy this class and go
back to my pie chart

so here i have written this i have this pasted this the same div class which is
over here so here i have paid two which will help me to pass my h which will
help me to pass my html and then i view the function which is find all so here
it will find all the div tag which has which is a class now in some cases it
may be id also so here we have div tag which is a class and the name of the
div tag and then i have stored it into containers so next what i'll be doing i'll
be printing the length of these containers which will basically tell me how
many products that i have on this webpage so i'll comment the whole code for
now

so here as we see there are 24 products on the very very first page of flipkart
so let me show you again so here as you can see there are many products now
using this length function i have calculated that there are 24 products which
are displayed on the very first page of flipkart site

so this was for the one diff class or you say just one container but let's say i
have to face details of each product which is present on the webpage so what
i have to do i have to traverse the dom elements so first of all i will first see
the containers or you can see the html code for the very first index so here i'll
be i'll be writing print soup dot prettify containers and the first index

so prettify is a function which is used to beautify your html or basically it will


bring your html in a structured or you can say an organized format

so let me just run this whole html

so here my html so this is my basically html now what i'll do i'll copy the
whole html and i'll paste it somewhere else let's say i'll place it in my notepad

so that we can see it simultaneously now let us try to read this html a bit now
here first we figure out what things we need to scrape from here so here the
first thing that it is visible that we need a title of this

we need the title of the phone which is apple iphone se space gui and it is 32
gb now this title is present inside a div tag in inside another div class and then
it has an image tag then let's see what what else we can scrape from here so
here we have 4.5 rating so this is the rating so we can skip this as well

and then moving on we have the price as well so these are three things that
we can scrape we have many more things but for now we'll just be scraping
these three things so let me go back to my pycharm and let's see what is the
first thing that will be going to scrape

so here what i have done i need a loop for travis for traversing these elements
so for that i have stored the elements of containers in a variable called as
container so this containers is my main div class which has all the elements
present so now what i'll be doing i'll be first printing the title or you can see
the product name so for that let me open my html so here as you can see in
this container i have a div class and inside that dip we have another div and
inside that div we have an image tag which has an title alt and this is
basically the attribute of it so attributes are always written in square brackets
so here as you can see i have print the container and inside container there is
div and inside there we have image and then we have a attribute which is alt
so let me just print the print this and let me see what what does it display so
here we have the first name or you can see the first phone or you can say the
first title of the phone so this is my apple iphone se space scene that we have
already seen in the html next what i have to do

i'll escape some other thing let me just comment this thing

so next i'll be i'll be scraping price so let's see where this price is present

so here is my price now i have to see that in which div class this price is
present so in this div class which has the title this so i'll just copy this and i'll
go back to my code and i'll paste it over here so this is the exact same div
class which i'm talking this now inside this i have container which find all the
div which has which is a class and then the name of the dip class now here if
you see i have print price zero dot text now why text because as you can see
here i have react id i have data react id then i have react text they have a
rupee symbol and we have many more tags but but this price is not enclosed
in any of the tags so for that this becomes my text now similarly i have 21
000 that's text and i have 26 000 and all these things will become as text so
let me go back and here i have print price 0 which is the first element and
then the text so let me just print it for you

so as you can see all the text has been displayed so it says 21 000 which has
some 19 off and then it tells me the ami option which starts from this price so
this so this is how i have fetched my price now what i have to do i'll be
printing ratings as well so it will be the same procedure so what i'll just print
i'll just comment the price

and for ratings let me again go back to my html and let's see where is my
rating

so this is my rating now again i have to see which class it is present in so this
is present in this class so i'll again copy this class i'll go to my pycharm i'll
write i'll paste this and then i'll say rate container which find all the diff class
div tag which ha which is a class and then the name of the class here also i
have done the text because if you go ahead and see html you will see a lot of
things you have 4.5 then you have stars in all these things so it will be very
easy if you write text so if i go ahead and run this program so as you can see
4.5 star 3 this rating and this reviews have been printed

next i have all the details like title price ratings so let me just print them once
again for you so we have we have your title we have price and then we have
rating so let me just print it together once more so as you can see i have the
title i have the price and i have the ratings so now what i have to do this is
showing in my terminal but what if i want to show this in my file so for so
now i'll be creating a file so i'll just again comment this and here i'll be
creating a file

so here i've created a file which is named as products.csv and then using the
open function i have instantiated a mode that is right and then stored the same
in f so this f is a normal convention of f writer then what i have done i have
created some headers to it so because csv do has do have headers so i have
added manually hidden headings to it so i have written product name or you
can say title then the pricing and then the ratings and then i have simply write
it so i have these three things for one containers now i have to do the same for
all the containers or you can see all the diff classes which is present on the
web page so for that i need a for loop so what i'll do next i'll create a loop
now here it will say for container in containers so containers is the main class
where all your element is present or your features are present so here i just i
want the same things i need the product name i need the price and i need the
rating so here i'll just simply copy the same things which i have already
showed you so here for printing the title i have written container.image and
alt so i have copied it here and then i've saved it into a variable which is
product name similarly for product similarly for price similarly for price i
have i'll be copying this thing and this and i'll be saving it to a variable which
is price and similarly for rating so here if you see i have added one more
function that is trip so strip basically eliminates all your unnecessary commas
or unnecessary spaces which are present on the website because every time
the spacing is not not present so in this case my extra spacing was there so
i've written this strip function

so let me now print all of these and let's see whether my loops work or not

so as you can see i have the title price and rating for all the products so this is
my first product name then i have the price for the same and then i have the
rating next i have the second product name i have the price and then i have
the rating so similarly we have 24 products ratings and price for the same
next what what you can do let's say i don't want the entire price or i don't just
need the discount or ami options that it provides so what i can do i can simply
pass my string so let me just again show you

so if you see here i just don't need the whole price i just need 44 999 but i
don't mean how much discount it has how much emi exchange it has and
everything like that so that so for that you need to you need to pass your
string so here if you see if you see i have passed my string i'll just remove the
commands so here i have first split my price so for that i have used a function
split which will basically split my price prices and then i have again use the
same function for the rupee symbol so here as you can see i have this rupee
symbol and in spite of this rupee symbol i want to add rs so here i have add
rupees rs and then i've added the same variable next i have again split it with
the e now why e because this because there are some there are some features
where it does not provide any discount it just provides your emi option so
here for that just to look a bit clean i have again split it with respect to e and
then the final price or you can say the split price has been saved in a variable
which is final price similarly i've done it for rating so if you see the ratings as
well i have 4.5 i have ratings and then this much reviews but i just need 4.5
so again i have split the string and then i have stored the final rating in the
variable which is final underscore rating

now what i have to do i have to concatenate all these three features so i'll be
concatenating final the product name my price and the rating so i'll be
concatenate concatenating it with the comma operator now if you see here my
now this i'll be storing in csv as all as well so you should keep in mind there
should be no extra commas because every time it finds a comma it will create
a new column for it so if you if you look at if you look at that closely you
have product name is this which has a comma as well so rose gold comma
32gb now for that if you want to eliminate this comma what you have to do
you have to write replace function which will basically replace your comma
with a pipeline and for final price and for rating it is fine for me so i will
simply print these things and let's see what it says

so this is my concordated string since i have not removed the previous one so
let me just remove the previous one so that it will it will not confuse you so
let me just commend these and i just want to show the final version which is
the concatenated string

so as you can see i have the title of the i have the title of the phone which is
this and then i have the pricing and then i have the rating similarly for all the
24 products i have the same next what i have to do i have to put the same in
my file also so i'll use the function right and i'll display the same i'll just copy
the same print statement over here and then i'll close my file also so we have
already seen the output over here now let's see what this file display so where
this file will be created so wherever your project is you will directly go to that
folder and the file will be saved automatically so it's in my d drive it's then
into ayushi and then in the web scraping i have my product.csv so let me go
and click it so here as you can see i have the product name i have the pricing
and then i have the ratings so this is what my csv file looks like now let me
go back again to code

so as you have seen we have fetch all the details from the flipkart website and
these details are automatically fetched and then stored in a csv file which is
named as products.csv this was the code that we have just discard so here we
have scraped the prices the title and the ratings of flipkart so this was all for
the day thank you guys for attending this i hope you guys like it and now if
you guys have any doubts you can simply ping it over the chat window and
we'll be happy to help you with the same well thank you everyone i hope you
have enjoyed listening to this video please be kind enough to like it and you
can comment any of your doubts and queries and we will reply them at the
earliest do look out for more videos in our playlist and subscribe to edueca
channel to learn more happy learning

You might also like