YouTube Transcript:
Python for Beginners – Full Course [Programming Tutorial]
Skip watching entire videos - get the full transcript, search for keywords, and copy with one click.
Share:
Video Transcript
Available languages:
View:
in this full course you will learn the
basics of python programming
i'm beau carnes with freecodecamp.org
i've previously created one of the most
popular javascript courses on youtube
and i've created many python tutorials
now i've created this complete python
course for beginners you don't need any
previous programming experience to
follow along and all you need to code in
python is a web browser in this course i
will teach you all the core aspects of
the python programming language and i
will simplify the more complex topics
python is considered one of the most
popular programming languages in the
world and it's only growing in
popularity python excels in a wide
variety of scenarios such as shell
scripting task automation and web
development and it's also the language
of choice for data analysis and machine
learning but it can also adapt to create
games and work with embedded devices
we're going to jump right into it so you
can start coding your first python
program as soon as possible to get
started quickly we'll use a replit which
is an online ide that allows users to
code and run programs in a variety of
different languages all in a web browser
and later i'll show you how to get
python set up on your local operating
system after the first project i'll go
into more detail about each of the main
features of python the section is
comprehensive and detailed and in the
final section you will use what you've
been learning to code a blackjack game
with me guiding you every step of the
way throughout the course there will be
a little repetition of some of the key
python programming concepts to make sure
you have a deep understanding of the
language so let's get started we're
going to start by creating a simple rock
paper scissors game and we'll start by
going to replit.com replied provided a
grant that made this course possible and
replie is going to make it super easy to
get up and running really quickly so you
can either sign up or log in
and create an account i'm just going to
use my google account
okay now that you're logged into replit
you can either just click the create
button or this plus button over here to
create a new replit and i'll make sure
to create a python replit but you can
see you can also select all sorts of
different programming languages oh these
are just the ones that start with the
word python but so there's there's tons
of different programming languages you
can select but in this case we are just
going to use python and then i'll click
okay so let me just kind of show off
replica a little bit
this is where we're going to create our
python code i'm going to zoom in just a
little bit so we're going to write the
code right here and then we can see some
output over on the right side and then
you can create different files over on
the left side here
and then there's some other things like
you can connect to version control and
and
if you have environment variables we're
not even going to be discussing those in
this course there's a debugger you can
connect to a database and just some
other things but we're mainly going to
just be using this main.pi program to
write our program and we're going to see
the results in the console so i'm just
going to close this files window so
it's a little bigger here
i'm going to start off by showing you
how to create a variable with python so
this is a rock paper scissors game and
there's going to be a players a player
is going to have a choice and a computer
is going to have a choice so i'm going
to create a variable called player choice
choice
and i'm going to set that equal to rock
rock
so let's look at a few components about
this this is the variable name player choice
choice
and you can see
if you
we use an underscore that's just kind of
the convention for python to use an
underscore if you're going to have a
space in the variable name and we're
going to assign it that's what this
equal sign this is the assign operator
and we're going to assign it to a string
a string is just a word or a collection
of characters like rock and we're going
to put quotation marks around it now we
could have also used a single quotes
instead of double quotes as long as you
use the same quote on each side that's
what's important so we've now created a variable
variable called
called
playerchoice and assigned it to rock and
now we can reference this variable later
and whenever we reference the variable
called playerchoice it's going to
the code is going to automatically
replace that player choice with rock
so this is going to be a very
interactive project i hope you're
following along i hope you have already
got replit loaded up like this now
throughout this project i'm going to
tell you what the next thing to do is
and i want you to try doing it yourself
before you watch what i'm going to do so
periodically you'll want to pause the video
video
based on and what i say you and try to
implement what i say
before you come back to the video and
watch me implement it and see if you've
implemented the the same way
so i'm just going to zoom in one more
time and
this is the first thing i want you to do
see if you can make another variable on
the next line so you're going to press
return or enter to go to the next line
and this variable should be called
computer choice and you should set it to equal
equal paper
paper
okay so you can pause the video and see
if you can make a variable called
computer choice and set it to equal paper
so here it's pretty simple here it's
going to start simple but it's going to
get harder as we go so computer choice equals
equals
paper okay so like i said it's starting
simple but it's going to get more
complex as we go along
if you've done that you've now written
your first line of python code in this course
course
okay now i'm going to talk about functions
functions
a function is a set of code which only
runs when it is called
so i'm going to show you how to put this
code into a function
now one thing about python is that
indentation is very important
so after we create a we define the name
of a function any line of code that's
indented the same amount is considered
within that function
so i'm going to create a new line of
code at the top and i'm going to call it get
get choices
okay so we define the function with def
and get choices and i'm going to select
all these these two lines of code at the
same time and just press the tab key and
that's going to indent all these the
same amount
and you can see sometimes they'll be
squiggly lines and if you hover over
some of the squiggly lines it will tell
you something in this case it just says
the local variable called player choice
is assigned to but never used that's not
necessarily bad it's just it's just
telling us that usually if you create a
variable you're going to want to use it
later well we are going to use it later
we just haven't gotten to it yet so
sometimes the squiggly lines will
indicate there's some sort of error in
the code
usually i think it's the color red will
indicate an error but if it's a
different color it just may mean that
there's something maybe not quite right but
but
it's not really that big of a deal so if
you have a variable that's assigned to
but never used that's not going to stop
your program
but it's just saying that it's not this
variable isn't really being used for
anything yet but we will change that
this function i'm going to show you how
to call a function later but we're
creating a function called getchoices
that assigns these two variables and
it's also i'm going to put another line
at the very end here and it's a return statement
statement
and i'm going to return player choice
choice
this will indicate what's returned when
this function is called so later we'll
call this function get choices and it
will return
something it will return the player
choice which is right here we'll turn in
this case rock that we can use somewhere
else in our code
and i did just happen to put an extra
line here
that's just that's optional i put a
blank line here just to kind of
make things easy to kind of organize the
code a little bit so
different sometimes i'll just put an
extra line between different sections of
code and it just makes it easier to
identify the different sections when
you're looking at the code
for the computer those extra lines don't
mean anything the indentation though
definitely does mean something
so as long as every line of code is
indented the same amount as the previous
line of code then it's all within the
same function
okay so this is what i want you to do
see if you can change the return
statement so instead of returning player
choice it's returning the computer choice
so that's pretty simple
it's now returning the computer choice here
here
now i'm going to create another function
down here this is just going to be an
example function just so i can
demonstrate something to you and then
we'll delete it it's not going to be
part of our rock paper scissors game but
i'm going to create a new function
called greeting
and then i am going to add what it's
going to do oh yeah put the semicolon
you also know a colon so a function
always has to have a colon at the end of
how we define it so i'm going to return
a string and it's just going to say hi
and one thing you'll notice is that
there's no you don't have to put any
anything at the end of each line some
programming languages such as javascript
you're going to put a semicolon at the
line at the end of the line
but in python it doesn't matter you
don't put anything at the end of each
line so now i'm going to call the
function to call the function i just
type the name and i put the parentheses
at the end so it's going to say so
greeting is now going to call it's going
to call this function and that's going
to return the string hi
now it's not going to do anything with
the string because our program doesn't
do anything with the string that's been
returned it's not going to go into the
console or anything but let's add
additional code so we will
make this string hi go on to the console
first let me create a variable that
takes what this greeting function
returns so i'm going to type in response
equals greeting so now we set the the
what greeting is being returned to this
variable called response and now i can
use the print function
and i can print the response and this
will print it to the console so now i
can we have this green button here this
runs the program i'll click this green
button here and now we can see it's high so
so
this response is getting this high from
here and then we're printing it right
there okay i'm actually going to delete
and what i want you to try to do now is
to call the get choices function and
store the response in a variable called
choices and then print the value of
choices to the console
so you can pause and try that really
quick and then i'm going to show you how
okay so remember the variable is called choices
choices
and we're going to set that equal to
the get choices variable now ins or the
get choices function now instead of
typing out get choices you can see that
this code editor is actually giving us
suggestions on what we want to put in
here so i just typed in get and you can
see it's now saying get choices right
here so i can instead of typing out the
whole thing i can either click there or
i can just press the tab key and it's
going to fill in the rest of that
function name so that's just something
little that makes it easier to write a
program and you don't have to type out
every single thing so if you've already
created a function or a variable then
the the code editor then reply will will
suggest what you may want to fill in
when you're typing and most other code
editors do something similar it's called
code completion so
i'm going to but i still have to add
parentheses at the end and now i'm going
to print
the choices [Music]
[Music]
okay so i'm gonna just click this play
button to make sure it does what we're
trying to do yep it clicked paper great
great
now let's talk about dictionaries
dictionaries in python are used to store
data values in key value pairs so let me
okay so a dictionary is going to have
these curly braces at the beginning and
end and then here's a key value pair
there's one it's separated by a comma
and then here's another key value pair
so we're setting name
we're setting that to equal bow and
we're saying the color
to equal blue so here's the key here's
the value here's the key
here's the value
and the key or the value in a dictionary
can be a variable
like the color we could set that we
already created this variable here i'm
just going to copy the word choices and
we can put choices and you can see now
it's not surrounded by the quotation
marks so if you surrounded by quotation
marks it's a string but if we don't
surround it by quotation marks it's
getting the the variable here choices so
this would be set to
paper because that's what choice is
going to is going to equal so we're
about to delete this line because that
was just an example
but now before the return statement in
this function we're going to add a new
line we're going to create a variable
named choices and make it equal to a
dictionary the first key should be
player with a value of the player choice
actually this variable here
the second key should be computer with a
value of computer choice
and then we're going to update the
return statement
to return the the choices dictionary
now i'm not going to keep telling you to
pause and try it yourself so just the
rest of this time whenever i say what
we're going to do you'll know that after
i get done explaining it you can pause
it and try it yourself but that's what
so i'm going to create choices
and it's going to be a dictionary and
then it's going to have
a player
that's the key and the value is going to
be player
choice and i was just able to press tab
to fill that in and then we're going to
have computer
and it's going to be
computer choice
and you can see sometimes if it goes to
the next line there just won't be a line
number right here
but i can
move this over for now
and then i am going to oh i forgot to
put the equal sign that's what that red
squiggly line means so because the red
means there is a problem in the program
so it's not going to run correctly now
the orange just means that we haven't
used choices yet which we will right now
because we're going to return choices
choices choices
okay so now we don't have any squiggly
lines because we're using every variable
that we created and we're returning
choices here
so you may have noticed that player choice
choice
it does not actually get set to the
player's actual choice
so let's fix that
the input function gets input from a
user and will use it to get the player's choice
choice
so instead of having players choice
equal rock we're going to make players
rock paper
paper scissors
okay so this is how you get input from a
user we use the input function and this
is going to be something that's going to
be printed
we'll print to the console here
and whatever the result of this input
will be that the the player that the
user entered will get stored to this
variable which we then can use later in
our program
so let's just try that out i'll click run
run and
enter
let me just stop and run it again
okay enter a choice rock paper scissors
i'll just put rock
and now you can see the player's choice
we're still printing that and it's going
to print as rock
great now let's just clean up this code
a little bit we still have this here we
don't need that dictionary that's not
going to be part of our final code
and now we'll make it so the computer
can actually make a choice
so we're going to learn about importing
libraries creating lists and calling methods
methods
python libraries are a set of useful
functions so you don't have to write
code from scratch when you import a
library to your program you get access
to more features without writing
additional code
with basic python it's challenging to
get your program to do something
randomly but it's easy to choose
something randomly using the random library
library
so let me show you how we can import the
random library
import statements are used to import
libraries and they're usually put at the
top of a program so i'm going to press
enter a few times here to add some lines
at the top and i'm going to do import random
random
so now we are going we we've
imported the random library
so we're going to use that random
library soon but now let's learn about lists
lists
a list in python is used to store
multiple items in a single variable
lists are surrounded by brackets and
each item is separated by a comma so
here's an example i could create a
variable called food and set it to this
list it's going to have three items pizza
carrots
and eggs [Music]
[Music]
so this is a list of strings
and then you can also get a random item
from the list
using we're going to use now we've
imported random we can get a random item
by using that that random library so i'm
going to put dinner [Music]
[Music] equals
equals
random dot choice
and then i'm going to pass in the the
list here
so using the random library we can call
choice and then we can pass in
a list and it's going to choose a random
item from that list and
and set it to equal this dinner variable
so right now the computer choice always
equals paper but we want it to be a
random choice between rock scissors and paper
paper
so before the computer choice variable
is created we'll create a new variable
called options and assign it to a list
of the possible options rock paper
scissors then we'll set the computer
choice variable to be a random choice of
one of the items in the options list
okay i hope you already tried this now
but let me show you how that's going to work
work
we'll create options
and we'll set it equal to this list of
of rock
[Music]
paper scissors
and you can see the code editor will
often pop up these boxes with more
information about what we're doing to
give us some some help with what we're
trying to do here so we're going to set
this computer choice to be random
random
dot choice
food not food i was looking at the food
there we go
and let's just um try running this
program and seeing what happens so i'm
going to put rock
and then we see the computer chose
scissor it should be scissors that's why
we're testing it out i guess i
spelled that wrong okay so scissors with
an s so now let me try running it again
and you can see it shows scissors but if
we run it enough time it should now it's
choosing paper because it's choosing it
at random okay
okay
that's working
okay so now let's just delete all this
code after the get choices function we
don't need to test that get choices
function anymore and now
let's create a new function called check when
when
so you shouldn't know enough how to you
should know enough about how to create a function
function
so def check
[Music] when
when
so this is just an empty function with
nothing inside it yet
but before we add oh with the
colon so before we add any code inside
the function we're going to create some arguments
arguments
function can re functions can receive
data when they're called the data are
called arguments so when creating a
function you can specify arguments
inside the parentheses so we've been
using this empty parentheses but i can
uh put in tooth i can put in things
within these parentheses
when this function is called we're going
to give it two pieces of data we're
going to pass two pieces of data into
the function the first piece of data is
going to be player the second piece of
data is going to be computer
so the you can basically call these
anything you want uh these are just
we're creating new variables but when we
call these functions we'll pass in two
pieces of information that will then be
assigned to the variable names player
and computer that we can use inside the function
function
so for now let's
finish off with to a for a complete
function the function has to have some
code within the function
so let's just add a return statement
that's just going to return a list
containing the elements player and computer
so this check when function shouldn't
actually return this
this is just to kind of get get it
quickly created it should actually
return different things depending on the
player and computer arguments
an if statement will allow a program to
do different things depending on certain conditions
conditions
so an if statement will first check a
condition and if the condition is true
then all the lines of code under the if
statement that are indented the same
amount will execute so as a quick
example i can say
a equals three
b equals five
and then we can create an if statement here
here if
if
a is greater than b
b
yes
or we can do if a is
less than b or we can do if we want to
check if a and b are equal we can do
eq we we'll put two equal signs now this
is very important you never want to use
one equal sign because a single equal
sign is the assignment operator that's
how you assign what variables are equal
to so if you use a single equal sign or
like then if i put if a single equal
sign b without a double equal sign that
is going to
set a to equal b which is not what we
want the double equal sign
is going to check if a and b are the
same value basically it checks if two
values values are equal now you can also do
do
a not equal so if you use the
exclamation point that's not equal or
you can use
less than or equal to or you can do more
than or equal to
so i'm just going to delete all this for now
now
so now we're going to update this risk
turn statement uh before the return
statement we want to we're going to
check if player if player equals computer
computer
and if so if true will return the string
it's a tie
so let's do that if player
equals computer and this is something
that maybe you figured out yourself
before you before you're watching this
will return a string and the string is
going to be
okay so now it's only going to return so
a function does not have to return something
something
and for this function it's only going to
return something
if this is true if player equals computer
computer
if not it won't return anything and just
to make make you notice this see this
this
line is indented within the if statement
which is indented within this function
and just really quick thing to note
for a return statement parentheses are
optional so i could also
add parentheses like that but you don't
need them but for now i'm just gonna get
rid of them [Music]
[Music]
so currently when there's a tie the
program now returns it's a tie
but how does the player know that's true
now let's have the program print which
options that the player and the computer chose
chose
you can concatenate strings with the
plus operator
that just means you can combine strings
with other strings or strings with variables
variables
so let me show you how you can print
which options were chosen so i'm going
and then i'll put player so you chose
and then we have to add a space here
because it's going to print a space and
then it will choose it will print this
so if the player chose rock we'll say
you chose rock
and then we can concave so we
concatenated these together but we can
add another plus sign
and put another string here and it's
going to say
computer chose oh it's like being
now i'm just about to type it in but see
if you can figure out what to add at the
end here to put in what the computer chose
so computer chose
computer or the the value of this
so
a lot of times when with programming
there's a bunch of ways to do the same
thing so this is one way to combine
strings and variables together there's
another way that's a little simpler
called an f string
so an f string will allow you to make
strings with and with variables and
other python code
so to do that you just put a variable or
you just put f at the beginning of a
string so let me just give you an
example so we do age equals 25 we're
going to create a variable and then i'm
going to make an f string we'll make it
a print statement and i'm going to put a
string in here but instead of starting
with a quotation mark it's going to
start with an f
and then i'm going to put gem is and
then whenever you want to put a variable
or any kind of python code we're going
to put some curly braces and i'm just
going to put the variable within the
curly braces
so years old and i'll put the end of the string
string
or let me put a
period here
okay so gem is
age which is going to be 25 years old so
the f string is just a slightly simpler
way to combine the strings and the
variables so what i want you to do see
if you can figure out how to update this
line right here so it uses an f string
and it uses these curly braces instead
so yeah we're going to put f and i can delete
delete
a lot of these
things here [Music]
[Music]
and then i'm going to put some curly
there we go okay you cho there was a
comma here you chose player computer chose
chose computer
okay so now we've been able to put in
the variable within this string with the
so we're going to test this out uh so
in a code
the code in this function never gets run
so when we press the run button it's not
going to run any of the code within the
function unless the function is called
within the program so
so
we're not going to test out this
function all right now what i want you
to do is see if you can add a line to
call the check when function and then
so we're going to just do
check when rock
rock
or actually we have to pass in strings
here rock paper
paper so
so
this is going to it's going to call this
function with rock in terms instead of
player and paper instead of computer
so let me try stride running this program
program
you chose rock computer chose paper and
just don't worry about these little
icons sometimes they just block what's
in there but it's still behind that
little search icon so it's to see it's
doing you chose rock computer chose paper
paper
now let's get back to checking the winner
winner
so far this function is only going to
check if there's a tie
now we'll start adding code to check
different wing conditions
so let's learn about else and elif statements
statements
okay so down here i'm just going to give
you i'm just going to paste an example
so so here's the if statement if age is
greater than or equal to 18 it's going
to print this else so anytime this is
not true then it's going to print you
are a child
okay now here i've combined it with
something else the ellis statement ls
just stands for else if it combines else
and if so you have to put a condition so
if age is greater than or equal to 18
print you're an adult else if now we're
going to check if age is more than
greater than 12 you were a teenager
else if age is greater than 1 print you
are a child
or else if none of these other things
so and it's it's only going to do one of these
these
it's going to get to the for once it
gets to the first one that's true then
it's not going to check the rest it's
just going to kind of go to the next
line of code after all these statements
so it's just going to choose one and
once it gets the first one that's true
then it's be done with this whole
you can also check for two conditions at
once let me give you an example i'm just
going to delete all this code and i'm
going to create an alif statement here elif
elif
else if and we're going to check if
player is equal to rock
and i'm just going to type in the word and
and
and computer
is equal to scissors
scissors
so now i'm checking if
both these conditions have to be true so
this condition and
this condition have to be true before
the following
statement will happen which we're going
rock smashes [Music]
[Music]
scissors you
you when [Music]
[Music]
okay now
the next thing we're going to do let's
see if we can figure out how to do this
we're going to add another lf statement
and this time we'll check if players
equal the rock and computer is equal to
paper and if so we'll return paper
covers rock
so we're going to make this kind of
easier by just copying this code and
then i'm just going to paste in this and
then i'll just change this so players
equal the rock and computer is equal to
paper instead of scissors paper
paper
paper
you lose
and we won't even have an exclamation
point anymore because it's not exciting
okay and you can kind of see there's a
few we could add a few more elif
statements to cover all the different situations
situations
but instead we're going to talk about refactoring
refactoring
refactoring is the process of
restructuring code while keeping the
original functionality when created pro
when creating a program it's common to
refactor code to make it simpler or more understandable
understandable
so we are actually going to refactor
this code that i've highlighted now
and we are going to instead use a nested
if statement
a nested if statement will make the code
more understandable at a quick glance like
like
so you can put an if statement inside
another if else or else statement
so you'll notice here the first elf
statement is if player equals rock and
the second l of statement is if player
equals rock so see if you can figure out
how to refactor this to
to
not have to use the and anymore we're
just going to use one if statement and
one else statement and then an if
statement under that
elif statement
if that doesn't make sense you can just
see what i do right now
so i'm going to just
move this down a little bit
i'm going to actually copy and paste
some of these items but we're going to
start with l if player equals rock we're
not going to have this
i'm going to put this on a new line and
say if computer equals scissors so first
we're going to check if player equals rock
rock
and then if so we're then going to check
it's going to be a nested if statement
if computer equals scissors and if
computer equals scissors then we're
going to use this this return statement here
here
so i have to make sure it's indented
correctly it's going to re so this we have
have
we have
player if player equals rock then if
computer equals scissors we'll return oh
this needs to be indented one more time
to be on inside that if statement
and now we don't even need this elf
statement this can just be an else
statement else
because if
the computer equals scissors there's
only one other option because we already
know if player equals rock and computer
equals rock will have already returned
it's a tie
and by the way once you return something
the rest of the code in a function does
not run so if we're returning it to tie
nothing else after that is going to run
so we know that computer can't equal the
rock at this point so it's either going
to be scissors or paper so i don't we
don't even have to check if computer
equals paper because at this point
computer has to equals paper and then
we'll just return this this line
let's see
there we go return paper covers rock
you lose
so now we just basically have to add two
more sections similar to this so this
one is if player equals rock
then we have to have another section if
player equals paper and then if player
equals scissors
and then we just have to have the the
stuff inside is going to be pretty
similar just corresponding to the
different relationships between rock
paper scissors
so i'm just going to copy that
and then i will paste it here and then
one thing is important to make sure this
elif statement
lines up with this else statement
and this is now going to be paper
paper
and then we are going to check if
computer equals rock
and a computer equals rock
then we will say that
you win
or we'll say scissors
cuts paper
paper
you lose and then the final one which at
this point i'm sure you can figure out
on your own we're going to add one more section
section
and this if
player equals scissors
and then first we're going to check if
computer equals paper
if so
we will do scissors
scissors cuts
cuts
paper we're just making sure we're just
making it so every time the first one is
you win the second one is you lose but
you could do it the other way around
rock smashes
smashes scissors
scissors
you lose
okay we're almost finished with this
whole program
so both
the get choices function and the check
win function they're both complete
now let code to call the functions and
play the game
so first let's remove this
this check when
now we'll create a variable called
choices and make it equal to the result
of calling the get choices function
and we just have to make sure it's not
indented it's on the the first
the first column i guess right here not
ended at all so we'll do choices
choices
equals get choices
choices [Music]
[Music]
and one thing about this is it's going
to return a dictionary so if we look at
the get choices
so it's returning choices and it's going
to be a dictionary like this now let me
just copy this i'm going to show you
something down here i'm going to just
paste it down here and we'll just make
an example of what it could look like it
could look like rock and paper i always
use rock and paper as examples because
scissors is a
little harder for me to spell
so so that's a little easier so so let's
one thing we haven't talked about is how to
to uh
uh
how to access a and specific element
within a dictionary so this is a
dictionary so let's say if i call this um
well i'll just call it choices even
because we're going to delete that and
so we're only going to have this choices
but if choices equals this and let's say
i just want to get the the choice of the player
player
let me show you how i would do that
i'll just do
p choice for player choice and i'm going
to put equal choices and to get just the
the value of the player i'm going to put
brackets so the brackets look like that
and then i have to
put the the key that i want the value of
so the key would be player
so if i
put the name of the dictionary which is this
this
and then i put some brackets we're going
to use brackets to identify what is the
key that we want the value of so here's
the key of the with the value of rock
and here's a key with a value of paper
so this is how we can get the player
choice and i'm sure you can under see
how you get the computer choices if
instead if
we take this computer word and put it
right here
uh computer
okay i'm just going to get rid of all
this here
and we're going to we have the get
choices here
and now listen carefully to what we're
going to do next
we are going to create a variable called
result and make it equal to the result
of calling the check win function and
when we call the check win function
we're going to pass in the value of the
player key
and the computer key
of the choices dictionary
so let's do that so then you'll see what
i mean a result
is going to be
we're going to call [Music]
[Music] check
check when
when
and then we are going to pass in
we're going to pass in we have choices player
player
computer
so because remember we had that we i
showed the example that dictionary so
we're getting the player key the value
of the player key and the value of the
computer key
so now we know who wins
we've now this result variable is going
to be one of these strings have been
returned either it's a tie rock space of
scissors paper covered rocks and so on
so now we just have to print the result
we're going to print
print
the result
okay we can try out this game
i'm going to click the run button
okay this is why it's sometimes better
to test a little earlier i just forgot the
the
semicolon on some of these so um semicolon
semicolon
and see there's a red arrow i should
have seen that semicolon
and semicolon
okay now let's try it i'm going to play
the program into a choice
i'm going to do
rock and i just noticed something else i
want to change so enter a choice here i
started there's a parenthesis here
there's no parentheses at the end so
again i'm just going to change that
really quick so enter a choice and we're
going to put it in parentheses here and
test again so rock okay you chose rock
computer chose rock
it's a tie okay i'm gonna play it again paper
paper
you chose paper computer chose scissors
scissors cuts paper you lose
okay we just created a python game
so hopefully this gives you a better
understanding of what it's like to
program in python and you you now know
about some of the basic concepts of
python now there's a lot more to learn
in python and we're going to be covering
a lot more in this course i just wanted
to start with a game and a full program
so just right off the bat you could go
to program
so in the next section i'm going to
start going over in detail all the most
common features of python
and we're going to cover some of the
features that we've already used in this
game plus a lot of additional features
additional common features that were not
used in this game
and then in the final section of the course
course
we're going to code a more complex game
a blackjack game
so let's get started with the next section
section
one of the quickest and easiest ways to
get started with python is by using
replit.com but you may also want to get
python running on your local computer so
if you want to do that you can start by
going on over to python.org
and these go to the downloads menu
and then you're going to just click
what you want to download for it for so
it's going to default to be for you the
operating system you're on but you can
also go to other platforms and make sure
you can and then just find the platform
that you want to download on and there's
going to be instructions on here that's
going to tell you how to go about
getting installed on your specific computer
computer
so there's a few different ways to run a
python programs and one of the ways is
with an interactive prompt so after you
get installed if you open up your
terminal and type in python or sometimes
it's going to be python 3 depending on
how you got it installed you're going to
see this interactive prompt and then you
can just this is called a python rebel
it's it's different from a rebel
creating with created with replit but
you can start coding in python right on
here so i could say
name equals bow
and then you have to make sure you
put the the quotation marks at the end
and now i've gotten a variable stored as
bow and then i can just type in the
variable name name and it's going to
show you show me the value of the
variable and you can type in most
different python commands right into
this inactive prompt here
and then i can just quit it when i'm
ready to quit
it's also common to run python using
visual studio code so if you just search
for visual studio code you can get to
the the download page and then you can
just download it for your system and
there's also you can download for
different systems and then once you open
up visual studio code to get python
working you're going to want to install
the python extension so i'm going to
click over here to extensions and you
can search for python or it may just be
listed here under popular extensions and
i'm just going to click install
and this is going to make it easier to
work with python on visual studio code
so now i can just kind of close some of
this stuff here
and i'm going to
create a new file
and i can just call the and i can just
type in name equals
equals bow
bow print
print name
name
and then if i save this as
as
test.pi it's going to now it's going to
add the colors that correspond to python
python
and then i'm just going to click this
play button here
and it's going to play it's going to
open up a terminal window here
and it's going to run the program and
it's going to print bow that's what my
program did if i zoom out a little bit
you'll be able to see the difference so
well we just print the name and it and
it runs the program just like that and
then you can see on the terminal how the
the command that was used to run that so
we could use the same command on any
terminal and instead of typing this
whole thing for the location of python 3
i can just do python
3 and then you this is where that file
is located so just copy that
and i can paste it in here and it's
going to run that program
in this section we'll learn about the
core features of python i'll go into
more detail about some of the things we
learned in the first project and they'll
be covering a lot more concepts this
section was heavily inspired by the
python handbook by flavio copes and you
can check that out on freecodecamp news
and like the first part of the course
i'll be running python in replit so once
you get logged into replit just like i
already showed you before you can hit
the plus button here or the create
button to create a new replit and then
you can search for the programming
language or you can just click it down
here python we'll just create a python repel
repel
and then we can instantly start creating
writing python code in replit
so like i showed before we got our
different files here we're just going to
start by using one file here and this
we're going to encode and this is where
it's going to
appear if we we run the code so i'm
going to
close off the list of files here
and let's just start at the beginning
again so you've gotten used to coding in
python through creating a rock paper
scissors game
but now we're going to
kind of do a deep dive into all the
basic commands of python so there's
going to be some review but we're going
to be going into more detail about each
of the elements and the first thing
we're going to talk about is variables
so we can create a new python variable
by assigning a value to a label using
the equal sign or the assignment
operator so let me give you an example
just like i was showing you before just
name equals bo
so let me just zoom in a little bit more
here and so now our variable name is
name and we've assigned it the value of bo
bo
and then we can also uh create we can
create a variable with a number so i
could do age equals
equals
39. so a variable name can be composed
of characters numbers and an underscore
character but and it cannot start with
the number
so it could be anything like name one
it could be all capital letters
it could
be it could have an underscore it can
start with an underscore like i said
like that and
and
you can see that these are all it's
putting these
red squiggly lines because it's showing
that that's not
actual python code if you're going to
create a variable you should be
assigning it to a value or you should be
using a variable that already exists but
i'm just showing you some different
examples of different variables now so
here's an example of an invalid variable
name if you just start with a number
like that that can't be a variable
because you can't start with a number
and i couldn't put something like test
exclamation point you can't use
exclamation points you can't use percent signs
signs
and other than that anything is valid
unless it's a python keyword so there
are some keywords a keyword is something
that's used to to write python like for if
if while
while
import these are all words that have
very specific meanings within python so
you cannot use them for a variable name
now there's no need to memorize them as
the python editor here will alert you if
you use one of those as a variable
so that was just like
if i say if equals hi
hi
and then you can see it's going to show
you right here with these squiggly lines
that we've done something wrong
invalid syntax because and then also you
can see that
it turns blue this word turns blue
because it's a keyword you can't use it
as a variable name
so like i said it's going to alert you
if you if you use a keyword as a
variable and you'll start to gradually
recognize them as part of the python
programming language syntax
now let's talk about talk about
expressions and statements in python so
an expression is any sort of code that
returns a value like for instance if you
do one plus one or if you just do a
string like
bow this is going to like this is going
to return to this is going to return the
string bow so a statement on the other
hand is an operation on a value
so for example these are this is a
statement here because we have an
operation we're assigning this to the
variable and then another statement
would be like this print name
name
so that's going to
be a statement because it's doing
something to the value now a program is
formed by a series of statements and
each statement is put on its own line
like we have these two lines here but
you can use a semicolon to have more
than one statement on a single line so i
i could put a semicolon here
and then if i run the program it's still
going to print the name and let's just
do that we already learned how to run a
program in replica click this button
right here but we can see it's going to
print bow and if i put these on two
different lines it's going to do the
same thing if i run the program it's
going to still do the same thing here
now let's talk about comments this is
something we haven't talked about in
this course yet so in the python program
everything after a hash mark is ignored
so if i put a hash mark i can say this
is a commented line and when we run the
program this line is going to be
completely ignored and then we can also
put in inline comment if i just put the
hash mark here this is an inline comment
and the cool thing about most code
editors including replit is it's going
to put comments going to make them gray
so you know that this isn't really part
of the program this is just some sort of
special note that the programmer wants
to put as part of the program
so i want to emphasize again how
important indentation is so it's very
meaningful in python so you can't
randomly indent things like you can't
just press tab here to indent here and
how this is kind of lined up here this
line up here you can see this red
squiggly line says unexpected expected indent
indent
so some other languages do not have
meaningful white space an indentation
doesn't matter but in python indentation matters
matters
so in this case if you try to run this
program we can run this and you'll see
an error right here showing up in red
here it says indentation error unexpected
unexpected indent
indent
because indentation has a special
meaning so i can just unindent that here
everything indented belongs to a block
like a control statement or a
conditional block or a function or a
class body and we'll be talking more
about those different blocks
now let's talk about data types python
has several built-in types
so for instance this is a string so
anything surrounded by quotation marks
is a string that's one data type and you
can check the type of a variable by
using the type function so i could say type
type
and then i'll put name and to make sure
to be able to see in the console i'm
going to print what the type is here
and if i press if i run the program
we'll see that the type is the class of
str which stands for string
and then we can test to see if something
is a string by comparing it to str so i
could do equals equals str
and then if i run that it's going to say
true because the type of name does equal
a string
and then we can also use is
instance so
i'm going to
uh so if we instead of doing type we do is
is
instance and then we
have to pass it two things so
the first thing we're going to pass it
so we have the is instance we're passing
it the name that's this variable and str
we're trying to see if name is an
instance of a string and if i run that
it should say true again
so we've been testing against the str
class the string class but it works the
same for other data types so so there
are some data types around numbers
so an integer number integer numbers are
represented using the int class or the
int class and floating point numbers or
fractions are a type of are the type
float so i can say age equals
equals 2
2
and then we can just check
and i can pass in the age and then i can
pass in an int
so if i run that
we're going to see that i've done
something wrong
oh i spelled that wrong there we go okay
now i'm going to try this and we'll see
true false it's not a false or it's not
a float because it doesn't have a
decimal point if i
did 2.9
then it should show that it is a float
because it has a decimal so python
automatically detects the type
from the value type so it automatically
knows this is a string it automatically
knows this is a float but you can also
create a variable of a specific type by
using the class constructor passing a
value literal or a variable name like
for instance we have this and we check
to see if this is a float and it's
saying false but i can make it a float
by typing in float
float
and just p putting the value
into the flow here so we're going to
make it a float so now it's true true
and you can do the same thing with
strings or integers or other data types
and you can also convert from one data
type to another by using the class
constructor so so that's basically what
we did we just converted this from an
integer to a float but i can also do
something else i can convert something from
from
a string
to an integer so for instance i'm going
to we'll just get rid of this one
completely here and we'll just use this
one so
a string is anything in quotation marks
so if i do
it's going to say
false it's not an n so i'm printing
whether it's an instance of an int but i
can convert this string
into an integer by just doing integer
and this let me run the program and it
says true
another thing about this is you don't
just have to pass in the actual data or
the actual string i can pass in a
variable so i can say number
equals and now i'm going to make it a an
x it says number but it's actually a
string but i can pass in the number here
and then it's going to set that to age
and it's going to be true so we create
the string we convert the string to an
integer and we tested that that age is
an integer
so when we do something like this this
is called casting
we are it's basically trying to extract
an integer from this string
of course the conversion might not
always work depending on the value
that's passed so for instance if we
write test here in the string
instead of the 20
we may get an air so let me just run
this and see now we have an error it
says invalid literal for
for int int with base 10 test so we
can't convert the word we can't convert
the string test to an integer so python
does its best to do the conversion but
it doesn't always work there are a few
other types so let me see are some other
common types of types so there's the
type of complex for complex numbers bool for booleans list for list tuple for
for booleans list for list tuple for tuples range for ranges
tuples range for ranges dict is our dictionaries and set
dict is our dictionaries and set is a type for sets
is a type for sets and we'll explore all these soon we'll
and we'll explore all these soon we'll go into more detail about about all
go into more detail about about all these different types of types well now
these different types of types well now let's talk about operators we've already
let's talk about operators we've already seen one operator that's this one that's
seen one operator that's this one that's the assignment operator but there's also
the assignment operator but there's also arithmetic operators comparison
arithmetic operators comparison operators logical operators bitwise
operators logical operators bitwise operators and plus some interesting ones
operators and plus some interesting ones like is and in so we're going to be
like is and in so we're going to be going over a lot of those right now
going over a lot of those right now so we talked about the assignment
so we talked about the assignment operator which is used to assign a value
operator which is used to assign a value to a variable or to assign a variable
to a variable or to assign a variable value to another variable now let's talk
value to another variable now let's talk about arithmetic operators
about arithmetic operators it's just what you use to do
it's just what you use to do math mathematics
math mathematics so here are the different
so here are the different arithmetic operators so we have plus one
arithmetic operators so we have plus one plus one equals two then minus
plus one equals two then minus multiplication division
multiplication division we have
we have remainder so four divided by three
remainder so four divided by three equals one but there's a remainder of
equals one but there's a remainder of one we have exponents four to the power
one we have exponents four to the power of 2 is 16 and floor division
of 2 is 16 and floor division so floor division does a
so floor division does a division problem and then just
division problem and then just basically rounds down
basically rounds down so floor division does the division and
so floor division does the division and rounds down to the nearest whole number
rounds down to the nearest whole number so actually this would be better seen if
so actually this would be better seen if we do four five divide by two five floor
we do four five divide by two five floor division divided by two is going to be
division divided by two is going to be two normally be 2.5 but floor division
two normally be 2.5 but floor division is rounding down to the nearest integer
is rounding down to the nearest integer the nearest whole number
the nearest whole number and then also note that that
and then also note that that the minus can also be a
the minus can also be a make something a negative number
make something a negative number so i could do 4 plus
so i could do 4 plus negative or i mean 1 plus negative 1 and
negative or i mean 1 plus negative 1 and then that's just going to equal 0. and
then that's just going to equal 0. and then the plus operator can also be used
then the plus operator can also be used to concatenate string values that's
to concatenate string values that's something we talked about earlier but i
something we talked about earlier but i could say
could say scamp
scamp and then put a plus
is a good dog and then like if i print this out
i put the the parentheses around it i can
can and then we'll see the whole string here
and then we'll see the whole string here sk scamp is a good dog
sk scamp is a good dog that was the name of my first dog when i
that was the name of my first dog when i was a kid so we can also combine these
was a kid so we can also combine these arithmetic operators with the assignment
arithmetic operators with the assignment operator let me show you what i mean so
operator let me show you what i mean so let me just get rid of this here and i'm
let me just get rid of this here and i'm going to do age
going to do age equals 8
equals 8 and age
and age plus equals
plus equals [Music]
[Music] 8
8 and i'll do print
and i'll do print age
age so we've so all these different
so we've so all these different operators can be assigned with it can be
operators can be assigned with it can be combined with the assignment operator
combined with the assignment operator and now it's going to add
and now it's going to add 8
8 to the age so if i
to the age so if i run this it's 16. so this actually just
run this it's 16. so this actually just means
means age
age equals age
equals age plus
eight so this age plus equals eight is the
so this age plus equals eight is the same as saying age equals age plus eight
same as saying age equals age plus eight so it's just going to add this number
so it's just going to add this number to the current age and set it equal to
to the current age and set it equal to the age and you can do that with any of
the age and you can do that with any of these like i could do
these like i could do times
times and that would be age equals age times 8
and that would be age equals age times 8 and
and 64. and so on with any of these
64. and so on with any of these arithmetic operators
arithmetic operators okay now let's talk about comparison
okay now let's talk about comparison operators
operators now we talked a little bit about them
now we talked a little bit about them before
before but let's see some examples again so
but let's see some examples again so this is to compare if two things are
this is to compare if two things are equal
equal and then we have not equal we're
and then we have not equal we're comparing them to see if they're not
comparing them to see if they're not equal or count this is if a is
equal or count this is if a is greater than b
greater than b or more than b and then this this is
or more than b and then this this is less than or equal to b
less than or equal to b now let me just tell you a trick of how
now let me just tell you a trick of how i keep the keep track of which one is
i keep the keep track of which one is greater than and which one is less than
greater than and which one is less than if you see this less than one if you
if you see this less than one if you kind of tilt your head a little bit it
kind of tilt your head a little bit it kind of looks like an l see like l and
kind of looks like an l see like l and this one doesn't look like as much of an
this one doesn't look like as much of an l so this
l so this less than operator kind of in some ways
less than operator kind of in some ways looks like a capital l that's kind of
looks like a capital l that's kind of just squished over and that's how i keep
just squished over and that's how i keep track of which one is less than which
track of which one is less than which one is greater than
one is greater than and so these are all going to give
and so these are all going to give either a false value or a true values
either a false value or a true values speaking of true and false
speaking of true and false true and false are examples of boolean
true and false are examples of boolean the boolean data type the boolean data
the boolean data type the boolean data type just means true false or true
type just means true false or true so a boolean is either going to be true
so a boolean is either going to be true or false there's only two options
or false there's only two options and there are a few boolean operators
so let me show you what the boolean the boolean operators are either not
boolean operators are either not and
and or or
or or so when working with two or false
so when working with two or false attributes
attributes those work like logical and or and not
those work like logical and or and not so when you're using uh not
so when you're using uh not it means it's not true you're checking
it means it's not true you're checking you're checking to see something is not
you're checking to see something is not true and means they both have to be true
true and means they both have to be true and or means either this one has to be
and or means either this one has to be true or this one has to be true in order
true or this one has to be true in order for the full thing to be evaluated as
for the full thing to be evaluated as true
true and let me show you something about or
and let me show you something about or now or using an expression returns the
now or using an expression returns the value of the first operator operand that
value of the first operator operand that is not a false value or a falsie value
is not a false value or a falsie value otherwise it returns the last operand so
otherwise it returns the last operand so it's going to return
it's going to return the first operand that is not a false
the first operand that is not a false value but since this is a false value
value but since this is a false value it's returning the second operand since
it's returning the second operand since this is a false value it returns the
this is a false value it returns the second one
second one since this is not a false value it will
since this is not a false value it will return the first one
return the first one and this is considered a false value if
and this is considered a false value if it's just an
it's just an empty bracket that's false so it's going
empty bracket that's false so it's going to return the second value which just
to return the second value which just happens to be false
happens to be false and since this is a false value it's
and since this is a false value it's going to return the second option which
going to return the second option which also happens to equal to false
also happens to equal to false so
so one way to think about it for the word
one way to think about it for the word or is so the pi this is how the python
or is so the pi this is how the python docs describe it if x is false
docs describe it if x is false then why
then why else x
else x so this would be like x this would be y
so this would be like x this would be y if else is false then why else x
if else is false then why else x and then for and down here let's look at
and then for and down here let's look at some examples for and and only evaluates
some examples for and and only evaluates the second argument if the first one is
the second argument if the first one is true so if the first argument is falsy
true so if the first argument is falsy such as false zero and empty string
such as false zero and empty string empty brackets it returns that argument
empty brackets it returns that argument otherwise it evaluates the second
otherwise it evaluates the second argument
argument so the way the way the python docs
so the way the way the python docs describe it is if x is false then x
describe it is if x is false then x else y
else y okay let's quickly discuss bitwise
okay let's quickly discuss bitwise operators they're very rarely used only
operators they're very rarely used only in very specific situations but it's
in very specific situations but it's worth knowing what these bitwise
worth knowing what these bitwise operators are just in case you're in the
operators are just in case you're in the very rare situation that you need to use
very rare situation that you need to use them
them and then two other types of operators
and then two other types of operators are is and in
are is and in now is is called the identity operator
now is is called the identity operator it's used to compare two objects and
it's used to compare two objects and returns true if both are the same
returns true if both are the same objects if both are the same object and
objects if both are the same object and i'll be talking more about that later in
i'll be talking more about that later in the section on objects and then in is
the section on objects and then in is called the membership operator this is
called the membership operator this is used to tell if a value is contained in
used to tell if a value is contained in a list or another sequence and we'll be
a list or another sequence and we'll be talking more about the in operator when
talking more about the in operator when we're discussing lists and other
we're discussing lists and other sequences later in this course
sequences later in this course and the final thing i want to talk to
and the final thing i want to talk to you about is the ternary operator now
you about is the ternary operator now the turn area operator in python allows
the turn area operator in python allows you to quickly define a conditional
you to quickly define a conditional so here will be like kind of the slow
so here will be like kind of the slow way to do it without a ternary operator
way to do it without a ternary operator so let's say you have a function that in
so let's say you have a function that in this function is comparing age with 18
this function is comparing age with 18 and it's going to return true or false
and it's going to return true or false depending on the risk result
depending on the risk result so instead of writing like this
so instead of writing like this we can implement it with a ternary
we can implement it with a ternary operator so let's do death
[Music] is
is adult i'll call it is adult 2 because
adult i'll call it is adult 2 because it's the second way of doing it and this
it's the second way of doing it and this time we're going to use the ternary
time we're going to use the ternary operator it's just going to be return
operator it's just going to be return true
true if age
if age is greater than 18
is greater than 18 else
so you can see first we define the result if the condition is true
result if the condition is true then we evaluate the condition
then we evaluate the condition and then we define the result if the
and then we define the result if the condition is false
condition is false it's basically an if else statement all
it's basically an if else statement all on a single line
on a single line okay let's talk more about strings in
okay let's talk more about strings in python so a string in python is a series
python so a string in python is a series of characters enclosed in quotes in
of characters enclosed in quotes in double quotes or it could be
double quotes or it could be single quotes
single quotes as long as the type of quote is the same
as long as the type of quote is the same on both sides and we already talked
on both sides and we already talked about how you can assign a string to a
about how you can assign a string to a variable
variable [Music]
[Music] and we already talked about how you can
and we already talked about how you can concatenate two strings using the plus
concatenate two strings using the plus operator like phrase
equals bo and then you can concatenate with the plus operator
with the plus operator is my
is my name
name [Music]
and then also instead of putting a string here
also instead of putting a string here you can put the variable so i could put
you can put the variable so i could put name is my name and we already have the
name is my name and we already have the variable here to equal bo so when you
variable here to equal bo so when you concatenate you can concatenate the
concatenate you can concatenate the strings or the variables
strings or the variables you can also append to a string using
you can also append to a string using the plus equal operator so let's say i
the plus equal operator so let's say i want to add to this name and i'm so i'm
want to add to this name and i'm so i'm going to say name
going to say name plus equals
is my name so we're adding is my name to the end of this so i can say
the end of this so i can say print
name and then we can see what it looks like
and then we can see what it looks like when you use the plus equal operator
when you use the plus equal operator so bo is my name
so bo is my name and then we already talked about how you
and then we already talked about how you can convert a number to a string using
can convert a number to a string using the
the str class constructor like if we had age
str class constructor like if we had age equals we could make this a string
equals we could make this a string but we passed this integer it converts
but we passed this integer it converts to a string and now it's going to be a
to a string and now it's going to be a string
string now here's something new a string can be
now here's something new a string can be a multi what can be multi-line when
a multi what can be multi-line when defined with a special syntax so if you
defined with a special syntax so if you enclose it if you enclose the string in
enclose it if you enclose the string in a set of three
a set of three quotes
quotes so let me show you an example get rid of
so let me show you an example get rid of all this
all this and i'm going to
and i'm going to print an entire
print an entire string here
string here so we're going to make this a multi-line
so we're going to make this a multi-line string i'm going to put three quotation
string i'm going to put three quotation marks
marks and then it's going to start with three
and then it's going to start with three quotation marks and end with three
quotation marks and end with three quotation marks and then i can make it
quotation marks and then i can make it multi-line so i can say bo is and then i
multi-line so i can say bo is and then i can
can put some extra lines
put some extra lines 39
39 years old now if i print that
years old now if i print that and you can see it's going to print
and you can see it's going to print the different lines here so we just made
the different lines here so we just made a multi-line string
a multi-line string and you can also instead of using the
and you can also instead of using the double quotes you can put a single quote
double quotes you can put a single quote as long as they're the same at the
as long as they're the same at the at the beginning and ending
at the beginning and ending now a string also has a set of built-in
now a string also has a set of built-in methods let me show you an example so if
methods let me show you an example so if i have this string
i have this string bow but i'm going to put at the end of
bow but i'm going to put at the end of the string i'm going to put dot
the string i'm going to put dot upper and i put parentheses at the end
upper and i put parentheses at the end so if i run this now it's going to print
so if i run this now it's going to print it in all capital letters
it in all capital letters and the same thing you can use with
and the same thing you can use with lower so if it if i had a string that
lower so if it if i had a string that had a few capital letters
had a few capital letters okay now it's all
okay now it's all lower now i can also type in a title
lower now i can also type in a title and this is going to
and this is going to make each lut so i can say
make each lut so i can say bow
bow person
person uh and i do this so it's going to cat
uh and i do this so it's going to cat it's going to a title that's going to
it's going to a title that's going to make the first letter of each string
make the first letter of each string a capital letter
a capital letter i can also check things like i can say
i can also check things like i can say is lower and it's going to check if it's
is lower and it's going to check if it's all lowercase letters false but if i
all lowercase letters false but if i make it so it is all lowercase letters
make it so it is all lowercase letters it's going to say true so here's just a
it's going to say true so here's just a list of a few common ones
list of a few common ones [Music]
[Music] you can do is alpha to check if it
you can do is alpha to check if it contains only characters
contains only characters is
is l num to
l num to check if a string contains characters or
check if a string contains characters or digits and is not empty is decimal
digits and is not empty is decimal lower to make it lower case is lower
lower to make it lower case is lower upper is upper title starts with to
upper is upper title starts with to check if it starts with a specific
check if it starts with a specific substring to check if it ends with you
substring to check if it ends with you can replace part of a string split a
can replace part of a string split a string you can strip the white space
string you can strip the white space from a string you can append new letters
from a string you can append new letters to a string you can find the position of
to a string you can find the position of a substring spring string and there's a
a substring spring string and there's a few more but these are some of the most
few more but these are some of the most common things you can do with a string
common things you can do with a string and then one thing to know about these
and then one thing to know about these is that they they all return a new
is that they they all return a new modified string they don't actually
modified string they don't actually alter the original string so let me show
alter the original string so let me show you what i mean by that so let's say we
you what i mean by that so let's say we have we'll do name equals bow again let
have we'll do name equals bow again let me zoom in a little bit
me zoom in a little bit and we're going to
and we're going to print
print name dot lower
now i'm going to print name
name so if i just run this
and we first figure out what went wrong here it looks like there's a few extra
here it looks like there's a few extra parentheses
parentheses [Music]
okay let's run this and you can see it's going to make it all lowercase but then
going to make it all lowercase but then when i print the name again
when i print the name again it's not still lowercase because this
it's not still lowercase because this just returns a brand new modified string
just returns a brand new modified string it doesn't actually change anything
it doesn't actually change anything in the original string
in the original string and then you can use some global
and then you can use some global functions with strings as well so one
functions with strings as well so one function we haven't discussed yet is the
function we haven't discussed yet is the l e n function which stands for length
l e n function which stands for length it can give the length of a string so
it can give the length of a string so i'm going to type an l-e-n
i'm going to type an l-e-n and then so there's just some global
and then so there's just some global functions that work with a lot of
functions that work with a lot of different types of data and the length
different types of data and the length of this is four you can see
of this is four you can see and then you can use the in operator now
and then you can use the in operator now i briefly mentioned the n operator
i briefly mentioned the n operator earlier so
earlier so let me show you one use case so we can
let me show you one use case so we can use the in operator to check if a string
use the in operator to check if a string contains a substring like for instance i
contains a substring like for instance i can say
can say a u
a u in
in name so let's check if name
name so let's check if name contains the letters a u
contains the letters a u well true it does but if if if it if it
well true it does but if if if it if it if it didn't if i just add an extra
if it didn't if i just add an extra string it's going to say
string it's going to say false
false okay another thing with strings um
okay another thing with strings um escaping is a way to add special
escaping is a way to add special characters into a string
characters into a string for example let's say we wanted to add a
for example let's say we wanted to add a double quote within the string how can i
double quote within the string how can i add a double quote into a string that's
add a double quote into a string that's wrapped in double quotes if i put a
wrapped in double quotes if i put a double quote like that that's not going
double quote like that that's not going to work because this is going to be the
to work because this is going to be the string and then it's not going to the
string and then it's not going to the code editor is not going to know what to
code editor is not going to know what to do with this last little bit here
do with this last little bit here so
so the way to go is to escape the double
the way to go is to escape the double quote inside the string with the
quote inside the string with the backslash character so right before this
backslash character so right before this quote i'm going to put the backslash
quote i'm going to put the backslash character
character and then you can see it now all is all
and then you can see it now all is all the same color as a string and if i
the same color as a string and if i print it it's going to it's not going to
print it it's going to it's not going to print the backslash character so putting
print the backslash character so putting a backslash is how you escape a
a backslash is how you escape a character and that just means
character and that just means this
this the the backslash character means that
the the backslash character means that the next character is not going to mean
the next character is not going to mean what it normally means
what it normally means it's going to actually just be the
it's going to actually just be the string of that character
string of that character and you can do the same thing with so
and you can do the same thing with so with in this particular example you may
with in this particular example you may not need to do it because you can always
not need to do it because you can always just put a single quote at the beginning
just put a single quote at the beginning and ending
and ending and as long as you have a different type
and as long as you have a different type of quote at the beginning and ending
of quote at the beginning and ending then
then you can put a double quote in the middle
you can put a double quote in the middle but let's say you want a string that
but let's say you want a string that contains both a single quote and double
contains both a single quote and double quote within the string
quote within the string then you will have to backslash like if
then you will have to backslash like if i just put a single quote there it's
i just put a single quote there it's going to mess it up but if i put it
going to mess it up but if i put it backslash
backslash now it's going to have the single the
now it's going to have the single the double quote and the single quote right
double quote and the single quote right within the string
within the string and
and you can also use the escape character
you can also use the escape character for
for special formatting characters like uh
special formatting characters like uh for instance what if i want there to be
for instance what if i want there to be a new line between the first two and the
a new line between the first two and the last two letters of the string if i do
last two letters of the string if i do slash n
slash n that is going to not actually just put a
that is going to not actually just put a slash in let's see what happens when i
slash in let's see what happens when i put that this is means new line you can
put that this is means new line you can see it says be new line a you
see it says be new line a you and then another way a reason why you
and then another way a reason why you may want to use an escape here like
may want to use an escape here like let's see what happens if i do this
let's see what happens if i do this this
this that's not looking how i want to look
that's not looking how i want to look because it's normally normally when
because it's normally normally when the code is running if it sees this
the code is running if it sees this backslash it thinks it's an escape
backslash it thinks it's an escape character so if you want to actually add
character so if you want to actually add a backslash to a string you have to
a backslash to a string you have to escape the backslash so now it's be
escape the backslash so now it's be backslash au
backslash au okay we're done talking about escape
okay we're done talking about escape characters now i'm going to tell you how
characters now i'm going to tell you how you can get a specific character in a
you can get a specific character in a string so given a string you can get its
string so given a string you can get its character using square brackets to get a
character using square brackets to get a specific item given its index starting
specific item given its index starting from zero
from zero so
so one thing to know about programming is
one thing to know about programming is that
that whenever you're counting from in most
whenever you're counting from in most programming languages you start counting
programming languages you start counting starting at zero so this is going to get
starting at zero so this is going to get the letter at index one so this is index
the letter at index one so this is index zero the b the e is at index one index
zero the b the e is at index one index two index three so if i run that we can
two index three so if i run that we can see we are getting the e that's at index
see we are getting the e that's at index one if i want to get the b i just put a
one if i want to get the b i just put a zero in the brackets and we get the b
zero in the brackets and we get the b and then we can use a negative number to
and then we can use a negative number to start counting at the end so if i put
start counting at the end so if i put negative one it's going to start here
negative one it's going to start here zero
zero one and that's going to be a oh you okay
one and that's going to be a oh you okay i guess when it's going backwards it's
i guess when it's going backwards it's not going to start zero because there is
not going to start zero because there is no negative zero that makes sense so
no negative zero that makes sense so negative one is going to be the last
negative one is going to be the last character in the string so negative one
character in the string so negative one negative two negative three and so on
negative two negative three and so on we can also use a range using what we
we can also use a range using what we call slicing so if i put 1 colon 2
call slicing so if i put 1 colon 2 this is going to be every character
this is going to be every character starting at index 1
starting at index 1 and ending before index 2. so it starts
and ending before index 2. so it starts at index 1 so it starts with that
at index 1 so it starts with that character and it ends before an x2 which
character and it ends before an x2 which is a so that's actually only going to
is a so that's actually only going to return an e
return an e but if i put 3 here
but if i put 3 here now we can return a u
now we can return a u and if i put bo is cool we can put one
and if i put bo is cool we can put one further down i'm going to put 7
further down i'm going to put 7 and we can see
and we can see it's going to return part of this string
it's going to return part of this string and then you can also start if you just
and then you can also start if you just put a blank before the colon then it's
put a blank before the colon then it's going to turn everything up to it's
going to turn everything up to it's going to start at the beginning and
going to start at the beginning and return everything up to character seven
return everything up to character seven and you can also do in the opposite
and you can also do in the opposite direction so if i put a blank after the
direction so if i put a blank after the colon it's going to go to the end of the
colon it's going to go to the end of the string so it's going to say is cool
string so it's going to say is cool so let's talk about
so let's talk about booleans well we already talked more
booleans well we already talked more about we already talked about booleans
about we already talked about booleans but we're going to talk a little bit
but we're going to talk a little bit more about boolean which is considered
more about boolean which is considered the bool type and this can have two
the bool type and this can have two values true or false so i can say done
values true or false so i can say done equals
equals true
true or you can do done
or you can do done equals false now
equals false now notice that it always has a capital t or
notice that it always has a capital t or a capital f so
a capital f so if you don't put a capital t or capital
if you don't put a capital t or capital f it won't be considered the the true
f it won't be considered the the true boolean value in python
boolean value in python and booleans can be especially useful
and booleans can be especially useful with the conditional co
with the conditional co with conditional control structures like
with conditional control structures like if statements
if statements well we already discussed if statements
well we already discussed if statements in the first part of the course and
in the first part of the course and we'll be discussing them more in detail
we'll be discussing them more in detail later but let me just show you an
later but let me just show you an example so if done and i'm going to
example so if done and i'm going to erase this done because we want to be
erase this done because we want to be true so if done
true so if done and then we'll say print
yes [Music]
[Music] else
else print
no okay so i can run that and it's going to
okay so i can run that and it's going to print yes because done
print yes because done equals true but if done equals false
equals true but if done equals false [Music]
[Music] then it's just going to say
then it's just going to say no
no so when evaluating a value for true or
so when evaluating a value for true or false if the value is not a bool or
false if the value is not a bool or boolean like if it's not true or false
boolean like if it's not true or false we have some rules depending on the type
we have some rules depending on the type we're checking so numbers are always
we're checking so numbers are always true
true except for the number zero
except for the number zero if i put 0 here it's going to evaluate
if i put 0 here it's going to evaluate to false but if i put any other number
to false but if i put any other number here it's going to be true even like
here it's going to be true even like negative 1 or anything like that it's
negative 1 or anything like that it's going to be true oh i guess
going to be true oh i guess that i didn't put negative 1 i put
that i didn't put negative 1 i put equals 1. so if it's negative 1 that's
equals 1. so if it's negative 1 that's going to be true
going to be true so strings are always false
so strings are always false oh
oh strings are false only when empty
strings are false only when empty so if i say
so if i say bow here this is going to be true
bow here this is going to be true because it's not an empty string but if
because it's not an empty string but if i make an empty string then it's going
i make an empty string then it's going to be
to be false
false lists tuples and sets and dictionaries
lists tuples and sets and dictionaries which we'll talk about more later are
which we'll talk about more later are false only when empty so it's going to
false only when empty so it's going to be if a list double star dictionary is
be if a list double star dictionary is is filled with something that is true
is filled with something that is true and then also you can
and then also you can check if a value is a boolean so if i
check if a value is a boolean so if i say done equals true
say done equals true i can do
i can do print
type we're going to check the type we're going to check if the type of done
going to check if the type of done equals
equals bool so let's check it does that equal
bool so let's check it does that equal boolean
boolean true it does now let's see let's
true it does now let's see let's change this to a different type and it's
change this to a different type and it's going to say false so it can still
going to say false so it can still evaluate whether this is true or false
evaluate whether this is true or false but the type is not a boolean the type
but the type is not a boolean the type is a string
is a string and let me show you another example code
so the global the any function it's a global function
the any function it's a global function it's very useful when working with
it's very useful when working with booleans
booleans it returns true if any of the values of
it returns true if any of the values of the iterable such as a list if any of
the iterable such as a list if any of them are true it's going to return true
them are true it's going to return true for all of them so
for all of them so for instance book one read that's true
for instance book one read that's true but book two read that's false but this
but book two read that's false but this is going to return true because it's
is going to return true because it's checking if any of them are true and
checking if any of them are true and then it's going to set this to true
then it's going to set this to true now the all function is is similar but
now the all function is is similar but returns true if
returns true if all of the values are true so
all of the values are true so we see we have this value as true
we see we have this value as true we have this value as false
we have this value as false whereas any would have returned true
whereas any would have returned true this is going to return false because it
this is going to return false because it only returns true if all of the values
only returns true if all of the values are true
are true okay now let's talk about more
okay now let's talk about more number data ties we already talked about
number data ties we already talked about int an integer whole number we've
int an integer whole number we've already talked about float which is any
already talked about float which is any number with a decimal point there's
number with a decimal point there's another type called complex
another type called complex complex numbers are an extension of the
complex numbers are an extension of the familiar real number system in which all
familiar real number system in which all numbers are expressed as a sum of a real
numbers are expressed as a sum of a real part
part and an imaginary part
and an imaginary part imaginary numbers are real multiples of
imaginary numbers are real multiples of the imaginary unit which is the square
the imaginary unit which is the square root of negative one often written
root of negative one often written i in mathematics or j in engineering
i in mathematics or j in engineering python is built in support for complex
python is built in support for complex numbers which are written with
numbers which are written with the the j notation so the imaginary part
the the j notation so the imaginary part is written with a s with a j suffix
is written with a s with a j suffix so you can combine it you can use a
so you can combine it you can use a literal value like complex
equals two plus
two plus three j so the the j means it's the
three j so the the j means it's the imaginary part of the number or you can
imaginary part of the number or you can use the complex constructor so i can put
use the complex constructor so i can put num
num equals
equals complex
complex and then i can pass in
and then i can pass in two comma three so
two comma three so the three part is the imaginary part the
the three part is the imaginary part the two is the the real part the integer
two is the the real part the integer part
part and then once you have a complex number
and then once you have a complex number you can get it's real or imaginary part
you can get it's real or imaginary part like this so i can say print
like this so i can say print [Music]
[Music] num
num dot real
dot real or num
or num dot match
dot match so this is going to be the 2 this is
so this is going to be the 2 this is going to be the 3. so if i just
going to be the 3. so if i just uh
uh let me
let me i think the problem was
i think the problem was num
num num one no so i'll do num one and num
num one no so i'll do num one and num two and we're gonna do this as num two
two and we're gonna do this as num two okay let's check this so
okay let's check this so this is the real part this is the
this is the real part this is the imaginary part you can see they're being
imaginary part you can see they're being returned as floats
returned as floats and you can use the type function to
and you can use the type function to check the type
check the type so now let's talk about some built-in
so now let's talk about some built-in functions that help with numbers so one
functions that help with numbers so one of them is abs abs will return the
of them is abs abs will return the absolute value of a number so if i say
absolute value of a number so if i say 5.5
5.5 that's just going to be
that's just going to be 5.5 but if i put negative 5.5 well
5.5 but if i put negative 5.5 well it will be 5.5 so
it will be 5.5 so [Music]
[Music] so if i print this see 5.5 basically it
so if i print this see 5.5 basically it just makes it so it's not negative
just makes it so it's not negative then you can also use
then you can also use round so if we do round
round so if we do round let's make this just 5.5 round is going
let's make this just 5.5 round is going to round to the nearest integer so if i
to round to the nearest integer so if i do this it's just gonna be six so point
do this it's just gonna be six so point five is going to round up but if we did
five is going to round up but if we did uh
uh four nine
four nine it's going to go down to five
it's going to go down to five you can also specify a second parameter
you can also specify a second parameter to set the decimal points precision so
to set the decimal points precision so i can
go to if i do one here and i round it it's going to
one here and i round it it's going to instead of rounding to the nearest
instead of rounding to the nearest integer it's now going to round to the
integer it's now going to round to the nearest tenths place value or one
nearest tenths place value or one decimal point
decimal point there are several other math utility
there are several other math utility functions and constants that are
functions and constants that are provided by the math standard library
provided by the math standard library like there's a math package a c math
like there's a math package a c math package decimal pages fractions package
package decimal pages fractions package that makes it easier to work with
that makes it easier to work with different types of numbers we'll explore
different types of numbers we'll explore some of those more later on
some of those more later on now let's talk about in nums and noms
now let's talk about in nums and noms are readable names that are bound to a
are readable names that are bound to a constant value so to use a noms we're
constant value so to use a noms we're going to have to import and numbs from
going to have to import and numbs from the inum standard library module
the inum standard library module like this from enum import enum and now
like this from enum import enum and now we'll be talking more about
we'll be talking more about importing
importing stuff from modules later but once you
stuff from modules later but once you import it then we can initialize a new
import it then we can initialize a new and nom in this way so do class
and nom in this way so do class state enum
and so we can have inactive [Music]
[Music] equals 0
equals 0 and active
and active [Music]
[Music] equals one
equals one so basically the the word state this can
so basically the the word state this can be anywhere any
be anywhere any word we like so we're setting
word we like so we're setting uh
uh basically a variable called
basically a variable called state.inactive
state.inactive which is going to equal 0 or
which is going to equal 0 or state.active to equal 1.
state.active to equal 1. so
so you can reference this how you would
you can reference this how you would reference it you can do print
reference it you can do print state
state dot
dot active
active and then if i just run the program we'll
and then if i just run the program we'll see
see now you can see it's just going to
now you can see it's just going to return state to active instead of one
return state to active instead of one so to actually get the value you use
so to actually get the value you use state to active dot value
state to active dot value and then we run that and then we'll see
and then we run that and then we'll see one here
one here if you we want to just return
if you we want to just return state.active that the sa that value can
state.active that the sa that value can be reached by the number assigned in the
be reached by the number assigned in the num so state we can do
num so state we can do one
one and if i print that it's now going to
and if i print that it's now going to say state.active
say state.active same for using the square brackets
same for using the square brackets notation so i could do states
notation so i could do states i'll do see square brackets and put
i'll do see square brackets and put active
active if i print that it's going to print
if i print that it's going to print state that active so this is basically
state that active so this is basically the only way to create constants in
the only way to create constants in python
python python is no way to enforce the variable
python is no way to enforce the variable should be a constant so some people use
should be a constant so some people use enums to create a constant
enums to create a constant and then nobody can reassign the value
and then nobody can reassign the value so
so when we do
when we do state
state or state active dot
or state active dot value
value so this is it's not going to be able to
so this is it's not going to be able to be reassigned so basically there's two
be reassigned so basically there's two ways to do we can do this bracket
ways to do we can do this bracket notation or we can go back to the other
notation or we can go back to the other way
way active
active now we can also list all the possible
now we can also list all the possible values for enum so
values for enum so our num is called state and we can now
our num is called state and we can now just print all the values oh i actually
just print all the values oh i actually did that wrong it's supposed to be a
did that wrong it's supposed to be a list
list so this is going to list the values of
so this is going to list the values of the state
the state and we can see we have inactive 0 and
and we can see we have inactive 0 and active is 1. and we can also count them
active is 1. and we can also count them using the length function so we're going
using the length function so we're going to print the result of a length state
to print the result of a length state and that's just going to give us 2.
and that's just going to give us 2. okay let's talk about more about user
okay let's talk about more about user input now we already discussed a little
input now we already discussed a little bit in our first program
bit in our first program but you can do get user input by using
but you can do get user input by using the input function so let's just get rid
the input function so let's just get rid of all this
of all this and we'll do
and we'll do age
age equals input
equals input and we can say
and we can say print
your age is and then we just can concatenate that
and then we just can concatenate that with the
with the variable age and then also if you want
variable age and then also if you want to
to so let's just do a quick test and right
so let's just do a quick test and right now it's looking for the age right now i
now it's looking for the age right now i can put five your age is five so there's
can put five your age is five so there's two ways to make it say what is your age
two ways to make it say what is your age we can do a print statement right before
we can do a print statement right before here
here and do what is
and do what is your age
your age and then
and then now we can put four your age is four
now we can put four your age is four now you can also ins instead of
now you can also ins instead of putting the print statement right before
putting the print statement right before here i'm going to copy this delete that
here i'm going to copy this delete that and we can put it right in this input
and we can put it right in this input function
function and then i'll say it'll still say what
and then i'll say it'll still say what is your age and i can
is your age and i can put an age here
so one thing to really realize about this is that it gets the input at
this is that it gets the input at runtime meaning the program will stop
runtime meaning the program will stop execution and will wait until the user
execution and will wait until the user types something and presses the enter
types something and presses the enter key
key you can also do more complex input
you can also do more complex input processing and accept input at program
processing and accept input at program invocation time and we'll see how to do
invocation time and we'll see how to do that later on
that later on if you want to get the input when the
if you want to get the input when the program is run that's going to work
program is run that's going to work better for command line applications
better for command line applications other kinds of applications will need a
other kinds of applications will need a different way of accepting input
different way of accepting input let's look more at control statements
let's look more at control statements this is another thing we've already
this is another thing we've already discussed earlier but we're going to
discussed earlier but we're going to review it and and look at it in a little
review it and and look at it in a little more detail so a control statement is
more detail so a control statement is like an if statement so if condition
like an if statement so if condition that's this variable here equals true
that's this variable here equals true then it's going to run everything in the
then it's going to run everything in the block a block is
block a block is the part that is indented one level
the part that is indented one level usually it's going to be either four or
usually it's going to be either four or two spaces in this case it's four spaces
two spaces in this case it's four spaces sometimes it's two spaces it doesn't
sometimes it's two spaces it doesn't matter it could even be one space as
matter it could even be one space as long as it's the same as long as every
long as it's the same as long as every line of code is indented the same amount
line of code is indented the same amount so if i just run that
so if i just run that the condition was true the block can be
the condition was true the block can be formed by a single line or multiple
formed by a single line or multiple lines and it ends whenever you move back
lines and it ends whenever you move back to the previous indentation level
to the previous indentation level so
so for instance if once we are not indented
for instance if once we are not indented i can say print
i can say print outside
outside if
if so then
so then that's always going to pres it's always
that's always going to pres it's always going to print this because it's not in
going to print this because it's not in that if statement
that if statement and then we have the if else statements
and then we have the if else statements where the else is if
where the else is if if this does not true then it's going to
if this does not true then it's going to do whatever is in here so if i just
do whatever is in here so if i just change this to false
change this to false then it's going to
then it's going to print whatever the condition was false
print whatever the condition was false and then we can have this series this is
and then we can have this series this is something that we showed in the per the
something that we showed in the per the program earlier but if and then elif
program earlier but if and then elif combines else and if so
combines else and if so if this is not true then i'll move on to
if this is not true then i'll move on to this line and else
this line and else if this is true then i'll do this else
if this is true then i'll do this else if this is true and it'll just keep
if this is true and it'll just keep going on and then it will always do the
going on and then it will always do the this is if none of the other ones were
this is if none of the other ones were true it's going to do this
true it's going to do this so since
so since it was testing this it's not even going
it was testing this it's not even going to evaluate anything later but if we
to evaluate anything later but if we move this to false
move this to false and we change this to bow
and we change this to bow then it's actually going to skip all the
then it's actually going to skip all the way down
way down all the way to this else here
all the way to this else here and if we do flavio
and if we do flavio you can print that and then it's going
you can print that and then it's going to say hello flavio from right here
to say hello flavio from right here okay that's all we're going to talk
okay that's all we're going to talk about for this for now since we've
about for this for now since we've already covered it earlier in the course
already covered it earlier in the course now i'm going to go into more detail
now i'm going to go into more detail about lists lists are an essential
about lists lists are an essential python data structure and so an example
python data structure and so an example of a list would be let's create a list
of a list would be let's create a list called dogs so we're going to create
called dogs so we're going to create the dog names we have roger we have sid
the dog names we have roger we have sid and this allows you to group together
and this allows you to group together multiple values and reference them all
multiple values and reference them all with a common name so we have a list of
with a common name so we have a list of dogs and this is just two strings so the
dogs and this is just two strings so the list always going to have the opening
list always going to have the opening closing brackets and each item in the
closing brackets and each item in the list is going to be separated with a
list is going to be separated with a comma and a list can hold different
comma and a list can hold different types of values so these are all strings
types of values so these are all strings but we can
but we can have a string
have a string an integer a string a
an integer a string a boolean
boolean and you can mix different types of data
and you can mix different types of data types
types in a single list
in a single list and then you can check if an item is
and then you can check if an item is contained in a list with the in operator
contained in a list with the in operator so we talked about the in operator
so we talked about the in operator earlier but let me show you how that
earlier but let me show you how that works so we're going to print here's
works so we're going to print here's where we can use the in operator we're
where we can use the in operator we're going to check if roger
going to check if roger is
is in
in dogs
dogs so let's see
so let's see so run that true but now let's check if
so run that true but now let's check if bo is in dogs well
bo is in dogs well false because it's checking
false because it's checking so this is how you can check if an item
so this is how you can check if an item is in a list
is in a list you can also define a list as an empty
you can also define a list as an empty string so i could actually just
string so i could actually just remove all this and now we just have an
remove all this and now we just have an empty list and this is obviously still
empty list and this is obviously still going to be false because there's
going to be false because there's nothing in that list
nothing in that list but let's go back to when we had some
but let's go back to when we had some items in the list
items in the list and you can reference items in a list by
and you can reference items in a list by their indexes starting with zero so i'm
their indexes starting with zero so i'm going to do dogs and then i can use
going to do dogs and then i can use these brackets so and now i'm going to
these brackets so and now i'm going to put the so this is where we're going to
put the so this is where we're going to reference the thing
reference the thing an item from the list and i'm going to
an item from the list and i'm going to type in 0 which will be this item right
type in 0 which will be this item right here roger or i could put 2 and it's
here roger or i could put 2 and it's going to do 0 1 2 and now we're going to
going to do 0 1 2 and now we're going to have sid
have sid and the same
and the same and you can use this same notation to
and you can use this same notation to update an item
update an item in a list so i'm going to add another
in a list so i'm going to add another line of code here and put dogs 2 is
line of code here and put dogs 2 is going to equal
bo and now i'm just going to print the
and now i'm just going to print the entire list here and now
entire list here and now instead of
instead of being roger 1 said true to roger 1 bow
being roger 1 said true to roger 1 bow true
true because we've updated the item at index
because we've updated the item at index 2 to be bo instead of sid
now you can also use the index method so
so um instead of
um instead of like if i want to find the first item in
like if i want to find the first item in the list i could do it like this
the list i could do it like this so you can also use a negative number
so you can also use a negative number here
here just how we saw on the string so
just how we saw on the string so negative 2 is going to start with one
negative 2 is going to start with one two
two actually let's do negative one so it
actually let's do negative one so it should return true here
should return true here okay true so it starts with this one if
okay true so it starts with this one if you put a negative number
you put a negative number you can also extract part of a list now
you can also extract part of a list now this is very similar to what we showed
this is very similar to what we showed using
using with the string let me just add another
with the string let me just add another item here
item here [Music]
[Music] now i am going to
now i am going to use the colon to do part of a list so
use the colon to do part of a list so i'm going to 2
i'm going to 2 4
4 and so this is a slice
and so this is a slice so it's going to start at the second or
so it's going to start at the second or zero
zero one
two which is now bow because we change it to
which is now bow because we change it to bow and it's going to go through four
bow and it's going to go through four it's going to go through four but not
it's going to go through four but not over pat not including four so it's
over pat not including four so it's going to be 2
going to be 2 3
3 and then not 4 so it's just sid and true
and then not 4 so it's just sid and true or bow and true because we updated 2 to
or bow and true because we updated 2 to bow
bow and you can also just leave this blank
and you can also just leave this blank so it's going to go through the end of
so it's going to go through the end of the list or if you
the list or if you leave the first number blank
leave the first number blank it's going to go it's going to start at
it's going to go it's going to start at the beginning of the list and we can go
the beginning of the list and we can go through for instance index three
through for instance index three and so that's a way to slice the list
and so that's a way to slice the list you can also
you can also use the the length function so let's
use the the length function so let's find out how many items are in the list
find out how many items are in the list i'll use the length the length of dogs
i'll use the length the length of dogs is six or six items in the list we can
is six or six items in the list we can also add items to the list by using the
also add items to the list by using the append method so i'm going to do dogs
append method so i'm going to do dogs dot append
dot append and then i can
and then i can add an item so i can say something like
add an item so i can say something like judah and now if we see the length
judah and now if we see the length there's now going to be 7 and if we just
there's now going to be 7 and if we just print
print the full list
the full list then we can see that we can see all the
then we can see that we can see all the items including the one that was just
items including the one that was just added we can also use the extend method
added we can also use the extend method the extend is another way to add an item
the extend is another way to add an item to a list so if i do instead of dogs
to a list so if i do instead of dogs append i can do dogs that extend
append i can do dogs that extend and then i'm going to pass in
and then i'm going to pass in instead of just passing in the string
instead of just passing in the string i'm gonna pass in
i'm gonna pass in the item as a list so i'm gonna and it's
the item as a list so i'm gonna and it's gonna add it just the same but now i can
gonna add it just the same but now i can actually
actually combine two lists together so i'm gonna
combine two lists together so i'm gonna put a five so if i do this we can see
put a five so if i do this we can see now we are taking this list and
now we are taking this list and extending it by adding this list on the
extending it by adding this list on the end this is a two item list and we have
end this is a two item list and we have that six m list and now we have the
that six m list and now we have the eight item list
eight item list you can also use the
you can also use the plus equals operator so
plus equals operator so to use the plus equals operator i'm
to use the plus equals operator i'm going to do dogs it's the same it's
going to do dogs it's the same it's going to do the same thing as extend
going to do the same thing as extend so plus equals
so plus equals and then we have this list take this
and then we have this list take this parentheses off here and it should look
parentheses off here and it should look exactly the same see it's showing up the
exactly the same see it's showing up the same thing up here
same thing up here so the plus equals is going to be the
so the plus equals is going to be the same thing as extend where it takes the
same thing as extend where it takes the list that's already exists and adds this
list that's already exists and adds this other list to the end
other list to the end and when you're using the extend or the
and when you're using the extend or the plus equals
plus equals you don't want to forget the square
you don't want to forget the square brackets
brackets here so if you if you forget the square
here so if you if you forget the square brackets and let's say i'm just going to
brackets and let's say i'm just going to add this iron to the list
add this iron to the list it's now actually going to put each
it's now actually going to put each letter individually here
letter individually here so if i you can kind of see it better if
so if i you can kind of see it better if i move over here
i move over here so it so that so you want to make sure
so it so that so you want to make sure you put the the brackets
you put the the brackets and another thing you can do is remove
and another thing you can do is remove you can remove an item using the remove
you can remove an item using the remove method so i'm gonna do
method so i'm gonna do dogs dot remove
dogs dot remove sid
sid okay now i'm gonna play it here and
okay now i'm gonna play it here and it's saying
oh obviously um i'm moving sid but we've already changed the element of sid to
already changed the element of sid to bow so let's remove
bow so let's remove quincy and let's try that
quincy and let's try that okay so now there's no quincy
okay so now there's no quincy so another common thing to do another
so another common thing to do another common list method is pop so if i do
common list method is pop so if i do dogs.pop
dogs.pop it's going to remove and return a single
it's going to remove and return a single item so first i'm going to
item so first i'm going to [Music]
[Music] do dot
do dot print dogs that pop and then i'm going
print dogs that pop and then i'm going to print dog so if i
to print dog so if i so first it's going to return 5 that was
so first it's going to return 5 that was the last item that we added onto the
the last item that we added onto the list and now when i print the list that
list and now when i print the list that item's not in the list so pop is going
item's not in the list so pop is going to remove the last item from the list
to remove the last item from the list and it's going to return the last item
and it's going to return the last item it's going to return and remove the last
it's going to return and remove the last item from the list and then it's not on
item from the list and then it's not on the list anymore
the list anymore now let's make this
now let's make this let's let's simplify this just go back
let's let's simplify this just go back to the initial list and i'm going to
to the initial list and i'm going to change this to items
change this to items now i'm going to show you how to add an
now i'm going to show you how to add an item in the middle of the list at a
item in the middle of the list at a specific index you can use the insert
specific index you can use the insert method so i'm going to do items dot
method so i'm going to do items dot insert
insert i'm going to put the index which is
i'm going to put the index which is going we're going to insert at the index
going we're going to insert at the index number two and the item is going to be
number two and the item is going to be test
test and then i'm just going to print that
and then i'm just going to print that print
print items
items and then i'll run that and then we can
and then i'll run that and then we can see it index number two we now see the
see it index number two we now see the item test
item test now to add multiple items at a specific
now to add multiple items at a specific index you need to use slices so
index you need to use slices so let me show you how you do that so we're
let me show you how you do that so we're going to do a slice
and i'm going to set that equal to test
test 1
test 2.
2. we print that
we print that so now you can see we have test 1 and
so now you can see we have test 1 and test 2 right here
test 2 right here right behind this search thing here
right behind this search thing here and we've inserted multiple items into
and we've inserted multiple items into the list starting at index 1.
the list starting at index 1. now you can also sort a list
now you can also sort a list so if i do
so if i do here we go um
here we go um items dot sort
items dot sort it will sort the list
but you have to make sure okay we have an error it's not supported between
an error it's not supported between we have a combination of ins and strings
we have a combination of ins and strings so let's
so let's make it so it's all strings in the list
and then it should
then it should be able to sort it
okay now the
now the strings are in alphabetical order and if
strings are in alphabetical order and if we're using integers or floats and they
we're using integers or floats and they would just be in numerical order
would just be in numerical order now one thing that's interesting about
now one thing that's interesting about that if i put change this to
that if i put change this to bow
bow you'll see now we have this at the
you'll see now we have this at the beginning and this at the end
beginning and this at the end so
so a the sort method orders uppercase
a the sort method orders uppercase letters first and then lowercase letters
letters first and then lowercase letters so to fix that actually to make it
so to fix that actually to make it make more sense we're going to change
make more sense we're going to change that to
that to bob and to fix that
bob and to fix that within the sort i'm going to i'm going
within the sort i'm going to i'm going to put key equals str dot lower
and now it's going to sort these correctly how
it's going to sort these correctly how you would imagine not caring about
you would imagine not caring about uppercase or lowercase letters
uppercase or lowercase letters sorting modifies the original list
sorting modifies the original list content so to avoid that you can copy
content so to avoid that you can copy the list content using
the list content using so let me show you if we do
items items
copy equals
equals items
items and then we make a slice
and then we make a slice with with nothing at the beginning and
with with nothing at the beginning and nothing at the end so it's going to
nothing at the end so it's going to start at the beginning of the list to
start at the beginning of the list to the end of the list and now we can have
the end of the list and now we can have a copy and i can print
a copy and i can print items copy
items copy so if i print that so now we see we have
so if i print that so now we see we have the sorted list that's that we ran the
the sorted list that's that we ran the sort on but we also still have
sort on but we also still have the original list
so it with all the words in the original order
and there is also a way to sort a list without returning a
without returning a new list
new list there is also a way to sort a list
there is also a way to sort a list without modifying the original list so
without modifying the original list so instead of copying a list
instead of copying a list um what i'm going to do
um what i'm going to do is
is i items
i items instead of doing items dot sort
instead of doing items dot sort we are going to do
we are going to do we're going to use a global function
we're going to use a global function called sorted
called sorted so in the sorted function
so in the sorted function we are going to pass in two parameters
we are going to pass in two parameters so first is the list items
and then the second is how we're sorting it so this just makes
it so this just makes sure that the key the case of the
sure that the key the case of the letters don't matter and then i'm just
letters don't matter and then i'm just going to print that
now if i run this you can see we it we print printed the sorted list
we print printed the sorted list and now we're printing the list and it's
and now we're printing the list and it's not it's no longer sorted because this
not it's no longer sorted because this creates a new list without modifying the
creates a new list without modifying the original list
original list okay now let's learn about another data
okay now let's learn about another data structure called
structure called couples
couples so
so this time i'm going to put
this time i'm going to put tuples
tuples so we're using a comment here so tuples
so we're using a comment here so tuples are another fundamental python data
are another fundamental python data structure they allow you to create
structure they allow you to create immutable groups of objects this means
immutable groups of objects this means that once a tuple is created it cannot
that once a tuple is created it cannot be modified so we already saw that we
be modified so we already saw that we could modify lists but tuple you can't
could modify lists but tuple you can't even add or remove items
even add or remove items they're created in a way similar to
they're created in a way similar to lists but using parentheses instead of
lists but using parentheses instead of square brackets so
square brackets so for instance i'm going to do names
for instance i'm going to do names equals instead of using square brackets
equals instead of using square brackets we're going to do parentheses roger
we're going to do parentheses roger and
and sid
sid okay so a tuple's order like a list so
okay so a tuple's order like a list so you can get its values by referencing an
you can get its values by referencing an index
index an index so i could say for instance
an index so i could say for instance names and if i do the bracket i could
names and if i do the bracket i could put a zero here to return
put a zero here to return roger
roger and then you can also use the index
and then you can also use the index method for instance names
method for instance names dot
dot index
index and then i can
and then i can pass in something like
pass in something like roger and then this is going to
roger and then this is going to return 0
return 0 because it's going to get the the index
because it's going to get the the index number of that so as with strings and
number of that so as with strings and lists using a negative index we'll start
lists using a negative index we'll start searching from the end so i could do
that i can do negative one to start not negative zero negative one to start
not negative zero negative one to start searching from the end here
searching from the end here and you can count the items in a tuple
and you can count the items in a tuple with the length function so i could do
with the length function so i could do if i do length and then do names it's if
if i do length and then do names it's if i printed that it would just print 2
i printed that it would just print 2 because there are two items in that
because there are two items in that tuple
tuple then you can also check if an item is
then you can also check if an item is contained in a tuple with the in
contained in a tuple with the in operators very similar to a list so i
operators very similar to a list so i can do this time i will print it i'll do
can do this time i will print it i'll do print
print roger
roger in
in names so if i print that and run it
names so if i print that and run it we'll see true because roger is in the
we'll see true because roger is in the names
names and then you can extract part of a tuple
and then you can extract part of a tuple using slices
using slices just like we could do with with strings
just like we could do with with strings and lists so i could do names and then i
and lists so i could do names and then i could do
could do 0 starting at the whoops
0 starting at the whoops 0
0 2
2 so that's just going to start at the
so that's just going to start at the zero index and be done at the index 2
zero index and be done at the index 2 and then
and then and then you can use the so you can get
and then you can use the so you can get a sorted version of the tuple using the
a sorted version of the tuple using the sorted global function so
sorted global function so remember when we were looking at lists
remember when we were looking at lists when we used the sorted function it
when we used the sorted function it created a new a new list or so when
created a new a new list or so when we're creating using the sorted function
we're creating using the sorted function for tuples it creates a new tuple so i
for tuples it creates a new tuple so i can say sorted
can say sorted [Music]
[Music] names
names and this would put them in alphabetical
and this would put them in alphabetical order they already in are in
order they already in are in alphabetical order but say there is one
alphabetical order but say there is one more
more word in this list
word in this list and then
and then i can print this
i can print this [Music]
[Music] to print the sorted version but it's not
to print the sorted version but it's not actually going to modify the list
actually going to modify the list because you cannot modify
because you cannot modify a tuple
a tuple and then you can create a new tuple from
and then you can create a new tuple from existing tuples using the plus operator
existing tuples using the plus operator so i could say something like
so i could say something like new tuple
new tuple [Music]
[Music] equals names and then i can use the plus
equals names and then i can use the plus operator
operator and then i would say i would just say
and then i would say i would just say tina
tina and
and quincy i could add a few i could add so
quincy i could add a few i could add so these will combine two tuples into a new
these will combine two tuples into a new tuple but you can never like i said you
tuple but you can never like i said you can't actually modify the original tuple
can't actually modify the original tuple now let's learn about dictionaries
now let's learn about dictionaries dictionaries are another very important
dictionaries are another very important python data structure
python data structure while lists allow you to create
while lists allow you to create collections of values dictionaries allow
collections of values dictionaries allow you to create key value pairs we already
you to create key value pairs we already discussed dictionaries a little bit but
discussed dictionaries a little bit but now we're going to discuss even more
now we're going to discuss even more about dictionaries so let me give you an
about dictionaries so let me give you an example of a dictionary with just one
example of a dictionary with just one key value pair so dog equals and then
key value pair so dog equals and then we're going to use the curly braces to
we're going to use the curly braces to create the dictionary and i'll put name
create the dictionary and i'll put name and then i will put
and then i will put roger and just like any type of strings
roger and just like any type of strings we could make these single quotes or
we could make these single quotes or they could be double quotes and the
they could be double quotes and the spaces here are not very important but
spaces here are not very important but it's common to put spaces in between
it's common to put spaces in between these things for better readability
these things for better readability and the key can be any immutable
and the key can be any immutable value so this is the key this is the
value so this is the key this is the value and the key can be any immutable
value and the key can be any immutable value
value such as a string a number or a tuple
such as a string a number or a tuple the value can be anything you want so a
the value can be anything you want so a dictionary can contain multiple key
dictionary can contain multiple key value pairs so like for instance we got
value pairs so like for instance we got the name we can have
the name we can have age
age and that's going to be
8. and you can access individual key values using the notation like this so i
values using the notation like this so i can say
can say dog
dog so i'm using the bracket notation i can
so i'm using the bracket notation i can do name so if i print this it's just
do name so if i print this it's just going to
going to print roger
and then again i can use the single quotes 2 if i want
quotes 2 if i want and it still prints roger
and it still prints roger and then you can use the same notation
and then you can use the same notation to change the value stored at a specific
to change the value stored at a specific index
index so let's say i want to change the name
so let's say i want to change the name so if i do dog
so if i do dog and i'm going to say that the name
and i'm going to say that the name is now going to equal
is now going to equal sid
sid now i'm just going to print the whole
now i'm just going to print the whole the whole thing
the whole thing and we can see the name is now sid
and we can see the name is now sid instead of roger
instead of roger so another way to get a specific element
so another way to get a specific element is to use the get method so if i do a
is to use the get method so if i do a dog dot
dog dot get
get and then i
and then i do name so i'm going to try to get the
do name so i'm going to try to get the name here
name here it's going to return roger so
it's going to return roger so one good thing about this is that you
one good thing about this is that you can add a default value like let's say
can add a default value like let's say i'm going i'm searching for color
i'm going i'm searching for color and it's saying none it's giving it none
and it's saying none it's giving it none because there is no color
because there is no color but what if i want a default value so
but what if i want a default value so i'm going to put comma and then i'll put
i'm going to put comma and then i'll put brown
so now if it cannot find the color in the dictionary it's going to return
the dictionary it's going to return brown but if it can find the color like
brown but if it can find the color like let's say
let's say color
color and this is a
and this is a green dog
green dog okay we'll return
okay we'll return green
green so with the bracket notation that was
so with the bracket notation that was showing you earlier you cannot have a
showing you earlier you cannot have a default value so that's one good thing
default value so that's one good thing about the get method
about the get method now you can also use the pop method to
now you can also use the pop method to retrieve the value of a key and delete
retrieve the value of a key and delete the item from the dictionary we also
the item from the dictionary we also showed the pop method for lists so for
showed the pop method for lists so for instance i can say
instance i can say get dot
get dot pop
pop and then i will pass in
and then i will pass in name
name and then right after that i'm just going
and then right after that i'm just going to print
dog that the the whole dictionary so first we're going to get roger and then
first we're going to get roger and then when i print the dictionary here it's
when i print the dictionary here it's not going to show roger anymore because
not going to show roger anymore because we we deleted it pop will return the
we we deleted it pop will return the item and delete the item
item and delete the item now you can also use a function a method
now you can also use a function a method called pop item the pop item method well
called pop item the pop item method well let me show you that one pop item
let me show you that one pop item it's going to retrieve and remove the
it's going to retrieve and remove the last key value pair inserted into the
last key value pair inserted into the dictionary
dictionary so
so in this case it should be color so if i
in this case it should be color so if i run this
run this it's going to return color green and now
it's going to return color green and now when i print out the dictionary it's not
when i print out the dictionary it's not going to show color green because that
going to show color green because that was already removed it removed the last
was already removed it removed the last item
item you can also check if a key is contained
you can also check if a key is contained in a dictionary by using the in operator
in a dictionary by using the in operator so we're going to say we're going to try
so we're going to say we're going to try to find out if
color is in
is in dog if there's a key called color in dog
dog if there's a key called color in dog we run that and it says
we run that and it says true another thing we can do is get a
true another thing we can do is get a list with the keys in the dictionary
list with the keys in the dictionary using the keys method so if i do dog dot
using the keys method so if i do dog dot keys
keys and then we'll run that it's going to
and then we'll run that it's going to show the keys so the keys are name age
show the keys so the keys are name age and
and color
color we can see that it's inside the thing
we can see that it's inside the thing called dick keys but we can also pass
called dick keys but we can also pass this into list so we return an actual
this into list so we return an actual just the list part so now we can see
just the list part so now we can see it's just an actual list name age and
it's just an actual list name age and color
color then we can do the same thing with
then we can do the same thing with values so
values so instead of dog.keys let's do
instead of dog.keys let's do values
values print that
print that and you can see we have roger 8 green we
and you can see we have roger 8 green we can pass it into a list
can pass it into a list to
to return the app just the list here
return the app just the list here roger 8 green
roger 8 green and then finally if we just do items
and then finally if we just do items [Music]
[Music] it's going to return all the items in
it's going to return all the items in the list or all the items in the
the list or all the items in the dictionary
dictionary and convert it into a list
so you can see this is the first item in the list this
this is the first item in the list this is the second item and then we have the
is the second item and then we have the third item here so
third item here so we can see each item of the list each
we can see each item of the list each item of the dictionary is now in a list
item of the dictionary is now in a list and then like a lot of the other things
and then like a lot of the other things we can use the length function and i'll
we can use the length function and i'll just put dog
and we can see that there are three items in dog now you can also add a new
items in dog now you can also add a new key value pair to the dictionary so
key value pair to the dictionary so let's say i want to do
let's say i want to do dog
food or i it doesn't even have to be a single
or i it doesn't even have to be a single word i could put favorite
word i could put favorite food
food and i'm going to say
and i'm going to say meet
meet and now we're going to print
and now we're going to print that
let's see what do we oh this was supposed to i did that a little
this was supposed to i did that a little wrong
there we go this is actually how you do it you put use the bracket notation
it you put use the bracket notation equals and let's put what it equals
equals and let's put what it equals there okay now you can see that we now
there okay now you can see that we now have a new item on the list favorite
have a new item on the list favorite food
food meet
meet then you can also delete an item from a
then you can also delete an item from a list or a delete a key value pair so i'm
list or a delete a key value pair so i'm going to d e l means delete dog
going to d e l means delete dog or
or dog there we go and this time i'm going
dog there we go and this time i'm going to delete
to delete color and i'm just going to use single
color and i'm just going to use single quotes instead of double quotes to show
quotes instead of double quotes to show you that doesn't really matter the type
you that doesn't really matter the type of quote and now you can see we don't
of quote and now you can see we don't know what color
know what color this dog is it's no longer a green dog
this dog is it's no longer a green dog and then you can also copy a dictionary
and then you can also copy a dictionary so if you want to make two copies of a
so if you want to make two copies of a dictionary you can do
dictionary you can do do like this dog copy that's the name of
do like this dog copy that's the name of the new dictionary i'll do dog dot copy
the new dictionary i'll do dog dot copy and that would be the new
and that would be the new copied version of the dictionary
copied version of the dictionary okay now we are going to talk about a
okay now we are going to talk about a new thing called sets
new thing called sets sets are another important python data
sets are another important python data structure
structure sets kind of work like tuples but
sets kind of work like tuples but they're not ordered and they are
they're not ordered and they are immutable so you can change them
immutable so you can change them you can also say that they kind of work
you can also say that they kind of work like dictionaries but they don't have
like dictionaries but they don't have keys
keys they're all they have an immutable
they're all they have an immutable version of a set called a frozen set so
version of a set called a frozen set so let me show you how you would create a
let me show you how you would create a set so let's do names
set so let's do names and you we're going to use
and you we're going to use curly brackets just like that
curly brackets just like that and
and just like that so we have two names so
just like that so we have two names so you can see the differences the a
you can see the differences the a dictionary
dictionary you use the curly brackets but there's
you use the curly brackets but there's going to be key value pairs but this
going to be key value pairs but this doesn't have key value pairs in a list
doesn't have key value pairs in a list it's just going to be a
it's just going to be a item after item like this but there's
item after item like this but there's going to be brackets instead of curly
going to be brackets instead of curly braces
braces so
so one thing about the sets is that they
one thing about the sets is that they are not ordered
are not ordered so sets work well when you think about
so sets work well when you think about them as mathematical sets
them as mathematical sets so for instance let's have we're going
so for instance let's have we're going to create a set 1
to create a set 1 with roger and sid and we're going to
with roger and sid and we're going to have a set
have a set 2
2 which is just going to have
which is just going to have roger
roger and so you can intersect two sets so
and so you can intersect two sets so uh the inner intersect
the intersection of these two sets will be set one
be set one and
and set
set two so if i just print that out print
two so if i just print that out print intersect
intersect and then we can just run that and we're
and then we can just run that and we're gonna see what so it's just roger so the
gonna see what so it's just roger so the intersection of these two sets are just
intersection of these two sets are just roger the all the items that they have
roger the all the items that they have in common you can also create a union of
in common you can also create a union of two sets so
two sets so instead of just calling this union i'll
instead of just calling this union i'll put
put mod for modification and so i can show a
mod for modification and so i can show a few different things with the same
few different things with the same variable name and the union symbol is
variable name and the union symbol is just the
just the straight line like this it's not an i
straight line like this it's not an i it's just the
it's just the straight line
straight line it's on the same key as a
it's on the same key as a as the was it the forward slash
as the was it the forward slash backslash one of the slashes
backslash one of the slashes now we're going to get every single item
now we're going to get every single item in both sets which happens to in this
in both sets which happens to in this case just happen to be the same as set
case just happen to be the same as set one but if we change this one to the
one but if we change this one to the word luna it's just a different name and
word luna it's just a different name and now we're going to get each item
now we're going to get each item in both sets or said luna roger for the
in both sets or said luna roger for the intersection and then we can also get
intersection and then we can also get the difference the difference between
the difference the difference between two sets so let me change this to back
two sets so let me change this to back to roger and for the difference between
to roger and for the difference between two sets i'll use a the minus
two sets i'll use a the minus and
and the difference is just going to be sid
the difference is just going to be sid that's the only thing that's different
that's the only thing that's different between the two sets
between the two sets you can also check if a set is a
you can also check if a set is a superset of another and if a set is a
superset of another and if a set is a subset of another so how you would do
subset of another so how you would do that is
that is so we're just saying like is this
so we're just saying like is this greater than that which means it has
greater than that which means it has everything of the in the other set true
everything of the in the other set true now if we put the other direction
now if we put the other direction is does this set have everything in this
is does this set have everything in this one no it doesn't
one no it doesn't you can also count items in a set with
you can also count items in a set with the length function that's pretty
the length function that's pretty self-explanatory i won't even show it to
self-explanatory i won't even show it to you we've seen the link function so many
you we've seen the link function so many times
times you can also get you can also get a list
you can also get you can also get a list from the items in a set by passing the
from the items in a set by passing the set to the list constructor so
set to the list constructor so i'm just going to remove this
i'm just going to remove this and we will do
and we will do list
list set
set one
one okay so now we have a list of the set
okay so now we have a list of the set and then you can check if an item is
and then you can check if an item is contained in a set with the in operator
contained in a set with the in operator just like the
just like the list and the other way we the other
list and the other way we the other places we use the in operator and then
places we use the in operator and then one more final thing about a set a set
one more final thing about a set a set cannot have two of the same item so
cannot have two of the same item so that's another thing that's useful about
that's another thing that's useful about sets so if i type in rogers now we have
sets so if i type in rogers now we have roger sid roger if i play this we'll see
roger sid roger if i play this we'll see it's only going to
it's only going to print sid roger it's not going to add
print sid roger it's not going to add the roger twice to the set
the roger twice to the set so that's another
so that's another useful thing about sets is that make
useful thing about sets is that make sure there's only one of each item in
sure there's only one of each item in the the set so if you have a list that
the the set so if you have a list that has multiple items you can convert it to
has multiple items you can convert it to a set
a set um and then i'll just make sure there's
um and then i'll just make sure there's only one of each thing in that set
only one of each thing in that set now let's talk more about functions
now let's talk more about functions we already talked about functions in the
we already talked about functions in the last section but we're going to do a
last section but we're going to do a review and then go into even more detail
review and then go into even more detail about functions so a function lets us
about functions so a function lets us create a set of instructions that we can
create a set of instructions that we can run when needed and i'm just going to
run when needed and i'm just going to paste in a function and again the
paste in a function and again the indentation it can be either four spaces
indentation it can be either four spaces two spaces
two spaces as long as it's indented the exact same
as long as it's indented the exact same amount
amount so functions are essential in python and
so functions are essential in python and in many other programming languages they
in many other programming languages they help us create meaningful programs
help us create meaningful programs because they allow us to decompose a
because they allow us to decompose a program into manageable parts and they
program into manageable parts and they promote readability and code reuse
promote readability and code reuse so this one is a function called hello
so this one is a function called hello that just prints hello this is the
that just prints hello this is the function definition
function definition so there's a name called hello this is
so there's a name called hello this is the name here and then the body of the
the name here and then the body of the function
function which is the the set of instructions
which is the the set of instructions and the body of the function is
and the body of the function is everything that's after the colon
everything that's after the colon and everything that's indented one level
and everything that's indented one level on the right
on the right so to run this function we must call it
so to run this function we must call it so i can just type in hello
so i can just type in hello hello
hello and then this is the syntax to to call
and then this is the syntax to to call the function and i can call it multiple
the function and i can call it multiple times so i can just copy this and paste
times so i can just copy this and paste it and now if i just run this program
it and now if i just run this program it's going to print hello
it's going to print hello three times
three times the name of the function is very
the name of the function is very important so the name of the function is
important so the name of the function is hello it should be the function name
hello it should be the function name should be descriptive so anyone calling
should be descriptive so anyone calling it can imagine what the function does
it can imagine what the function does a function can accept one or more
a function can accept one or more parameters this is something else that
parameters this is something else that we saw
we saw before
before but
but i can type in a parameter right here and
i can type in a parameter right here and this becomes a variable that we can use
this becomes a variable that we can use in the function so i can change this
in the function so i can change this instead of printing hello
instead of printing hello it's going to print hello
it's going to print hello and then we'll just put name
and then we'll just put name and now i can call the function with the
and now i can call the function with the name
and i can actually um call it with different names so we'll do bow
different names so we'll do bow and we'll do
and we'll do quincy
quincy and then if i just play that we see
and then if i just play that we see hello bo
hello bo hello quincy
hello quincy so
so as you can see we call the function by
as you can see we call the function by passing the argument
passing the argument and again you can use single quote or
and again you can use single quote or double quotes here it's better to be
double quotes here it's better to be consistent just always use single quotes
consistent just always use single quotes or always use double quotes
or always use double quotes but for teaching i like to switch it up
but for teaching i like to switch it up to just to emphasize that you can use
to just to emphasize that you can use either so let me tell you about the
either so let me tell you about the difference between parameters and
difference between parameters and arguments
arguments these two words parameters and arguments
these two words parameters and arguments are sometimes used interchangeably
are sometimes used interchangeably and it's common to get confused about
and it's common to get confused about the distinction
the distinction we call
we call parameters
parameters the values accepted by the function
the values accepted by the function inside the function definition
inside the function definition and arguments are the values we pass to
and arguments are the values we pass to the function when we call it also an
the function when we call it also an argument can have a default value
argument can have a default value that's applied if the argument is not
that's applied if the argument is not specified so let me show you how i would
specified so let me show you how i would do that so we have it name so right now
do that so we have it name so right now it always needs to be get a name well
it always needs to be get a name well first let me show you what would happen
first let me show you what would happen if i called the function without passing
if i called the function without passing the name
the name i'm just going to run that and we can
i'm just going to run that and we can see we're going to get an error hello
see we're going to get an error hello missing one required positional argument
missing one required positional argument name but we can make it so you can call
name but we can make it so you can call this function without passing in a name
this function without passing in a name where it's optional you can't if you
where it's optional you can't if you want so i'm going to put an equal sign
want so i'm going to put an equal sign and then i'm gonna type in my friend
and then i'm gonna type in my friend and just to make consistent make this
and just to make consistent make this consistent i'm gonna make this all
consistent i'm gonna make this all double quotes
okay so this is now an optional argument so it's it's you can pass in the name
so it's it's you can pass in the name but if you don't pass a name it's going
but if you don't pass a name it's going to default to my friend so i'll just run
to default to my friend so i'll just run this again with that default
this again with that default value and now it's hello bow hill quincy
value and now it's hello bow hill quincy hello my friend because we called this
hello my friend because we called this and we didn't specify any argument or
and we didn't specify any argument or parameter and then we can also accept
parameter and then we can also accept multiple parameters so i'm just going to
multiple parameters so i'm just going to get rid of this default value and i'll
get rid of this default value and i'll put 8 so now we're accepting a name and
put 8 so now we're accepting a name and an age so we can now use both parameters
an age so we can now use both parameters in our function so i can do plus
in our function so i can do plus hello
hello name
name [Music]
[Music] you are
you are and we're going to add
and we're going to add the age
the age and now it's going to be passed in as a
and now it's going to be passed in as a number but we're going to convert it to
number but we're going to convert it to a string
a string so you are
so you are [Music]
[Music] years old
years old and then we have to make sure we have to
and then we have to make sure we have to make sure to add a space in here so
make sure to add a space in here so there'll be a space space after this
there'll be a space space after this word then the number then a space and
word then the number then a space and then years old
then years old so i'm gonna now have to pass in the
so i'm gonna now have to pass in the number
number and now i can run this function
and now i can run this function now showing the red
now showing the red squiggly lines
squiggly lines i sometimes the the red squiggly lines
i sometimes the the red squiggly lines will appear when it's
will appear when it's actually correct
actually correct so let me what am i am i doing something
so let me what am i am i doing something wrong here
wrong here oh i need to put the parentheses
oh i need to put the parentheses if the red squiggly lines appears when
if the red squiggly lines appears when it's actually correct they'll it they'll
it's actually correct they'll it they'll go away
go away usually within a few seconds or if you
usually within a few seconds or if you hit enter
hit enter so that actually was a problem i forgot
so that actually was a problem i forgot the parentheses at the end um so
the parentheses at the end um so you can see this is what the whole
you can see this is what the whole function looks like
function looks like if it's all on one line but i'm just
if it's all on one line but i'm just going to
going to move that over so hello bo you are 39
move that over so hello bo you are 39 years old so we've used the name and the
years old so we've used the name and the age
age so parameters are passed by reference
so parameters are passed by reference all types in python are objects but some
all types in python are objects but some of them are immutable including integers
of them are immutable including integers booleans floats strings and tuples this
booleans floats strings and tuples this means that if you pass them as
means that if you pass them as parameters and you modify their value
parameters and you modify their value inside the function the new value is not
inside the function the new value is not reflected outside of the function
reflected outside of the function let me just give you an example of that
let me just give you an example of that so if i just i'm just going to paste in
so if i just i'm just going to paste in some new code here and we can see we
some new code here and we can see we have this function called change and
have this function called change and we're going to pass in this value if we
we're going to pass in this value if we pass in this this valve variable 1 to
pass in this this valve variable 1 to the change function and we set value to
the change function and we set value to 2
2 well then we're going to print the value
well then we're going to print the value and see what happens
and see what happens and you can see it's now just 1 here so
and you can see it's now just 1 here so so it didn't change the value
so it didn't change the value the value so what we change inside the
the value so what we change inside the function doesn't affect anything from
function doesn't affect anything from outside the function
outside the function and then you can see we have these
and then you can see we have these orange squiggly lines here local
orange squiggly lines here local variable value is assigned but never
variable value is assigned but never used it's just showing that actually
used it's just showing that actually this isn't really doing anything once
this isn't really doing anything once it's inside the function and we change
it's inside the function and we change it doesn't change anything outside the
it doesn't change anything outside the function
function so if you pass an object that's not
so if you pass an object that's not immutable you do change one of its
immutable you do change one of its properties and the change will be
properties and the change will be reflected outside so this was
reflected outside so this was mutable this is immutable an object that
mutable this is immutable an object that would be
would be mutable would be like a dictionary so if
mutable would be like a dictionary so if i change this to a dictionary and i put
i change this to a dictionary and i put name
and i set it to bow but then inside the change i do value
but then inside the change i do value dot name or not i'll put the the
dot name or not i'll put the the brackets value name
brackets value name so the key of this dictionary and i set
so the key of this dictionary and i set that to sid
that to sid and i run this we'll see now the name
and i run this we'll see now the name has changed to sin so we changed we use
has changed to sin so we changed we use the change function to change name to
the change function to change name to sid and now it actually is changed
sid and now it actually is changed because a dictionary is mutable
because a dictionary is mutable so a function can also return a value
so a function can also return a value using the return statement
using the return statement so i'm going to update this whole thing
so i'm going to update this whole thing and talk about return statements a
and talk about return statements a function can return a value using the
function can return a value using the return statement so it's going to return
return statement so it's going to return this name that we then can continue to
this name that we then can continue to use in our in our program it doesn't
use in our in our program it doesn't have to return name it can return
have to return name it can return anything that happens inside the
anything that happens inside the function
function and
and the when the function meets the return
the when the function meets the return statement the function ends so you can
statement the function ends so you can have a return statement have code after
have a return statement have code after it but it will just end like for
it but it will just end like for instance if you have the return
instance if you have the return statement in a conditional like in an if
statement in a conditional like in an if statement we can also omit
statement we can also omit the return the return value
the return the return value so it's just going to end the function
so it's just going to end the function and not return anything so i had
and not return anything so i had mentioned having the return statement in
mentioned having the return statement in a conditional so that's a common way to
a conditional so that's a common way to end a function if the starting condition
end a function if the starting condition is not met
is not met like for instance if we update the
like for instance if we update the function to
function to this so if not name return this so if i
this so if not name return this so if i mean if not name return
mean if not name return or
or else
else you don't even need an else because this
you don't even need an else because this will just in the function and you don't
will just in the function and you don't even need an else this will happen if
even need an else this will happen if there is a name now we just said that
there is a name now we just said that you have to pass in something if you
you have to pass in something if you don't have a default value so the way to
don't have a default value so the way to get to that would just be to call the
get to that would just be to call the function
function with false
with false so if we call with false then it's just
so if we call with false then it's just going to return it doesn't do anything
going to return it doesn't do anything but if we call it with
but if we call it with bo
bo then let's see
then let's see hello bo so you can also return multiple
hello bo so you can also return multiple values by using comma separated values
values by using comma separated values so
so for instance i can i'm just going to
for instance i can i'm just going to take this part off here and then add a
take this part off here and then add a return statement
return statement return and then i can return the name i
return and then i can return the name i can return
can return bo in case that's not the name i can
bo in case that's not the name i can return
return 8 and then i can call this and i'm just
8 and then i can call this and i'm just going to call this with sid
going to call this with sid and we can see what happens
and we can see what happens now
now oh
oh it doesn't it's not it doesn't actually
it doesn't it's not it doesn't actually print what's been returned but if i
print what's been returned but if i print this
print this here we go then we can really see what
here we go then we can really see what happens so
happens so in this function it's going to print
in this function it's going to print this but now we're also going to print
this but now we're also going to print what's returned so let's see what that
what's returned so let's see what that looks like so
looks like so this is what when we print what was
this is what when we print what was returned it looks like this so it's sid
returned it looks like this so it's sid bo
bo 8
8 so one thing related to functions and
so one thing related to functions and also related to other parts of python is
also related to other parts of python is variable scope
variable scope so let's look at this
so let's look at this we've declared a variable up here and
we've declared a variable up here and when you declare a variable that
when you declare a variable that variable is visible in parts of your
variable is visible in parts of your program depending on where you declare
program depending on where you declare it
it so if you declare a variable outside of
so if you declare a variable outside of a function the variable is visible to
a function the variable is visible to any code running after the declare after
any code running after the declare after the declaration including functions so
the declaration including functions so we call this a global variable so we've
we call this a global variable so we've declared this before the function so we
declared this before the function so we can now access it inside a function and
can now access it inside a function and also outside the function so if i
also outside the function so if i so we can see 8 and 8 and it shows right
so we can see 8 and 8 and it shows right here what's going to
here what's going to show in the
show in the console here
console here but if we declare a variable inside a
but if we declare a variable inside a function let me give you an example if
function let me give you an example if we declare
we declare this variable
this variable inside the function i'm just going to
inside the function i'm just going to move it down to here
move it down to here now it's a
now it's a local variable and it's only visible
local variable and it's only visible inside the function so let me just
inside the function so let me just delete with this because it's not
delete with this because it's not actually going to be
actually going to be doing that so if i run this we're going
doing that so if i run this we're going to see there's there's an error
to see there's there's an error name
name age is not defined we're trying to print
age is not defined we're trying to print the age here but since the age was
the age here but since the age was declared inside the function it's not
declared inside the function it's not available outside the function it's only
available outside the function it's only available
available inside the function
inside the function so you just have to be aware sometimes
so you just have to be aware sometimes there's local variables that only apply
there's local variables that only apply inside the function and there's global
inside the function and there's global variables if you that can apply inside a
variables if you that can apply inside a function and outside a function
function and outside a function okay now let's look at something else
okay now let's look at something else with functions and this is nested
with functions and this is nested functions
functions functions in python can be nested
functions in python can be nested inside other functions
inside other functions a function defined inside a function is
a function defined inside a function is visible only inside that function this
visible only inside that function this is useful to create utilities that are
is useful to create utilities that are useful to a function but not useful
useful to a function but not useful outside of it so you might ask why
outside of it so you might ask why should i be hiding this function if it
should i be hiding this function if it does no harm
does no harm well one because it's always best to
well one because it's always best to hide functionality that's local to a
hide functionality that's local to a function if it's not useful elsewhere
function if it's not useful elsewhere also because we can make use of closures
also because we can make use of closures which we'll talk more about later so so
which we'll talk more about later so so look at this example so we have this
look at this example so we have this function talk and inside the function we
function talk and inside the function we defined another function called say
defined another function called say and then
and then what we
what we what we do is that we can call that say
what we do is that we can call that say function
function inside the function and so the way this
inside the function and so the way this works is we pass in the phrase so here's
works is we pass in the phrase so here's the phrase and the phrase i'm going to
the phrase and the phrase i'm going to buy the milk
buy the milk and here we do we we split it so split
and here we do we we split it so split is a way to
is a way to create a list
create a list of out of this string so we have this
of out of this string so we have this string but it's going to split it on
string but it's going to split it on every space so it's going to create a
every space so it's going to create a list of each word individually and then
list of each word individually and then we're going to run this loop
we're going to run this loop more on loops later
more on loops later and we're going to for every word in the
and we're going to for every word in the the words list we're going to say
the words list we're going to say the word we're going to say the word
the word we're going to say the word it's just going to print the word so if
it's just going to print the word so if i just run that i am going to buy the
i just run that i am going to buy the milk and every time it prints it it
milk and every time it prints it it prints it on a new line so this would
prints it on a new line so this would just be an example because we're never
just be an example because we're never going to want to use this save function
going to want to use this save function outside the talk function so it's better
outside the talk function so it's better just to put it inside the talk function
just to put it inside the talk function and then i'll just paste in
and then i'll just paste in another example here if you want to
another example here if you want to access a variable defined in the outer
access a variable defined in the outer function from the inner function
function from the inner function you first need to declare it as
you first need to declare it as non-local
non-local so
so we're using non-local here at non-local
we're using non-local here at non-local count and this allows us to access this
count and this allows us to access this variable that was declared inside the
variable that was declared inside the out so this is the outer function count
out so this is the outer function count and we have this variable called count
and we have this variable called count and to be able to access that variable
and to be able to access that variable in the inner function we have to
in the inner function we have to call non-local or we already talked
call non-local or we already talked about variable scope and if we didn't
about variable scope and if we didn't call
call call this non-local then we could not
call this non-local then we could not access the count variable from inside
access the count variable from inside the function so like for instance i'm
the function so like for instance i'm going to run this it's going to print
going to run this it's going to print the count which is just count plus 1 is
the count which is just count plus 1 is just adding 1 to this number that's all
just adding 1 to this number that's all the function does but if i take off this
the function does but if i take off this word non-local here and i run this we're
word non-local here and i run this we're going to get an error because it doesn't
going to get an error because it doesn't know what count is it doesn't know that
know what count is it doesn't know that we're referring to this count in the
we're referring to this count in the inner function so we'll just put that
inner function so we'll just put that back on there and then it should work
back on there and then it should work again
again this is especially useful with closures
this is especially useful with closures which we're just about to talk about
which we're just about to talk about so closure is a special way of doing a
so closure is a special way of doing a function in python if you return a
function in python if you return a nested function from a function that
nested function from a function that nested function has access to the
nested function has access to the variables defined in that function even
variables defined in that function even if that function is not active anymore
if that function is not active anymore so let me show you an example i'm going
so let me show you an example i'm going to paste some code that'll be very
to paste some code that'll be very similar to this code but just a a little
similar to this code but just a a little different and then i'll explain it so
different and then i'll explain it so now instead of count it's a counter so
now instead of count it's a counter so we're returning count from this nested
we're returning count from this nested function and from the outer function
function and from the outer function we're returning the nested function
we're returning the nested function we're returning the increment function
we're returning the increment function and then here instead of just calling
and then here instead of just calling the function directory the outer
the function directory the outer function we're assigning it to this
function we're assigning it to this variable and now we're going to print
variable and now we're going to print we're just going to call we're going to
we're just going to call we're going to call this variable which is the returned
call this variable which is the returned inner function so we're basically
inner function so we're basically calling the inner function and it's
calling the inner function and it's still going it's because we're calling
still going it's because we're calling the inner function it's not going to
the inner function it's not going to reset the count to zero every time and
reset the count to zero every time and it can keep track of that value and we
it can keep track of that value and we have this
have this using a comment what it's going to
using a comment what it's going to return but we can also
return but we can also run the program and we can see one two
run the program and we can see one two three just like that so we return the
three just like that so we return the increment inner function and that still
increment inner function and that still has access to the state of the count
has access to the state of the count variable even though the counter
variable even though the counter function has ended
function has ended so let's move on to
so let's move on to objects
objects [Music]
[Music] everything in python is an object
everything in python is an object even values of basic prim of types like
even values of basic prim of types like integers strings floats are objects
integers strings floats are objects lists are objects as well as tuples
lists are objects as well as tuples dictionaries and pretty much everything
dictionaries and pretty much everything so objects have attributes and methods
so objects have attributes and methods that can be accessed using the dot
that can be accessed using the dot syntax for example let's define a new
syntax for example let's define a new variable of type int so i'm going to do
variable of type int so i'm going to do age equals eight
age equals eight age now has access to the properties and
age now has access to the properties and methods defined for all int objects
methods defined for all int objects this includes for example access to the
this includes for example access to the real and imaginary part of that number
real and imaginary part of that number so i can do
so i can do a print
a print age dot real
age dot real and then if i just run that
and then if i just run that the real part is eight i can also print
the real part is eight i can also print the imaginary
the imaginary part of the number
part of the number and manage
and manage and there is no imaginary part of the
and there is no imaginary part of the number so it just
number so it just does zero i can also get the the bit
does zero i can also get the the bit length age dot
length age dot bit
bit length
and if i run that we can see the bit length is four so the
we can see the bit length is four so the bit length method returns the number of
bit length method returns the number of bits necessary to represent this number
bits necessary to represent this number in binary notation
in binary notation so there's just a lot of
so there's just a lot of things that you can use for all int
things that you can use for all int objects and these are just a few of them
objects and these are just a few of them so a variable holding a list value has
so a variable holding a list value has access to a different set of methods so
access to a different set of methods so i'm going to
i'm going to update this again we're going to do
update this again we're going to do items
items equals and we're going to create a list
equals and we're going to create a list one
one two
two so
so i can do
i can do items dot
items dot append
append i can append a three i can append
i can append a three i can append another item i can do
another item i can do items dot pop
items dot pop which is going to
which is going to remove and return the last item which is
remove and return the last item which is the three
the three and the methods so so these are the
and the methods so so these are the methods of pin and pop and the methods
methods of pin and pop and the methods available to an object depend on the
available to an object depend on the type of value
type of value the id global function provided by
the id global function provided by python lets you inspect the location in
python lets you inspect the location in memory for a particular object so for
memory for a particular object so for instance i could do a print and i'm
instance i could do a print and i'm going to do id what's the id of the
going to do id what's the id of the items
items object
object and we can see this is the location in
and we can see this is the location in memory
memory so some val some objects are mutable
so some val some objects are mutable while others are immutable this is
while others are immutable this is something that we already talked about a
something that we already talked about a little bit that depends on the object
little bit that depends on the object itself if the object provides methods to
itself if the object provides methods to change its content then it's mutable
change its content then it's mutable otherwise it's immutable
otherwise it's immutable most most types defined by python are
most most types defined by python are immutable for example an int is
immutable for example an int is immutable there are no methods to change
immutable there are no methods to change its value so if you increment the value
its value so if you increment the value like with um
like with um age equals age
age equals age plus
plus one
one it's actually going to create an
it's actually going to create an entirely
entirely new value
new value so it it's not going to even be the same
so it it's not going to even be the same object at all because age you it has to
object at all because age you it has to create a whole new one to reassign it
create a whole new one to reassign it but something like a in in a dictionary
but something like a in in a dictionary it would actually be the same object but
it would actually be the same object but you could just change different parts of
you could just change different parts of it now let's talk more about
it now let's talk more about loops
loops so this song we already discussed a
so this song we already discussed a little bit in the previous section but
little bit in the previous section but loops are
loops are one essential part of programming
one essential part of programming and in python we have two kinds of loops
and in python we have two kinds of loops while loops and for loops
while loops and for loops so before i um show i'm going to paste
so before i um show i'm going to paste in this code but i just want to show
in this code but i just want to show something really quick see how there's a
something really quick see how there's a line like dotted line here and a dotted
line like dotted line here and a dotted line here this is showing the default
line here this is showing the default indentation which we can change so i'm
indentation which we can change so i'm actually going to go and change
actually going to go and change that really quick let me wait i think
that really quick let me wait i think i'm gonna have to yeah i'm gonna zoom
i'm gonna have to yeah i'm gonna zoom out so i can get to this and i'm gonna
out so i can get to this and i'm gonna change the indent to four and now it's
change the indent to four and now it's not going to have a little line right in
not going to have a little line right in there so now i'm going to go back here
there so now i'm going to go back here and let's zoom in again
okay so let's talk about while loops
while loops while loops are defined using the
while loops are defined using the while
while keyword
keyword and they repeat their block until the
and they repeat their block until the the condition is evaluated as false so
the condition is evaluated as false so while condition equals true so
while condition equals true so this particular example is an infinite
this particular example is an infinite loop it never ends because this
loop it never ends because this condition is always going to so if we
condition is always going to so if we run this program which i'm not going to
run this program which i'm not going to do right now because it just goes on
do right now because it just goes on forever while this condition is true
forever while this condition is true keep running the code inside the loop
keep running the code inside the loop all the lines of code that are indented
all the lines of code that are indented the same amount
the same amount so let's halt the loop right after the
so let's halt the loop right after the first iteration i can do condition
first iteration i can do condition equals
equals false
[Music] so now if i run it it just runs the loop
so now if i run it it just runs the loop one time
one time so in this case the first iteration is
so in this case the first iteration is run as the condition is evaluated true
run as the condition is evaluated true and then at the second iteration the
and then at the second iteration the condition test evaluates to false so the
condition test evaluates to false so the control goes to the next instruction
control goes to the next instruction after the loop which in this case there
after the loop which in this case there is no next instruction after the loop
is no next instruction after the loop it's common to have a counter to stop
it's common to have a counter to stop the iteration after some number of
the iteration after some number of cycles
so here's a while loop with a counter so you you start the counter at zero and
you you start the counter at zero and then while count is less than 10.
then while count is less than 10. we're we're gonna print this count
we're we're gonna print this count equals count plus one so it's going to
equals count plus one so it's going to increment the counter every time
increment the counter every time until we get to the end so it's gonna
until we get to the end so it's gonna see it's gonna print this until
see it's gonna print this until eventually the count is
greater than 10 so or 10 or 10 or greater while count is
so or 10 or 10 or greater while count is less than 10. so once it gets to 10 the
less than 10. so once it gets to 10 the loop will stop um again another way to
loop will stop um again another way to doing to do this we could have just done
doing to do this we could have just done plus equals plus equals one so if i run
plus equals plus equals one so if i run that it's going to do the exact same
that it's going to do the exact same thing
thing and other type is the for loop so using
and other type is the for loop so using for loops we can tell python to execute
for loops we can tell python to execute a block for a predetermined amount of
a block for a predetermined amount of times up front and without the need of a
times up front and without the need of a separate variable and conditional to
separate variable and conditional to check its value
check its value it's commonly used to iterate the items
it's commonly used to iterate the items in a list so we have this list there's
in a list so we have this list there's obviously four items here and then four
obviously four items here and then four item in items so items is this list and
item in items so items is this list and then for each item in the list we're
then for each item in the list we're going to print
going to print the item pretty straightforward and it
the item pretty straightforward and it prints each item in the list
prints each item in the list or you can iterate a specific amount of
or you can iterate a specific amount of times using the range function so let's
times using the range function so let's say we don't have we're not going to
say we don't have we're not going to define this here we're just going to do
define this here we're just going to do 4 item in and then here i'm going to
4 item in and then here i'm going to type in range
type in range and then i'm just going to type in a
and then i'm just going to type in a number how about
number how about 15
15 so i'm using the range function that
so i'm using the range function that basically just returns a list and then
basically just returns a list and then if i do that we can see it's going from
if i do that we can see it's going from 0 to 14. so the range function is going
0 to 14. so the range function is going to return a
to return a a list that goes from 0 to 14 so there's
a list that goes from 0 to 14 so there's 15 items and it's going to print the
15 items and it's going to print the items
items now if we just go back a few steps to
now if we just go back a few steps to when we had the list here
when we had the list here we can i can show you how to get the
we can i can show you how to get the index so right now it's just printing
index so right now it's just printing the items one two three four but what if
the items one two three four but what if we want the index of the list
we want the index of the list we can do that by using the by wrapping
we can do that by using the by wrapping the sequence in the enumerate function
the sequence in the enumerate function so for items in and then
so for items in and then i'm going to do
i'm going to do enumerate
so this is going to return each item and
each item and the index of the item and since there's
the index of the item and since there's going to be an item in an index
going to be an item in an index but it's actually the index and then the
but it's actually the index and then the item i'm going to type an index comma
item i'm going to type an index comma item so this enumerate is going to get
item so this enumerate is going to get the index and the item so now i can
the index and the item so now i can print the index and the item here and if
print the index and the item here and if i run that
i run that so index zero item one index one item
so index zero item one index one item two index two item three and so on and
two index two item three and so on and it doesn't even have to be numbers we
it doesn't even have to be numbers we can
do names [Music]
and if i just run that whoops not that one
one and then we can see the the index and
and then we can see the the index and the item then let me put in some more
the item then let me put in some more code here so i can talk about break and
code here so i can talk about break and continue
continue both while and for loops can be
both while and for loops can be interrupted inside the block using
interrupted inside the block using either break or continue
either break or continue continue stops the current iteration and
continue stops the current iteration and tells python to execute the next one
tells python to execute the next one and break stops the loop altogether and
and break stops the loop altogether and goes on with the next instruction after
goes on with the next instruction after the loop ends so i'm going to just play
the loop ends so i'm going to just play this so here we're saying if item equals
this so here we're saying if item equals two continues that means it's going to
two continues that means it's going to skip that iteration so if i play this
skip that iteration so if i play this one three four so it's not going to it's
one three four so it's not going to it's not going to get to the print item
not going to get to the print item because it's actually skipped that
because it's actually skipped that iteration it just
iteration it just doesn't run any code after the continue
doesn't run any code after the continue if this is true
if this is true and so it doesn't print 2. so if we
and so it doesn't print 2. so if we change this to break it will be very
change this to break it will be very it'll be a little different here this
it'll be a little different here this time it's going to just print one
time it's going to just print one because now it's breaking out of the
because now it's breaking out of the loop
loop entirely and it's not going to run any
entirely and it's not going to run any more iteration of the loop
more iteration of the loop okay let's talk about another thing
okay let's talk about another thing classes classes in python
classes classes in python so in addition to using the python
so in addition to using the python provided types we can declare our own
provided types we can declare our own classes
classes and from the classes we can instantiate
and from the classes we can instantiate objects
objects an object is an instance of a class
an object is an instance of a class a class is the type of an object so
a class is the type of an object so here's an example i'm going to create a
here's an example i'm going to create a class called
class called dog
dog so
so uh to create a class you just put the
uh to create a class you just put the word class and then put the the class
word class and then put the the class name
name and
and now
now i can i can
i can i can add a method for the class so to define
add a method for the class so to define a method i'll just do define bark
a method i'll just do define bark [Music]
[Music] and i'm going to put the word self here
and i'm going to put the word self here and inside this i'll print
[Music] woof
woof [Music]
okay so self as an argument of the method
method will point to the current object
will point to the current object instance and must be specified when
instance and must be specified when defining a method so when you're
defining a method so when you're creating a method inside a class you're
creating a method inside a class you're always going to start with self so we
always going to start with self so we create an instance of a class
create an instance of a class which is an object
which is an object like this
like this so i'm just going to put
so i'm just going to put roger
roger equals
equals dog
dog okay so i've created a dog just like
okay so i've created a dog just like this
this and then i can
and then i can print
print type
type roger so let's see what the type of this
roger so let's see what the type of this roger is we can see it's the class to
roger is we can see it's the class to dog class
dog class roger is a dog
roger is a dog a special type of method
a special type of method called in there's a special type of
called in there's a special type of method called init which is a
method called init which is a constructor
constructor so let me show you how to create a
so let me show you how to create a constructor
constructor deaf
so we can use this a constructor like this
a constructor like this to initialize one more properties when
to initialize one more properties when we create a new object from that class
we create a new object from that class so you can see we always have to add
so you can see we always have to add self but now these are the two
self but now these are the two variables we can pass in when we create
variables we can pass in when we create a dog and that will associate be
a dog and that will associate be associated with that
associated with that that
that object
object so down here i can call um i can call
so down here i can call um i can call dog but i can pass in roger for the name
dog but i can pass in roger for the name and
and the age
the age and now when we create this
and now when we create this dog it's going to assign the name to
dog it's going to assign the name to self.name and it's going to assign the
self.name and it's going to assign the age to self.age and let me show you how
age to self.age and let me show you how you can access that information
you can access that information so i'm going to print instead of
so i'm going to print instead of printing the type i'm going to do roger
printing the type i'm going to do roger dot name
dot name and now it's going to when i do
and now it's going to when i do roger.name that's self.name so self is
roger.name that's self.name so self is roger and we do self.name it's going to
roger and we do self.name it's going to be the name that was passed in
be the name that was passed in and then we can also
and then we can also do the age
do the age and then we can finally
and then we can finally call the bark method so we have bark
call the bark method so we have bark here now we can see what that does so
here now we can see what that does so i'm just going to run that
i'm just going to run that and we have roger
and we have roger we have eight
we have eight and then
and then this is because i should have put
this is because i should have put parentheses here so let me put
parentheses here so let me put parentheses after bark
parentheses after bark and so we have wolf here so roger 8
and so we have wolf here so roger 8 wolf and the reason why it says none
wolf and the reason why it says none here is because i didn't have to put the
here is because i didn't have to put the print see i i put pranks that was in
print see i i put pranks that was in this groove if you're playing print on
this groove if you're playing print on everything but calling bark
everything but calling bark already prints wolf
already prints wolf so when i do
so when i do it when it's when it's printing it's
it when it's when it's printing it's printing because since
printing because since roger.bark doesn't return anything
roger.bark doesn't return anything there's no return statement that's why
there's no return statement that's why it printed none so there'd be two ways
it printed none so there'd be two ways to fix that either instead of printing
to fix that either instead of printing wolf i could return wolf
wolf i could return wolf or i could just not do the print here so
or i could just not do the print here so let me just take that off
let me just take that off okay roger 8
okay roger 8 wolf
wolf so one important feature of class is
so one important feature of class is inheritance let me show you an example
inheritance let me show you an example of inheritance i'm going to create a new
of inheritance i'm going to create a new class before the dog class and this is
class before the dog class and this is going to be
going to be a class
a class called
called animal
animal and the animal class i'm going to put a
and the animal class i'm going to put a function called walk
function called walk and i'm going to always pass in self
and i'm going to always pass in self and this is going to print
and this is going to print [Music]
[Music] walking
walking [Music]
[Music] and then we can make the dog class
and then we can make the dog class inherent inherit from the animal class
inherent inherit from the animal class so we have class dog but if i put
so we have class dog but if i put parentheses here
parentheses here then i can type in animal
then i can type in animal and now the dog class is going to
and now the dog class is going to inherit from the animal class and now i
inherit from the animal class and now i can go down here and after roger.bark i
can go down here and after roger.bark i can do roger.walk
can do roger.walk and if i run that
and if i run that okay so roger 8wolf but now it's going
okay so roger 8wolf but now it's going to be able to do walking and you can see
to be able to do walking and you can see the dog class doesn't actually have a
the dog class doesn't actually have a walk method but it's getting it from
walk method but it's getting it from the animal class it's inheriting this
the animal class it's inheriting this method
method and in that way you're able to i could
and in that way you're able to i could create a class cat a class frog
create a class cat a class frog a class bird and each of them could
a class bird and each of them could inherit the walk
inherit the walk method and then it would have
method and then it would have walking
walking and we'll be doing a little more with
and we'll be doing a little more with classes in the the final project
classes in the the final project in this course
in this course because we'll be going a little more
because we'll be going a little more over object oriented programming
over object oriented programming but right now let's talk about something
but right now let's talk about something new i'm going to just delete all this
new i'm going to just delete all this and we're going to be talking about
and we're going to be talking about modules
modules so every python file is a module you can
so every python file is a module you can import a module from other files and
import a module from other files and that's the base of any program of
that's the base of any program of moderate complexity as it promotes a
moderate complexity as it promotes a sensible organization and code reuse so
sensible organization and code reuse so it's basically how you can create a
it's basically how you can create a software that has multiple python
software that has multiple python programs in the same piece of software
programs in the same piece of software so in the typical python program one
so in the typical python program one file acts as the entry point and the
file acts as the entry point and the other files are modules and exposed
other files are modules and exposed functions that we can call from
functions that we can call from other files so
other files so let me just show you an example i am
let me just show you an example i am going to
going to open up this
open up this files tab and i'm going to create a new
files tab and i'm going to create a new file and this is going to be called dog
file and this is going to be called dog dot pi
dot pi and now i have dog dot pi open i no
and now i have dog dot pi open i no longer have the main dot pi open and i'm
longer have the main dot pi open and i'm going to define
going to define bark
bark and what bark is going to do is just
and what bark is going to do is just print
print woof
woof [Music]
[Music] okay now i'm going to it's just going to
okay now i'm going to it's just going to automatically save for me i'm going to
automatically save for me i'm going to go back to the the python file and now
go back to the the python file and now i'm going to
i'm going to import
import dog
dog and let's see oh it's just saying it's
and let's see oh it's just saying it's unused i thought maybe this thing wrong
unused i thought maybe this thing wrong but that just means i import dog and i
but that just means i import dog and i haven't used it which i'm about to do
haven't used it which i'm about to do right now so dog
right now so dog dot
dot bark
bark so now if i run this program
so now if i run this program it's going to say wolf but that's not
it's going to say wolf but that's not from this file it's actually importing
from this file it's actually importing this function from from the dog file so
this function from from the dog file so that's a way you can
that's a way you can break up your code into multiple files
break up your code into multiple files we can also use the from import syntax
we can also use the from import syntax and call the function directly
and call the function directly let me show you what i mean so instead
let me show you what i mean so instead of import dog i'm going to say
of import dog i'm going to say from dog
from dog import
import bark
bark and then instead of calling it dog.bark
and then instead of calling it dog.bark i can just call
i can just call bark
bark because we're only importing bark well
because we're only importing bark well we've imported bark directly instead of
we've imported bark directly instead of the whole dog so i can run that and it
the whole dog so i can run that and it says
says wolf
wolf so
so the first strategy allows us to load
the first strategy allows us to load everything defined in a file when i just
everything defined in a file when i just said
said import dog that
import dog that allows everything defined in a file so i
allows everything defined in a file so i could have a bunch of function like bark
could have a bunch of function like bark or walk
or walk name or there could be a bunch of
name or there could be a bunch of functions if i just say import dog it
functions if i just say import dog it imports all of them but the second
imports all of them but the second strategy from dog import bark allows us
strategy from dog import bark allows us to just pick the things we need so we're
to just pick the things we need so we're only going to import the specific
only going to import the specific functions that we need
functions that we need those modules are specific to your
those modules are specific to your program and importing depends on the
program and importing depends on the location of the file in the file system
location of the file in the file system so
so suppose you put dog.pi in a
suppose you put dog.pi in a subfolder for instance let's say i
subfolder for instance let's say i create a folder
create a folder and i call it liv for library and let's
and i call it liv for library and let's say i put dog.pi in this subfolder like
say i put dog.pi in this subfolder like this
this now in this folder to make this work i'm
now in this folder to make this work i'm going to have to create an empty file
going to have to create an empty file named init.pie so i'm going to add file
named init.pie so i'm going to add file and i'll do init dot or under underscore
and i'll do init dot or under underscore underscore init underscore underscore
underscore init underscore underscore dot pi
dot pi and this tells python that
and this tells python that the folder contains modules
the folder contains modules now i'm going to go back to my main file
now i'm going to go back to my main file and i can
and i can i can import dog from
i can import dog from lib so i'm going to say from
lib so i'm going to say from lib
lib that's that subfolder import
that's that subfolder import dog
dog and then i can do
and then i can do dog
dog dot bark so let's run that to make sure
dot bark so let's run that to make sure there's no errors it worked
there's no errors it worked correctly so i was able to import this
correctly so i was able to import this file from the subfolder
file from the subfolder or you can reference the dog module
or you can reference the dog module specific function by importing from
specific function by importing from lib.dog so i can do from
lib.dog so i can do from lib.dog
lib.dog import
import bark and now instead of calling dog.bark
bark and now instead of calling dog.bark i can just call
i can just call bark
bark and it says
and it says wolf
wolf so i'm going to close this here
so i'm going to close this here and
and now let's talk about the python standard
now let's talk about the python standard library so basically there's all these
library so basically there's all these pre-built modules you can
pre-built modules you can you can load a lot of code from the
you can load a lot of code from the standard library python exposes a lot of
standard library python exposes a lot of built-in functionality through its
built-in functionality through its standard library
standard library the stand library is a huge collection
the stand library is a huge collection of all sorts of utilities ranging from
of all sorts of utilities ranging from math utilities to debugging to creating
math utilities to debugging to creating graphical user interfaces
graphical user interfaces so there's a bunch of them but here's
so there's a bunch of them but here's some of the more common ones we have
some of the more common ones we have math for math utilities re regular
math for math utilities re regular expressions json to work with json date
expressions json to work with json date time sqlite 3 os for operating system
time sqlite 3 os for operating system utilities random for random number
utilities random for random number generations
generations so
so statistics requests for http request
statistics requests for http request http to create servers url lib to manage
http to create servers url lib to manage urls so you can import these modules
urls so you can import these modules that allow you to get extra
that allow you to get extra functionality so
functionality so we already looked at a little bit at the
we already looked at a little bit at the math one we already looked a little bit
math one we already looked a little bit at random in the the first
at random in the the first uh project that we did but let's just
uh project that we did but let's just kind of look at a little more how you
kind of look at a little more how you would do this so now we are going to use
would do this so now we are going to use the the math one we're going to import
the the math one we're going to import math
math and
and so this is how you would introduce you
so this is how you would introduce you would use a module of the standard
would use a module of the standard library so we already saw how to import
library so we already saw how to import modules that we created it's very stan
modules that we created it's very stan it's very similar with the standard
it's very similar with the standard library so now that i've imported math i
library so now that i've imported math i can now use
can now use functions and methods from from the math
functions and methods from from the math module so i can do math dot
module so i can do math dot square root and i can pass in 4 and then
square root and i can pass in 4 and then i can just
i can just print that so we can see what the result
print that so we can see what the result is
okay 2.0 or we can
or we can just like we shall
just like we shall we saw before instead of importing math
we saw before instead of importing math i can say
i can say from math
from math import
import square root and then instead of just
square root and then instead of just doing math dot square root i can just
doing math dot square root i can just call
call this
this square root method here and it's going
square root method here and it's going to do the same thing so that's basically
to do the same thing so that's basically how it works for for all the modules in
how it works for for all the modules in the standard library okay now we're
the standard library okay now we're going to start going over a few kind of
going to start going over a few kind of miscellaneous
miscellaneous slightly more advanced topics in python
slightly more advanced topics in python so we're going to talk about how to
so we're going to talk about how to accept arguments from the command line
accept arguments from the command line in python
in python well first of all let's see how to run a
well first of all let's see how to run a program from the command line
program from the command line in replit so let's say we have a program
in replit so let's say we have a program it just says print
it just says print hello okay so we've been running it by
hello okay so we've been running it by just clicking this play button but
just clicking this play button but there's another way to run a program in
there's another way to run a program in replit and i go over to the shell so
replit and i go over to the shell so this is the command line in replica we
this is the command line in replica we can clear this
can clear this and now i'm just going to type in
and now i'm just going to type in python main dot pi
python main dot pi okay so what we call python to run the
okay so what we call python to run the python program and then we just put the
python program and then we just put the name of our file with main.pi
name of our file with main.pi so
so whether you're in replit or if you're
whether you're in replit or if you're running things locally
running things locally you should be able to
you should be able to run a program in the same way
run a program in the same way depending on how you install the program
depending on how you install the program locally instead of typing python you may
locally instead of typing python you may type in python 3.
type in python 3. sometimes the way people install python
sometimes the way people install python it will be python 3 because we're using
it will be python 3 because we're using version 3 of python
version 3 of python so now let's see how you can
so now let's see how you can call a python a program on the command
call a python a program on the command line and pass in some arguments right
line and pass in some arguments right when we run the program from the command
when we run the program from the command line
line so
so a basic way to handle arguments is to
a basic way to handle arguments is to use the sys module from the standard
use the sys module from the standard library so let me give you an example so
library so let me give you an example so first of all we're going to import sys
first of all we're going to import sys now just so you know usually you're
now just so you know usually you're always going to have import statements
always going to have import statements on the first line i'm just putting this
on the first line i'm just putting this comment on the first line to remind us
comment on the first line to remind us what we're working on right now so now
what we're working on right now so now i'm going to we're going to import the
i'm going to we're going to import the sys library
sys library now i'm going to
now i'm going to print
print and i'm going to first i'm going to
and i'm going to first i'm going to oh
oh we're going to print the argument
we're going to print the argument cis.arg
cis.arg the
the so this is how we can print all the
so this is how we can print all the arguments that were passed in
arguments that were passed in when we called the program so so i'm
when we called the program so so i'm going to see we have python main.pi and
going to see we have python main.pi and now i'm going to put
now i'm going to put bow
bow 39
39 okay so you can see it's printing the
okay so you can see it's printing the list of arguments so this is basically
list of arguments so this is basically just a list the first item is the name
just a list the first item is the name of file
of file then we have
then we have the the first word and then the second
the the first word and then the second one and you can see they're both strings
one and you can see they're both strings even though this is a number it's coming
even though this is a number it's coming in
in as a string so then we could do
as a string so then we could do something like this we could say name
something like this we could say name equals cis.arg v
equals cis.arg v and then i would
and then i would get the element at index 1 which is the
get the element at index 1 which is the name here and i could print
[Music] hello
hello and then we're going to do a name oh
and then we're going to do a name oh hello hello and then name so let's call
hello hello and then name so let's call this again
this again and instead of i'm not going to do 39
and instead of i'm not going to do 39 it's just going to be python main.pi bow
it's just going to be python main.pi bow hello bo so we've now been able to use
hello bo so we've now been able to use the argument that was passed in
the argument that was passed in now this is a simple way to do it but
now this is a simple way to do it but you
you really would have to do a lot of work
really would have to do a lot of work using this method because you really
using this method because you really should validate the arguments make sure
should validate the arguments make sure the type is correct and you need to
the type is correct and you need to print feedback to the user if they're
print feedback to the user if they're not using the program correctly
not using the program correctly so i got zoomed out a little bit and i'm
so i got zoomed out a little bit and i'm going to show you this other method
going to show you this other method so python provides another package in
so python provides another package in the standard library to help you called
the standard library to help you called arg parse so first you would insert
arg parse so first you would insert import arg parse
import arg parse [Music]
[Music] and then let me show you
and then let me show you how you would use it
how you would use it so you call arc parse dot argument
so you call arc parse dot argument parser
parser and then pass in the description of the
and then pass in the description of the program so the description of the
program so the description of the program is this program prints the name
program is this program prints the name of my dogs
of my dogs then
then you proceed to add arguments you want to
you proceed to add arguments you want to accept
accept so for this example program we are going
so for this example program we are going to accept the c option or it can be
to accept the c option or it can be slash
slash c or dash that's color
c or dash that's color and we are going to
and we are going to be calling it color and then later we
be calling it color and then later we can we do
can we do parser.parse args
parser.parse args and then we can access args
and then we can access args dot color to get the color that was
dot color to get the color that was passed in and then you can specify
passed in and then you can specify whether it's required and what help is
whether it's required and what help is going to go along with that so let me
going to go along with that so let me show you how you would do that
show you how you would do that we're going to do python
we're going to do python main dot pi i'm going to put dash c and
main dot pi i'm going to put dash c and then i'm just going to put red
then i'm just going to put red okay so
okay so you can see if i
you can see if i go this out a little more you can see
go this out a little more you can see this is the
this is the command i called this is the command i
command i called this is the command i run i pass in red and then it just
run i pass in red and then it just printed red that's what we have right
printed red that's what we have right here
here and so let me show you what would happen
and so let me show you what would happen if we if we
if we if we don't specify the argument so if i just
don't specify the argument so if i just run it without the red so it's now
run it without the red so it's now giving me
giving me some information usage well main.pi we
some information usage well main.pi we need to put dash c and then we have to
need to put dash c and then we have to put a color and then it says the
put a color and then it says the following
following arguments are required this dashi or
arguments are required this dashi or dash sc so it's it's showing us that we
dash sc so it's it's showing us that we need to
need to if we we've called the program wrong and
if we we've called the program wrong and we're going to need to call it with the
we're going to need to call it with the dash c
dash c you can also
you can also set this option
set this option we can set an option to have a specific
we can set an option to have a specific set of values using choices so after
set of values using choices so after required true after this comma i'm going
required true after this comma i'm going to type in choices and i'm going to set
to type in choices and i'm going to set this to equal
see i have this empty dictionary
dictionary but i'm just going to well not a
but i'm just going to well not a dictionary but
dictionary but because it's not going to key value
because it's not going to key value pairs i can do red
pairs i can do red and yellow
and yellow so now it's it can only accept
so now it's it can only accept two options so i can
two options so i can call it here
call it here with
with red
red but if i call with blue
but if i call with blue it will say
it will say invalid choice blue i need to choose
invalid choice blue i need to choose from red or yellow so
from red or yellow so using this arc parse makes it easier to
using this arc parse makes it easier to deal with arguments and also makes it
deal with arguments and also makes it easier to
easier to communicate information back to the user
communicate information back to the user about what we're trying to get
about what we're trying to get so there are more options with this but
so there are more options with this but those are those are the basics
those are those are the basics now let's talk about something
now let's talk about something completely different
completely different lambda
lambda lambda
lambda functions
functions so let me just give you a quick example
so let me just give you a quick example [Music]
lambda num num
num [Music]
[Music] times
times 2. so
2. so lambda functions
lambda functions also called anonymous functions are tiny
also called anonymous functions are tiny functions they have no name and only
functions they have no name and only have one expression as their body
have one expression as their body so they're defined using the lambda
so they're defined using the lambda keyword and so
keyword and so this is going to be the argument
this is going to be the argument and this is going to be the expression
and this is going to be the expression the body must be a single expression and
the body must be a single expression and it has to be an expression not a
it has to be an expression not a statement so this difference is
statement so this difference is important an expression returns a value
important an expression returns a value a statement does not so it has to return
a statement does not so it has to return a value so the value that's being
a value so the value that's being returned is the number times two the
returned is the number times two the number that was passed in going to
number that was passed in going to multiply it by 2 in this example
multiply it by 2 in this example so this is basically the simplest
so this is basically the simplest example of a lambda function it just
example of a lambda function it just doubles the value of a number and lambda
doubles the value of a number and lambda functions can accept more
functions can accept more arguments so
arguments so so for instance i could do
so for instance i could do [Music]
[Music] lambda
lambda a comma b
a comma b and then we can multiply a times b
and then we can multiply a times b lambda functions cannot be invoked
lambda functions cannot be invoked directly but you can't assign them to
directly but you can't assign them to variables so for instance i can assign
variables so for instance i can assign this to the variable called
this to the variable called multiply so multiply is going to this
multiply so multiply is going to this function is going to be assigned to this
function is going to be assigned to this variable here so then the way that i
variable here so then the way that i would use that i could print now i'll
would use that i could print now i'll print the result of calling multiply
print the result of calling multiply and then i pass in
and then i pass in two
two and four
and four so if i just run that okay 2 times 4 is
so if i just run that okay 2 times 4 is 8. we can see right in the console here
8. we can see right in the console here and then i'm going to just
and then i'm going to just zoom in just a little bit
zoom in just a little bit so the utility of lambda functions comes
so the utility of lambda functions comes when combined with other python
when combined with other python functionality for example in combination
functionality for example in combination with map filter and reduce so speaking
with map filter and reduce so speaking of map filter and reduce that's what
of map filter and reduce that's what we're going to talk about now map
we're going to talk about now map filter
filter reduce
reduce so python provides three useful global
so python provides three useful global functions we that we can use to work
functions we that we can use to work with collections so this is map filter
with collections so this is map filter reduce so first let's talk about
reduce so first let's talk about map and since their functions are going
map and since their functions are going to have the
to have the parentheses at the end so map is used to
parentheses at the end so map is used to run a function
run a function upon each item in an iterable item like
upon each item in an iterable item like a list and create a new list with the
a list and create a new list with the same number of items but the values of
same number of items but the values of each item can be changed so here's an
each item can be changed so here's an example we have this list
example we have this list and then here's the function
and then here's the function and then we are going to map through
and then we are going to map through each item in the list
each item in the list and so here's the function we're going
and so here's the function we're going to run we're going to run this function
to run we're going to run this function on each item in the list
on each item in the list and now we're going to get a new list so
and now we're going to get a new list so i can do print
i can do print result now if we print that i'll just
result now if we print that i'll just run that function and we can see
run that function and we can see okay we get a map object
so then we can always just pass it into the
the list function
list function and then we can
and then we can run the program again two four six so
run the program again two four six so one two three became two four
one two three became two four so yeah whenever you want to do run a
so yeah whenever you want to do run a function on each item in a list you can
function on each item in a list you can use map
use map and when the function is a one-liner
and when the function is a one-liner it's common to use a lambda function so
it's common to use a lambda function so we just talked about lambda functions so
we just talked about lambda functions so now let me show you how you would do
now let me show you how you would do this as a lambda function so
this as a lambda function so double
double is going this is going to be a variable
is going this is going to be a variable and we're going to assign it to a lambda
and we're going to assign it to a lambda function
function and i'm going to
so now this lambda function takes the number
number a
a and then does a times two so and this we
and then does a times two so and this we just keep the same because now we're
just keep the same because now we're using a lambda function here and we're
using a lambda function here and we're taking each number and passing it
taking each number and passing it through this function where we have the
through this function where we have the the this is each number in the list and
the this is each number in the list and we multiply it so if i run this program
we multiply it so if i run this program it should look exactly the same
it should look exactly the same and we can even simplify it even more so
and we can even simplify it even more so this is where lambda functions really
this is where lambda functions really shine instead of assign it assigning it
shine instead of assign it assigning it to double first i can copy the whole
to double first i can copy the whole function i can delete this completely
function i can delete this completely and now i can just put it right in here
and now i can just put it right in here so now we're mapping over this function
so now we're mapping over this function and we don't even have to create the
and we don't even have to create the function in a different line and assign
function in a different line and assign it to a variable first we can put the
it to a variable first we can put the lambda function right in the same line
lambda function right in the same line right within the map and now i run this
right within the map and now i run this and it's going to give us the same
and it's going to give us the same result so remember we started with
result so remember we started with when i first showed you this example we
when i first showed you this example we had a much longer piece of code now
had a much longer piece of code now we've simplified it with the
we've simplified it with the lambda function
lambda function so the original list the original list
so the original list the original list is left untouched in a new list with the
is left untouched in a new list with the updated values is returned by map
updated values is returned by map the result is a map object which is an
the result is a map object which is an iterable so
iterable so that's why we needed to cast it to list
that's why we needed to cast it to list to print its content
to print its content okay now let's talk about filter
okay now let's talk about filter let me put in let me just update the
let me put in let me just update the code here it's kind of similar but now
code here it's kind of similar but now we're using filter filter takes an
we're using filter filter takes an iterable and returns a filter object
iterable and returns a filter object which is another iterable but without
which is another iterable but without some of the original items so you can do
some of the original items so you can do so by returning true or false from the
so by returning true or false from the filtering
filtering the filtering function so here's the
the filtering function so here's the filtering function we are going to check
filtering function we are going to check if the item passed in is even so
if the item passed in is even so so here's the list here so
so here's the list here so you can see we're calling filter we pass
you can see we're calling filter we pass in the function the filtering function
in the function the filtering function and then the list
and then the list and we're going to return true or false
and we're going to return true or false from this function so if it can be if
from this function so if it can be if it's divisible by if when you divide it
it's divisible by if when you divide it by two we have zero remainder
by two we have zero remainder then it's even
then it's even so
so that would return true so this line
that would return true so this line would return true
would return true and then if not it would return false if
and then if not it would return false if it's odd so now any even number is going
it's odd so now any even number is going to be added to the result and any odd
to be added to the result and any odd number is not going to be added to the
number is not going to be added to the result so basically we're filtering the
result so basically we're filtering the list based on this function and then
list based on this function and then here we just print
here we just print we convert that result to a list and if
we convert that result to a list and if we run that it's two and obviously if we
we run that it's two and obviously if we can just put in
can just put in uh more numbers here
uh more numbers here and run that again
and run that again we have two four six
we have two four six and then we can just like before we can
and then we can just like before we can use a lambda function so
use a lambda function so i'm just going to
i'm just going to copy this here we can just delete this
copy this here we can just delete this whole thing and we are going to put a
whole thing and we are going to put a lambda function here so lamb
lambda function here so lamb duh
duh [Music]
[Music] so now you can see we're just putting
so now you can see we're just putting the lambda function in the in line here
the lambda function in the in line here and we are checking to see if it's this
and we are checking to see if it's this is going to turn true or false whether
is going to turn true or false whether it's even or not
it's even or not and so i run the program and it's going
and so i run the program and it's going to give me the exact same result here
to give me the exact same result here okay the final thing we're going to talk
okay the final thing we're going to talk about is reduce
about is reduce reduce is used to calculate a value out
reduce is used to calculate a value out of a sequence like a list so for example
of a sequence like a list so for example suppose we have this list of expenses
suppose we have this list of expenses stored as tuples
stored as tuples and so so we had dinner 80 car repair
and so so we had dinner 80 car repair 180 or 120 and we want to calculate the
180 or 120 and we want to calculate the sum
sum of this property
of this property in each tuple
in each tuple in this case the cost of the expense
in this case the cost of the expense so here's kind of the long way of doing
so here's kind of the long way of doing it without using reduce
it without using reduce we basically take every expense in
we basically take every expense in expenses and then we add to the sum here
expenses and then we add to the sum here and we add expense one that's going to
and we add expense one that's going to be the
be the the item at index one and then we get
the item at index one and then we get the sum and we can print the sum so
the sum and we can print the sum so that's kind of like the long way of
that's kind of like the long way of doing it without reduce but there's a
doing it without reduce but there's a quicker way so
quicker way so to use reduce reduce is a little
to use reduce reduce is a little different from map and filter where it's
different from map and filter where it's not available it's not it's not
not available it's not it's not available automatically we have to
available automatically we have to import it from the standard library func
import it from the standard library func tools so i'll do from
tools so i'll do from funk
funk tools or function tools
tools or function tools import
import [Music]
[Music] reduce
create a new i'm going to create a new variable called sum
variable called sum and we're going to set it to
and we're going to set it to reduce we're going to use reduce and now
reduce we're going to use reduce and now i'm just going to
i'm just going to pass in i'm going to go directly to the
pass in i'm going to go directly to the lambda function so
lambda function so lambda
let me just kind of explain this for a little bit so reduce the first is going
little bit so reduce the first is going to take a function the reduction
to take a function the reduction function
function and then
and then the iterable here
the iterable here and the function has to take two
and the function has to take two arguments
arguments so this the first argument is the
so this the first argument is the accumulated value and then the the right
accumulated value and then the the right argument is
argument is the updated the update value from the
the updated the update value from the iterable so we're going to
iterable so we're going to continue adding
continue adding these two item we're going to
these two item we're going to basically add every item together and
basically add every item together and reduce
reduce the
the i the numbers at the first index all
i the numbers at the first index all into down to one value by adding them
into down to one value by adding them all together so i'll just
all together so i'll just pray here play here and then we get the
pray here play here and then we get the same number 200 and you can see it's a
same number 200 and you can see it's a lot it's a lot quicker just to use the
lot it's a lot quicker just to use the reduce function compared to the other
reduce function compared to the other code we had previously
code we had previously okay next up we are going to talk about
okay next up we are going to talk about recursion
recursion in
in python not recursion error just
python not recursion error just recursion
recursion and a function in python can call itself
and a function in python can call itself that's what recursion is and it can be
that's what recursion is and it can be pretty useful in many scenarios a common
pretty useful in many scenarios a common way to explain recursion is by using the
way to explain recursion is by using the factorial calculation
factorial calculation so let me show you how you would
so let me show you how you would calculate factorial this isn't python
calculate factorial this isn't python code this is just an example here so a
code this is just an example here so a fact when you do 3 factorial that means
fact when you do 3 factorial that means you do 3
you do 3 you multiply every number between three
you multiply every number between three between this number and one together so
between this number and one together so three times two times one equals six
three times two times one equals six four factorial is four times three times
four factorial is four times three times two times one five factorial is you know
two times one five factorial is you know five through one and so on and then
five through one and so on and then every number you multiply every whole
every number you multiply every whole number down to one so using recursion we
number down to one so using recursion we can write a function that calculates the
can write a function that calculates the factorial of any number so let me show
factorial of any number so let me show you so here's the function you can see
you so here's the function you can see inside the function it's calling the
inside the function it's calling the same function so a recursive function
same function so a recursive function it's always going to have a base case
it's always going to have a base case that's this
that's this and the recursive case so the base case
and the recursive case so the base case is when we're going to leave the
is when we're going to leave the the recursive function so if n is equal
the recursive function so if n is equal to one we're going to return one and
to one we're going to return one and that's basically going to get out of the
that's basically going to get out of the recursive function uh but if n is not
recursive function uh but if n is not going to equal one then we have the
going to equal one then we have the recursive the recursive case where we're
recursive the recursive case where we're going to call the function so you always
going to call the function so you always need to have at least you always have
need to have at least you always have need to have a base case so eventually
need to have a base case so eventually the recursion can stop
the recursion can stop if the recursion doesn't ever stop
if the recursion doesn't ever stop then you're going to get a recursion
then you're going to get a recursion error
error basically python by default will halt
basically python by default will halt recursions at 1000 calls and that's when
recursions at 1000 calls and that's when you get the recursion error so this is
you get the recursion error so this is going to get the factorial three but
going to get the factorial three but let's just do this a few more times so
let's just do this a few more times so you can see the difference so three
you can see the difference so three four
four five and now we'll test this out
five and now we'll test this out 6 24
6 24 120.
120. okay now let's talk about decorators
okay now let's talk about decorators so decorators in python are a way to
so decorators in python are a way to change enhance or alter in any way how a
change enhance or alter in any way how a function works decorators are defined
function works decorators are defined with the at symbol followed by the
with the at symbol followed by the decorator name just before the function
decorator name just before the function definition
definition so for instance let's say we have a
so for instance let's say we have a function
function hello
hello and it's just going to be the simplest
and it's just going to be the simplest function we're just going to print
hello uh so
uh so to make that to add a decorator i'm
to make that to add a decorator i'm going to put like this an at sign and
going to put like this an at sign and then the decorator name in this
then the decorator name in this case we're going to type in log time so
case we're going to type in log time so the function has the log time decorator
the function has the log time decorator assigned so
assigned so whenever we call the hello function the
whenever we call the hello function the decorator is going to be called a
decorator is going to be called a decorator is a function that takes a
decorator is a function that takes a function as a parameter wraps the
function as a parameter wraps the function in an inner function that
function in an inner function that performs the job it has to do and
performs the job it has to do and returns that inner function
returns that inner function so for instance i'm going to create
so for instance i'm going to create another function here that's going to be
another function here that's going to be the log time function
the log time function and now we we can do something before
and now we we can do something before and after the function like for instance
and after the function like for instance we can say
we can say print
before and then after
and then after we are going to print
we are going to print after
after now if i run this
oh and we have to call the function that's always important
that's always important now if i run this
now if i run this before hello after
before hello after so you're going to often use decorator
so you're going to often use decorator functions when you want to change the
functions when you want to change the behavior of a function without modifying
behavior of a function without modifying the function itself so a few good
the function itself so a few good examples are when you want to add
examples are when you want to add logging test performance perform caching
logging test performance perform caching verify permissions and so on
verify permissions and so on you can also use one when you need to
you can also use one when you need to run the same code on multiple functions
run the same code on multiple functions okay now let's talk about doc strings so
okay now let's talk about doc strings so doc strings
doc strings [Music]
[Music] documentation is hugely important not
documentation is hugely important not just to communicate to other people what
just to communicate to other people what the goal of a function or class or
the goal of a function or class or method or module is but it's also it
method or module is but it's also it also communicates to yourself when you
also communicates to yourself when you come back to your code like many months
come back to your code like many months from now you might not remember all the
from now you might not remember all the knowledge you were holding in your head
knowledge you were holding in your head when you wrote the code so at that point
when you wrote the code so at that point reading your code and understanding what
reading your code and understanding what it's supposed to do
it's supposed to do so that at that point reading your code
so that at that point reading your code and understanding what it's supposed to
and understanding what it's supposed to do will be a lot more difficult so a lot
do will be a lot more difficult so a lot that's one of the reasons why people add
that's one of the reasons why people add comments so another way is to use a doc
comments so another way is to use a doc string so let me show you what a doc
string so let me show you what a doc string looks like
string looks like the utility of a doc strings is that
the utility of a doc strings is that they follow conventions
they follow conventions so they can be processed automatically
so they can be processed automatically so this is how you would define a doc
so this is how you would define a doc string for a function
string for a function basically you're putting the three
basically you're putting the three quotation marks here three quotation
quotation marks here three quotation marks there and then this is a
marks there and then this is a description of what the function is
description of what the function is this is how you would define a doc
this is how you would define a doc string for a
string for a a class and a method so
a class and a method so got the class this is what the class
got the class this is what the class does is this is what the method does
does is this is what the method does and then it's also common to
and then it's also common to add docs place a doc string at the top
add docs place a doc string at the top of the file so if you put a doc string
of the file so if you put a doc string at the top of the file it's going to
at the top of the file it's going to look like this
look like this and it's going to explain what the file
and it's going to explain what the file is all about
is all about and docs stock strings can also span
and docs stock strings can also span multiple lines just like this is a
multiple lines just like this is a multiple line docs string as long as it
multiple line docs string as long as it has the three quarts three quarters at
has the three quarts three quarters at the top three quarts at the bottom
the top three quarts at the bottom and then python will process the doc
and then python will process the doc strings and you can use the help global
strings and you can use the help global function to get the documentation for a
function to get the documentation for a class a method a function or a module
class a method a function or a module for example i'm going to go to the
for example i'm going to go to the bottom of this and i'm going to say
bottom of this and i'm going to say print
print help
help and then i'm just going to type in
and then i'm just going to type in dog now i'll run this
and let me just run it again so now you're going to get information
so now you're going to get information about the dog we know that the dog has a
about the dog we know that the dog has a name and age it's a class representing a
name and age it's a class representing a dog and the has these specific
dog and the has these specific methods
methods and then it says more we can get more
and then it says more we can get more information data descriptors defined
information data descriptors defined here we have
here we have and this is just going to give us all
and this is just going to give us all this information
this information about
about the dog and we and so that's why it's
the dog and we and so that's why it's good to use doc strings because there
good to use doc strings because there are specific standards and it makes it
are specific standards and it makes it easier to get information using
easier to get information using different helper methods
and standards allow and standards allow us to have tools to
and standards allow us to have tools to extract doc strings and automatically
extract doc strings and automatically generate documentation for your code so
generate documentation for your code so besides just this help functions there's
besides just this help functions there's a lot of other methods to pull out these
a lot of other methods to pull out these docs strings and get information about
docs strings and get information about your code and next we will learn about
your code and next we will learn about annotations
annotations python is dynamically typed so we do not
python is dynamically typed so we do not have to specify the type of a variable
have to specify the type of a variable or function parameter or a function
or function parameter or a function return value
return value annotations allow us to optionally do
annotations allow us to optionally do that so if we want to actually show what
that so if we want to actually show what type we're expecting for different
type we're expecting for different values so here's a function without
values so here's a function without annotations and then here's how we would
annotations and then here's how we would make it have annotations so uh we want
make it have annotations so uh we want to make this function only accept an int
to make this function only accept an int so i'm going to put colon int
so i'm going to put colon int and then after here
and then after here i'm going to put
i'm going to put actually before the colon here i'm going
actually before the colon here i'm going to put a little arrow here
to put a little arrow here and then i'm going to put in int so now
and then i'm going to put in int so now we're specifying that this function
we're specifying that this function receives an int and then it's also going
receives an int and then it's also going to
to return an end
return an end and you can do the same thing with
and you can do the same thing with variables so if we have a variable if i
variables so if we have a variable if i had a variable called count and was
had a variable called count and was equal to zero i can add an annotation to
equal to zero i can add an annotation to make it be an int like that so now
make it be an int like that so now we're specifying that this variable is
we're specifying that this variable is going to be an integer
going to be an integer python will actually ignore these
python will actually ignore these annotations a separate tool called mypi
annotations a separate tool called mypi can be run standalone or integrated by
can be run standalone or integrated by ides to automatically check for type
ides to automatically check for type errors statically while you're coding
errors statically while you're coding it'll also help you catch tight
it'll also help you catch tight mismatched bugs before even running the
mismatched bugs before even running the code
code a great help especially when your
a great help especially when your software becomes large and you need to
software becomes large and you need to refactor your code
refactor your code okay now we'll talk about exceptions
okay now we'll talk about exceptions [Music]
[Music] it's important to have a way to handle
it's important to have a way to handle errors and python gives us exception
errors and python gives us exception handling to do so so for exception
handling to do so so for exception handling you would wrap lines of code in
handling you would wrap lines of code in a try block
a try block and then inside this block you'll put
and then inside this block you'll put the lines of code and then if an error
the lines of code and then if an error occurs
occurs python will alert you and you can
python will alert you and you can determine which kind of error occurred
determine which kind of error occurred using an accept block so
using an accept block so we're we're trying some lines of code
we're we're trying some lines of code here and then we're checking for a
here and then we're checking for a specific error and then if that error
specific error and then if that error happens we would handle that error but
happens we would handle that error but if a different error happens then we
if a different error happens then we will handle the different error you can
will handle the different error you can also catch
also catch all exceptions
all exceptions using an accept without an error type so
using an accept without an error type so at the very end you could just do accept
at the very end you could just do accept and then if you don't have an error type
and then if you don't have an error type then it's going to handle the rest of
then it's going to handle the rest of the exceptions and just to make this
the exceptions and just to make this clear this is just an example where it
clear this is just an example where it says air one you have to put a specific
says air one you have to put a specific error in that spot
error in that spot you can also put an else block at the
you can also put an else block at the end to handle that that will run if the
end to handle that that will run if the no exceptions are found so if there are
no exceptions are found so if there are no errors in this code that's right up
no errors in this code that's right up here we can have an else and then run
here we can have an else and then run specific code at the bottom that that
specific code at the bottom that that runs if there's no errors
runs if there's no errors and then we can have a finally block so
and then we can have a finally block so anything
anything in a finally block is going to just
in a finally block is going to just always run at the end whether or not
always run at the end whether or not there are exceptions or no exceptions
there are exceptions or no exceptions the code in the final block is always
the code in the final block is always going to run the specific error that's
going to run the specific error that's going to occur depends on the operation
going to occur depends on the operation you're performing for example if you're
you're performing for example if you're reading a file you might get an eof
reading a file you might get an eof error would just look like this eof
error would just look like this eof error which means end of file
error which means end of file if you divide a number by zero you'll
if you divide a number by zero you'll get a zero division error if you have a
get a zero division error if you have a type conversion issue you might get a
type conversion issue you might get a type error so
type error so let's try this code
let's try this code so i'm going to just delete all this and
so i'm going to just delete all this and we'll do result
we'll do result equals 2 divided by
equals 2 divided by 0 which
0 which you cannot do
you cannot do so just print the result
so just print the result and if i run that
and if i run that we'll see this error over here
we'll see this error over here zero division error division by zero so
zero division error division by zero so it's going to get an error when we run
it's going to get an error when we run the code and then whenever there's an
the code and then whenever there's an error anything after the error occurs
error anything after the error occurs will not happen so we're not going to
will not happen so we're not going to print the result because there is
print the result because there is because the this
because the this this line resulted in error so we're not
this line resulted in error so we're not going to run the following line of code
going to run the following line of code so now let's try adding that operation
so now let's try adding that operation in a
in a try block
try block so i'm just going to paste it all in
so i'm just going to paste it all in here and so we're putting the operation
here and so we're putting the operation in a try block and then we're expecting
in a try block and then we're expecting a zero division error
a zero division error where we'll print cannot divide by zero
where we'll print cannot divide by zero finally we will set the result to one
finally we will set the result to one and then print the results so let me
and then print the results so let me just run that code see cannot divide by
just run that code see cannot divide by zero and then we print one we because we
zero and then we print one we because we set it in the final block here
set it in the final block here so this try block lets us recover
so this try block lets us recover gracefully and move on with the program
gracefully and move on with the program you can raise exceptions in your own
you can raise exceptions in your own code too using the raise statement so i
code too using the raise statement so i could type in raise
could type in raise and then we can raise an exception
and then we can raise an exception intentionally
intentionally and error
and error so if i just run this
so if i just run this it will say
it will say an error because that's what we typed in
an error because that's what we typed in so you can make it say anything you want
so you can make it say anything you want for your error
for your error and this raises a general exception and
and this raises a general exception and you can and you can intercept it
you can and you can intercept it just like this so i could say
just like this so i could say try
try and then we raise that exception
and then we raise that exception and then we can do accept
and then we can do accept exception
exception as error
as error and then we can print
and then we can print the error
okay if i run that so now instead of we don't see all that
so now instead of we don't see all that red anymore because it's not stopping
red anymore because it's not stopping our program because of the error but
our program because of the error but it's now printing the error message
it's now printing the error message right here
right here just like that
just like that you can also define your own exception
you can also define your own exception class extending from exception so i
class extending from exception so i could do class
could do class dog not
dog not found
found [Music]
[Music] exception
exception and then i will
and then i will extend from exception
extend from exception [Music]
[Music] and then i can just put
and then i can just put pass for this one here let me adjust
pass for this one here let me adjust that
that so
so pass here just means nothing and we must
pass here just means nothing and we must use it when we define a class without
use it when we define a class without methods or a function without code so if
methods or a function without code so if you're not going to put anything so this
you're not going to put anything so this is just an example so i can just put
is just an example so i can just put pass to mean that we're not going to
pass to mean that we're not going to have any code in this
have any code in this so now we can try it out so i'll just
so now we can try it out so i'll just paste that uh so we're going to raise
paste that uh so we're going to raise dog not found exception and then if
dog not found exception and then if we're we're going to
we're we're going to candle this exception and just print dog
candle this exception and just print dog not found so let's try that yep dog nut
not found so let's try that yep dog nut bound because it raised this exception
bound because it raised this exception here we can also actually do something
here we can also actually do something in the exception
in the exception so if i can say print
so if i can say print inside
inside and then i'm going to run that
and then i'm going to run that and i'll do inside and dog not bound the
and i'll do inside and dog not bound the with statement is very helpful to
with statement is very helpful to simplify working with exception handling
simplify working with exception handling for example when working with files each
for example when working with files each time we open a file we must remember to
time we open a file we must remember to close it with makes the process more
close it with makes the process more transparent so let me show you some
transparent so let me show you some example code without the with statement
example code without the with statement so
so we're not going to go into a lot of
we're not going to go into a lot of details about working with files here
details about working with files here but i just want to kind of just give
but i just want to kind of just give this one quick example so if we're going
this one quick example so if we're going to be working with files in python so we
to be working with files in python so we can open the file and then we can read
can open the file and then we can read the file we can print the content from
the file we can print the content from the file
the file and we
and we we're going to try that because there
we're going to try that because there could be an exception and then finally
could be an exception and then finally we're always going to make sure to close
we're always going to make sure to close the file
the file but
but an alternate way to do it would be like
an alternate way to do it would be like this
this um so with
um so with we're going to open the file as file and
we're going to open the file as file and then content file.read and then print
then content file.read and then print the content and with using with it's
the content and with using with it's going to make sure to automatically
going to make sure to automatically close the file at the end in other words
close the file at the end in other words we have built-in implicit exception
we have built-in implicit exception handling as close will be called
handling as close will be called automatically for us
automatically for us and with can do a lot more stuff as well
and with can do a lot more stuff as well this example is just meant to introduce
this example is just meant to introduce its capabilities
its capabilities now let's talk about third-party
now let's talk about third-party packages
packages and we're going to talk about pip so
and we're going to talk about pip so let's learn how to install third-party
let's learn how to install third-party packages in python using pip the python
packages in python using pip the python standard library contains a huge number
standard library contains a huge number of utilities that simplify our python
of utilities that simplify our python development needs but nothing can
development needs but nothing can satisfy everything
satisfy everything that's why individuals and companies
that's why individuals and companies create packages and make them available
create packages and make them available as open source software for the entire
as open source software for the entire community so the modules are all
community so the modules are all collected in a single place called the
collected in a single place called the python package index which is available
python package index which is available available at pipe.org that's
available at pipe.org that's pi
pi pi.org
pi.org and they can be installed on the system
and they can be installed on the system using
using pip there's over 270 000 packages freely
pip there's over 270 000 packages freely available
available most computers are already going to have
most computers are already going to have pip installed and it already has pip
pip installed and it already has pip installed so let me show you how you
installed so let me show you how you would install a package we'd have to go
would install a package we'd have to go over to the shell here if you're not on
over to the shell here if you're not on replit you can just do in your terminal
replit you can just do in your terminal and i'm going to clear this here
and i'm going to clear this here and i'm just going to do pip
and i'm just going to do pip install and then you can put the name of
install and then you can put the name of a package for instance one popular
a package for instance one popular package is called the request package
package is called the request package it's an http library so i can do
it's an http library so i can do requests
requests and let me just
and let me just so you can see i have to make sure i
so you can see i have to make sure i spelled that right
spelled that right [Music]
[Music] and it's going to install that package
and it's going to install that package right now so once the we install this
right now so once the we install this package it's going to be available for
package it's going to be available for all our python scripts because packages
all our python scripts because packages are installed globally and the exact
are installed globally and the exact location depends on the operating system
location depends on the operating system you can also upgrade a package to its
you can also upgrade a package to its latest version by doing pip install
latest version by doing pip install dash u and then i will just put the
dash u and then i will just put the package name so in this case we'll just
package name so in this case we'll just do request again
and then it's going to just update it to its
its latest version
latest version in this case
in this case it updated from
it updated from 2.28.0 to 2.28.1
2.28.0 to 2.28.1 you can also specify a specific
you can also specify a specific version when you're installing
version when you're installing and then you can also uninstall a
and then you can also uninstall a package so i'll do pip
package so i'll do pip uninstall
uninstall requests
and then i can say that yes i do want to uninstall that
uninstall that and then once when you have a package
and then once when you have a package installed
installed i'm just going to install request again
and then you always have to make sure you spell it right
you spell it right so once you have it installed you can do
so once you have it installed you can do pip show
pip show requests
requests and then it's going to show some
and then it's going to show some information about the package
information about the package so see we can see the name the version
so see we can see the name the version uh the summary and then a bunch of the
uh the summary and then a bunch of the author and a bunch of other information
author and a bunch of other information about the package
about the package okay i'll just clear this
okay i'll just clear this now we're actually gonna backtrack a
now we're actually gonna backtrack a little bit we already talked about lists
little bit we already talked about lists but i'm gonna talk about a more advanced
but i'm gonna talk about a more advanced way of using lists called
way of using lists called list
list compression
compression list compressions so list compressions
list compressions so list compressions are a way to create lists in a very
are a way to create lists in a very concise way so suppose you have this
concise way so suppose you have this list like this it's a list of numbers
list like this it's a list of numbers and we'll just do
and we'll just do one
one two three
two three four five
four five so we can create a new list using a list
so we can create a new list using a list compression
compression composed by the numbers list elements to
composed by the numbers list elements to the power of 2.
the power of 2. let me show you what i mean so let's get
let me show you what i mean so let's get make a new list numbers
make a new list numbers power
power [Music]
[Music] 2
2 equals
equals and let me just show you how you do this
and let me just show you how you do this list compression
so this is the list compression syntax and if i print this
and if i print this [Music]
[Music] we can see that now we have every
we can see that now we have every element in the list to the power of two
element in the list to the power of two list compressions are a syntax that's
list compressions are a syntax that's sometimes preferred over loops as it's
sometimes preferred over loops as it's more readable when the operation can be
more readable when the operation can be written on a single line
written on a single line so for instance this is how you would do
so for instance this is how you would do it uh with a loop so what we do in a
it uh with a loop so what we do in a single line up here we take a few lines
single line up here we take a few lines to do
to do in the method with a loop so list
in the method with a loop so list compression just makes it
compression just makes it simpler
simpler and then you can do the same thing with
and then you can do the same thing with map as well
map as well but again it's just a little more
but again it's just a little more complex sometimes it's just simpler to
complex sometimes it's just simpler to use a list compression using the syntax
use a list compression using the syntax here
here now let's talk about a few more advanced
now let's talk about a few more advanced topics in regards to functions
topics in regards to functions polymorphism
polymorphism polymorphism generalizes a functionality
polymorphism generalizes a functionality so it can work on different types
so it can work on different types it's an important concept in object
it's an important concept in object oriented programming so see in here
oriented programming so see in here we've defined the same method on
we've defined the same method on different classes so the dog has eat and
different classes so the dog has eat and the cat also has an eat method
the cat also has an eat method then we can generate objects and we can
then we can generate objects and we can call the eat method regardless of the
call the eat method regardless of the class the object belongs to and will get
class the object belongs to and will get different results so we create the two
different results so we create the two objects the dog and the cat here
objects the dog and the cat here and we're calling the eat method on both
and we're calling the eat method on both objects and if we run this you can see
objects and if we run this you can see what we're getting eating cat dog food
what we're getting eating cat dog food eating cat food and so you could do a
eating cat food and so you could do a lot of things with this like maybe you
lot of things with this like maybe you have a list of different animals and
have a list of different animals and then you can
then you can loop through that list and call the eat
loop through that list and call the eat function or the eat method on each
function or the eat method on each animal in that list and they don't have
animal in that list and they don't have to be the exact same class to be able to
to be the exact same class to be able to still run the eat method
still run the eat method so we build a generalized interface and
so we build a generalized interface and now we do not need to know that an
now we do not need to know that an animal is a cat or dog we just need to
animal is a cat or dog we just need to know that we can call eat on it
know that we can call eat on it now let's talk about
now let's talk about operator
operator overloading
overloading [Music]
[Music] operator overloading is an advanced
operator overloading is an advanced technique we can use to make classes
technique we can use to make classes comparable and to make them work with
comparable and to make them work with python operators so let's take this
python operators so let's take this class dog so here's a dog class and you
class dog so here's a dog class and you can create a dog with a name and age
can create a dog with a name and age then we'll create two dog objects we'll
then we'll create two dog objects we'll do roger equals dog
do roger equals dog and we can pass the name
and eight [Music]
[Music] and then i'll make another one
we can use operator overloading to add a custom way to compare these two objects
custom way to compare these two objects based on the age property
based on the age property so like how could you compare
so like how could you compare this dog and this dog well we can make
this dog and this dog well we can make it possible with operator overloading so
it possible with operator overloading so let me just show you this example here
let me just show you this example here so
so this
this function here gt
function here gt is going to compare things as to figure
is going to compare things as to figure out what what is greater than you can
out what what is greater than you can now we'll be able to compare
now we'll be able to compare two dog objects to see which one is
two dog objects to see which one is greater than the other and this is how
greater than the other and this is how we're going to figure out which is
we're going to figure out which is greater than return true if self.age is
greater than return true if self.age is greater than
greater than other dot age which is the other one
other dot age which is the other one you're comparing it to else false
you're comparing it to else false now we can
now we can do print
roger is greater than sid so we're trying to
is greater than sid so we're trying to figure out this is true or false if i
figure out this is true or false if i run this it's going to say true roger is
run this it's going to say true roger is greater than sid because 8 is bigger
greater than sid because 8 is bigger than 7. but if we like put 9 here run
than 7. but if we like put 9 here run that
that now it's going to be false
now it's going to be false so in the same way we define this
so in the same way we define this underscore underscore gt underscore
underscore underscore gt underscore which means greater than we can also
which means greater than we can also define methods for like less than
define methods for like less than lower or equal to greater equal to or
lower or equal to greater equal to or not equal
not equal and then you can also create methods to
and then you can also create methods to go with different arithmetic operators
go with different arithmetic operators so
so we can do add subtract multiply
we can do add subtract multiply division floor division mod power so you
division floor division mod power so you can see all these different ones you can
can see all these different ones you can make it respond to the different
make it respond to the different operators so the example was just a
operators so the example was just a greater than operator but we can
greater than operator but we can make functions to show how it's going to
make functions to show how it's going to respond to all these different
respond to all these different operators there's even a few more
operators there's even a few more methods to work with other operators but
methods to work with other operators but you get the idea we've learned a lot
you get the idea we've learned a lot about python and now we're going to
about python and now we're going to bring a lot of what we've learned
bring a lot of what we've learned together to code a blackjack card game
together to code a blackjack card game and in the process we'll learn about
and in the process we'll learn about object oriented programming in python so
object oriented programming in python so we'll start by creating a new python
we'll start by creating a new python project on replit
and i'm just going to close this tab here
here and i'll zoom in just a bit
and i'll zoom in just a bit and just like our first project
and just like our first project i'm going to
i'm going to say what i'm about to do and i want you
say what i'm about to do and i want you to see if you can do it on your own
to see if you can do it on your own before i show you how to do it
before i show you how to do it and with all you've learned so far a lot
and with all you've learned so far a lot of this you're probably going to be able
of this you're probably going to be able to figure out on your own as i give you
to figure out on your own as i give you the instructions without even seeing how
the instructions without even seeing how i how i do it but then you can come back
i how i do it but then you can come back to the video and see how i do it
to the video and see how i do it or i guess you can just watch and not
or i guess you can just watch and not even try to do it yourself but you're
even try to do it yourself but you're going to learn a lot more if you try to
going to learn a lot more if you try to code this by yourself along with me as i
code this by yourself along with me as i do it but right before i do the
do it but right before i do the different steps
different steps so the first thing we're going to do is
so the first thing we're going to do is create a
create a variable called a suit
variable called a suit and set it equal to hearts and then a
and set it equal to hearts and then a variable called rank and set it to equal
variable called rank and set it to equal k for king
k for king and then a variable called value and set
and then a variable called value and set to equal
to equal 10.
10. [Music]
[Music] okay simple two variables equal to
okay simple two variables equal to strings and one variable equal to an int
strings and one variable equal to an int so now we are going to add a print
so now we are going to add a print statement and print the the phrase your
statement and print the the phrase your card is with a colon at the end
card is with a colon at the end and then we'll add another print
and then we'll add another print statement and print the rank
statement and print the rank so now we're just printing the variable
so now we're just printing the variable here
here and we're going to be doing a lot of
and we're going to be doing a lot of refactoring as we create this program
refactoring as we create this program let's refactor this so it's just one
let's refactor this so it's just one print statement that's going to print
print statement that's going to print your card is colon space and then the
your card is colon space and then the rank
so we are going to be doing string concatenation
string concatenation [Music]
[Music] just like that
just like that so
so you can concatenate as many strings and
you can concatenate as many strings and variables as you want so let's update
variables as you want so let's update the code so that the print function
the code so that the print function print prints your card as
print prints your card as k
k of
of hearts
hearts so we just need to add
so we just need to add of and we have to make sure we put
of and we have to make sure we put spaces on each side of the word of
and then suit
suit and let me just
and let me just adjust this here okay as you know you
adjust this here okay as you know you can use a list in python to store
can use a list in python to store multiple values or items at a time so
multiple values or items at a time so above the suit variable
above the suit variable create a suits
create a suits variable and assign it to a list of
variable and assign it to a list of suits in this case spades clubs hearts
suits in this case spades clubs hearts diamonds
we learned about how you can use the bracket operator to access a specific
bracket operator to access a specific element in a list the number inside the
element in a list the number inside the bracket specifies the index of the list
bracket specifies the index of the list to access remember the indexes start at
to access remember the indexes start at zero
zero so you update the suit variable so that
so you update the suit variable so that the value of hearts come from comes from
the value of hearts come from comes from the suits list
the suits list now we'll practice a for loop so add a
now we'll practice a for loop so add a for loop to the end of the code that
for loop to the end of the code that prints each suit
prints each suit and then we'll just test this out
and then we'll just test this out i really hope you actually are following
i really hope you actually are following along and trying it out right before i
along and trying it out right before i show it to you that's how you're going
show it to you that's how you're going to learn the best here so spades clubs
to learn the best here so spades clubs hearts diamonds
hearts diamonds now this next thing is is just to see if
now this next thing is is just to see if we can do it so it's not going to be
we can do it so it's not going to be part of our final code but right before
part of our final code but right before the loop we just added see if you can
the loop we just added see if you can add another item to the suits list
add another item to the suits list that's the string snakes
there's a few different ways to do it but we will use append snakes so this is
but we will use append snakes so this is just going to append the word snakes at
just going to append the word snakes at the end
the end of the list so if i run this we can now
of the list so if i run this we can now see snakes at the bottom
see snakes at the bottom okay now we're going to start the
okay now we're going to start the process of representing a full deck of
process of representing a full deck of cards with python code
cards with python code so we're going to actually get rid of a
so we're going to actually get rid of a lot of this we're going to get rid of
lot of this we're going to get rid of all this we're just going to have the
all this we're just going to have the suits and then we're going to have this
suits and then we're going to have this for loop at the bottom we're going to do
for loop at the bottom we're going to do a lot of refactoring as we go mainly for
a lot of refactoring as we go mainly for educational purposes but also so we can
educational purposes but also so we can get the a really good blackjack game so
get the a really good blackjack game so we have a list of suits after that we're
we have a list of suits after that we're going to create a list of ranks that's a
going to create a list of ranks that's a 2 3 4 5 6 7 8 9 10 j q
2 3 4 5 6 7 8 9 10 j q k
k [Music]
[Music] now before the suits list
now before the suits list create a new variable called cards and
create a new variable called cards and assign an empty list to the variable
you can an empty list is just two brackets with nothing inside
brackets with nothing inside now in the cards list there should be an
now in the cards list there should be an item for each card in the deck each item
item for each card in the deck each item in the suits list should be combined
in the suits list should be combined with each item in the ranks list for a
with each item in the ranks list for a total of 52 items or cards
total of 52 items or cards let's work our way up to that so first
let's work our way up to that so first we'll update the print statement in the
we'll update the print statement in the for loop so that it prints a list with
for loop so that it prints a list with two elements the first element should be
two elements the first element should be suit and the second should be the first
suit and the second should be the first element of the ranks lists so this
element of the ranks lists so this should print
should print an ace in every suit
so i'm going to update this so it's going to be a list with
going to be a list with suit
suit and ranks
and ranks the first item is going to be at index
the first item is going to be at index zero now let's print that out
so we got them these four right here now instead of just printing an ace in
now instead of just printing an ace in every suit let's print every rank in
every suit let's print every rank in every suit
every suit this can be done easily with a for loop
this can be done easily with a for loop nested within another for loop so inside
nested within another for loop so inside the for loop add another for loop that
the for loop add another for loop that loops through the ranks
loops through the ranks then update the print statement so that
then update the print statement so that it's not just printing the first element
it's not just printing the first element in the ranks list but it's printing the
in the ranks list but it's printing the rank from the for other for loop
rank from the for other for loop so let me show you what i mean
so let me show you what i mean we're going to do four
we're going to do four for rank and ranks
for rank and ranks and then
and then we have to make sure to indent this
we have to make sure to indent this print statement so it's inside this
print statement so it's inside this other for loop
other for loop and this is now just going to be
and this is now just going to be rank so it's going to print the suit and
rank so it's going to print the suit and rank and i'll just run that
rank and i'll just run that and now we with this nested for loop we
and now we with this nested for loop we have every card at every rank in every
have every card at every rank in every suit all 52 cards are printed as two
suit all 52 cards are printed as two item lists
item lists an element in a list can be another list
an element in a list can be another list so instead of printing 52
so instead of printing 52 two item lists
two item lists let's append those 52 cards to the cards
let's append those 52 cards to the cards list
list so we already have the cards list here
so we already have the cards list here it's empty but i'm going to do
it's empty but i'm going to do cards
cards dot
dot append
append and so we're appending
and so we're appending this item
this item all these items to the cards list
all these items to the cards list so let's check what the cards list looks
so let's check what the cards list looks like by printing out printing it out at
like by printing out printing it out at the bottom remember make sure this is
the bottom remember make sure this is not indented at all and we'll do print
not indented at all and we'll do print cards
cards and i'll run that
and then here it is here so this is the list it's not
list it's not one there's just a comma between each
one there's just a comma between each item in the list here
item in the list here you may notice that all the cards are in
you may notice that all the cards are in order in the cards lists
order in the cards lists for a game like this though the cards
for a game like this though the cards must be shuffled so to help with this
must be shuffled so to help with this import the random module at the top of
import the random module at the top of your code so that's just we just do
your code so that's just we just do import
import random
random [Music]
[Music] now we'll be able to use the the random
now we'll be able to use the the random module so this is going to import the
module so this is going to import the random module which contains a variety
random module which contains a variety of things related to random number
of things related to random number generation
generation and as you probably remember when you
and as you probably remember when you import a python module it allows you to
import a python module it allows you to use additional commands in your code
use additional commands in your code specifically we're going to be using the
specifically we're going to be using the random.shuffle function
random.shuffle function so right before at the end where it says
so right before at the end where it says print cards we're going to call
print cards we're going to call random.shuffle and pass in the cards
random.shuffle and pass in the cards list to that function
list to that function and then if i play this here or run the
and then if i play this here or run the program we can see that these are not in
program we can see that these are not in order anymore see ace of spades
order anymore see ace of spades three of spades king of diamonds jack of
three of spades king of diamonds jack of hearts so these are no longer in order
hearts so these are no longer in order because they've been shuffled now let's
because they've been shuffled now let's remove a single element from the cards
remove a single element from the cards list this is similar to dealing a card
list this is similar to dealing a card from a deck and this can be done with
from a deck and this can be done with the pop method
the pop method so after the cards are shuffled
so after the cards are shuffled let's create another card variable and
let's create another card variable and just
just pop off a card from the cards list and
pop off a card from the cards list and put it into that variable called card
put it into that variable called card and just print that card
and just print that card so i'll do card
so i'll do card equals cards dot pop
equals cards dot pop and then instead of printing all the
and then instead of printing all the cards i'm just going to print a single
cards i'm just going to print a single card i'll run the program
card i'll run the program see every time i run the program you can
see every time i run the program you can see we're getting a different card we're
see we're getting a different card we're dealing a different card because it's
dealing a different card because it's been shuffled
been shuffled so we've already learned all about
so we've already learned all about functions and now we're going to create
functions and now we're going to create a function
a function so create a
so create a function called shuffle that just has
function called shuffle that just has the single line that shuffles the cards
the single line that shuffles the cards so it's just def shuffle
so it's just def shuffle and then i just have to make sure this
and then i just have to make sure this is indented so now when we call the
is indented so now when we call the shuffle function it will shuffle the
shuffle function it will shuffle the cards
cards so right before the print statement
so right before the print statement call the shuffle function and instead of
call the shuffle function and instead of just printing the single card print the
just printing the single card print the cards
cards so do shuffle
so do shuffle and then i will print all the cards and
and then i will print all the cards and let's just try out the program
let's just try out the program and we can see there was a problem it's
and we can see there was a problem it's because we didn't put the the colon here
because we didn't put the the colon here so that's an important part of creating
so that's an important part of creating a function is putting the colon there
a function is putting the colon there now we'll create another function called
now we'll create another function called deal and we'll put this line inside the
deal and we'll put this line inside the the deal function
the deal function so we're going to define deal
so we're going to define deal and i'll put the colon this time and
and i'll put the colon this time and make sure to
make sure to indent that
indent that and we can see this has a orange
and we can see this has a orange squiggly line underneath it because
squiggly line underneath it because variables can only be accessed in the
variables can only be accessed in the context that they were created so the
context that they were created so the card variable will not be available
card variable will not be available outside of the deal function
outside of the deal function you can get a value out of a function by
you can get a value out of a function by returning a result using the return
returning a result using the return statement so at the end we're going to
statement so at the end we're going to return the card
okay now we've taken care of that squiggly line there so after the shuffle
squiggly line there so after the shuffle function is called we'll call the deal
function is called we'll call the deal function and assign the return value to
function and assign the return value to a variable named card then we'll update
a variable named card then we'll update the print function to print card instead
the print function to print card instead of cards
of cards so card
so card equals
equals deal
deal and then we'll just print
and then we'll just print the card
and again we see a different card every time we run
see a different card every time we run the program
the program what if you want the deal function to
what if you want the deal function to deal more than one card well let's
deal more than one card well let's refactor the deal function to and accept
refactor the deal function to and accept to accept an argument so any number of
to accept an argument so any number of arguments can appear inside the
arguments can appear inside the parentheses when a function is created
parentheses when a function is created separated by commas inside the function
separated by commas inside the function the arguments are assigned to variables
the arguments are assigned to variables called parameters so start by making it
called parameters so start by making it so we'll start by making it so the deal
so we'll start by making it so the deal function takes an argument named number
function takes an argument named number then we'll make sure when we call the
then we'll make sure when we call the function we use the new parameter
function we use the new parameter by
by making it so we're gonna deal two
making it so we're gonna deal two so i'm just gonna put number here it's
so i'm just gonna put number here it's gonna it's gonna deal a number of cards
gonna it's gonna deal a number of cards we're gonna deal two and i just didn't
we're gonna deal two and i just didn't say this before but now instead this is
say this before but now instead this is not one card anymore so we're going to
not one card anymore so we're going to update this to be cards dealt but
update this to be cards dealt but there's a special shortcut you can
there's a special shortcut you can either it's going to be
either it's going to be command or control d
command or control d and now i'm actually selecting the card
and now i'm actually selecting the card two different times see i i now have
two different times see i i now have multiple cursors here so basically i
multiple cursors here so basically i selected the word i double clicked to
selected the word i double clicked to select the word then did command or
select the word then did command or control d now it's selecting two words
control d now it's selecting two words and now i can type in
and now i can type in cards
cards delt
delt so now i can type in two places at one
so now i can type in two places at one time so that's a cool thing that you can
time so that's a cool thing that you can do in replit and you can do it in many
do in replit and you can do it in many other code editors and i'll run the
other code editors and i'll run the program but it should still only deal
program but it should still only deal one card because even though we're
one card because even though we're passing this parameter into here we're
passing this parameter into here we're not doing anything with it yet here so
not doing anything with it yet here so we want to update the deal function so
we want to update the deal function so it's going to return a list of cards
it's going to return a list of cards instead of a single card
instead of a single card in the first line of the function create
in the first line of the function create an empty list named cards delt then
an empty list named cards delt then update the last line of the function to
update the last line of the function to return cards dealt instead of return
return cards dealt instead of return card so let's do that really quick we're
card so let's do that really quick we're going to do
going to do cards
cards dealt
dealt is going to equal an empty list and i'll
is going to equal an empty list and i'll just copy that and paste it
just copy that and paste it right here
right here now do you remember how to use a the
now do you remember how to use a the range function with a for loop we talked
range function with a for loop we talked about it earlier in the course we just
about it earlier in the course we just briefly touched on it but let's create a
briefly touched on it but let's create a for loop that's going to
for loop that's going to add a card from the deck
add a card from the deck for each
for each card dealt
card dealt so we can do that by creating a for loop
so we can do that by creating a for loop for x and range
for x and range number now this is a common thing you're
number now this is a common thing you're going to be doing in python creating a
going to be doing in python creating a for loop that's going to be in range
for loop that's going to be in range number because now it's going to loop
number because now it's going to loop this many times it's going to loop this
this many times it's going to loop this many times which is the number we passed
many times which is the number we passed in here and we're going to do a few
in here and we're going to do a few things in this for loop
things in this for loop first we are going to
first we are going to actually do this what we already have
actually do this what we already have card equal cards dot pop and then we'll
card equal cards dot pop and then we'll do cards
do cards delt
delt dot append
dot append card
card so now just this card that we popped off
so now just this card that we popped off the deck we are appending it to the
the deck we are appending it to the card's delt and then we're returning the
card's delt and then we're returning the cards dealt here
cards dealt here so down here in the code
so down here in the code let's separate out a single card from
let's separate out a single card from the two cards dealt
the two cards dealt so let's create a variable called card
so let's create a variable called card and set it equal to the first item in
and set it equal to the first item in the cards delt list
the cards delt list and then we'll just print that card
and then we'll just print that card instead of cards dealt
instead of cards dealt so we are going to do card
so we are going to do card equals cards
equals cards delt and then we just use the brackets
delt and then we just use the brackets and put 0 to get the first item in that
and put 0 to get the first item in that list
list and then we'll just print
and then we'll just print a card
a card now i'm just going to test out the
now i'm just going to test out the program we're still just seeing a single
program we're still just seeing a single card here but it's doing a lot more
card here but it's doing a lot more behind the scenes now
behind the scenes now so now let's separate out the rank part
so now let's separate out the rank part of a single card so after we create the
of a single card so after we create the card there let's create a variable named
card there let's create a variable named rank and assign it the rank from the
rank and assign it the rank from the card
card so we'll do rank
so we'll do rank equals card
equals card and then i have to get index one because
and then i have to get index one because the rank is this that's the nine here
the rank is this that's the nine here the second item in this card is the rank
the second item in this card is the rank so each rank has a different value in
so each rank has a different value in blackjack the value of an ace or an a in
blackjack the value of an ace or an a in this in this program is 11
this in this program is 11 or sometimes it can actually be one it's
or sometimes it can actually be one it's going to be 11 or 1 but we'll get to the
going to be 11 or 1 but we'll get to the one part later so jack j q and k which
one part later so jack j q and k which is jack queen and king have the value of
is jack queen and king have the value of 10 and then the numbers have the value
10 and then the numbers have the value of the number so we need to check what
of the number so we need to check what the rank is and set the value depending
the rank is and set the value depending on the rank
on the rank so this is the perfect time for a
so this is the perfect time for a conditional statement specifically an if
conditional statement specifically an if statement
statement before the final print statement or
before the final print statement or program we're going to add an if
program we're going to add an if statement to check if the rank equals a
statement to check if the rank equals a and if so we'll assign 11 to a variable
and if so we'll assign 11 to a variable named value
named value so we'll do if
so we'll do if rank and i hope you remember if you're
rank and i hope you remember if you're flying along i hope you remember to use
flying along i hope you remember to use two equal signs instead of one equal
two equal signs instead of one equal sign here so if rank equals a
sign here so if rank equals a then value is going to equal with a
then value is going to equal with a single equal sign is going to equal
single equal sign is going to equal 11.
11. now if rank does not equal a we'll want
now if rank does not equal a we'll want to check if it equals j q or k
to check if it equals j q or k that can be done with an elif statement
that can be done with an elif statement for now we'll just create an if
for now we'll just create an if statement to check if the rank equals j
statement to check if the rank equals j and then if so we will set the value to
and then if so we will set the value to 10.
so we talked about the three logical operators and or
operators and or and not you can use these three
and not you can use these three operators in conditional statements to
operators in conditional statements to check multiple conditions at once so we
check multiple conditions at once so we want to check if
want to check if rank is j or rank is q
rank is j or rank is q or rank is k so update the code with the
or rank is k so update the code with the the and with the ors
now there can be any number of ls statements after an if statement but at
statements after an if statement but at the end there can only be a single else
the end there can only be a single else statement
statement and like we discussed the else is just
and like we discussed the else is just going to be if none of the other ones
going to be if none of the other ones are true so let's add an else statement
are true so let's add an else statement and inside we'll just assign rank to
and inside we'll just assign rank to value because we've already gotten all
value because we've already gotten all the letters out of the way the rest are
the letters out of the way the rest are numbers and we can assign it directly to
numbers and we can assign it directly to the value
now we'll instead of printing the card at the end
instead of printing the card at the end let's print the rank and the value
let's print the rank and the value so i can just type in rank comma value
so i can just type in rank comma value and
and when that multiple values in a print
when that multiple values in a print statement are listed with a comma
statement are listed with a comma separating them both values are printed
separating them both values are printed with a space in between so let's test
with a space in between so let's test this out a few times q10 five five 6 6
this out a few times q10 five five 6 6 so we can see every time we press it
so we can see every time we press it it's going to be a random rank and value
it's going to be a random rank and value now we already talked about dictionaries
now we already talked about dictionaries in python it's like a list but more
in python it's like a list but more general you can think of a dictionary as
general you can think of a dictionary as a mapping between a set of indices which
a mapping between a set of indices which are called keys and values so key value
are called keys and values so key value pairs each key maps to a value so above
pairs each key maps to a value so above the print statement let's create a
the print statement let's create a variable called rank
variable called rank underscore dict for dictionary and
underscore dict for dictionary and create a dictionary with two items
create a dictionary with two items a key value pair for the rank and a key
a key value pair for the rank and a key value pair for the value
so we have the string rank here and then the actual rank variable string value
the actual rank variable string value and the actual value variable
and the actual value variable before we are
before we are printing the rank variable and the value
printing the rank variable and the value variable but let's update this code so
variable but let's update this code so we're actually getting the rank and
we're actually getting the rank and value from the rank dictionary right
value from the rank dictionary right here
here so i'm going to copy that and then i
so i'm going to copy that and then i just pasted that but now i'm going to
just pasted that but now i'm going to use bracket notation
use bracket notation and so i'll put two brackets but then i
and so i'll put two brackets but then i also have to surround this in quotation
also have to surround this in quotation marks
marks and then i'm gonna
and then i'm gonna put the rank dictionary the brackets
put the rank dictionary the brackets and then the quotation marks because
and then the quotation marks because we're accessing that key there
we're accessing that key there and then i can just run the program and
and then i can just run the program and it's still doing the same thing as
it's still doing the same thing as before just a lot more complicated as
before just a lot more complicated as far as the code goes but it's going to
far as the code goes but it's going to be good to have more complicated code as
be good to have more complicated code as our program is going to become more
our program is going to become more complicated as we go
complicated as we go so when writing a program there are many
so when writing a program there are many ways to do almost everything
ways to do almost everything now we're going to refactor the code to
now we're going to refactor the code to get the value of each rank without using
get the value of each rank without using an if statement
an if statement instead we'll store both the rank name
instead we'll store both the rank name and value in the ranks list using
and value in the ranks list using dictionaries so let's delete all the
dictionaries so let's delete all the code lines of code after where it says
code lines of code after where it says shuffle
shuffle so
so here i know we typed in a lot of stuff
here i know we typed in a lot of stuff there but it was just kind of to
there but it was just kind of to practice and now we're going to practice
practice and now we're going to practice a different method of doing this
a different method of doing this so now let's create a new card variable
so now let's create a new card variable a new variable called card at the end
a new variable called card at the end and let's assign to the card variable
and let's assign to the card variable a a single card that will deal from the
a a single card that will deal from the deck but we'll make sure that card is
deck but we'll make sure that card is not
not in a list so this is a little tricky i'm
in a list so this is a little tricky i'm gonna do deal and i'll deal one card
gonna do deal and i'll deal one card but now i have to get
but now i have to get the first item so this is going to deal
the first item so this is going to deal one card but the one card is going to
one card but the one card is going to deal is going to be in a list so i want
deal is going to be in a list so i want to get the first item in the list which
to get the first item in the list which is going to be the only item in the list
is going to be the only item in the list so i had to put the zero in brackets
so i had to put the zero in brackets here to get that card out of a list
here to get that card out of a list before it goes into the card variable
before it goes into the card variable now we're going to update the ranks list
now we're going to update the ranks list so here's the the ranks list each
so here's the the ranks list each element the list should now be a
element the list should now be a dictionary when lists or list elements
dictionary when lists or list elements are long it's common to put each element
are long it's common to put each element on its own line so we're going to put
on its own line so we're going to put each element on its own line and each
each element on its own line and each element is going to have the rank and
element is going to have the rank and the value so for instance it will be
the value so for instance it will be rank a value 11
rank a value 11 rank 2 value 2.
rank 2 value 2. so it's going to look like
so it's going to look like this
this and i'm now i'm actually going to zoom
and i'm now i'm actually going to zoom out just a little bit and we have all
out just a little bit and we have all these they're all these ranks and each
these they're all these ranks and each one in this list
one in this list is a dictionary each element in the list
is a dictionary each element in the list is a dictionary
is a dictionary okay now that this is updated let's go
okay now that this is updated let's go down and just print a card so we can see
down and just print a card so we can see now that we've updated that ranks list
now that we've updated that ranks list so print
so print card
card okay so this is what it's going to look
okay so this is what it's going to look like coming from
like coming from our list
our list so we got the suit
so we got the suit and then we have the rank that's also
and then we have the rank that's also going to have the value here the rank
going to have the value here the rank and the value
and the value we can see every time we click it we get
we can see every time we click it we get a random item
a random item now let's update the code so instead of
now let's update the code so instead of printing the whole card we just
printing the whole card we just print the value so in this example the
print the value so in this example the value is two so we just want to print
value is two so we just want to print this to just that that value so how can
this to just that that value so how can we update this see if you can figure out
we update this see if you can figure out how to update this line so only prints
how to update this line so only prints just the value number there
just the value number there so first of all we have to see that
so first of all we have to see that we're in a list and we need so this is
we're in a list and we need so this is the first element of the list this is
the first element of the list this is the second element so wait to start by
the second element so wait to start by getting the second element of the list
getting the second element of the list which is
which is index one
index one and then
and then we have an object here or a dictionary i
we have an object here or a dictionary i mean and we need to get
mean and we need to get so here we have this key value pair so
so here we have this key value pair so we need the value at that key so to get
we need the value at that key so to get the value of that key we are going to
the value of that key we are going to put more brackets and i'm going to put
put more brackets and i'm going to put value the key of value so now with that
value the key of value so now with that should work let's try it
should work let's try it okay nine
okay nine seven see every time it's gonna just
seven see every time it's gonna just give us the value of the card
give us the value of the card now we'll start defining classes that
now we'll start defining classes that will be used in order to separate out
will be used in order to separate out different aspects of the game
different aspects of the game so classes you may remember provide a
so classes you may remember provide a way of bundling data and functionality
way of bundling data and functionality together creating a new class creates a
together creating a new class creates a new type of object allowing new
new type of object allowing new instances of that type to be made an
instances of that type to be made an object can contain a number of functions
object can contain a number of functions which we call methods as well as data
which we call methods as well as data that is used by those functions called
that is used by those functions called attributes so
attributes so we're going to use classes to model
we're going to use classes to model three parts of the game a card a deck
three parts of the game a card a deck and a hand so far we've mainly worked on
and a hand so far we've mainly worked on the elements of the debt class
the elements of the debt class so right after this import statement at
so right after this import statement at the top
the top we're going to
we're going to make a class a class called
make a class a class called dec and we're going to put everything
dec and we're going to put everything that we've written so far in that class
that we've written so far in that class so we're just gonna do class
deck colon
colon okay now we just highlight
okay now we just highlight everything here and then i'm gonna press
everything here and then i'm gonna press tab
tab to put everything in the class of deck
to put everything in the class of deck because everything's
because everything's indented a little bit
indented a little bit and then these last few lines of code we
and then these last few lines of code we don't need so i'll just delete those
don't need so i'll just delete those those are just for testing out
those are just for testing out a class is like a template you can use
a class is like a template you can use that class to create an instance of the
that class to create an instance of the class called an object
class called an object then you can use the instance each
then you can use the instance each instance keeps track of its own state so
instance keeps track of its own state so you can update an instance created from
you can update an instance created from a class and it won't impact other
a class and it won't impact other objects created from the same class soon
objects created from the same class soon you'll see an example of all this to
you'll see an example of all this to make it easier to understand
make it easier to understand but first let's prepare a class to
but first let's prepare a class to create an instance from it
create an instance from it when you create an instance of a class
when you create an instance of a class python automatically calls a function
python automatically calls a function also called a method in the clast named
also called a method in the clast named init remember we already discussed this
init remember we already discussed this earlier in the course so the contents of
earlier in the course so the contents of this init method should be code that is
this init method should be code that is run one time to initialize the instance
run one time to initialize the instance so at the beginning of our class let's
so at the beginning of our class let's create this init function so we'll do
create this init function so we'll do def
def underscore underscore init
underscore underscore init underscore underscore and if you
underscore underscore and if you remember from before we always have to
remember from before we always have to pass in
pass in self
self to all of these
to all of these functions in a class because then it
functions in a class because then it gets itself is referring to the instance
gets itself is referring to the instance of the class that we've developed now
of the class that we've developed now we're going to indent all the code
we're going to indent all the code that's not part of the shuffle or deal
that's not part of the shuffle or deal function so the code will be part of
function so the code will be part of this new function so i'm just going to
this new function so i'm just going to highlight
highlight all this here
all this here including
including the suits here and then just press
the suits here and then just press tab
tab so like i said we just added self in
so like i said we just added self in here you should always
here you should always all the methods in a class or all the
all the methods in a class or all the functions should have self
functions should have self anything inside the parentheses remember
anything inside the parentheses remember is called an argument their variables
is called an argument their variables pass them from the color to the
pass them from the color to the functions
functions as i've said all functions in a class
as i've said all functions in a class should receive self as an argument and
should receive self as an argument and self represents the instance of the
self represents the instance of the class by using the self keyword the
class by using the self keyword the function can access the attributes and
function can access the attributes and methods of the class
methods of the class so let's make sure to add self as the
so let's make sure to add self as the first item in the parentheses of the
first item in the parentheses of the other functions
other functions so we are going to add self here
so we are going to add self here and then see how we already have number
and then see how we already have number here but we're going to hit self at the
here but we're going to hit self at the beginning
beginning and we so we can still
and we so we can still call this function with just
call this function with just a single number but it's going to also
a single number but it's going to also get a reference to the instance here now
get a reference to the instance here now i want you to notice that
i want you to notice that the cards here is underlying in
the cards here is underlying in red so before it wasn't when we were
red so before it wasn't when we were before we made this into a class we
before we made this into a class we could just access
could just access this cards variable but now we cannot so
this cards variable but now we cannot so let's fix that
let's fix that inside a class in order to access a
inside a class in order to access a variable in multiple functions also
variable in multiple functions also called methods the variable has to start
called methods the variable has to start with self dot
with self dot so we're going to change all instances
so we're going to change all instances of cards in every function to self.card
of cards in every function to self.card starting
starting with this so self dot cards
with this so self dot cards now this is going to make it so we can
now this is going to make it so we can access it in other places and then we'll
access it in other places and then we'll change this to self dot cards
change this to self dot cards and then this is self
dot cards and then self
and then self dot cards
so now this will be a variable that's specifically associated with the
specifically associated with the instance of the deck that's created and
instance of the deck that's created and then we can access it in all of these
then we can access it in all of these other methods
other methods okay we can now create an instance also
okay we can now create an instance also called an object of the deck class so at
called an object of the deck class so at the very end of the code
the very end of the code let's create a variable called deck 1
let's create a variable called deck 1 and make it an instance of the deck
and make it an instance of the deck class
so to make sure i'm not indented at all and i'll do deck
and i'll do deck 1
1 equals
deck there we go now since we created cards with
now since we created cards with self.cards
self.cards we can access that we can access cards
we can access that we can access cards from the instance of the class so let's
from the instance of the class so let's just print out the cards from our deck
just print out the cards from our deck one so do print
one so do print deck
deck one dot cards
and we can try that out now you can see the the list of all of these cards
the the list of all of these cards it has the suit
it has the suit and the rank and the value for each card
and the rank and the value for each card so underneath where we created deck one
so underneath where we created deck one let's create deck two we'll create
let's create deck two we'll create another instance of another deck
another instance of another deck so
so [Music]
[Music] so now we can call methods on these
so now we can call methods on these instances and you see some of the
instances and you see some of the methods we have we have shuffle and deal
methods we have we have shuffle and deal so on deck 2 right after we create the
so on deck 2 right after we create the deck 2 let's shuffle the deck so deck
deck 2 let's shuffle the deck so deck 2 dot shuffle
2 dot shuffle and then i have to make sure to put the
and then i have to make sure to put the parentheses
parentheses at the end here
at the end here right if we print deck one let's print
right if we print deck one let's print deck two or the cards of deck two so i'm
deck two or the cards of deck two so i'm gonna copy that and then we'll print
gonna copy that and then we'll print deck two cards so now we should see that
deck two cards so now we should see that the deck one cards are not shuffled and
the deck one cards are not shuffled and the deck two cards are shuffled so let
the deck two cards are shuffled so let me move this over here i'm gonna run the
me move this over here i'm gonna run the program
program and let's see if we can see that where
and let's see if we can see that where deck one so here's where here's deck one
deck one so here's where here's deck one and we can see how it's all diamonds
and we can see how it's all diamonds diamonds diamonds diamonds diamonds all
diamonds diamonds diamonds diamonds all the diamonds are in a row because
the diamonds are in a row because unshuffled but then if we go into deck 2
unshuffled but then if we go into deck 2 we can see we have diamonds clubs spades
we can see we have diamonds clubs spades diamonds hearts so these are shuffled in
diamonds hearts so these are shuffled in deck 2 they are shuffled
deck 2 they are shuffled okay the deck works
okay the deck works now let's add safeguards to prevent
now let's add safeguards to prevent errors every time the deal function is
errors every time the deal function is called a card is removed from the cards
called a card is removed from the cards list
list you can only remove a card if there are
you can only remove a card if there are cards to remove
cards to remove so before the program tries to pop a
so before the program tries to pop a card off self.cards is to check if the
card off self.cards is to check if the length of self.cards is greater than
length of self.cards is greater than zero
zero remember you can get the number of items
remember you can get the number of items in a list with length so see if you can
in a list with length so see if you can figure that out on your own and then i'm
figure that out on your own and then i'm about to show you how it's done
about to show you how it's done so when it's going to deal here
so when it's going to deal here right as we're dealing we're going to
right as we're dealing we're going to add an if statement here so if
add an if statement here so if the length
the length of self dot cards
is greater than zero and we do we don't need this parentheses
and we do we don't need this parentheses here so if the length of self.cards is
here so if the length of self.cards is greater than zero
greater than zero then we will
then we will do this we'll pop up a card and add it
do this we'll pop up a card and add it to the cards dealt if not we just won't
to the cards dealt if not we just won't do anything and then we'll return cards
do anything and then we'll return cards dealt which could be an empty array if
dealt which could be an empty array if there were no cards on the deck
there were no cards on the deck now let's add something to the shuffle
now let's add something to the shuffle function a deck with only one card does
function a deck with only one card does not need to be shuffled so let's add the
not need to be shuffled so let's add the appropriate if statement to the shuffle
appropriate if statement to the shuffle function
function so we'll do
so we'll do if the length of self
if the length of self dot cards
dot cards is
is greater than one
greater than one then we will shuffle and then make sure
then we will shuffle and then make sure i'll make sure to put the
i'll make sure to put the colon there
colon there okay
okay since a card is a separate concept than
since a card is a separate concept than a deck
a deck next we'll make a card class
next we'll make a card class so let's create a card class with an
so let's create a card class with an init function and in that init function
init function and in that init function we'll set self.suit to equal hearts
so hopefully you already tried this i'm going to do class
going to do class card
card and then i will do def
and then i will do def net
net [Music]
[Music] and then after the suit will lose self
and then after the suit will lose self dot rank and set it to a
so currently anytime a card is created it will be an ace of hearts let's
it will be an ace of hearts let's refactor the code so the suit and rank
refactor the code so the suit and rank are specified when a card object is
are specified when a card object is constructed so the init method can take
constructed so the init method can take additional parameters besides self that
additional parameters besides self that are passed into it as objects is
are passed into it as objects is constructed so we'll update it to take
constructed so we'll update it to take suit and rank
suit and rank [Music]
[Music] now we'll create a special method
now we'll create a special method that's underscore underscore str
that's underscore underscore str underscore underscore
when a class has this specific method it's called when print is invoked on an
it's called when print is invoked on an object from the class
object from the class so we want to make it so when we print
so we want to make it so when we print an object from the card class it will
an object from the card class it will print something like 10 of hearts or
print something like 10 of hearts or three of clubs or something like that
three of clubs or something like that so we don't do print here we do return
so we don't do print here we do return it's going to return this to the print
it's going to return this to the print statement it's going to turn self dot
statement it's going to turn self dot rank
rank and then we have to get
and then we have to get the rank
the rank [Music]
[Music] and we do plus
and we do plus and then of or to put a string there
and then of or to put a string there plus
plus self dot suit
self dot suit so now it's going to return the rank
so now it's going to return the rank which is like 2 or a of and then the
which is like 2 or a of and then the suit which is one of these
suit which is one of these so let's just try it out real quick and
so let's just try it out real quick and we go to the bottom we don't need any of
we go to the bottom we don't need any of these to test because we're testing
these to test because we're testing something completely different now let's
something completely different now let's do card one
do card one equals
equals [Music]
[Music] card i'm going to create a card and i
card i'm going to create a card and i have to pass in remember i have to first
have to pass in remember i have to first pass in the suit so how about hearts and
pass in the suit so how about hearts and then i have to pass in the rank but we
then i have to pass in the rank but we want to make it look like these ranks so
want to make it look like these ranks so i'm just going to
i'm just going to copy one of these here
and then after we create the card i can just
after we create the card i can just print
print card one
card one let me clear this and then i'll just run
let me clear this and then i'll just run that j of hearts
that j of hearts oh see i got the j of hearts and feel
oh see i got the j of hearts and feel free to add a few more cards like this
free to add a few more cards like this and test out a few more if you want
and test out a few more if you want okay now we're going to refactor this
okay now we're going to refactor this slightly you remember way toward the
slightly you remember way toward the beginning of this course we talked about
beginning of this course we talked about f strings so f strings allow us to put
f strings so f strings allow us to put variables right within a string do you
variables right within a string do you remember how to do that let's see if you
remember how to do that let's see if you can update this to use enough string
can update this to use enough string so first we're going to create a new
so first we're going to create a new string but we're going to start with the
string but we're going to start with the letter f
letter f and then
and then inside this string we put curly braces
inside this string we put curly braces around
around the
the python code and we don't need these
python code and we don't need these other strings here so
and then an ending string here
ending string here okay it's still showing these um red
okay it's still showing these um red squiggly lines because if i have a
squiggly lines because if i have a double quote around the strings and
double quote around the strings and anytime other quotes are in the middle i
anytime other quotes are in the middle i have to put a different type of quote so
have to put a different type of quote so we're going to use
we're going to use single quotes okay so now we can make
single quotes okay so now we can make this a whole a string but we use the
this a whole a string but we use the brackets to put the variables right
brackets to put the variables right within the string so now we've updated
within the string so now we've updated that to use an f string
that to use an f string so currently in the deck class the last
so currently in the deck class the last line of this init method
line of this init method appends a list as an item to the cards
appends a list as an item to the cards list
list instead of appending
instead of appending suit
suit comma rank
comma rank we'll create and append an instance of
we'll create and append an instance of the card class
the card class then afterwards when a deck is created
then afterwards when a deck is created it's filled with cards
it's filled with cards so it's just like this we're just going
so it's just like this we're just going to delete that i'll put card
to delete that i'll put card and then i'll pass in a suit and they
and then i'll pass in a suit and they rank so now we're passing in
rank so now we're passing in card instances
card instances so we're done with the deck and card
so we're done with the deck and card classes and we created them in such a
classes and we created them in such a way that they could basically be used
way that they could basically be used for any card game
for any card game now let's make a hand class
now let's make a hand class this will represent a hand in the game
this will represent a hand in the game of blackjack so create a hand class and
of blackjack so create a hand class and add an inet method and initialize a
add an inet method and initialize a variable called self.cards that is set
variable called self.cards that is set to an empty list so let's go down here
to an empty list so let's go down here and we can also get rid of all this test
and we can also get rid of all this test code here
code here so the new class is called hand
and we'll also make the hand keep track of the value of the hands a self.value
of the value of the hands a self.value will start it at zero
in this blackjack game there will be a human controlled player and a program
human controlled player and a program controlled dealer so let's add a dealer
controlled dealer so let's add a dealer parameter in the init constructor method
parameter in the init constructor method of the hand class
of the hand class and then when the hand classes create a
and then when the hand classes create a dealer should be set to true or false to
dealer should be set to true or false to keep track of what type of hand it is
keep track of what type of hand it is so i'll pass in the parameter dealer and
so i'll pass in the parameter dealer and then we just have to create a variable
then we just have to create a variable and call dealer and set it to dealer so
and call dealer and set it to dealer so self dot dealer
self dot dealer equals dealer
equals dealer [Music]
[Music] if you remember from before function
if you remember from before function parameters can have default values so we
parameters can have default values so we want to make it so the default value of
want to make it so the default value of dealer is false
dealer is false so then if
so then if we create a hand and we don't set the
we create a hand and we don't set the dealer value it will automatically be
dealer value it will automatically be false
false and i'm just going to take out these
and i'm just going to take out these spaces here to make it smaller here
spaces here to make it smaller here so now a hand can be created
so now a hand can be created let's give it some functionality we'll
let's give it some functionality we'll add an add card method and the method
add an add card method and the method should take a card list as a parameter
and then we need to add that card list to the cards
to the cards so we can use the extend function the
so we can use the extend function the extend method to append each item in
extend method to append each item in card list onto the cards list so it's
card list onto the cards list so it's just going to look like this self dot
just going to look like this self dot cards dot append no extend i mean dot
cards dot append no extend i mean dot extend
extend and then we pass in
and then we pass in card list
card list now let's just add some code to test out
now let's just add some code to test out what we have so far so let's create a
what we have so far so let's create a deck and then we will shuffle the deck
deck and then we will shuffle the deck deck.shuffle
deck.shuffle [Music]
[Music] now we'll create a hand
now we can add cards to the hand so hand dot
dot add
add card
and we will deck dot deal we'll deal two cards into the hand
cards into the hand and then we'll just print
and then we'll just print hand cards
okay so this is what how it printed out i was expecting this to look a little
i was expecting this to look a little different
different because of this function it print it
because of this function it print it should print like that
should print like that but i think the reason is
but i think the reason is because
because this is a list so it's printing a list
this is a list so it's printing a list not an individual card so let's change
not an individual card so let's change this to print an individual card i'll
this to print an individual card i'll print the first card so put zero in
print the first card so put zero in there i'll try it again nine of diamonds
there i'll try it again nine of diamonds and then we can also print the next card
and then we can also print the next card three of hearts
three of hearts and then we can also print both cards if
and then we can also print both cards if we just copy that and do
we just copy that and do hand that cards
hand that cards zero
zero handout cards
handout cards one
one okay ace of hearts and nine of spades so
okay ace of hearts and nine of spades so those are the two cards that were dealt
those are the two cards that were dealt to the hand
to the hand now we'll go back to the hand class and
now we'll go back to the hand class and we'll add the ability to calculate the
we'll add the ability to calculate the value of a hand so let's add a method
value of a hand so let's add a method called calculate value
called calculate value and inside the method we'll set
and inside the method we'll set self.value to zero
now we'll take this one step at a time first let's let's make a for loop that's
first let's let's make a for loop that's going to go through every single card
going to go through every single card and inside the for loop we'll just set
and inside the for loop we'll just set the value
the value of the card to a variable called card
of the card to a variable called card underscore value so i'll do four card
underscore value so i'll do four card and self.cards
okay so we're not doing anything with that yet but we're going to in a second
that yet but we're going to in a second here
here now we want to make sure that this is an
now we want to make sure that this is an integer
integer so let's convert that to an integer if
so let's convert that to an integer if you remember you just use int
you remember you just use int [Music]
[Music] and then put it in print int and then
and then put it in print int and then inside the parentheses we put this value
inside the parentheses we put this value not just getting the card value for each
not just getting the card value for each card is not enough something must be
card is not enough something must be done with the variable so let's add that
done with the variable so let's add that value
value to
to self.value
self.value so we'll do self
so we'll do self dot value
dot value and then if you remember from before we
and then if you remember from before we can use the plus equals to
can use the plus equals to add that to the current value those will
add that to the current value those will do a card
do a card value
value so as you may know in blackjack and ace
so as you may know in blackjack and ace can have the value of either 11 or 1
can have the value of either 11 or 1 depending on what is better for the
depending on what is better for the player so there's a few ways to
player so there's a few ways to implement that in code so we're going to
implement that in code so we're going to do one way that's relatively simple
do one way that's relatively simple first we'll check if the hand has an ace
first we'll check if the hand has an ace so let's first create a variable that
so let's first create a variable that will store whether the
will store whether the hand has an a so just be called hand has
hand has an a so just be called hand has underscore ace we'll set to false and
underscore ace we'll set to false and we'll put it right under here
we'll put it right under here so we'll do
so we'll do has ace and we'll set to false and since
has ace and we'll set to false and since we're only going to be using has ace
we're only going to be using has ace within
within this
this method we don't need to use self that
method we don't need to use self that has ace because we're only using it here
has ace because we're only using it here and now when we're going through the the
and now when we're going through the the list of cards let's check if the the
list of cards let's check if the the rank of a card is an ace and then set
rank of a card is an ace and then set has aced equals true
has aced equals true so i'll do it
so i'll do it if
if card dot rank
card dot rank the rank is going to be equal double
the rank is going to be equal double equal sign if it equals ace
after this entire for loop we're going to check if the card has an
we're going to check if the card has an ace
ace and if the value is over 21
and if the value is over 21 if so then we'll just subtract 10 from
if so then we'll just subtract 10 from the value
the value because that'll be the same as setting
because that'll be the same as setting the ace to equal one instead of 11.
the ace to equal one instead of 11. so we'll just do if has
so we'll just do if has ace
is greater than 21 to self.value
to self.value minus equals
minus equals 10.
10. okay and look at this this is something
okay and look at this this is something i don't think i've discussed yet
i don't think i've discussed yet you could say if has
you could say if has equals true and self.value is greater
equals true and self.value is greater than 21.
than 21. but you can also it's like a shorthand
but you can also it's like a shorthand you don't have to say if has ace equals
you don't have to say if has ace equals true
true if has a because has ace is just going
if has a because has ace is just going to equal true or false you can just say
to equal true or false you can just say if has ace so that's just the same as
if has ace so that's just the same as saying if true or if false
saying if true or if false and so we're seeing if both of these
and so we're seeing if both of these evaluate the true then we will subtract
evaluate the true then we will subtract 10 from the value okay now we'll just
10 from the value okay now we'll just add another method to get the value of a
add another method to get the value of a hand called getvalue and the function
hand called getvalue and the function will just return self.value
will just return self.value so we're going to make sure that we're
so we're going to make sure that we're not we're indented correctly and do def
not we're indented correctly and do def get
get value
value return
return self
self dot value
and then i have to make sure i put the parentheses here
parentheses here and then i have to remember to put self
and then i have to remember to put self since this is a self.value we could call
since this is a self.value we could call down here like we could call
down here like we could call hand
hand value to get the value but it's
value to get the value but it's generally better to make a function to
generally better to make a function to return the value so i can do get
return the value so i can do get value that way there may be some extra
value that way there may be some extra code you want to run in there like
code you want to run in there like depending on different conditions
depending on different conditions you may want to modify the value before
you may want to modify the value before you return it
you return it so it's best practice to create a method
so it's best practice to create a method that will get a value like this for you
so currently this value that's returned could be incorrect
could be incorrect because
because if someone's going to get the value the
if someone's going to get the value the value has to be calculated correctly
value has to be calculated correctly first and like checking for aces and and
first and like checking for aces and and other things so let's call
other things so let's call let's calculate the value before we
let's calculate the value before we return the value so i'm going to do self
return the value so i'm going to do self dot calculate value so
dot calculate value so this is something that i think is new
this is something that i think is new where to call calculate value from
where to call calculate value from within this we're going to have to call
within this we're going to have to call self.calculatevalue
self.calculatevalue and self will refer to the instance that
and self will refer to the instance that we're working with so we're calling the
we're working with so we're calling the calculate value on the instance that's
calculate value on the instance that's that is the the hand instance and we're
that is the the hand instance and we're getting the value and then we're
getting the value and then we're returning the value
returning the value okay let's create another method called
okay let's create another method called is blackjack and it'll return true if
is blackjack and it'll return true if there's a blackjack and false otherwise
there's a blackjack and false otherwise so it's a blackjack if the value is 21.
so it's a blackjack if the value is 21. so i'm gonna do
so i'm gonna do def
def get or is
get or is oh and put self here
oh and put self here okay so this is going to evaluate you to
okay so this is going to evaluate you to either true or false and return true or
either true or false and return true or false depending on whether there's a
false depending on whether there's a blackjack
blackjack now we'll create the final method in the
now we'll create the final method in the hand class that will display information
hand class that will display information about the hand so let's create a method
about the hand so let's create a method called display they'll
called display they'll to start with will just print your hand
to start with will just print your hand [Music]
[Music] okay now let's do a quick refactor
okay now let's do a quick refactor instead of saying your hand it should
instead of saying your hand it should either say dealer's hand or your hand
either say dealer's hand or your hand depending on whether
depending on whether self.dealer
self.dealer is
is true or not
true or not so we're going to you to to do this all
so we're going to you to to do this all in one line we're going to use a few
in one line we're going to use a few things that we learned about earlier
things that we learned about earlier including
including ternary operators
ternary operators f strings and going between double
f strings and going between double quotes and single quotes and then one
quotes and single quotes and then one other new thing we are going to make
other new thing we are going to make this into an f string
this into an f string and then we are going to be using
and then we are going to be using actually
actually single quotes and double quotes within
single quotes and double quotes within this f string so if you want to use
this f string so if you want to use single quotes and double quotes within a
single quotes and double quotes within a string
string then you can surround it with a triple
then you can surround it with a triple single quote so i'm going to delete this
single quote so i'm going to delete this quote and just do three single quotes
quote and just do three single quotes and then delete this quote and do three
and then delete this quote and do three single quotes and so
single quotes and so we got the
we got the double quote
double quote single quote and now this is a triple
single quote and now this is a triple quote so now we can use the double quote
quote so now we can use the double quote and single quotes within this string
and single quotes within this string so i'm going to um i'm just going to
so i'm going to um i'm just going to delete your right here and we are going
delete your right here and we are going to
to put a ternary operator to see if it's
put a ternary operator to see if it's going to say dealers or yours in the
going to say dealers or yours in the dealer's hand or your hand so
dealer's hand or your hand so to do some code i'm going to put these
to do some code i'm going to put these curly braces here
curly braces here and then to do this ternary operator
and then to do this ternary operator we're going to put dealer
we're going to put dealer and now here so here's the double quote
and now here so here's the double quote and here's the single quote so dealers
and here's the single quote so dealers it will
it will return dealers
return dealers if
if self.dealer
so basically if self.dealer equals true so return dealers if self.dealer
so return dealers if self.dealer else will return
else will return your
your okay that's the line so it's going to be
okay that's the line so it's going to be the dealer's hand or your hand and next
the dealer's hand or your hand and next we will add a for loop that will print
we will add a for loop that will print out each of the cards
out each of the cards so
so for card and self.cards
for card and self.cards print
print card
card and then finally if the player is not
and then finally if the player is not the dealer it should print value
the dealer it should print value and then a colon and then print the
and then a colon and then print the value of the cards so to do this we can
value of the cards so to do this we can actually use the the not operator so
actually use the the not operator so if not
if not self.dealer
self.dealer [Music]
then we will print and we'll print value
and we'll print value value
value and then i can just put a comma to print
and then i can just put a comma to print two different items so the string and
two different items so the string and it'll print self dot get
it'll print self dot get value
value and it's gonna when you put a comma and
and it's gonna when you put a comma and two different things it's gonna put a
two different things it's gonna put a space in between
space in between and then finally we'll just add an empty
and then finally we'll just add an empty a print statement that will print a
a print statement that will print a blank line
blank line okay let's test this out by
okay let's test this out by instead of printing this we are going to
instead of printing this we are going to print
print hand
hand dot display
dot display to see if this all works how we thought
to see if this all works how we thought it was going to work
it was going to work so your hand k of spades two of spades
so your hand k of spades two of spades value is 12. so it's actually
value is 12. so it's actually calculating that correctly because
calculating that correctly because that's 10 plus 2 is 12 and then it's
that's 10 plus 2 is 12 and then it's going to print none which indicates that
going to print none which indicates that we did something wrong which is that we
we did something wrong which is that we did not need to print this because hand
did not need to print this because hand display display already prints so now
display display already prints so now just call hand.display
just call hand.display okay so now it doesn't put none or
okay so now it doesn't put none or doesn't yeah it doesn't put none at the
doesn't yeah it doesn't put none at the end so that looks right
end so that looks right okay when you're playing blackjack you
okay when you're playing blackjack you don't get to see
don't get to see everyone else's cards
everyone else's cards so
so we're going to update this so when the
we're going to update this so when the dealer's cards are printed during the
dealer's cards are printed during the game
game only the second one should display
only the second one should display the first card should display as hidden
the first card should display as hidden so in this for loop
so in this for loop when we're displaying the cards
when we're displaying the cards we're going to need to get access to the
we're going to need to get access to the card index since that will determine
card index since that will determine which to display
which to display since we're only going to display the
since we're only going to display the second card
second card so let's start by updating this for loop
so let's start by updating this for loop so we can get access to both the card
so we can get access to both the card and the card index
and the card index we briefly touched on this earlier in
we briefly touched on this earlier in the course we're going to be using the
the course we're going to be using the enumerate function
enumerate function so
so when it's for card in
when it's for card in and now i'm going to type in enumerate
and now i'm going to type in enumerate and i'm going to pass in self.cards
and i'm going to pass in self.cards and this is going to return the index
and this is going to return the index and the card for each card so i'm going
and the card for each card so i'm going to type it index
to type it index comma
comma and so
and so in we're getting the index and the card
in we're getting the index and the card for all the items in self.cards
for all the items in self.cards and so now we just have to update what's
and so now we just have to update what's in the for loop
in the for loop to print
to print hidden
hidden if it's the first card and it's a dealer
if it's the first card and it's a dealer so we'll do
so we'll do if index
if index equals zero and self.dealer
then we will print
and then we can use an else any other time
any other time and let's make sure this lines up
and let's make sure this lines up correctly any other time we will print
correctly any other time we will print the card
the card so
so what we did wrong here is this should be
what we did wrong here is this should be double equal sign i did almost did the
double equal sign i did almost did the the main mistake you always have to
the main mistake you always have to watch out never use a single equal sign
watch out never use a single equal sign when you're checking equality
when you're checking equality because that's the single equal sign is
because that's the single equal sign is the assignment operator so if index
the assignment operator so if index equals zero and self and we it is the
equals zero and self and we it is the dealer then we'll print hidden
dealer then we'll print hidden so in our version of the game at the end
so in our version of the game at the end of the game
of the game that all the dealer's cards will be
that all the dealer's cards will be shown so you can see what the dealer had
shown so you can see what the dealer had so to do that we're going to create a
so to do that we're going to create a new parameter in this
new parameter in this display method and it's going to be
display method and it's going to be called show all dealer cards with
called show all dealer cards with underscores for spaces and we're going
underscores for spaces and we're going to set the default value to false
to set the default value to false show
show all
all dealer
dealer cards
cards and when the default value is going to
and when the default value is going to be false
be false now we'll add it to this if statement
so we'll add another
we'll add another and
and not
not show
show all
all dealer cards
dealer cards so
so it's going to be hidden if we're not
it's going to be hidden if we're not showing all the dealer cards
showing all the dealer cards but if we are showing all the dealer
but if we are showing all the dealer cards then this whole if statement will
cards then this whole if statement will be false so we'll just print the card
be false so we'll just print the card and there's going to be one other
and there's going to be one other scenario where we're not going to print
scenario where we're not going to print hidden if there's a blackjack then the
hidden if there's a blackjack then the game is over the person with the
game is over the person with the blackjack is just going to win and then
blackjack is just going to win and then we'll just print all the cards so we're
we'll just print all the cards so we're going to add that to this long if
going to add that to this long if statement here so we'll say
statement here so we'll say and not is
and not is black jack
black jack and it should be
and it should be self dot is blackjack to be able to call
self dot is blackjack to be able to call this method here
this method here and since this is such a long line is
and since this is such a long line is always going to go to this next line we
always going to go to this next line we can do this special thing
can do this special thing we can add a slash here
we can add a slash here and then just go to the next line
and then just go to the next line so
so this slash or it's a backslash i mean
this slash or it's a backslash i mean this backslash will indicate that the
this backslash will indicate that the line continues on the following line
line continues on the following line okay we're done creating the hand class
okay we're done creating the hand class so we'll delete
so we'll delete everything that we were using for
everything that we were using for testing before
testing before okay it's time to code the final and
okay it's time to code the final and longest class that runs the game so what
longest class that runs the game so what i want you to do is create a class
i want you to do is create a class called game and inside the class create
called game and inside the class create a method called play and inside the
a method called play and inside the method create a variable called
method create a variable called gamenumber with the underscore for the
gamenumber with the underscore for the space
space and set that to zero so class game
and set that to zero so class game and then we'll create another variable
and then we'll create another variable games to play and set that to zero
games to play and set that to zero now we're going to set games to play
now we're going to set games to play to be whatever the user inputs
to be whatever the user inputs after they're asked how many games do
after they're asked how many games do you want to play
you want to play so you may remember how to do
so you may remember how to do input from before
input from before so we just do input
so we just do input now we want to make sure the games to
now we want to make sure the games to play is an end so we just need to
play is an end so we just need to convert this to an end
[Music] okay now let's test things so far so at
okay now let's test things so far so at the end i will put g equals game i'm
the end i will put g equals game i'm going to create a new game
going to create a new game and then g dot play
how many games you want to play five
five okay well it's not going to play the
okay well it's not going to play the games yet we still have to create that
games yet we still have to create that so there is a potential for an error
so there is a potential for an error here if i do this again and i just put
here if i do this again and i just put how many games i put you or some letter
how many games i put you or some letter we're going to get an error
we're going to get an error so basically anytime someone puts
so basically anytime someone puts something that's not a number is going
something that's not a number is going to be an error
to be an error so let's create a try accept block to
so let's create a try accept block to handle the exception
handle the exception and
and if they put something that's not a
if they put something that's not a number we'll
number we'll print you must enter a number so let me
print you must enter a number so let me arrange this and we've already learned a
arrange this and we've already learned a little bit about try except blocks i'm
little bit about try except blocks i'm going to put try
going to put try and it's going to try this
and it's going to try this and then if that doesn't work if there's
and then if that doesn't work if there's an exception
an exception [Music]
[Music] it will print
it will print [Music]
[Music] you must enter a number
you must enter a number so currently the user gets only one
so currently the user gets only one chance to input a correct value let's
chance to input a correct value let's make the program keep asking the user
make the program keep asking the user for a value until the user enters a
for a value until the user enters a number this can be done with a while
number this can be done with a while loop the while loop just keeps looping
loop the while loop just keeps looping while something is true so keep looping
while something is true so keep looping until the user enters a number by
until the user enters a number by putting the entire tri-catch block into
putting the entire tri-catch block into a while loop that keeps looping while
a while loop that keeps looping while the game's a play is less than or equal
the game's a play is less than or equal to zero
to zero [Music]
[Music] oh and i have to make sure i spell
oh and i have to make sure i spell while correctly
while correctly okay now let's create the main game loop
okay now let's create the main game loop this is a new loop that will loop one
this is a new loop that will loop one time per game played it should loop
time per game played it should loop while game number is less than games to
while game number is less than games to play and the first line of loop should
play and the first line of loop should increment the game number by one
inside the loop we'll create a deck object in a deck variable and shuffle
object in a deck variable and shuffle the deck
the deck now we'll create a variable called
now we'll create a variable called playerhand and set it to a hand object
playerhand and set it to a hand object and then we'll create a variable called
and then we'll create a variable called dealerhand and set it to a hand object
dealerhand and set it to a hand object but this time we'll make sure to specify
but this time we'll make sure to specify that dealer equals true
okay this next part will be a little more complicated we'll create a for loop
more complicated we'll create a for loop that loops two times and each iteration
that loops two times and each iteration should add a card to the player's hand
should add a card to the player's hand that is dealt from the deck and add a
that is dealt from the deck and add a card to the dealer's hand that is also
card to the dealer's hand that is also dealt from the deck
dealt from the deck [Music]
[Music] okay we just dealt two cards each player
okay we just dealt two cards each player now information is going to be printed
now information is going to be printed to the console for each game so let's
to the console for each game so let's start by printing an empty line
start by printing an empty line now we'll print an asterisk 30 times to
now we'll print an asterisk 30 times to make a divider
make a divider there's a trick to printing something a
there's a trick to printing something a lot of times so i can put an asterisk
lot of times so i can put an asterisk in in quotation marks and then just do
in in quotation marks and then just do times 30.
times 30. so it's going to print it 30 times now
so it's going to print it 30 times now we'll print the current game number out
we'll print the current game number out of the total number of games
of the total number of games so it'll be something like game 4 of 10
and we'll use an f string and then we'll just print 30 more
and then we'll just print 30 more asterisks
now we'll display the player's hand and then the dealer's hand
and then the dealer's hand at this point in the game someone could
at this point in the game someone could already have won if they got a blackjack
already have won if they got a blackjack the code should check if there's a
the code should check if there's a winner let's put the code to check if
winner let's put the code to check if there's a winner in a separate method of
there's a winner in a separate method of the game class so create a method called
the game class so create a method called check winner for now the method should
check winner for now the method should just return false
and just make sure everything's indented correctly this should be less indented
correctly this should be less indented than the previous line here
than the previous line here the check winner function should take
the check winner function should take the playerhand and dealer hand as
the playerhand and dealer hand as arguments
now before this return statement we're going to check if
we're going to check if playerhand.getvalue is greater than 21.
playerhand.getvalue is greater than 21. if so we'll print you busted dealer wins
if so we'll print you busted dealer wins and then return true and remember once
and then return true and remember once the program gets to a return statement
the program gets to a return statement none of the following statements in the
none of the following statements in the block are run
block are run [Music]
now we'll use a few lf statements to check for various other conditions so
check for various other conditions so we'll add an lf statement to see if the
we'll add an lf statement to see if the dealer got over 21
dealer got over 21 and then we'll print dealer busted you
and then we'll print dealer busted you win and then return true
win and then return true [Music]
[Music] oh and i just copied all this but this
oh and i just copied all this but this should be an l if not if
should be an l if not if and then we'll add an lf statement to
and then we'll add an lf statement to check if both players have a blackjack
check if both players have a blackjack and then we'll print both players have a
and then we'll print both players have a blackjack tie
blackjack tie and then return true
[Music] and then we'll add an elf statement to
and then we'll add an elf statement to check if player hand has a blackjack and
check if player hand has a blackjack and then we'll print you have blackjack you
then we'll print you have blackjack you win
win and then return true
and then we'll check if the dealer hand has a blackjack and then say dealer has
has a blackjack and then say dealer has blackjack dealer wins
blackjack dealer wins and return true
and return true [Music]
[Music] okay we're done with all the hand when
okay we're done with all the hand when conditions but the game can also end if
conditions but the game can also end if both players choose not to get more
both players choose not to get more cards so we're going to add a new
cards so we're going to add a new argument to the check winner method with
argument to the check winner method with a default value it's going to be game
a default value it's going to be game over equals false
over equals false so we'll add game
so we'll add game over
over equals false
equals false if it's true that means both players
if it's true that means both players have chosen not to get more cards now
have chosen not to get more cards now we'll use the new argument
we'll use the new argument the string of if and lf statements
the string of if and lf statements should only be run
should only be run if it's not a game over and we'll make
if it's not a game over and we'll make sure the line returned false is not in
sure the line returned false is not in the if statement
the if statement so
so here we'll say
here we'll say if
if not game
not game over
over and then i'll just select all these and
and then i'll just select all these and put them
put them in here
in here so if game over is true we'll check if
so if game over is true we'll check if the player hand's value is more than the
the player hand's value is more than the deal hands value and if so we'll print
deal hands value and if so we'll print you in
you in so we can do this with an else here
so we can do this with an else here else
else if player
if player [Music]
[Music] and then we'll do an lf for if it's a
and then we'll do an lf for if it's a tie
so this is an lf and we'll say if these are
and we'll say if these are equal to each other
equal to each other and we'll print
and we'll print tie
and then make sure we have the correct emoji for a tie
emoji for a tie [Music]
[Music] and then else the dealer is one
and then else the dealer is one so we'll just do
so we'll just do else
else [Music]
[Music] and then at the exact same level of
and then at the exact same level of indentation as the else we just added
indentation as the else we just added we'll add return true this will make the
we'll add return true this will make the method return true if game over equals
method return true if game over equals true
true now let's go back to the play method
now let's go back to the play method inside the while loop
inside the while loop and then we'll do an if statement and
and then we'll do an if statement and we'll do if and then we'll call the
we'll do if and then we'll call the check winner function with the player
check winner function with the player hand and the dealer hand so let's go
hand and the dealer hand so let's go back up here
winner and then we'll enter the player hand and
and then we'll enter the player hand and the dealer hand
the dealer hand [Music]
[Music] so if this is true that means we should
so if this is true that means we should go on to the next game
go on to the next game to do that we do continue
to do that we do continue so continue is going to just go to the
so continue is going to just go to the next iteration of the loop and the loop
next iteration of the loop and the loop we're on is this loop so when we go to
we're on is this loop so when we go to the next iteration we start a new game
the next iteration we start a new game at this point in the game the player
at this point in the game the player will be able to choose hit or stand
will be able to choose hit or stand so inside the while loop but not inside
so inside the while loop but not inside the if statement we just added we'll
the if statement we just added we'll create a variable called choice and set
create a variable called choice and set it to be an empty string
the player should be able to keep choosing until the value of their hand
choosing until the value of their hand is over 21. so right under the choice
is over 21. so right under the choice variable we'll add a while loop that
variable we'll add a while loop that loops while player hand's value is less
loops while player hand's value is less than 21 and inside the loop we'll add a
than 21 and inside the loop we'll add a line to get the choice
line to get the choice that's either going to be hit or stand
and then we'll just add this to convert whatever the answer is whatever the user
whatever the answer is whatever the user put in we are going to convert it to
put in we are going to convert it to lowercase
lowercase the while loop we just added should also
the while loop we just added should also stop if the user's choice is stand or or
stop if the user's choice is stand or or s so we'll update the line that starts
s so we'll update the line that starts the while loop to also stop if the
the while loop to also stop if the choice isn't s or stand so just do and
choice isn't s or stand so just do and choice
choice not in
not in and this is there's a few ways to do it
and this is there's a few ways to do it but this is kind of a new way that i'm
but this is kind of a new way that i'm just showing you here
just showing you here [Music]
[Music] so we are checking if choice is not in
so we are checking if choice is not in this list and inside the list we have
this list and inside the list we have two elements s or stand so if choice is
two elements s or stand so if choice is not in that if the choice is not s or
not in that if the choice is not s or stand then we'll continue the loop
stand then we'll continue the loop and then after the input we'll print an
and then after the input we'll print an empty line
also we want the program to keep asking the user for a choice until the user
the user for a choice until the user enters a valid choice
enters a valid choice the valid choices are hs hit and stand
the valid choices are hs hit and stand so right after the last print statement
so right after the last print statement at the same indentation we'll add a
at the same indentation we'll add a while loop that will keep looping until
while loop that will keep looping until the user enters a valid choice
the user enters a valid choice and inside that while loop we'll ask for
and inside that while loop we'll ask for input again
input again but we'll specify it can be h or s as
but we'll specify it can be h or s as well
well [Music]
[Music] so this is going to look very similar to
so this is going to look very similar to this line but it's going to kind of
this line but it's going to kind of clarify things just a little bit
clarify things just a little bit and then we'll print another empty line
and then we'll print another empty line the last while loop we checked if choice
the last while loop we checked if choice was not in a list
was not in a list outside of the recently added a while
outside of the recently added a while loop but inside the loop we just added
loop but inside the loop we just added before that one we'll add an if
before that one we'll add an if statement to check if choice is in the
statement to check if choice is in the list hit or h and if so we'll add a card
list hit or h and if so we'll add a card to the player's hand that is dealt from
to the player's hand that is dealt from the deck
and then right below that will display the player's hand
outside all the while loops about the player making a choice we'll check for a
player making a choice we'll check for a winner we'll use the same if statement
winner we'll use the same if statement and continue statement that we use last
and continue statement that we use last time we checked for winner so i'll just
time we checked for winner so i'll just copy this
copy this and then
and then we have to make sure it's lined up
we have to make sure it's lined up correctly
correctly okay so this is outside of this while
okay so this is outside of this while loop so after this all is all done we
loop so after this all is all done we check for a winner let's just add an
check for a winner let's just add an empty line there to
empty line there to make it more clear that the while loop
make it more clear that the while loop is over
is over now we'll store the value of the
now we'll store the value of the player's hand in a variable named player
player's hand in a variable named player hand value with underscores for spaces
hand value with underscores for spaces [Music]
[Music] and we'll do the same thing with the
and we'll do the same thing with the dealer's hand
dealer's hand [Music]
[Music] remember i could use the command d or
remember i could use the command d or control d to select two words at once
control d to select two words at once and change them both at the same time
and change them both at the same time okay the dealer should keep drawing
okay the dealer should keep drawing cards until dealer hand value is more
cards until dealer hand value is more than 17 so we'll make this happen with a
than 17 so we'll make this happen with a while loop
while loop and inside the loop we'll make sure the
and inside the loop we'll make sure the dealer is dealt a card from the deck and
dealer is dealt a card from the deck and that dealer hand value is updated
that dealer hand value is updated so you can try that yourself but i'm
so you can try that yourself but i'm going to show you right now while
going to show you right now while dealer
dealer hand value
hand value is less than 17.
is less than 17. then we will do dealer
then we will do dealer hand dot
hand dot add card
okay and after this while loop will display the dealer's hand and when we
display the dealer's hand and when we call the display method we'll make sure
call the display method we'll make sure to set show all dealer cards to true
[Music] and since it's the end of the game
and since it's the end of the game that's why we're just showing all the
that's why we're just showing all the cards
cards now we'll check for a winner just like
now we'll check for a winner just like before
then we'll print your hand colon and then the player hand value
then the player hand value [Music]
[Music] and then the dealer's hand
now we'll call the check winner function one final time
one final time but this time it should not be an if
but this time it should not be an if statement and we'll pass in the hands
statement and we'll pass in the hands like before but this time we'll add a
like before but this time we'll add a third argument of true to indicate that
third argument of true to indicate that the game is over
and at this point in the code the game is over
is over so outside the outer while loop and in
so outside the outer while loop and in the play method we'll add the final line
the play method we'll add the final line of saying
of saying thanks for playing
so it's going to be outside that while loop and we'll put print
and just to demonstrate it i use an escape character to add a new line so
escape character to add a new line so this slash in is going to add a new line
this slash in is going to add a new line and then do thanks for playing and when
and then do thanks for playing and when i line this up for with the while loop i
i line this up for with the while loop i realize that this entire function should
realize that this entire function should not be lined up with the while loop
not be lined up with the while loop sometimes it gets tricky with um
sometimes it gets tricky with um figuring out the exact right indentation
figuring out the exact right indentation so if i
so if i kind of go up straight up here
kind of go up straight up here i should say see that this should be
i should say see that this should be lined up with this play function
lined up with this play function so i'm going to come back down to this
so i'm going to come back down to this function
function i'm going to
i'm going to copy this all
copy this all and i'm just going to do shift tab
and i'm just going to do shift tab to indent it all one less
to indent it all one less this happens sometimes when running
this happens sometimes when running python code sometimes the indentation
python code sometimes the indentation can get all mixed up but that should be
can get all mixed up but that should be correct now and i think the red squiggly
correct now and i think the red squiggly lines here on the return true are not a
lines here on the return true are not a mistake in the code but a mistake in the
mistake in the code but a mistake in the error checking because it comes after
error checking because it comes after that emoji and it doesn't know how to
that emoji and it doesn't know how to handle the emoji but it's perfectly fine
handle the emoji but it's perfectly fine for code to have emojis okay let's run
for code to have emojis okay let's run the program and try it out so i'll press
the program and try it out so i'll press play how many games i want to play i'll
play how many games i want to play i'll do three
do three so game of one of three so i can see i
so game of one of three so i can see i have 17 i don't know what the dealer has
have 17 i don't know what the dealer has but i'm going to s for stand
but i'm going to s for stand okay it's always good to test so it says
okay it's always good to test so it says deal is missing one required positional
deal is missing one required positional argument so let's go up to
argument so let's go up to it says line 139 so this can kind of
it says line 139 so this can kind of help us know where to go so let's go up
help us know where to go so let's go up to 139
and yeah i want to deal a single card so i'm going to deal one card here
i'm going to deal one card here and
and were there any other times i did use
were there any other times i did use deal
i want to deal one card here
and yeah i got the deal one up here so i
yeah i got the deal one up here so i just think i just forgot the deal one in
just think i just forgot the deal one in those places
those places so uh thanks to these error messages
so uh thanks to these error messages whenever you have a problem make sure to
whenever you have a problem make sure to read the error messages and it can often
read the error messages and it can often give you a very good idea of what you
give you a very good idea of what you need to do wrong because even says deal
need to do wrong because even says deal is missing one required positional
is missing one required positional argument the number so that can really
argument the number so that can really help figure out what's wrong with your
help figure out what's wrong with your code so let's try that again we'll do
code so let's try that again we'll do three games
three games and then this time i will hit
and then this time i will hit and i'm going to stand
and i'm going to stand okay so now we have another error
okay so now we have another error so it says 173
so it says 173 and oh this i can already see this is
and oh this i can already see this is spelled wrong so let's go to
spelled wrong so let's go to 173
and make sure i spell that correctly
make sure i spell that correctly and make sure i spell that correctly
and make sure i spell that correctly okay let's try again
okay let's try again how many games you want to play three
how many games you want to play three i'm going to hit
i'm going to hit and hit
and hit okay so the first game
okay so the first game you busted dealer wins and now we're on
you busted dealer wins and now we're on game number two i'll hit
game number two i'll hit and this time i will stand
and this time i will stand okay dealer busted you win now we're on
okay dealer busted you win now we're on game three of three
game three of three and i will hit
and i will hit and i will stand
and i will stand and final results your hand 20 dealer's
and final results your hand 20 dealer's hand 19
hand 19 you win
you win thanks for playing
thanks for playing we just completed this whole game
we just completed this whole game okay we've reached the end of the course
okay we've reached the end of the course so you've learned the basics of python
so you've learned the basics of python and if you've been coding along you've
and if you've been coding along you've written two python programs good luck on
written two python programs good luck on your programming journey thanks for
your programming journey thanks for watching and remember use your code for
watching and remember use your code for good bye bye bye
good bye bye bye bye bye
Click on any text or timestamp to jump to that moment in the video
Share:
Most transcripts ready in under 5 seconds
One-Click Copy125+ LanguagesSearch ContentJump to Timestamps
Paste YouTube URL
Enter any YouTube video link to get the full transcript
Transcript Extraction Form
Most transcripts ready in under 5 seconds
Get Our Chrome Extension
Get transcripts instantly without leaving YouTube. Install our Chrome extension for one-click access to any video's transcript directly on the watch page.
Works with YouTube, Coursera, Udemy and more educational platforms
Get Instant Transcripts: Just Edit the Domain in Your Address Bar!
YouTube
←
→
↻
https://www.youtube.com/watch?v=UF8uR6Z6KLc
YoutubeToText
←
→
↻
https://youtubetotext.net/watch?v=UF8uR6Z6KLc