Transcripts
1. Why You Should Watch This Masterclass: Hi, my name is Michael, founder of Two M Python Death. I specialize in helping
students go from complete beginners to absolute a masters in Python program. I've developed a strategy
that has helped hundreds of students achieve their goals of becoming Python developers. And I want to do
the same for you. But before I tell you how, you need to know that
92% of those that start Python programming stop within just two weeks due to
ineffective learning methods. Watching Youtube
videos, reading books, and doing projects of your own are not sufficient
resources to fully grasp the concepts of Python coding and programming
philosophy in general. At two Python deaf, we provide a clear
learning structure with a unique approach that focuses on application
and practice, rather than just
watching and theory. Once you finish the course, you'll become a master
problem solver. You will understand
fundamental coding concepts such as object oriented
programming in Python. You'll also become
highly skilled in data handling using
lists, couples, dictionaries, and
sets, and you'll excel at working with databases
using SQL language. You will receive personalized
one on one lessons with highly trained instructors that specialize in teaching
students Python, even if they have zero
prior coding experience. Hi, sorry for cutting into
the video so ruthlessly. But I had a few notes
that I would like to add. We don't need a
private instructor in order to finish
this master class. Everything was
thoroughly explained, so you can do it on your own. But if you're looking to
save hundreds of hours, learn from experienced
Python developers and guarantee that you become a
Python developer yourself. I highly recommend that
you go to two m Python dev.com forward slash
private tutoring Python. I will have the
link posted in here somewhere and I will
leave it in my profile. Hey, just wanted to
give you a quick tour of the website so you
know your way around. First of all, you're going
to be greeted with the elite Python one on one
private tutoring lessons, you'll know why it's
elite in just a bit. Then you'll see that we
guarantee that you mastered Python in as little
as ten weeks. And you'll see this
button right here. Look what happens when
you have over it. You won't believe how long it took me to do this,
even if I told you. But anyways, when you
click this button, you book a free call. You need to add your
name, your best e mail, and make sure to add your
phone number as well, so that I can contact
you over what's up. And finally, click on this
button right here to book your free 100% free
strategy session. Next, right here, you can
see that we have the video. You can watch it again, but
it's basically the same one. And then you have the
e mail where you can contact us at two point on dev. Or you can contact me personally using this number right here. You can actually
click on this button and it will take
you to Whatsapp. And you can then contact
me directly from the next. If you scroll down, you'll see that this bar at
the top hops up. This also took me a long time. So you can use it to go through different sections
of this website. Right here we have the
beliefs and you should really believe in your future
as a Python developer, even if you have zero
coding experience. So don't worry about that. Next you're going to see
the Y learn with us. I'm not going to
read all of this, You can do it on your own, but I'm going to skim
over the main ideas. First of all, we build a
solid programming foundation. We don't want to rush things, we want to make sure that
you understand everything. Next, we are very
beginner friendly and very advanced
friendly as well, so you are covered on all sides. Time, flexibility, you choose
what times you want to learn during the week and how many hours you
want to learn. Next, we have a huge amount
of time saved from studies. We've found that to learn
four loops on your own, you need at least ten days to learn it in a
class of ten or five, You need five days, but with private
tutoring, one on one, private tutoring,
you can learn it in as much as one or 2 hours. So you're saving a
huge amounts of time, hundreds and hundreds of hours. Next, everything that we do
is going to be project based. Everything that we learn
is going to be applied to real world scenarios
and practice. Practice, practice,
every lesson will have a challenge that
you need to complete, because doing is superior to
watching In section three, these are the possible careers. So you are investing in a future where you
could be earning up to $71,000 and this
is the lowest end. You can see that you can
either become data analyst, BI analyst, AI engineer,
and data scientist. These are just the basics. You can always go
to this website to check the numbers
for yourself. This is why Python is
such a good language. A nice graphic that I
created right here. Also in here, you can see
that we have this button now, the two M Python master
class curriculum. I recommend that you go through every single section in here
to understand how it works. I'm going to cover this
in upcoming videos, but not in this one, because the most important section is going to be the success story. So I want you to
go through this if you're still unsure
whether we are legit. I love transparency. So I want you to read every single review
that we have in here from different platforms. And the most important part is I want you to get to
this point right here. Because any of these
screenshots could be faked. I'm not going to lie,
these can be faked easily. But the interviews that I
have with the students that learned at two Python
dev cannot be faked. As again, I love transparency. I want to be as transparent
as possible and I want you to know exactly what you
are getting yourself into. This is not a small
amount of money that you would pay to learn Python Again, this is an investment
in your future, but I want you to know exactly what you will get with the amount
that you invest. So please take the time. Watch the videos. Understand
these people's story. These people, they started from complete beginners and became absolute masters in
Python programming. So I highly recommend that
you watch these videos. Thank you so much for watching. I have the link in my
profile if you want to check out all of these
things for yourself. So the way this works
is first you'll have a strategy session with me where you will learn all
about the core structure, understand the benefits you'll get out of every single section, and we'll have a lesson
together where I will assess your
Python level and then pair you with the
perfect instructor that will fit your exact needs. And unlike boot camps with large class sizes
and rigid schedules, forcing you to attend
specific hours during the week and charging
you huge fees. On top of that, we offer a
tailored learning experience, allowing you the
freedom to choose flexible hours and the number
of hours you want per week, all at a fraction of the cost. So if you're interested, book a call with us by
clicking the button below, and I hope to see you soon.
2. Section 1 - Introduction | 1. Python For Windows Mac: Welcome back my favorite
Python programmers. In this video, we're going
to be talking about Python, what it is, how it works, just surface level things. Then we are going to go
and download Python to set up the environment
on your PC. First of all, what is Python? Python is this logo right here. Well, it's not just this logo, it's a high level and general purpose
programming language. First of all, let's talk
about a high level. High level means
that we are using regular English language to communicate with our processor. We start off with the
usual high level language, which is Python,
Which is just words like print and hello world
and things like that. And string and integer. Then it's converted
into a cold code called assembly. We are not going to be looking into
assembly in discourse. It's a bit of an advanced subject, very
complicated subject. But I do recommend that you go and see how assembly looks like. It's basically like sending
information and guides to the processor and
telling the processor how it should interpret this information
in zeros and one. And finally, we have
the lowest level, which is just ones and zeros
being sent to the processor. The processor then sending
you back information. It's also a general purpose
programming language, and that's the most fun and
exciting part about Python, is that you can use it
for data visualization, for data analytics, for software
development, for AI, for front for back. You can even create games
and websites using Python. So it's a general purpose
programming language. Python is designed to
emphasize code readability. So if you're coming
from another language, you know that you have to use
a lot of squiggly brackets, a lot of minute details to make sure that
everything works. Python doesn't do that. Python uses indentations
instead of brackets, and we're going to
see all of that in our upcoming examples. Let's go ahead and download
Python to our PC in here. I've already prepared
the web page. All you need to do is go to Python.org I will leave
the link somewhere maybe, but let's say very easy link. You can even type
in Python.org on Google and you should find
this website right here. First of all, you need
to go and download and you can see
all the releases. But if you're on
a Windows or MX, I suggest selecting
one of these two. I'm going to select Windows. When you go to Windows,
you should see the latest version of Python. Now maybe you're watching
this in the future and there's an even newer
version than this one, but everything that's 3.8 and upwards I think is going to work 100% with whatever
version you get. Everything above 3.8 is going
to work with the course 100% Just click on
latest Python release. Once you do that, the
installer should get going. So right here you can see
some general information and rules about this Python, this new release of Python. You should come down
to the files right here and you should
find or wait in here, you can see that this is Python 3.11 0.4 these are all
just small versions. The most important thing
is that you download Python three point
something, it's faster. You can see right here, you
can read a little bit about the general changes
that were made. Sometimes this can be
very useful. You can even use that to run your
programs much faster. So for example, you
can see right here, it runs faster than
the older version. But the most important
part is going down to the files right here and understanding if you
have a Windows installer 64 bit or 32 bit, you can right click
on my computer. And looking at that, select
Windows installer 64 bit, and it should start installing. Now obviously because
I already have Python, I'm not going to
install it again, it's a very straightforward. Once you download the installer, you double click
open the installer, click on, yes, yes,
yes, yes, yes. All the way until you get this. You might see something
like Add Python 3.9 path, or maybe it's 3.11
0.2 In your case, this is one of my older images. If you have this,
you must check it. You check it, and then you
continue because you do want Python added to your path.
That's basically it. Thank you so much for watching. In the next video,
we're going to be downloading Intellig
and setting it up, and it's going to be the IDE that we use in order
to write Python code. I hope you enjoy it
and I will see you in the next video. Bye bye for now.
3. 2. Downloading IntelliJ IDE for Windows Linux Mac: Welcome back my fellow Python programmers to a
brand new video. And in this one we're
going to be downloading Intellij and setting
a few things up. So first of all, what the
heck is even Intellig, Intelli is Intellij idea. I think it's an
acronym for something. I'm not sure what
that acronym is, but it's an IDE. So what is the acronym for IDE? It's Integrated
Development Environment. And what that means
is that we're going to be using
Intellij to help our computer understand
Python language and compile the
code that we want. I told you we have high
middle level and low level. Some people just consider
the high and low level. I tend to think that assembly
is in the middle level of programming languages, IDE, IDE. What it does, it basically takes the high level,
which is Python, because, remember,
our computer does not understand English language. It only talks in two numbers, 0.1 Believe it or not, we're not going to go into software engineering and
computer engineering. For now, let's just
stick with what we have, which is Python and Intellij. Basically, Intellij
takes the words that we've written
in English and converts them into 0.1
sends it to the processor. The processor comes back with some information and
we write it down. Or we get some kind of output
or something like that. So, we're going to be using
Intellig. Why Intellij? Because I found that
it is the easiest, it's the most user friendly, It gives you a lot of
suggestions very fast, and because it's free, we don't want to
pay for anything. And in my experience,
I found that Intellig gives you the
best bang for your buck. So without any further ado, let's go ahead and
download Intellij. So you should go to
a website called Jetbrains.com When you
go to that website, it should look
something like this. If you can't find the Jetbrains.com
for any weird reason, just simply type in Jetbrains
on Google or something, and you should find
the following page. Once you're here, you can
read through everything. You can see that Jetbrains
is not only used for Python, it's used for a lot of other
programming languages. But for now we
just need to go to the developer tools and we
should have a dropdown. Okay, when we click on it, we have a dropdown
and we need to go to Intelligdea.
You'll see it here. We have different things, of
course, by charm and so on, but for now, intelligent idea is what we need. We click on it. You should see a page
like this right here. You can accept the cookies,
you don't have to. Right here you can
see intelligent ID, the leading Java and Plean IDE. Don't worry about that.
Just click on Download. When you go to download,
you will have this page. And I want you to be very
careful because this one, the ultimate
edition, is the free only for 30 days trial version. What we want is
scroll down a little bit and download the
community edition. So this is going to be the
addition that we want. Now again, I already have
intelligence on my computer. I don't want to
download it again, but it's very simple, very straightforward.
Download open the, the program E that you download. Enter, Enter, accept everything. But there's one crucial thing in here that you need
to keep in mind. You might come up to a window
like this where it will ask you to either create
a 32 bit launcher or 64. Again, this depends on the
computer that you're running. Click on 64 bit, make sure that this is clicked, and then you will come up
to this data sharing click. Don't Send, because
you don't want to send information
unless you trust intelligent. I think they are going to take your
information either way. I don't, I'm not
sure they even ask for you to share your
data, they just take it. But if you do get this, you don't have to
share your information and that is all
that I have to say. Thank you so much for
watching. I hope you enjoyed. And in the next video we're going to be working
on setting up Intellig for future
the use with Python. So thanks so much for
watching and I will see you in the next
video. Bye bye for now.
4. 3. Setting up IntelliJ IDEA: Welcome back my fellow
Python developers. In this video, we're going
to be setting up tellg. The first thing you'll see
is this layout right here. It might be a little
bit different, but generally speaking,
every vlog looks the same. We're going to click
on New Project. In here, you should see
the following screen. You click on Python
and you should see Python 3.9 If you do see it, that's it. That is enough. You can continue
to the next video, although I do recommend
that you finish this one just in case
there's something missing. Some of you might
not see this because you haven't installed
correctly or your computer is weird. What you can do is you can click on this
drop down and you should find Python
3.93 0.11 3.5 15. I don't know whatever
version you're on right now. But if you still don't see it, that means that your computer
has not detected it yet. You can click on an
Ad Python S decay. And now you have to go and find the location where
this was saved. In my case, it was
saved in C user ish. I called my computer
ish whenever I got it. That was like four years ago and I was never
able to change it. Next thing you need
to do is right here. You should find the
base interpreter. This should also
be found just in case you don't have it,
go and look for it. And finally, you
need to make sure to make available to all projects and you can also inherit
global site packages. And then in here you
should click okay. But because I haven't
made any changes, you should be able
to click on that. And boom, there we go. And then when you're back here, you can click on next, you can call your project. You can select where you want to add all
of your projects. Of course, find a
suitable location, create a file for
all the projects. And I do recommend if
you have an SSD and not an HDD to save
it in that SSD, it will help open up your
projects much, much faster. That's basically,
that is intelligent. In the next video,
we're going to be creating our first Python code. Yeah, how fun is that
going to be? I hope it is. By the way, you don't have
to have the Z in search. I just typed it in because
I don't want to reveal the privacy of my students and the projects that
we've had together. Thanks so much for watching. As I told you in the next
video, we're going to have first Python program created. So I will see you then. If you're still facing
challenges in here, just please contact me or leave a question wherever you can
and I will get back to you. But this is pretty
much straightforward. I've never had any very bad, none of my students were
very complainative, even a word, a word. Complainative about
setting up intelligence. So I hope you don't
face any issues. I will see you in the next
video. Bye bye for now.
5. 4. Our First Python Program: Welcome back my favorite
Python programmers. In this video, we're going to be creating our first
Python program. It's going to be a
very simple program. It's mainly for you to make sure that you've set up
everything correctly. We're just going to look at
a few minute small examples. Just a small, very simple
print just to get you started, just to get over the
scariness of Python, even though it's one of the
simplest languages out there. But first of all, we
need to understand what is the dot py file. As we said, we have Python, it was created by
the Python people. We have another program
that is Intellig. There is no inherent connection between Python and Intelligi. As you saw, Intelligi can
be used to write Java, could be used to write SQL, it can be used for a lot
of different languages. Python can also be written on other
programming languages, on other IDEs, not
just Intelligi. What is the connection
between these two? How do we make sure that they
communicate with each other while we do that using
the dot py file. Whenever we create
a new project, we cannot start
writing code unless we create these dot py files. And you'll see that
creating dot py files is a very easy,
easy thing to do. So let's go ahead
and get started. First of all, I'm going to go back into my analogy in here. I'm going to click
on New project, make sure that you have the
project as decay. Right here. You can see we need to copy and pace this
into introduction. And then we will hit Finish. Boom. There we go. As I told you, the first
thing we need to do is go to file new and create a new Python file
that I will call Hello World and head Enter. Now we have Hello World. Now a few things about
the py file name in here. I made a mistake. Usually when we want to
name our dot py files, they shouldn't have
any upper case letters and they shouldn't
have any spaces. Now this will work. It's not a huge problem,
that's why I did it. But it's customary to name our files in the following way. So hello, and either you type in world or you add an
underscore in between them. It depends on your preference. And as I told you,
using Hello World with capitalized letters
is not going to break or re ruin your project. But later on down the line, you'll see that if
you want to import a dot py file to
another dot py file, you cannot have spaces
and weird symbols. It will just not work. But anyways, look at
what we have right here. You can see that
we have the cursor blinking and we have
line number one. And we can click
right here and we can start typing stuff. Obviously, we're not
here to type gibberish. We want to type something
that is going to be useful. And the thing that is
useful is going to be to type in print.
And look at that. I want you to stop and look
at the beauty that we have. This is why I love
love Intellij. Because as soon as we
start typing things in, we immediately get suggestions. And you can see that
we have tons and tons of suggestions like
print and property. So intelligent just puts it in the order that most people use. So for example, in here
you can see that P R, the first thing that
we get is the print. And I want you to
get in the habit of auto completing
things using the tab. And why use this autocomplete. There are many beneficial things that can come out of this. First of all, it helps you write faster code instead of typing in print and opening up
the parentheses here. You just hit Tab, Boom, you have everything
in front of you. Second of all, it
helps you avoid any errors or any typos. So for example, print if
you have a capital N, you'll see that
we have an error. And that error is shown because
of the red squiggly line. If I hover over the
red squigly line, it tells me there's an error,
unresolved reference print, because Python does not recognize print
with an upper case, it only recognizes print
with a lower case. The autocomplete will
help us with that. Also, maybe you make a mistake with the syntax, for
example, right here. Maybe you just forget to add the second parentheses
immediately. You have an error
if you have over the red squiggly
line expression, expected or something like that, just an error using the tab
helps with that as well. And finally, if somebody
sees you typing in code and sees you or completing
that code and typing, you know, like
being in the zone, they'll be like am that person
knows what he's doing or what she's doing please
use the or complete. Get in the habit of doing it. It's going to be tremendous
for your professional career. Let's continue on
Inside of print, we need to provide it with some information to be
actually printed out. If you're not sure
if the print prints something, the name is obvious. You can always hover over this. And you can see that
we were fetching documentation and you can read all about the print and the
parameter that it takes. Of course, we're
going to be talking a lot more about
what the print is, how it's a function,
what a function is. We have an entire section
dedicated to functions. You can always read about it. But for now, all that we
need to do is we need to know that we should provide
it with something to say. And we should provide
it with open up the double quotation marks
and type in Hello World. Boom, there we go. Now if I write Click and
I go to run Hello World, you can see that I get Hello World printed out in
our console at the bottom. This is also something that
I like a lot about Intellij, is that you don't need any external tools to
run your programs. You just write, click run, And everything happens
inside of Intellij and it's all controlled
and it's all good. Now, why did I say hello world? Maybe some of you know this,
maybe some of you don't. But when it's customary, whenever you start a new
project or a new program, you always type in Hello World. Just to check like what's
happening in the background. So there we go,
that's Hello World. One last thing before we go. Like I use the double
quotation marks in here around the Hello world. You might be asking, well, why? Well, because this is a string. And when we want to display
a string in Python, we need to use either the
double quotation marks or the single quotation marks. And I will be explaining
more when we use double, when we use single,
and when do we need them to be used together. Of course, all of that in the upcoming sections,
but for now, if I remove the space in here, you'll see that I get a
yellow squiggly line. So we've seen the
red squiggly line. And I will be going over this again in one of the next videos. But when we see a
red squigly line, it means we have an error. It means that our code
is not going to run. So for example, if
I type in print, I write click and I run. I get an error because the
name print is not defined. But sometimes I might get
these yellow squarely lines. So these are warnings, these are not errors. They might break your code, but most of the time they don't. So what is the issue in here? If we hover over it, you'll see that it's telling us a nine to no new
line at the end. So what is step eight, P eight is how should I call it? Like it's the style in which the Python gods have told you to write Python code
in order to make it clean. So one of the things that they
require from you is to add an extra line at the end
because it looks just better. You don't want to finish on just the code you want to
finish on an empty line. So for example, if you
add a space in here, you also get a small
warning, please. Pep 82 oh two white spaces
before the parentheses. We don't want that, we want
to have it clean like this. Following the eight is a very good idea because if you show this
code to someone, they will appreciate it more. If you ever go back to your
code, you will like it more. And just having
clean, easy to read, understandable,
well organized code will benefit you
a lot, trust me. Sometimes you go back to
previous codes and you see all the gibberish that you
wrote, and you'll be like, I wish I did it more correctly or had it
better organized. But in any case, warnings such as these will not
break your program. As you can see, we still
have the same output. So I hope you understood. I hope all of that makes sense. And now it's time
for a challenge. And what do I mean by challenge? Now I will explain
and go in depth into what challenges are in the next video when I tell
you how to use this course. But for now, you need to
print out a personal message. This is something that you
need to do on your own. So I want you to change
the printed line from a simple hello
world to say hello, and then next to it, your name. I want you to run the program
to make sure it works. And I want you to
congratulate yourself on your first Python
program. Very nice work. So, pass the video right now
and go do the challenge. Okay, welcome back. How did you get on with that? It shouldn't be too hard. You should only
say hello Michael. You don't have to say Michael unless your name is Michael. Right click and run and
it says hello Michael. And of course, you can't type in whatever
you want in here. We can even duplicate this
line using control D in here. I'm going to say thank
you for watching, leave a review if you can, because at this
point, maybe they've already asked you for a review. Wherever you are watching
this or if you want, you can simply hit me up, like call me or text text
me over what's up and tell me how you're
enjoying the master class. I don't know why I
wrote master with a small M and then
are the one word. I'll just keep them as one word. So if I write click and I run. Boom, Ladies and gentlemen, thank you so much for watching. I really appreciate it. In the next video, we're
going to be talking about how to use the scores, please. It's very important that you understand how to
use the scores. I'm going to talk
about the sections. I'm going to talk about the challenges and how
you should do them. I will see you in the next
video. Bye bye for now.
6. 5. How To Use This MasterClass: Welcome back my favorite Python programmers to a
brand new video. And in this one, we're
going to be going over how you can
use this course. This will be probably
the most updated video because I will keep
adding new lessons, new techniques, new
stuff to the course. This is the biggest master
class anywhere in the world. I mean, I don't know
if the entire world, but I'm pretty sure that this
is top notch information. So first of all, this is your challenge slide. You can see that this is a
slide inside of another slide. So this is slide seption
or slide inception. Please don't click
over the video. Continue with the on
the master class, but anyway, this is
your challenge slide. So when you see this slide, you need to pause the video
and do the challenge on it. No matter how hard, no matter how much you feel that you are not able to
do the challenge, it's imperative
that you try and do your best because it's a
much better way to learn. And because doing is much more important than
just watching. This is the philosophy that I've built my entire career on, and this is exactly what I
used to do in university. So maybe some of you
have been through this. You sit in a class, you know the instructor just does some things, you
know, some weird things. It doesn't have to
be just programming anything like imagine math. You're looking at the
instructor like solving all of these nice
equations and you're like, yeah, this is so
easy, I got this. You go back home, you
open up the textbook, you start doing
whatever challenges or whatever exercises. And then you find that you don't know anything or you
don't know everything. At least because when the
instructor is doing it, you feel that it's very easy. Because in your head you
don't see the minute detail, the small thinking that the
instructor needed to have. So that's why if you do the challenges yourself
and you try your best, very best, even if you fail, you don't have to do all
the challenges correctly. If you take at least
five to 10 minutes of your time to try
and do the challenge, to mess things up, to
break your code entirely. And then when you see the
instructor, even if it's me, or maybe you're doing
one on one sessions with a specialized instructor
that I've assigned to you. You'll see the process, You'll see the mistakes
that you made. And you'll see how you
can fix those mistakes. And more importantly,
you'll understand why you did those mistakes and why we write the code
the way that we do. Because sometimes is more
important, not sometimes. I think almost 99% of the time, the why is more
important than the how. Why did we have to
solve this solution? Why did we write the code this
way and not the other way? So when you make
mistakes, you understand, oh, that's why get it. So please, whenever you see
this window right here, you pause the video or wait until I give you
some instructions. You pause the video and
you do your absolute best. Let's look at the
lessons structure. First of all, we have
lesson number one, which is the introduction. This is like inception. We're talking about
lesson number one and we've already almost
finished lesson number one. You'll notice that throughout the course or throughout
the master class, I will use this joke repeatedly. At any point, you
can complain to me. But please don't leave me a
bad review because of it. Lesson number two is
getting started in Python. I believe in building
a solid foundation. Some instructors like
to just jump into the heavy duty stuff and start creating
projects and whatnot. I like to build a solid foundation if you're
trying to build a building. If you're trying to build
the Empire State Building or whatever the bush,
Kalifa for example. You don't just start
building on sand. We have to go down
into the very depth of the earth to find
solid foundations. And then you can build the
tallest tower in the world. And that's exactly what we
do in lesson number two. We make sure that before we start writing very fancy code, we are getting
started with Python. We are understanding the
programming philosophy behind Python and
other languages. You might find this
lesson number two boring. It's not very exciting. But throughout the years, I found that the people that
do build a solid foundation are incredible at moving
forward with everything, with all the complicated
stuff that we learn later on. Getting started in Python
is the foundation building. Lesson number three is our
first steps in Python. After building a
solid foundation for like maybe 1
hour or 2 hours, we can now take our first steps are our introduction
to blocks of code. It's going to be where we
learn about debugging, we learn about if statements, We understand complex
expressions like s and or ors, and we just look through. Different and variable
testing areas in our code. Lesson number four is going
to be loops in Python. This is our
introduction to loops. A lot of people struggle
in introduction to loops. We're going to be
debugging our loops. We're going to understanding
what loops are, We're going to see four
loops over a range. Nested loops will be using
brakes and continue, even though continue
is not very well used. We're also going to be looking
at why loops and how we can use L statements in there. Most importantly, this
is where we are going to learn a binary
search algorithm. As a future developer, as a future Python programmer, you should know what
algorithms are. So we're going to learn a
fairly simple algorithm. Of course, I will need
your entire concentration in that section for you to properly understand
what we're doing. But because once we learn
our binary search algorithm, we are going to create
our first project. It's a game, but it's
going to be a project. And it's sort of an AI, but not a real AI. So don't get your
hopes too high. But lesson number four, lesson number 12.3 are
going to be very simple. Lesson number four
is going to be the next step of evolution. Then we have data handling
with lists and topples. This is where we are going to be introduced to sequence types. We're going to see mutable
and immutable objects. We're going to be
iterating over lists. We're going to be
removing items. We're going to be adding items. We're going to look
at nested lists. Lists inside of lists. So it's a list inception. We're going to be looking at nested data structure
and we're going to also be creating a mini project which is going to
be a car creator. Section number six
is going to be our introduction to functions. You can start
considering everything, section six and upwards as
being slightly more advanced. We have the baby
steps one to three, then we have the intermediate
at 4.5 and then we have the slightly more
advanced at level number six. Lesson number six is going to be the introduction
to functions. We're going to be
defining functions, setting up parameters,
debugging our parameters, look at how we can
call our functions, how they can return values, how we can handle invalid
arguments being sent. And again, of course, we're
going to have a mini project in our functions to get
everything wrapped together. My favorite lesson is Less Or section is
lesson number seven. It's object oriented programming
in Python. I love this. If you want to take
anything away, like please, if you at any point feel tired of the course and
you want to give up, it's imperative that you get
to section number seven. After that, you can stop. But lesson number
seven is crucial. I cannot say it enough, because lesson number seven, If you can understand object
oriented programming, if you want to learn
any other language, it will take you a
maximum of two weeks. You will understand what
object orienting is. We will understand instances, constructors, and
how to use self. We will work on class attributes methods
and static methods. We'll learn about
attribute accessibility. We'll learn about inheritance,
polymorphism composition, subclassing, overloading
a lesson number seven, very crucial, very important. Under no circumstances do you skip or you quit before
lesson number seven. Then we have lesson
number eight, which is dictionaries
and sets in Python. Very important at
data handling it, where we're going to be introducing
dictionaries and sets. So this is the continuation
of lesson number five, but I didn't want to have lists and couples and
then dictionaries and sets right after each other because they
are kind of slow, kind of boring, but
very imperative. We're going to be
learning how we can iterate over dictionaries. We're going to be creating a new mini project,
and at this point, it's not called a mini project, it's called a project, which is going to be
the computer builder. We're going to be creating and updating our values
and dictionaries. We're going to learn about
shallow and deep copy. And of course we're
going to have an introduction to sets, so we're going to be erasing, removing, and discarding
items from sets. We're going to create
unions and intersections, and we're going to be creating
subsets and supersets. Now we're getting into
the more advanced part. Now we're going into
reading and writing files. We're going to
learn about opening reading and parsing text files. We're going to look at
writing data to text files. We're going to learn about
Json files and CSV files. And understanding dialects and sniffers and writing
to CSV files. And looking at dict
readers and dict writers. And see how we can use
dictionaries with reading and writing from
files. Very exciting. Complicated, but you
need to go through it. And then we have
lesson number ten. It's going to be the big
daddy of all lessons. This is, at this point
you're going to be learning a new language which
is going to be SQL. So we'll learn about databases. We'll learn about SQL Lite. We'll learn about updating,
deleting, ordering. We'll learn about
database administration. We're going to learn about using SQL and database in Python. After we learn SQL, don't worry, it's not a very
complicated language, but it's a different
language. It's kind of hard at first, but then it gets
very, very easy. We're also going to
learn how to hack, which is very non ethical. But now it's going to be very
simple and easy hacking. Don't think like we're going
to be hacking any country, so just keep your expectations leveled when it
comes to hacking. We're also going to
introduce exceptions and creating a mini project that is going to
be a bank account. And we'll also be creating
Netflix. How about that? Not the actual Netflix,
as I told you, it's going to be
sort of a Netflix. Don't get your hopes to up. You're not going to become a billionaire after
doing this mini project, but still, it's going to
be very, very worth it. Ladies and gentlemen,
before I leave you a few things
that I need to say. First of all, I want
you to take your time. I want you to go through
every single section. I want you to be very
thorough with your learning. If you ever have any questions, you can always ask your
dedicated instructor. You can always ask me. You can always ask
the community. So please, please, please. I want you to go through this entire course.
Never give up. Try to do as much as you can during your day to
learn every single thing. This is a very well structured. I took so much time to make sure that
everything in the course, all the examples, all
the mini projects, everything builds on
top of each other. If you go through it
step by step slowly, you are going to have tremendous
and incredible results. If you go through
this entire course, you will become a certified
Python developer. You will be able to go
into any interview, look them in the eye,
and tell them that I am a Python programmer. And I thank Michael because
he helped me and taught me. And I left him a review
because I like him so much. And now I'm just kidding. If at any point you feel
that you need extra help, you can always contact me. We can set up personalized
one on one sessions together. And yeah, that's basically it. All I want to tell you is please don't lose hope. I want
you to continue right now. Don't stop you,
set everything up, it's time to get started. It's time to get your
feet wet and start the first section or the second section or
the second lesson, which is getting
started in Python. You can understand strings, variables, data
types, handling data. Also, thank you so much. I hope I didn't talk a lot. I just wanted to
be thorough with my explanations
about the sections and what you should expect. Hope you enjoyed and I will see you in the next
video. By by far now.
7. Section 2 - Getting Started With Python | 1. Print() in Python: Welcome back my favorite python programmers to a brand new video and a brand new section where we are going to be
kicking things off. The first thing we're going
to do is we are going to create a new project
right here in IntellG. Yours might be a
little bit different. I stopped updating
IntellG because sometimes the new
updates get broken, the same things will hold true. The thing that we
need to do is create a new project right
here, select Python, go to Next and make
sure that you select the proper place for this,
and you can call this. Of course, you have the freedom to call this whatever you want, but I'm going to call this
Getting Started with Python. This section is going to be
all about the introduction, all about creating
the environment and the philosophy of programming
of Python programming. And seeing what happens
under the hood to understand later on how
things work in the end game. Throughout all of the sections
that will be coming up. As soon as you create this, you already know
you need to select the following thing inside
of your project bar. Go to file, go to new, and create a new Python file
where you'll be prompted to name this something and you can name it
whatever you want. Of course, in here
I'm going to type in the print underscore function and hit Enter. And there we go. Once you do that, you are able to start typing any
code that you want. We're going to go through
the print to understand how it operates and the different ways that
we can use it. But before we do that, I need
to tell you a little bit about functions and how
they actually work. This is the typical
function that you can see. It's a print function. Of course, we have
an entire section dedicated to functions, but we're going to
look slightly at this. First of all, we have
the function name. The function name has to always reflect what this function does. For example, this is
the print function. What does it do? It
prints something out. Next we have the argument that is being sent to the print. What are we looking to print? We are looking to print
hello world, for example. This is called the argument. And of course, as I told you, we're going to be seeing a
lot more of this later on. And finally, we
have the brackets. There are always
syntaxes that we need to follow in any
programming language, not just in Python. So in the case of Python, we need to use round
brackets in front of the print where we are going
to be sending the arguments. And even if we don't want
to send any arguments, we should also still
use the brackets. So let's go ahead
and get started. I'm going to go
back into Intellij, and in here I'm going to
print out, Hello World. Now you might be wondering, why did I use single
quotation marks? Why not use double quotation
marks like I didn't here? Why do I use double quotation or single quotation marks at all? Well, because this is
called a string and we're going to be explaining
string variables more down the line, especially in this section. But whenever we are trying
to print out a word or a sentence or anything that's
in the English language, we use the quotation marks, indicating that these are letters that we are
trying to print out. And we can use single
quotation marks or double quotation marks. It does not make a
difference except for, you'll see later on why
sometimes it's better to use single or double
quotation marks. For now, I will run
this program and you'll see that we get Hello
World Printed out. Let me close down the project. And let me duplicate this line of code by
clicking at the end of it and hitting control
D. As you can see, this line was duplicated. And I'm going to use double quotation marks instead
of single quotation marks. And when I write
Click and I run, I get Hello World again. Now you might have noticed that I added an extra line in here. And you'd be thinking, well, maybe Michael did a mistake. Well, Michael did
not make a mistake. I am the God of Python program. Now I'm just kidding. I
always make mistakes. But as you can see, when
I removed the last line, I have a squiggly yellow line. If I hover over it,
it tells me 292. No new line at the
end of the file. What does that
mean? First of all, what is P? Eight. And actually even before
talking about eight, what is the yellow
squiggly line? We have many different
indications from intelligent that can tell
us if there's an error, if there's a warning, if
there's a big warning, if there's something that
we need to look out for. And throughout the
process of the course, we're going to be
seeing all of them. But for now, let's talk
about this warning. Now, this warning is not
breaking our program. So if I write Click and I run even with the small warning, I still have everything working. But what it's trying to tell us is that we are not following the style that needs to be used to write clean and
proper Python code. What does that
mean? For example, pep eight is the version or. If you want to call
it the gods of Python all sat down and determined that the best way to write Python code,
to have it clean, and precise, and neat, and be able to show other people your
code and for them to feel at ease when reading it is to follow
the p eight rules. So p eight is the eighth
version of these rules. And one of these rules is to add an extra line at the
end of your program. It doesn't change anything, it doesn't break your code. It just makes it more pretty for other people to see and even for you to go back
and look at it. So for example, if I add a
space in here, look at that. Does that look clean to you? It's obviously something
that's not really nice. And one of the more important
things in this section and in this entire master class that I want you to understand, it's not only about how
you write your code, It's about why you're writing your code the
way that you're doing, and how to make it the best and cleanest version possible. Of course, we need it to work, but we also need
it to be clean and easily readable for anyone
that's looking at your code. It will go a long way. For example, in here,
if I hover over this white space before the round brackets,
we don't want that. We want to keep it
clean and precise. If I, for example,
add a space in here, again, all of this
still works normally, but it just doesn't look nice. Imagine this code. It's not nice, it's
not organized. It doesn't look pretty. We make sure that we write
it in a correct way. Always follow the eight rules whenever you can. Let's move on. The print can do
some other things. For example, the print in here can also print out
a number like 84. Right click and
run and we get 84. Notice that 84 in
here is not a string, it's an integer,
and we're going to be looking at variables
more later on. A string is limited by either
double quotation marks or single quotation marks while integer doesn't
have these on it. Let me duplicate this again, control D. Instead of
just typing in 84, I can type in 12 plus 13. If I write Click and I
run these two numbers are added together and
then they are printed out. You can do arithmetics inside
of your functions as well. Let me duplicate this again, and this time I'm going
to change this to seven and this one to 71. Instead of adding them, I will multiply them when
I write click and I run. There we go, I get 497. Now you might have
noticed that I left an empty space in here and you might have also
noticed that it's not reflected in our console
right here at the bottom. Why is that? Well,
because empty spaces are not considered to
be just empty spaces. They are considered nothing. It's just for
organization's sake, I wanted to separate
the string in the print from the integers
and the numbers in the print. Well, now this
begs the question, what can we do in order
to create a space in our print out or in our console? Well, we can use print
and then nothing at all. Now if I write, click
and I run, there we go. You can see that I
have a print in here. Now again, something that I just did and I still haven't
explained to you. Look what happens when I
start typing any letters. I start getting suggestions
by intelligent. And this is a habit
that you have to get into regardless of
what you do going forward. If you want to become a
good software developer, Python programmer, data analyst, anything that you do in life, always look for the Or Complete
whenever you can hit Tab. As you can see, this
completes for me, not just the words print
or the letters in print. It also completes
the syntax for me, which is beautiful, because there are three
benefits to this. First of all, it avoids you causing problems,
because, for example, if you type in capital N, this is no longer a
working function. Look, we have a
red squiggly line. And a red squiggly line means
that there is an error. And it says it's a name error, telling us that name
print is not defined. There's nothing that's
print with the capital. If I hover over it, unresolved
reference and it actually does break our code and look at the error
that we get a link. If I click on that link, it takes me to the line
where the error occurred. You can also look for
the line right here. The autocomplete helps you avoid making mistakes
such as these. Tab for autocompletion also
helps you write code faster. And third and most important
is that if somebody sees you typing in code and using the tab to
autocomplete thing, they'll be like, oh my God, who's that guy? Or Gal. They are incredible programmers. They're using the autocomplete. Now, I'm kidding. This, it's
not going to be that good. But still, of course, when they see you using autocomplete, it'd be like okay, this person
knows what they are doing. So let's continue on. And now let's try
to print something. So you can see I use the
tab and I'm going to say this is the end. Then I'm going to
add a comma in here. I'm going to say,
nope, I was kidding. Add another type and
three, add another. We are doing more. If I write a click and I
run, this is what I get. First of all, I have
the empty space from the print I did right here
with no arguments being sent. And then this is the end. No pi was kid. We
are doing more. What is happening in here? Well, we are providing
multiple arguments to our function print
instead of just having a single argument like we had in the hello world and
hello world here, and the 84 and even this
expression right here, it's a single argument
because arguments are delimited by the
commas between them. As you can see, because we've
sent in multiple arguments, they were added together
and then printed out. I hope that makes sense. Thanks so much for watching. Before we leave, you
have a challenge to do, and your challenge is to combine everything
that we learned. I want you to print
out a line where you combine both
words and numbers. Make sure to use the
comma between them, so you need to send
multiple arguments to your print function and run
the code without any errors. Pass the video right now
and go do the challenge. Okay, welcome back. So I will add an extra print in here and I'm
going to say print. If we add 6.8 we get six plus eight, right click and run. And there we go. If we
add 6.8 we get 414. Ladies and gentlemen, thank
you so much for watching. In the next video,
we're going to be learning more about
strings and we're going to be looking at how we
can get inputs from a user. So thank you for watching.
I hope you enjoyed. Congratulations on
starting this journey. You are amazing and you're doing incredibly
well, stick with it. Make sure to give me
your full concentration. If at any point you feel that
you're a bit frustrated, you're not sure what to do, please contact your instructor that's dedicated to you
or you can contact me. Of course, We you
have my number. I have your number on
Whatsapp or something. You can always do
that. Before we leave, I just noticed something. We have the green
squiggly line in here. If I hover over it,
it's just a typo. The green squiggly
line is not a warning. It's not an error,
because sometimes the warning could be
potentially an error. It's just a typo, for example. Now, there we go. No more typos. Thank
you for watching. See you in the next video.
8. 2. Strings Variables in Python: Welcome back, my favorite
Python developers. In this video, we're
going to be looking at string variables in Python
and also looking at inputs. Let's go ahead and create
a new Python file by going to file new and then
python file and we're going to call this one
underscore variables in here. The first thing I'm going
to do is I'm going to print out forest run between
single quotation marks. Then I'm going to print out, Python is a really easy language to learn and between
double quotation marks. Then I'm going to print out, we can include
double cooptations inside our single quotations. Exactly. Double
quotation. Of course, just to adhere to the
rules of P eight, we add an extra line. If I write click and I run. This is why what I
get run for run. Python is really easy language. We can include
double quotations. But what makes this special? Well, let me try and
duplicate this line. Instead of using single
quotation marks on the outside, I'm going to use
marks on the outside. And notice when I changed
the one on the left, the one on the right
automatically changed. And you already see that we have seven errors, seven
freaking errors. What is the problem here? You'll notice that we have
double quotations in here. Unresolved reference, double unresolved
reference quotation, and then end of statement. Expected a lot of things
going wrong in here, what the heck is happening? Well, you'll notice
in here that we have a single quotation mark or the first double
quotation mark, correct? So what Python thinks, and the way this
works is Python, okay, is the print. All right, our programmer, our fellow developer is trying
to print something out. All right, double
quotation mark. Nice. That means there's
a string coming. All right, the
string coming, nice, character space space, I, N, C, L, D, E space. And then it finds another
double quotation mark. And then Python
thinks to itself, all right, there we go. The developer found
the end of his string. We can close down
the string now. But then it sees D and the D is not considered
a string because we've, Python is thinking like we've
already closed our string. What the heck is
the problem here? Why do we have the D and
then the o and then the U? Is this a variable that
the user tried to create? Well, no. We were trying to add double quotation marks
inside of the print, but it does not work like that. And then it saw that
another string is starting. All right, this is the
string and this is the end of the
string right here. That is why if you want to use double quotation
marks inside of your sprint or inside of a string where you have double quotation marks on
the outside, you cannot. You have to use single
quotation marks on the outside. The same holds true if we
want to do it reverse way. For example, in here,
if I try to change this to a single quotation mark,
look at what happens. We have an error here because
Python thinks to itself, well, this is the first string, this is the second string. I don't know what happened here. We just close things off. If you want to make
sure that this works, you need to use single
quotation marks on the outside and double
quotation marks on the inside. Look in here. Because they
changed automatically. This is how it would work. This changed again. Can you please
just stop changing automatically? It's
driving me crazy. Anyway. Single quotation
marks on the outside, double on the inside. And can you please
stop doing this? Thanks. Okay, there we go. Okay. I wanted to have single
quotation marks on the inside. There we go. And in here, single, if it will allow me. I mean, the autocompletion can sometimes be a pain in the butt. But there we go. We finally
were able to solve it. Of course, change
this to single. That's why we have
double quotations, and single strings can
also be added together, for example, if I print out. Hello plus world. This is not called addition, this is called
concatenation right here. When I write click and on, you'll see that we
get Hello World. You might have also noticed
that it's squished. Let me add just a print to
differentiate between things. You'll notice that they
are squished. Why is that? Well, because Hello world Don't have any empty
spaces in them. The space is also considered
a character in your string. You either have
to add it in here or you have to add it behind
world to make it work. Notice this is not
using two arguments. These two are a single
argument in here. If we add notes, we didn't have any space yet. Still, we created
the space between these because these are
multiple arguments being sent. While in here we
are working with a single argument function, It's two strings that are added together and then printed out. By the way, we don't have to explicitly be using
strings in here. When I mean explicit,
it means when we use these two parentheses, or, sorry, dequotation marks, we can do something
like the following. We can say that we
have a variable that is equal to the message. This is a variable
that I created and I call it hello there. Then I have name which
is equal to Michael. Of course, you can
add your own name. Now what we can do
is I can print out message plus the name. And what do I get when I
run hello there, Michael. Now, as a small challenge, I want you to create a space
between these 23 to one. There are many ways
of creating a space. I can add a space in here, I can add a space
behind Michael. Both are valid, Both work fine. But there is even better
way of doing this, and that is of adding a space right here so I can concatenate multiple
strings together. So now we're going to have
message space, Michael. Okay, I hope that is clear. Now, what if we don't want to have this
created beforehand? At the end of the day,
this is called a variable. Shouldn't it be variable? Shouldn't it vary? Well, it does, and it will. Instead of just
having name equal to this thing that we want, we can say name equal to input. And inside of the
input I can say, give me your name. I will just give a small
indication. Okay, what is that? I will give a small indication in here to the user about where
he should write the name. Right click and
run, Hello World. Give me your name. You'll see that the program hasn't stopped. And now in here I
can type in Michael. There we go. Now we were able to put any name that we want
using the input function. And the input function
takes in a prompt. So this is the definition
of the function. We don't worry about
this right now. We're going to be
delving deep, deep, deep into these things
in the upcoming section. But just so you know,
this is a prompt, What do you want to print out with the input you need to give an indication to the user
what they are trying to add. We're trying to add a name
in here, for example. If I try something
different, like for example, Kalen, there we go,
a head and enter. It tells me hello there, Kalen. If I write, click and I run
again and it's Santa Claus. That's how you
write Santa Claus. I'm not sure. There we go. Hello there, Santa Claus. Okay, I hope that makes sense. As you can see,
these are variables, and we can get input
of these variables. We can cacateinate all
of these together. Time for a challenge. Your challenge is going to be to print out your own input, create two new
inputs for the user, from the user, a
string and a number. We want one to be a string, the other one to be a number, and can catinate them
together and print them out to our console. Pause the video right now
and go do the challenge. Okay, welcome back. How did you get on with that? First things first, add a print, and then in here I'm
going to say print out, please type your
name and a number. Then in here I'm going
to say name is equal to input name, two dots. Duplicate this with the
control D number number and then I'm going to print. And here I will say that
I want to have name plus just eight plus number
plus chocolate bars. There we go. I deliberately
use double quotations and single quotations
just so you know that we can interchange them in here. When I write Click
and I run in here, let me just type anything. Okay. Hello there. Then please type
in your name and a number. The name will be, let's
just stick with Michael. The number is going to be 129. Hit Enter. So Michael just ate 129 chocolate bars,
which is very bad. So I hope you understood
how all of this works. Always try to do the
challenges please. If you think that you
cannot do the challenge, if you feel that it's
too hard, I don't care. Just pause the video and
try to do your best. It's much better for you
to try to do your best. Fail at it, and then see the solution because your brain has already thought
about things. It will help you learn faster. Learn better, clearly understand what happened and maybe
some of the questions. If you just skip
over the challenges, you might not even
know what you don't know when you do a challenge
and you fail at it. If you take like
five to 10 minutes to do the challenges
and you fail at it, at least your brain worked. You're not just watching me
doing this stuff on my own. I'm a great programmer already. I don't need to do these. You're not here to
watch me do this stuff. You are here to learn. So please, every single
challenge, Pause the video. Do the absolute
best that you can. And of course, at the end, leave my review, because
I deserve one. Thanks so much for watching, and I will see you in
the next video, where we are going
to be learning about special characters. So I will see you then. Bye bye.
9. 3. Special Characters: Welcome back my favorite python programmers to a
brand new video. And in this one
we're going to be looking at special characters. These are sometimes also referred to as
escape characters, and these are special
characters that allow us to do certain
things to strings. To demonstrate
this, I'm going to create a new Python file. Sometimes if you don't see
the Python file in here, you should just simply click on the string variable
or in the project, or not on the string variable like anywhere in
the code inside. And then go to File New. And you'll find your Python file and I'm going to call this the escape underscore
characters and hit Enter. In here, I'm going to create the split variable and I'm going to say that this split variable
is equal to, this string, has backslash t, has several back lines in it. There we go, This string, see it catches it immediately. Very nice. And I will
print out the split. When I write, click and I run, look at the output that I get. This string has
several lines in it. Now you might be thinking, what does that matter? Like
I could have done this. Okay, let's remove these s, we don't need them. We
can write it like this. If I write, click now and I
run and oh, oh, oh, okay. So unless you add
the backslash n, which means a new line, that's why it has an n in
front of it means new line. That is the only way that
you can create the split. Now, there is another way, but not right now. Later on I will tell
you what it is. So using the backslash n is
how you create extra spaces. Now let's look at
another example. I will add a print in here and then I will call this tabbed. Equal to this string
is backslash. Tab. Backslash t several times. Tab is written incorrectly. Can you okay Tab, double B. All right. I think, there we go. And I'm going to
print out the tab. All right. Click and run, and boo, look at that. This string is tabbed. Notice in here we
have an extra space. It's stabbed to the front. Now, I think these are
pretty self explanatory. There's nothing too
much in here to say. Let's continue on and I'm going to write the following sentence. I'm going to say he was
screaming, No, please. It was Jordan. He's the one who
jumped notice in here, we have lots of problems. Some of you have already seen. Of course, if you watched the previous video
and you should have, you'll see that we start with
a single quotation mark. We have a double quotation mark, but then we have a single quotation mark
which breaks everything. Then another single
quotation then, so then double. It's
all over the place. If we have a line that
has double and single, some of you might have already asked yourself that question. What do we do? Well, we have the backs
that we can add to this single quotation mark and to this single quotation mark, and to this single
quotation mark. And now we have everything
working right click and run, and boom, we have
double quotations and single quotations
inside of our string. The backslash allows us to have this output working neatly. I'm going to duplicate
this line of code, and I'm going to change
this from a single to a double quotation
mark on each side. Let me try this again because
it did not look clean. Double double quotation.
And there we go. Now we have the
problem on the inside. We add the backslash here
and the backslash here. And if I write, click and I run, there we go, I get my output. And I don't even need or
the backslash in here on the single quotation marks
anymore because they are surrounded by the
double quotations. All right, right click and run and everything
works perfectly fine. So I hope you understood. I hope you are not too confused. These are the
special characters. You're not going to
encounter them too much. But please remember, we will be seeing them down the line. I will be using
them. If I remember, I will tell you why
we're using it. Maybe I won't. But
after you've seen this, it's your responsibility
to recognize them down the line.
Before we move on. Aber of a challenge
to print out a link. So print out the following
link to your console using the print.python.org slash
terminator slash, nothing else. Of course, I'm not sure, but I don't think this
leads to anywhere. But I want you to
print out the link. Nonetheless, the trick here is to print out the backslash. We're trying to print
out the backslash. How would that work?
There are two ways. One is very obvious, the second one is
more tricky and needs a bit more research. Pass the video right now
and go do the challenge. Okay, welcome back. How did you get on with that? I hope you tried your
best to do it in here. I'm going to print out python dot or terminator back. Nothing else matters. As you can see in here, this is where the problems comes in. If I write click Run,
this is what I get. Python.org and then terminator and else what is the problem? Well, I deliberately
created this type of link in here because I wanted to have
backs which created the tab. And then the backslash n, which created a new line.
How do we fix this? The first way is to have a
backslash to the backslash. Now, right click and run. And there we go, we have the
link printed out properly. But there is also
a different way. I'm going to duplicate
this and remove. We can add an R
at the beginning. As I told you, this will require more research
on your part. But basically the R, make sure that we
printed out as it is. Or it tells the function that this string should
be printed out without special characters
or to be more precise, the R stands for raw. You print out the raw string
that you have in here, ladies and gentlemen,
I hope you enjoy it. In the next video,
we're going to be looking at variables and their types and
we're going to be understanding better
how these things work. Thank you so much for
watching and I will see you in the next video.
Bye bye for now.
10. 4. Variables and Types: Welcome back my favorite python programmers to a
brand new video. And in this one we're
going to be talking about variables and types. First of all, let's try and explain what variables
literally or actually are. Let's just imagine a box. Variables are like boxes. Imagine we have a box. That box has a name. The name is lives. What
do we do with this box? We put in three
inside of that box. Now we have a box
that has three in it. The same concept holds
true when working with variables in Python and any other programming
language for that matter. In Python, we create a variable that has the name
lives, so that is the name. And then we have the data that we want to put into
that variable, which in this case
would be three. Now, in Python, if you're coming from a different
language in Python, you do not need to specify
the type of variable. You only send in the data. And based on the data
that you've sent, the variable will
take the type of it. Let's talk about some
different types of variable. First of all, we
have the type float. For example, velocity velocity can just be two or
three, or four or five. It can be 4.87 0.96 0.54 100.75
whatever that number is. It could be a float. Then we have the Ty
bullion for example, if we want to check if
something is dead or not, it can be equal to four. Is that can be equal to seven. It has to be either
true or false. The bullion is going to be very handy in the upcoming lessons. And then finally,
we of course not. Finally, we have many,
many types of variables, but these are the most
common ones that we're going to be using in
the upcoming videos, which is the type string. It's a string of characters, for example, my name, this is the name
of the variable. And then we have a
string of characters. The characters are M, I, C, H, E, L, form together,
string together, create the name Michael. Let's stop talking about theory and let's
go ahead and take an actual example
and see how all of that operates back in here. I'm going to create a new
Python file that I'm going to call variables in here. I'm going to have age equal 25 and I will simply
print out the age. Nothing too special in here. Just when we run, you can see
that we get the number 25. Nothing too crazy, right?
We've done this before. Let's now print out
something slightly different and you'll get why
we're doing this in a few. I'm going to print
out the type of H. Now if I write click and I run, I get the class in
stands for integer. These are whole numbers
like minus one, minus two, minus 312340, et cetera. These are all
considered integers. If I type in 25.6 for
example, look at that. Now I have a flat, no longer an integer, it is a float. Now notice what's
going to happen now. I'm going to add two single
quotation marks, around 25. And I want you to look very carefully at what's
going to happen. Look, when I write
a click and I run, I get the same output, 25.6 But the difference is that now the
class is a string. This is very important
for you to know because sometimes things
are not the same. Maybe you would
think that, okay, 25.6 should always
be a float, correct? This is the output.
Look at that. You tell me, Michael,
25.6 we don't care. Is it a float? Is it
a string? Who cares? You should care because a lot of things can happen
down the line. So having the ability and the flexibility of changing
the type of your variable by simply changing the data
that you are giving to said variable is both a blessing and a curse
at the same time of Python. So you have to be very
careful when you change the type of variable or the data that you're sending to
the variable, okay? The variable type will change with the data
that you're sending. But if you're using that data in a certain way or that
variable in a certain way, this can cause a lot of
problems down the line. And we'll see a lot
of those problems as we progress
through the video. Now it's time for a bit of
a challenge for you to do. Your challenge is going to be to create and
print variables. First of all, create a float, an integer, and a
bullion variable. Print them out using the print. Print out the type
of each on a line, and make sure they all
match what is given to them past the video right
now and go do the challenge. Okay, welcome back. How did you get on
with that in here? A print and then a number float equal to 70.4 b. Then we're going to have a t and we'll just have like 72. We're going to have
a string. A string. And it's going to be, I love this master class and
I will leave a review. This has nothing to do with
what's happening right now. This is just off
the top of my head. Okay. So yes, exactly. 55 star review. Okay. With a few exclamation, with a few exclamation marks. Okay. Just off the
top of my head. And now we're going
to print out the type of a number float, Duplicate this, a number, Duplicate this and a string. And the bullion of a bull. Sometimes bullions are
referred to as bull, we'll just say true. Let's just also
create one that's false since there are only two. A false false bull because you don't want
to have the same name for two different variables, A, B, a false bull. Right click and run. As you can see, we have a float, a integer, a string, a bull, and a bull. Ladies and gentlemen, thank
you so much for watching. In the next video,
we're going to be looking at something that
we need to watch out for, especially with our new found
ability to change things. Thank you for watching.
I will see you in the next video.
Bye bye for now.
11. 5. Something To Watch Out For: Welcome back, my favorite
Python programmers. In this video, we're
going to be looking at something that can potentially
break our program. What I'm going to
do is right here at the top I have the H correct. I'm going to create
another variable and I'm going to call it name. And I will say that the
name is equal to Michael. Okay, so let's say
I want to print something out to the screen and here I'm going to do that. I will first of all add the sprint and then above it I'm going
to do the following. I'm going to print out the
name and cactinate it with is, with a space on each side, plus age plus years old. This looks like a very
innocent sentence. 25. Let's just make it 25 red click
and run. And there we go. Michael is 25 years old. He needs a space in here. And now everything
should look good. Correct. Michael
is 25 years old. No problem anywhere except
for, not 25 years old. But that's beside the
point. The problem in here will come up if I try to do the following. Now look, even before we run, we already have a highlight. Now, we've never seen
this highlight before. This is an expected error. This could potentially
break our code. It's more serious than
a normal warning. Always take heed whenever
you see something like this. Now if I write Click and I run, I do get an error. And
what does it tell me? It tells me that there
was a type error and can only cactinate STR, meaning strings, not integers, two strings, the
age was a string, we concateinated it,
and then we decide, you know what, I don't want
to have it as a string. I will remove it, and I
will make it an integer. And Python allows
you to do that. It's very simple, very easy. But these are the types of problems that we
can potentially run into if we just try to change
things out of our own will, please we, even though you have the ability to change the type of your variable
whenever you can, Python gives you that ability and we're very grateful for it. But Python also considers
you a grown adult. They consider that the person
that's writing Python code should know what they are doing and should not do
things like this. So please be very careful when changing
the variable type. Thank you so much for watching. This was a quick video, there's not even a challenge in here. In the next video,
we're going to be looking at number operators. So we're going to
look how we can operate on numbers
using different pluses, minuses, divisions,
et cetera, et cetera. I will see you in the next
video, and bye bye for now.
12. 6. Numbers Operators: Welcome back my fellow
Python developers. In this video, we're going to be looking at number operators. We're going to create
a new Python file that we are going to call numbers
underscore operators. Boom. I'm going to create the first variable
which is going to be a equals to 25 and
B equals to five. Then I'm going to print
out A plus B, double that. Then a minus duplicate that A times duplicate
that A divided by B. Control D to duplicate
just in case. And then A divided divided
by B and then a percentage. This is also known as modulo, if I write Click and I run, this is what I get. 403-01-7057 0.0 7.0 These
are pretty obvious. 35 plus five is 40, 35 minus five is 30, 35 times five is 175. I think the divided
is a bit weird, because it gives us 7.0 Whenever
you divide two numbers, even if both of
them are integers, the return type is always
going to be a float, unless you give it
a second divided, which removes all
the floating points. For example, if I had 35/4
you can see that I get 875. And then when divided
divided, I get eight. It does not round to
the closest number. This is a big confusion
that a lot of students have. It
does not round. It simply removes everything that's after the floating point. Even if you have
let's say 9.99 9999, the answer is not
going to be ten, the answer is going to be nine. Before we move on, let's
go ahead and print out the type of a divided by B. Then the a divided divided by what do you expect the
output is going to be? What do you think the types of these two are
going to be like? Right click and run
float and integer. Okay, I don't think there's
too much to say in here. I mean these are
pretty basic stuff. Just know that we can do
arithmetics inside of Python using all of these
different things without any further ado. It's time for a
bit of a challenge for you to operate
on these inputs, on the input, not these inputs. Get two inputs from the user. Use addition, subtraction,
multiplication, and division. I apologize, I did not talk
about the modulo in here. So the modulo gives
us the remainder. So for example, 35/4
the remainder is three. If I have it divided by five, there is no remainder. Okay, so the remainder is zero. There's nothing
that's remaining. 32/5 the remainder would be two, so it's the remainder what is remained
after the division. Use addition, Substraction,
Multiplication and division Research how you
calculate the power in Python, for example, two
numbers to the power. There is a small hint
that you need to know and that is the int input. We are used to
getting the input, but we haven't used
the t on it yet. And you'll see why
this is so important, Put the video right now
and go do the challenge. Okay, how did you
get on with that? So I am going to come in
these two lines out in here. Instead, I'm going
to say that a is equal to an integer input. Oops, Duplicate this
input. There we go. Now if I write, click and I run, let's say 6.10 Hit Enter and
boom, this is what we get. 16 -4,600.6 0.6 These are the various
additions and divisions that we are using,
something in here. Why did we have to convert
it into an integer? Well, I'm going to show you. Let's say I remove this
from here. By the way. The end, if you hover over it, it says creates and
return a new object of the same type, or
the integer type. Whatever you give it, it
converts into an integer. What's the problem in here? The problem in here is that
we've already learned that we cannot concatenate
two different types. Meaning that when you get
the input is a string. That is why we have
to convert it into an integer because
a is an integer, when we do a plus B,
it does not work. We've already seen
that in variables. Right here, you can
see H does not work. You cannot concatenate a string, an integer, with a string. And the same happens in here. We get the input a, we convert it into an integer, and then we are adding
it to B, which is an. Should be an integer. But now, because we don't have the
int function around it, it stays a string. And the same holds
true for a minus B. Now, a times B does work because you can multiply a
string with a number. I will show you that
in later videos. We also cannot divide, of course, and we
cannot take the module. It's very important
that we do have int around our input
in order to be able to convert it 52.10
we get these outputs. Now last part, research how
to calculate the power. Now some of you might
have found some function, some of you might have found
it easier than others. The easiest way is to simply
add an extra star in here. And this actually creates, let's try numbers.
Boom, there we go. This is 14 to the power
three, or a to the power. Now, before I move on, there is something that you need to know, and that is that, just like in regular math, we also have operator precedence when working with Python. For example, in here,
if I do the following, if I print out a plus B divided by three minus
three multiplied by four, we all know that
the division and the multiplication go before the addition and subtraction. Now if I write Click and I run
and I get a to be equal to 2.1 you'll see that the
answer is -9.666 Why? Let me try this again to
pick some easier numbers. Let's pick three because it's divided by three minus nine. What happened? We have three, this is one plus
A, this is three. Minus three times four. We do three times 412 minus the three that
we have in here. So we get minus nine
operator presidents. Precedence also applies in here, but we can change it
using parentheses. I can add parentheses around
three multiplied our, actually, this doesn't
make any sense. Let's add parentheses
around A and B. Now, the answer was minus nine, when we had 2.3 Let's
strike this again. 23. Boom. There we go. We had minus nine. Now
we have -10.333 Why? Because two plus three
is 5/3 I have no idea. Minus three times four. There we go. We can add parentheses to change
things around. Thanks so much for watching.
I hope you enjoy it. And in the next video, we're going to be looking
at string data types. We're going to be delving deeper into strings and what they are. Thank you for watching new.
13. 7. String Data Type: Welcome back my favorite Python programmers to a
brand new video. And in this one we're
going to be looking at string data types on surface. Strings might be
very simple to you, but strings have something
hidden deep inside of them. Let's go ahead and get
started to explore what these hidden
secrets of strings are. First of all, I'm
going to create a new Python file
that I'm going to call string data type. I always add an underscore
inside of my file names. You don't have to
add it sometimes when you can have spaces
inside of your files. But if you want to import these files to a different file, you cannot unless they
have underscore in them. The best conventional
way is to use underscores and to have
no upper case letters. I'm going to hit Enter. In here, I'm going to create
the following message. I'm going to say the
message is equal to, Python is a great language. Python is a great language. In here, I'm going to print out the message. Pretty simple. I don't think there's going
to be any confusion here. When I write, click and I run, I get Python is a
great language. Perfect, I just printed
out the message. But did you know that I can access individual characters
using the message? I can print out message
at position number two. Let's look at what's going to happen if I write,
click and run. I get. Now where
did this come from? Well, if we look right here, we have P y. Now you might be
thinking, well, is one, y is two and is three, but I used two in here. How does this work? Well in Python and in most
programming languages, when you want to
count something, you start at zero. Here, I'm going to add a common. This is a common, by the way, when you have a hash tag, this is zero, then
12345. Look at that. At position number two, I have, what would I get? For example, at
position number four, I can hear you in
the back saying I get o and you would be correct, you get, let's continue
naming these 56789. And then I'm going to
add another level of comments that will be in here. For example one, and then
012-345-6789 and then 012345. And here I will add
a one, sorry, two. Now, if I tell you what would be the number or what would
be the character at 16, what would you tell me it's
going to be because it's 16. Well, now, if I tell you 11, what will be the answer? Oh, nothing. It's not, it's actually a space. The space or the empty space is also considered
to be a character. This is what the string
hides under its surface. It's called a interval. When iterable is a item or
a data type such as lists, topples, dictionaries, sets,
and lists, also ranges. We'll see all of that
in upcoming sections. Don't worry about it for now. Just know that you
can go through your string using indexes. These are called the indexes, the on the zero, the 11, When you are able to access them using the square brackets. These are indexes. Okay?
So I hope that's clear. I hope it's not too hard, because I want you to
really understand it before moving on to the challenge to print out a
message differently. So I want you to use
the message that we have to print out
another message. And that other message
is going to be, you are hot using the indexes of your
original string method. So pass the video right now
and go to the challenge. Okay, welcome back. How did you get on
with that in here? In order to print out U are hot, obviously we need to find the Y, O, U, et cetera, et cetera. So I'm going to print
out message brackets, and then let's start with the U. The U is at one plus message, the O is at four. Then plus message,
the U, we need a U, it's at 22, plus message, we need a space. A space could be found at six. And there we go.
Excellent. I'm going to hit enter in here. And don't worry, this is not
going to break anything. It will stay the same in here. Message, open this up, you are A, we need
an A. Where's the A? It's at ten plus message. We need a U R. We need an R. Where's the R? At 13:13? Plus the message to 213. Where's the other U R? You need an E, it's at 14. Let's see what we have so far. Practically can run.
Okay, you are excellent. Now again, we need to have
a space with the six. Now for the hut, I'm going to find the H, which is three plus these four, plus the message at 02:16 Right the click
and run and there we go. You are hot. Thank you so much
for watching ladies and gentlemen. I
hope you enjoyed. In the next video,
we're going to be looking at negative indexes, so we can actually go through
this going backwards. Thank you for watching
and I will see you in the next video.
Bye bye for now.
14. 8. Negative Indexing in Strings: Welcome back my favorite Python programmers to a
brand new video. And in this one we're
going to be looking at negative indexing in strings. Just like we have
positive indexing, where we use positive numbers, we can also use
negative numbers. Let me show you what I mean. First of all, I
will select all of these lines and hit
control forward, which will comment
out everything. Again, select all of these. Hit control forward if you
ever want to uncommon them. You can also hold down
control forward slash while selecting
these lines of code. Control forward slash. And now in here
I'm going to print out message at
position minus one. What do you think the
answer is going to be like? Well, if you said it's going
to be E, you are correct. Once we start indexing,
going backwards, we start going from the end of the message or from the
string to the very beginning, for example, minus eight. What would that give us?
Right click and run. I have no idea. I generally do. Don't I mean, 12345678?
Yes, exactly. So on the L, so for example, if I wanted the, I would do minus ten because
this is minus eight. Minus nine. Minus ten. So right click and run. And there we go. We get the, so we can do negative
indexing. Pretty simple. Nothing too much in here.
I think you get it. I don't think there's
too much complications with how this all works. It's exactly like using
the positive indexes. It's just negative
the other way around. So with that out of the way, it's time for a bit
of a challenge. Your challenge is to print
out the message differently. So I want you to use negative indexes to print
out the same message. And that message
is, you are hot, but I want you to print it out now using negative indexes. So pause the video
right now and go do the challenge. Welcome back. How did you get on with that? A lot of you might have went through this in
the very hard way. Meaning that you want to
find, for example, the Y. You have to count it
all the way to the Y. That is probably the
non cheating way, but I have a cheating way. I already have these
messages in here. Let me actually copy this. Mm hmm. And based it in here. And some of you who spent
a lot of time on this are already angry because
they feel that there's an easier
way of doing this. The easier way is since we already have 26
characters in here. And why do we have
26 characters? Because we start at
zero and end at 25, which means we have 26. What I can do is I can add
-26 to this immediately. Now I can calculate it, this is -25 or you can use
a calculator for example. And I calculate Ok, 13 -26 et cetera, I get -13 it will be -13 and
here it will be minus minus. But I can keep it as it is, so I can keep the equation inside without having
to change anything. And I will, you are hot
using negative indexes, I have a problem -13
-26 is out of range. I'm so glad that I
actually got this problem. The issue in here is
that I can maximum, for example, in here, let me, let me just remove this and show you that this
actually does work. Okay, there we go. You are hot. The problem is if I go to -22
for example, what do I get? I get the O, so I'm right here. If I go -25 right click and run, I get y, that's great. -26 I get correct,
Everything is good. But if I go -27 I am now outside of the
range of my string. So I am again, There's no more minuses
where I can go. And the same thing
holds true if I try to go in the
positive direction. So I know that the last
index is 25, where I get, but if I try to go 26, I am now outside of the range
and this no longer works. I hope you understood. Some of you might not have even
heard the last part. Some of you might
have clicked off. And now you're like,
you know what, I don't want this course, I
don't want this master class. And you're using the slur words that I'm not going to repeat in here because of
what I didn't hear. Some of you had to calculate
all of this stuff, or some of you might
have found this. I have students that did find
this equation on their own. So congratulations
to those who did. Those who don't feel bad, You still have a lot of
challenges ahead of you where you can prove
yourself in them. So thank you so much for
watching. I hope you enjoyed. And in the next video
we're going to be looking at slicing strings which is using the indexes not to extract only
a single character, but to extract, extract an entire slice out
of your strings. So, I will see you then. Bye bye for now.
15. 9. Slicing Strings: Welcome back my favorite python programmers to a
brand new video. In this one, we're
going to be looking at slicing our strings. Let's go ahead and get started. I'm going to create a
new Python file in here, or actually we can
stay in the same file. No need for a new file. I'm just going to
comment all of this out and then start a new. I'm going to print out
the following message. Open up the brackets, and this time I'm going
to say zero, column five. Now when I write
Click and I run, I get the word pytho. As you can see, this is
called a slice where I have the starting and then I
have the end that I want. Now you might be saying, wait, five is the end. Is the end. Why do I
not have an n in here? Well, that's because the rule here to keep in mind is that it's up to, but not always. Keep that in mind when working with almost anything in Python. It's always up to,
but not in up to, but not including if I
wanted to have Python. What should I write in
here? Yes, I can hear you. It's six. Now I get
the full word Python. And notice that there
are no spaces in here. Let's look at slicing just
in a more theoretical way. Here we have the string
that we want to slice, we have the start
stop and the step. We haven't seen the step yet, We're going to be seeing
the steps in later videos, but for now, this is
the starting index, this is where we start slicing, this is the stopping index
and it's not included. And then we have
the step through, what are the steps
that we are taking? For example, right now
our step is one because we're going y H O. And you'll see we can
use a step of two, for example, to have instead. We'll see all of that in
later videos, but for now, let's focus on using the slices. Without these steps, it's hard enough to
understand the slices, the steps right here message. If I do the following 12, 17, what do you think the
output is going to be? If I write, click and I run, I get the word, great. Because I start at
12 and I stop at 17. There we go. And no
spaces in there. Now my question to you is, what would I print out if
I type in the following? What do you think
I get? If I write, click and I run, you'll see that I get
the word by thumb. Why is that? Well,
when you don't specify the beginning or
you don't specify the end, you simply start from. Then if you don't
specify the beginning, you start from the beginning. And if you don't
specify the end, you just go until the very end. So I hope you understood, I hope it wasn't too hard. I'm going to issue you a challenge where you will
have to print using slices. So print out the word language
by slicing our string. And there are two
methods of doing it. So pass the video right now
and go do the challenge. Okay, welcome back. How did you get on with that? We need to use slicing. Some of you might have used the regular extraction of
variables of using the indexes. No, we need to use slicing.
It's pretty simple. I think message in here you
have to go from number 18, right, because we start at L, L starts at 18 or the
index of L is at 18. And then we need to
go until the end. So I can go 25, right right click and run
and oh, where's the E? 25 does not work
well in this case. I can use 26 even though I got an error on 26
here, if you remember. But when using slicing,
it is manageable. Now if I go 27, as you can see, I
still have everything. The slices isn't as bad. Let me try, for example, 30 and I write Click and
I run, boom, there we go. I still have language
when using slices, there's no worry of going
outside with the index. That is the first method, 18 to 26, I get the language. The other method is 18 and
nothing because as I told you, I can go until the end when
I write click and I run. I also get a language when I don't provide the beginning
or I don't provide the end. I simply start from
the beginning or I go until the end before we move on. I still have a few tricks
that I want to ask you. A few quizzes if you'd like. For example, what
would I get if I do the following message column 18, plus message brackets 18. What do you think the
output is going to be? Well, if I write
Click and I run, I get Python is a
great language. Why is that? Because in here I start from the beginning
and I go until 18. In message, I start from
18 and I go until the end. I hope that's understood. Quiz that I want to ask you. What would we get if I
do this just a column? Well, some of you might
have answered that we get the entire message. It's because I start from the beginning and I
go until the end. Thanks so much for watching. In the next video,
we're going to be slicing using negatives, which is going to be
a bit of a headache, but it's going to be very
important for us to get used to everything that's happening under the surface in Python. Once we finish this section, you're going to have a
very solid foundation, not just for Python programming, but for programming
philosophy in general. So thank you for watching. If you have the time,
leave me review. Wherever you're watching this
or you can just contact me. Tell me, hey Michael, like I don't get anything about this master class, please. Can you help me I'm like, yeah, of course What's the problem? I don't know why I said
that. Thank you so much for watching and I'll see
you in the next video.
16. 10. Slicing with Negatives: Welcome back, my favorite
Python developers. In this video, we're
going to be looking at sliding using negatives. Again, I am going
to comment all of these out and I'm
going to start a new. Now you can see that
we have a lot in here, but still we are going to
be using the same message. So it's worth staying
in the same file. If you want, you can dissect
it into multiple files. You can do whatever you want. As long as you keep
everything neat and clean. If you ever want to
go back and look at your files from time to time, let's go ahead and get started. First of all, I
want to print out the message from
-14 to minus nine. What do you think the
output is going to be? If I write, click and I run, I get the words, great, how is this working? I'll start from the end. 123-45-6789 101-112-1314
-14 is at great. And then 123-45-6789
minus nine is at seven, which is the space right here, -14 to minus nine is the
slice that gives us great. Now what would happen
if I, for example, do -14.4 bit weird, right? If I right click and I run, I don't get anything
that is because -14 is right here on and
four is right here on A. You might be thinking, well
maybe that's not the problem. The problem is that you just can't use negatives
and positives, but you can if you do
-14 17 is right here. Right click and run. You get the word.
Great. It's not about that you cannot slice from a negative
to a positive. It's about, you cannot
slice going backwards. For example, I cannot print out the message from,
let's say nine. I mean 19 to, I don't know, 15. That is not possible. I cannot go backwards
unless I use a step that we're going to
learn in the next video. But for now you cannot
going backwards. You don't get
anything printed out. But if you, for example, let's say I start at minus,
just like I have in here. -14 is at 17 is at the space. I'm not slicing backwards,
I'm not going back. I sing forward, I
cannot slice like this. I can only slice like
this from left to right. I can slice from right to left. I cannot slice and
that is the only rule. Before moving on,
you have a bit of a challenge to print out
using negative slices. Print out the word language
by slicing our string. But this time you can only
use negative slicing. And a small warning
that there are a few traps in here that
you should try to avoid. Pause the video right now
and go do the challenge. Welcome back. How did you
get on with that in here? If I try to do the following, I'm trying to print
out the language. Some of you might have been
tempted to do the following. Minus eight and then
minus one, correct. The only issue in here is
when I write click and I run is I do not get the E.
So how do I solve this? Well, there are two ways I can. For example, use
00 is right here. If I write click in Iran, it does not work. Why is that? Well, because the way it operates is it
thinks that we are at minus eight right here on the L. Then we're trying
to go backwards. So does not work. That is the second trap. Now the last solution or
the only solution is to actually do the following from
minus eight until the end. And when I write Click in Iran, I get the entire language. So thanks so much for watching. I hope you enjoy it. And in
the next video we're going to start using the step
in order to slice. And I will see you in the
next video. Bye bye for now.
17. 11. Using a Step while Slicing: Welcome back my favorite
Python developers. In this video, we're
going to be using a step while slicing. Finally again, I
will comment out, I'm going to start
from the beginning. In here I'm going to, excuse me, print out message and I
will start from zero, go to 17, and use a step of two. I will then duplicate this, and I will use a step of three. So what do you think
I am going to get? Some of you might have
thought about this, some of you might have
already used this. And I'm very proud of you. So when I write Click and I run, I get po saget and ga. My pronunciation of these ancient symbolic
words is going to be weird. But what's happening in
here is that I get P, Y. I'm using a step of two. And when in here I'm
using a step of three, I'm skipping over
two letters in here, I start with Y, H, O, and space IS space, that's why I have
two spaces in here. Then I skip over
the And space and I get and then skip over
the R and E and get A. So that is the basics
of having steps. Now with that knowledge,
and by the way, when we don't specify the step, we just default to one and
we just get the normal step. Let's now find a useful
use of these steps. I'm going to create a
new file and call it the data coming in here. I'm going to have data
underscore underscore N, And it will be equal, it
will be equal to 63548. You don't have to write
the exact same numbers. Semiclumn 6957 forward 3267, multiplication 48 to 926, square bracket 36 14. And then finally we will
have the plus sine and 406-70-9907 I mean this
is data coming in, but as you can see, we have corruptions
inside of it. We have, we have
multiplications, we have weird symbols. What we want to do is we
want to create a filter. What we'll do is
we want to extract all of these separators
and print them out. Okay? So that then we can
use it as a filter in order to filter out all the bad and negative
things in here. So what I want you to do is I want you to
do the following. To print out the separators. I want you to print
out the separators. I mean, I don't know why I
have that point in here. Use steps in slicing
to avoid the numbers. So pass the video right now
and go do each challenge. Okay, welcome back. How did you get on with that? First of all, I will print, obviously, data coming in. And now we need to understand
what the slices will be. Where do we start? Some of you might
have started at zero, but it's not at zero
where we want to start. We want to start at one. Why is that? Because we
want to, first of all, catch the comma, then to
where do I want to go? Some of you might have counted how many characters
we had in the string, but there's a much easier way, and that is just
going until the end. Now the final question is, what step do I need to use? Well, if I start here and I want to skip
over four letters, it means that the
step should be five. Now when I write
click and I run, you'll see that I get all
of the symbols printed out. And now I can use this filter in order to put it on
the data coming in. And if for example, I find this parentheses or this
one or this one, they will all get wiped. So ladies and gentlemen, thank you so much for watching. In the next video, we're going
to be looking at slicing, but this time we are going to be going backwards
with the slicing. So I will see you
then. Bye bye for now.
18. 12. Slicing Backwards: Welcome back my favorite
Python developers. In this video, we're going to be looking at slicing backwards. And it will be the last lesson
about slicing, hopefully. So let's go ahead
and get started. First of all, I'm going to
create a new Python file that I'm going to call back
underscore slicing, and I will, because
Intellij froze, I will use the
power of editing to see you in just a few seconds. Okay, welcome back. Letters equal to A, B, C D E F G H R J K L M
N O P R S T U V W X. As you can see, look
how helpful IntellG is. I forgot X, Y, and Z. So if I write Click
Show context, okay. It just tells me that I forgot
a few letters. So Y and Z. No, there we go.
Now what I want to do is I want to create a
variable that is the reverse. It's equal to letters. And now I'm going
to start at 25, go until zero, and have
a step of minus one. What will this do?
It will start from the last one and
then go to zero. With a step of minus one. It will reverse the letters. If I print out reverse, if I write click, you'll
see that I get Z, Y, X, U, T, S, Q, Q, P, O, N, L, et cetera. But as you can see, we
have the A missing. How do we solve this issue? You should know by now. Come on, I know you know
it. What do we do? We'll remove this in the middle. And now we're right click
and we run and we get the A. Why did we not get the
A when we use the zero? Because it's up to
but not including, we don't include A
in the beginning. I hope you understood
how this works. This is the basics of it. This is slicing,
going backwards, when we use a negative step. We've looked at indexing, we've looked at slicing, we've looked at slicing
using negative indexing. We've used steps, and
we've used negative steps. As a final challenge to
this entire new concept, I want you to print out
the following three. I want you to print out IJK using positive
steps and indexes. Positive steps,
positive indexes U TSR. Using negative indexes, I mean negative steps or the
step should be negative, the indexes can be positive. Then the last eight
characters in reverse order using negative index and
a negative step, okay? The last one is the
most important one, negative index and
negative step. The second one only
negative steps. And the first one using
positive steps and indexes positive video right
now and go do your best. Okay, welcome back. How did you get on with that? First of all, we had
a print and then I will create IJK
equal to letters. And this should be pretty easy. We simply go from IJK. Wait, let me just double check. 12345678. Wait to 012-34-5678. Yes, eight until 11, and we print out. Ijk. Ijk. There
we go. Very nice. Now, let's do UTR and it's
going to be equal to. Now, we said that UTS R should be using
the negative step. It means that we are going backwards since we only need
to use positive indexes. So this means that
we have 0123, 4567, 8910, 1112, 1314, 1516, 1718. 1920. We start at 20 and we need to go back four
steps, which means 16, I will have letters and
we're using a negative step, so we start at 20, go to 16 and it's not
included and minus one. Let's just check if
this is correct. Uts R, right click, Run. There we go. Very nice. And why is it telling me in the word typo? Okay, no worries. A typo in the word. Finally, we need the
last eight characters. We want to have the
last eight characters with a negative step, with a negative index. How are we going to do that? So first of all, we need to go to the end. So we need to get to that, we need the last eight
characters, so 12345678. Okay, so first of all, let's set the negative
step minus one. So I am going backwards. That means I need to start at minus nine and
get to the end. No, I need to get to minus
nine in reverse order. Okay, Now it makes
sense. In reverse order. Step minus one and a negative
index minus nine in here. And we want to start
at the beginning. If I print out the
last eight characters, right click and run,
There we go, 12345678. All right, so ladies
and gentlemen, thank you so much for watching. In the next video, we're
going to be looking at a few string operators
and we'll see how we can print out numbers
with strings and we will be done with this
introductory section. Thank you for
watching. If you're enjoying the scores,
leave me a review. If you're not doing
the challenges, this is the time to
start doing them. Thank you for
watching and I will see you in just a few seconds.
19. 13. String Operators: Welcome back my favorite Python programmers to a
brand new video. And in this one
we're going to be looking at string operators. Just like we have operators
format like the plus, multiplication,
division, et cetera, we also have ones for strings. I'm going to create a
new Python file and call it underscore operators here. I'm going to create
string number one, String one, which is going
to be equal to one space. I will duplicate
this a few times. We will have string
2345 in here. I will say does not simply walk into Mordor. If you're familiar with
Lord of the Rings, you might know this mean. If you're not, I'm sorry
that I'm such a geek, then we're going to print
out string number one. And actually, I'm not
sorry for me being I'm sorry for you not having
watched the movies yet. String number two,
string number three, string number four, and
string number five. These are strings being concatenated and we've already seen what happens when we run. You can see that we
form a single sentence, which is one does not
simply walk into. Now let's add a print in
here to separate the lines, and let's do the following. I'm going to say, hey, there my name is Rodo Baggins. As you can see, we
are not providing multiple variables or
multiple parameters to our print in here. Unlike what we did, for example, in this case where we had
a comma between each of our parameters being sent
to the print in here, there are no, this is a single variable in
here that's being sent. So when we run, you can see
that we get the following. We do need to add spaces in between in order for
this to be readable. As you can see, if we want to print multiple strings
next to each other, we don't have to add a plus. They just get added
on their own, or they get concatenated
automatically. We can also use the
multiplication. So for example, in
here I can print out string number five
multiplied by three. And what do you think the
output is going to be? Think of it for a
second. Right click. And I run, I get
mordor, Mordor, Mordor. You can multiply the
number three times. I mean, you can multiply
a string by a integer. Now, what do you think the
answer in here is going to be? Well, you might have already seen that we
have a highlight, which means that we will
probably get an error. If I hover over it, it
says that it expected STR, meaning string, and got integer instead, limited by the end. If I write click and I run, I get the error telling
me that you can only concateinate a string and
not an integer to a string. This is an integer and this is a string because the
multiplication happens before. How can we fix this? Think of two ways that
we could fix this. 321, I can add
parentheses in here. Now, the three plus six is going to be equal to nine
string five multiplied by nine, we will get to nine mods. That's one more mordor
than we should have. Now the other way of fixing this is we can change the
six into a string. Now when we right
click and we run, we get more mod and
then six added to it. Okay. Now we could also do this in a
slightly different way. I will duplicate this, I will cut, put it at the start. Add plus to it. And what do you think the answer in this
situation is going to be? I want you to really think
about it and write it down in your head before
you actually run the program. Right click. And we run, we get
six mod mod mod. The multiplication works before the addition six is
added at the beginning. But then only mordor is
multiplied three times. I hope that makes sense.
If we wanted to have the six also multiplied with mordor, then we would have to
do something like this. And now we get six mod
six mod six mordor. That's just too many modors. Before we move on, there is one more thing that we need
to understand in here, and that is that we can
print or in string five. This checks if we have or inside of string five
and returns a bullion. If I write click and I run, I get true because I do
have or in more door. See I actually have two Ors. Now let me check if I have an but this time
with a upper case. What do you think the
answer is going to be? If I write Click and
I run, I get false. Why? Because the characters, when we talk about
string references should be the same as they
are in the string. For example, the
upper case is not present or the upper case
is not present in mordor. That's why it has
not been detected. Let's now try something else. Let's try do in string five. What do you think the
answer is going to be? It's also false even
though we have D, and then, and then, and then R. But they are not in the same sequence that
we are looking for. They don't form the
word door in here. I hope that makes sense.
Finally, we're going to print, print out and check if rain is or in My name is Michael. What do you think the
answer is going to be? If I write, click and run, you'll see that
rain, unfortunately, is not in Michael, even if I tried to
add rain like this. So notice I do have rain, but I have a space
in between them. What do you think the
answer is going to be? Is it going to be
a true or a false? It is still a false because the space is also
considered a character. The only way to get a true
in here is to actually have the word rain
somewhere in our string, and now we have it as true. Thanks so much for watching.
I hope you enjoy it. And in the next video, we're going to be
looking at how we can embed integer numbers into our strings and print them out. Because currently you've
noticed that we cannot do that. We cannot concatenate
numbers and integers. But there is definitely
a way of solving this. So thanks so much for watching. I hope you're
enjoying the lessons. We are almost at the
end of the section, so I will see you in just
a few. Bye bye for now.
20. 14. Printing Numbers: Welcome back my favorite
python programmers. In this video, we're going to be looking at printing numbers. And when I say printing numbers, I mean the ability to be able to print integer numbers
with strings. So let's go ahead
and get started. First of all, I'm
going to create a new Python file in here that I'm going to call
printing underscore numbers. I'm going to create a
variable that is numb, underscore of underscore rings. And I will say that
it's equal to three. And I will print
out the following. I will print out there
were plus number of rings, rings forged by Sauron. There were three rings
forged by Sauron. If I right click on, of course I get an error. I already had a highlight. I should have seen that coming. I cannot concatenate
an integer with a. Now, there are many
ways of changing this. We can, for example, add the single quotation marks
around the three in here. But as we've seen, this
is a risky maneuver. You don't want to
always be able to change the type of your. There is a different way
we can convert this into a string using the SDR method. Now when I write it,
click and I run. I get there were three
rings forged by saw. Looks like this works, not bad. The only issue in here is that using the SDR every single time you have an integer
that you want to print is not very feasible, it's a bit of a
pain in the butt. We can use something
called replacement fields. Let me show you what that is. I will control D to
duplicate this line and I'm going to there were
replacement field. This is called a replacement
field with a zero inside. Then at the end of the
string I will type in format num of rings, the number of rings,
the squiggly bracket. Zero, squiggly brackets
is a replacement field and it replaces whatever
we have in the format. Now when we use a zero, we replace the first one. Right click run, there we go. There were three rings. This is much easier than using the SDR right
here. Much faster. Now if you only have one
item that you're replacing, you can actually use this
right click and run. You don't have to indicate
that you're using the zero. Now let's go ahead and
try something else. I will duplicate this. Instead of using the format, I can directly inside of
the replacement field, type in number of rings. But it's very important that
you hit the tab in here. Why? Because it adds a
small F at the beginning, which means that the
replacement field is actually going to
be useful in here. If we don't have the
F, this does not work. This is the output that we get. You need to actually
have an F at the beginning of the print
and then print it out. And this is, by the way,
something that's fairly new. You'll see me using it
later on down the course, but I might also use the format. So these two ways are
very important to know. You might see other
people use the format. Some situations the format
is better than the, at the beginning of the string, but it depends on the situation. You can use the F, you
can use the format, use whatever you want. Now let's go ahead and
look at the following. I'm going to add
a print in here, just a empty line, and I will print out there were replacement field
zero rings made, one for the elves, seven for the
replacement field two, and replacement field
three for the men. Then hit enter again, format, and inside I will have 19, because in total
there were 19 made, the number of rings, then dwarves, then nine. Now, what will happen is we
have an index in the format, 19 is at zero, number of rings is at one, dwarfs is at 2.9, is at three. When I write click and I run, you'll see that everything
was replaced properly. Now we can add a space in here. Notice that even though
we add an enter, the new line does not
get created in here. How do we create a new line? Of course you remember
it's the back, it's the special character, but we don't want to
do that right now. As you can see, this works. Now why do we use numbers? We could have just
had the following. And notice if one of
them uses numbers, everybody has to use numbers, or none of them have
to use numbers. So when I write the
click and I run, you'll see that I
get the same output. So why use the numbers
in the first place? Well, let's say you
wanted the words which are at position three being
used at the beginning. So you can type in, for example, two and then you want to have 12.3 Now when you write
Click and we run, you see that there
were dwarf rings made doesn't make sense, but I'm trying to highlight
to you how this works. For example, let's
say you wanted nine. You wanted this item
that's in the third, or it's in the fourth position, but at index number three. So when I write Click
and I run, there we go. There were nine rings made. So that's the power of
using replacement fields. As I told you, you can
either use the format or you can use the variable name directly through the
replacement field. And the F at the beginning
choose the methods wisely. It depends on the situation. And when you're done with understanding how
all of this works, it's time for Aber,
a challenge for you to print out the
days in a month. I want you to use
replacement fields to print out the number of days
corresponding to the month. Only use three
replacement fields, and what do I mean by that? This is an example of
how this should look. You should have January 31, February 28, March 31, et cetera, et cetera, et cetera. And then you also need to, or if you want, you can
print it out in this way. Depends on the situation. Pass the video right now
and go do the challenge. Okay, welcome back. How did you get on with that? In here I will add a print. I'm going to do the following. I'm going to print out January replacement field,
February replacement field, March, March, April, May, June, July, the month
of Julius Caesar, August, and the month of
Augustus, maybe I don't know, September and October, November, December. And I will just separate these so that the
line is not too long. Boom, boom, boom. There we go. Now, at the end, I
want to add a format. So we will have a 31, 30. And of course, 29, 29 is for February, correct? And in here we have an error. And what does it
tell us that too few arguments for the format string. All right. So it wants us to
add the replacement field. So first of all we
will have two for February because it's the
only month that has 29 days. Then we have January with 31. I think this is January 31. Yes, I think it's 31. So this is going to be zero. What other month
do we have a 31? Wait, let me check.
We have January, March, May. Let's do these. January, May, and then
July, July, August, October and December, July, August, October and December. And the rest will have. Once, there we go. If I write click and I run, I get exactly the
output that I wanted. Very nice. I hope
you were able to do this challenge on your own. Now let me copy this because I want to show
you something very neat. Now, you could have
went around and just added a back to
create a new line, and that would
have been correct. You would have been
correct in doing so, adding a back to set every single month
on a different line. But there's a small trick in
here that you can use and that is using three
quotation marks around it. So the three quotation
marks will actually produce the exact same thing
that you're trying to write. What I mean by that, if I write, click and I run, look
at how my output works. Looks, it looks
exactly the way I had, I had said it intentionally. So right here, look. January, February, March, April, January, February, March, April. And then we have
May, June, July. And you'll see that
it's even pushed. So I'm going to remove these
single quotation marks. And let's also add
a print in here. Using three quotation
marks will produce an answer that's exactly like the one that
you are looking for. Let me move January and
these to the same line. Okay, there we go. Now
we still have February. Actually, we will just add
an answer right here at every single month shift
tab to go backwards, let's right click and run,
and look at how this looks. Okay, very nice. Shifting back, right click and
boom. There we go. We get the same outputs. Ladies and gentlemen, thank
you so much for watching. I think this is the
end of the section. Maybe later on I will add
more videos to the section. Who knows, we'll see, but I hope you enjoyed. I hope you took your time to understand everything
that we've done. Some of these things
are not going to be super useful down the line. We will not be using everything
that we learned here, but this is a crucial
section where you will build your foundation for programming to later on go to harder
and harder things. In the next section,
we are going to be taking our first steps. We're going to be
understanding blocks of code. We're going to be
understanding if statements. And these are going to be the essential building
blocks for your path and your journey to
Python programming and becoming a Python developer. Thank you so much for watching. I hate to say it
again, but I have to. I shamelessly plug the ask for a review if you're
enjoying the course. If not, continue watching the course until you enjoy
it and then leave my review. Thank you so much for watching. I hope you enjoy it. Hit me
up. You send me a message. Tell me, Michael,
what Upman like. I'm liking the
scores. I'm enjoying the stuff that I'm learning. It would make my day.
It would really do. Thank you for watching. See you in the next video.
Bye bye for now.
21. Section 3: Taking Our First Steps | 1. Introduction to Blocks: Welcome back to my favorite
Python programmers, to a brand new video and
a brand new section. And in this section,
we're going to be taking our first steps, even though we've
already kind of started, but we were just
getting our feet wet. We were just understanding
the philosophy behind the programming and how things operate in Python
below the hood. But now we are actually taking our first steps and understanding
Python programming. And we are starting
with blocks of code. First of all, we
need to understand what blocks of codes are. In fact, like many
programming languages, Python uses blocks of code
to program their language. Python design philosophy
emphasizes code readability. This is something that I've told you in section number one, where I was introducing
you to Python. Python uses indentations instead of brackets to the limit code. If you are familiar with any
other programming language, you might recognize the
squiggly brackets that are used in order to define
where a block of code begins. And you might have reduced
those squigly brackets in many different languages such as Java or C Sharp, et cetera. But in Python, we don't
require blocks of code to be determined or to be delimited
by squiggly brackets. We can simply use indentations. And I will show you
what I mean by that. Well, what do I mean by that? Let's say we are working
with a block of code. If you are experienced
with different languages, blocks of code begin and end
with these squigly brackets. For example, we
have a four loop. This is a four loop extracted
from a C Sharp or Java. And you can see that we start
with this block of code, and then we end with
these squiggly brackets. Or we start with
squiggly brackets, we have the block
of code inside, and we end with a
squiggly brackets. This is the other
languages, Python, we have something different, we use these two
indentations right here. As you can see, this is
the four loop, of course. In the next section,
you'll see that four loops are written
differently in Python. But this is just an example. So this is the code that
we want to execute, and these are the indentations
that we use in Python to limit our blocks of code
Without any further ado. Let's go ahead and start taking some examples to properly understand what we
are talking about. In here. I'm going to go to file new and create a new project. I'm going to call this project. Of course, select where you want this project to be created. In here you can call
this Getting Started. You can call this
blocks and statements. I'm going to call it, actually, let's make it more specific. I'm going to call it
blocks of code in Python, and then we are going
to finish this window. All right, looks like
we are good to go. Make sure to select the
project right here. Go to file new, and I'm going to create a new Python file that
I'm going to call block, underscore and
underscore statements. So the first thing we're going to do in here is
create a four loop. Now, don't worry,
I don't expect you to understand everything
about four loops, but this is going to
be a very useful tool for us to properly understand where the block of code starts and
where it ends. Just follow my lead,
and don't worry in the next video, In
the next section, I mean we will be expanding a four loops and
loops in general. First of all, I'm going
to type in four in ran, the range will be 1216
and then hit Enter. Notice when I hit Enter, I don't go back to the
beginning of the line. Look where I go. I am tabbed, I am indented in here. I will print out and add an
extra space for the P eight. Notice what I have in here. I have something
called an indentation. This is the indentation I told you about when
we were talking about the structure of a
block of code in Pipa. If I write click and I run, this is the output that I get. I'm going to talk this
right here to the right. You see I go one through to 15. Basically what this line
of code in here means. It means that for I
in a range of 116, I want to print out, I start with I equals
one, I print it out. Then I go back, I
make I equals two, and then I printed
out, I go back, make I equals three, printed out 456, et cetera, until we get to 15. And you'll learn more about ranges in the upcoming section. But for now, all that you need to know is that it's up two, but not including,
we go up to 16. But. It's not included. Now let's continue on and let's look at if we
do the following. If I hit another enter
from this print line, you'll see that I
am still indented. So I can type in print and
then in here I can add just a dash and I will
multiply it by 20. What do you expect
is going to happen? Please, just take a few seconds. Think of the output before
you actually run it. Boom, there we go. Just like we've had with the
eye, at every iteration, we are printing out
these 20 dashes that we've seen before. We've already seen how this works and the getting started. That's why it was very
important for us to build the foundation in the first or the second
section to be more specific, that is, our update. Now if I write the following, I print out, hey I indented. What do you think the
output is going to be? Notice that this line
is no longer indented. It is not part of
this block of code. What do you think the
output will be like? If I write, click and
I run, look at that. Hey, I'm indented is
only printed out once. Why is that? Mm hmm. Why is that? Well, because it's not part of the block of code. It's no longer inside
of the fore loop, so it's on the outside. So it just behaves like
a normal line of code, not as indented or as part of the block of code
that's in this fore loop. But for example, if I Tab, it hit Tab when you click
on here and then hit Tab, it will get indented. So now if I write click and
I run, think of the output. Yes, exactly. There we go. As you can see, we've added
an indentation and then we print it out at every
iteration of our four loop. I hope you understood how a block of code
operates in Python. Now it's time for a
bit of a challenge. And your challenge is going
to be to explore the code, use the code I've written for
you to play around with it, and go wild in your exploration. Add indentations,
remove indentations, try to add a few more print
lines, see what happens, play around with
the indentations, see how it affects your code, Pose the video right now
and go do the challenge. Okay, welcome back. How did you get on with that? Let's try a few things in here and just try to
break out our code. For example, if I hit Shift, tap on the second
line. Look at that. If I try to write,
click and run, it tells me that there is
an unexpected indentation. If I click on the link and
it takes me to the line, it's on line number four, MI in. There's an unexpected
indentation. Because Python uses indentation to delimit the blocks of code, we cannot just add indentations for the sake of adding them. They have to be precise. They have to be concrete in indicating where the blocks
of code begin and end. The problem with this
is that I already had a block of code right here, print, then I removed
the indentation, so the block of
code ended right. But then I had
another indentation, so that is no longer correct. When we stop inventing, that's where the
block of code ends. So for example, I can do this, but I cannot do this because
I stopped the block of code. I ended the block of code for this four loop when I
stopped the indentation. So I need to have
an indentation. Now, what would
happen in this case, Again, if I right click an iron? You've already seen the error. You've already seen
the squiggly red line. We cannot do double
indentations. You'll see later on we can indeed do double
indentations when we are working with nested if
statements or nested loops. But for now, just
for the sake of this example right
here, as you can see, we cannot add
double indentations if I remove, hey, I'm indented. And if I print out hello, what do you think
the output will be? And I will add also
an empty print. As you can see, hello is
printed out at every iteration. Ladies and gentlemen,
thank you so much for watching
the next video. We're going to be looking
at if statements, which is a very exciting
place to get started. It will really begin to form
your skills in programming. Thank you so much for
watching and I will see you in the next video.
Bye bye for now.
22. 2. if Statements: Welcome back my favorite
Python programmers. In this video, we're going to
be looking at if statement. If statements are going
to be a continuation or a more practical use of
blocks of statement. So let's go ahead
and get started. First of all, let's look at the structure of
an if statement. We have if some condition, so we're not sure what this
condition is right now, but we are going to have some kind of condition
if some kind of variable is greater than a certain number or whatever
condition there is. So if some condition is true, this condition has to be true. Then we will create a block of statement that will execute. Again, only if this
condition is true, we will execute
that block of code. But we also have
something called the L, where if this condition is
not true or is not satisfied, then this block of
code will execute. And you'll notice that we always have the indentations
right here. Again, you'll see what this or what these conditions
will look like. But for now, just
understand that if we have some condition
in here that is true, we will execute the
code that's inside. And again, we're using
a block of code, or blocks of code delimited
by indentations right here. Let's look at an example
to properly understand. And then I will take you back
and show you the structure again back in our code in here. Let's go ahead and
create a new Python file that we are going to call if underscore statements in here we are first of all
going to take an input. We're going to say age
equal to an integer input, because we want it
to be an integer. And we're going to say, hey, there Mr. Potter,
how old are you? So this is going
to be our input. And we'll also indicate
that this is an input using this little indicator
here, right? So that the user knows exactly where they should
be adding their input. Age equals whatever. And then we are going to
simply print out the age. This is just for
debugging purposes, just so we make sure that
everything works correctly. Right click and run. Hey, Mr. Potter,
how old are you? Let's say 18. Hit Enter. Boom. The answer is 18. Great. But now let's go ahead
and create an if statement or a line of code that will only execute under a
specific condition. I will remove the print H,
we don't need it anymore. This was just for
debugging purposes. And when I say debugging, I mean just so we make sure that our program
works correctly, I'm going to say if age is
greater than or equal to 17, then I'm going to print out, welcome to the party Harry. I should write. Well, come not with 15 mistakes
in one word. Now let's look again
at the structure. If some condition, and then
we have the block of code. Notice the indentations.
Oh my God, can I get to my code if the age is greater
than or equal to 17? Look at this block of code. We print out, welcome to the party it's greater
than or equal to. That is why we had to convert our input into an integer
because if we hadn't, we wouldn't be able to compare
a string to the integer. I will show you what
I mean by that, but for now, let's
right click and run. Hey, Mr. Potter,
how old are you? 21. Hit Enter. Welcome to the party. Harry Only because we
have 21 as the input, it's greater than
or equal to 17. We can go to the party. If I write it, click
again, I run again. For example, I type
and 12, I hit Enter. Boom, there we go. We
don't get anything. This is a conditional
if statement, only under a certain condition. Which in here is if the age is greater than or equal to 17. Does this work? Let me show you what I mean by
greater than or equal to. We can just have greater than. If I write, click and I
run and I type in 21, again, this works
perfectly fine. But if I try to run this
and then if I type in 17, note is 17 and I hit Enter, I don't get anything.
Why is that? Because we only execute
if it's greater than 17. 17 is not greater than 17, it's equal to 17. And our condition in here, if age is greater than 17, we need to actually
add this equal sign. And now if we type in 17, there we go, We are welcome
to the party. Great. But what would we do? Or what should we add in here, just in case we get a output in case we are not
greater or equal to 17. Well, that's where the
L statement comes in. We've already explored
the L statement. We talked about it. It's simply added right
here under the L. Notice it's not indented because it's not part
of the block of code. This is the block of code. This is the L is part of
the entire if statement. Right here, we
type in print out, sorry Potter but but your two or actually, you're not old enough for
the party as you can see, because we have a little
single quotation mark in here. We have to add a backslash in order to be able to
print it out correctly. There we go,
everything looks good. We add the extra line for the P eight and then
right click and run. Now, how old are you if
I type in 12 and hit, but you're not old
enough for the. If I run this again and
I type in 25, hit Enter. Welcome to the party Harry. Now again, one last thing
before we continue on in here. We need to know that we can actually add multiple
lines in here. We can say here
have a want also. Okay, so this is
a block of code. We can have as many lines as we need in each one of
these blocks of code. If I write Click
and I run 18, boom. Welcome to the party here. Have a want also, and you
can add as many as you need. So I hope this is clear. This is an introduction
into if statements. These are crucial. Every single language
that you will ever encounter will have If
statements in them. So take the time, make sure that you understand
what is happening. If you want to play around, play around, change
the condition, see what happens, and then
move on to the challenge. Your challenge is going to be to create your own F statement. Create an F statement that
checks if the age is 17. Do it right below our
current condition. Print out a message and
create an L statement. Print out another
message in that case. And what I want you to do, I want you to get the same message as in the
first conditional statement. And notice I didn't say I want you to write
the same message. I want us to get
the same message. What I mean by that is in here, I will just get you started
with the challenge. So I will print
out, for example, in here, a few dashes
multiplied by 20. Then in here I will want
if statement statements. Statement with the L, et cetera. What's wrong in here? I forgot the All right, the if statement with
the Ls and et cetera. And I want to get the same
output when I run right here. Okay, let's say we
type in 18, Hit Enter. I want under these dashes to have the same out.
Welcome to the party. Harry here on the condition
should be less than 17. You need to know how
you need to change your code when you have
a different condition, but we still want
the same outcome. That is the goal. Pass the video right now and go
do the challenge. Okay, welcome back. How did you get on with that? In here, I'm going
to remove this. I'm going to say if the
age is less than 17, I will print out
the following line else I will print
out these two lines. Now if I write the click
and I run, how old are you? 18, boom we get
the same outcome. If I write the click and
I run and type in 12, boom we get the same outcome. How is this working? In here we check if the
age is greater than 17 or greater than or
equal to everything, 18 and upwards is
welcome to the party. If they are not 18 or upwards, they are not welcome
to the party in here. We do the same thing, but this time the
condition changes. So now we check if the
age is less than 17, then we say, sorry, Mr. Potter, you're not allowed. If it's less than the
same idea holds true, but it's written in
a different way, and this is very important that something very important that you need to understand. We want or we are able to have the same output but
have different code. And you'll see that
even though we get the same output
with different code, there are codes that are
better than under codes. And we'll explore that
in the next video. But for now, I hope you understood this is
not too complicated. If you're not sure
how this is working, think of it logically, go back through it, understand
it properly. Take your time. You're
beginning to build your foundational
skills in programming, so it's okay if you're not understanding everything
100% correctly, just take your time,
do the examples, redo them, continue
through the section, and I will see you
in the next video. And if you're
enjoying the video, please leave me a
review somewhere. Just hit me up, You
send me a message like, hey Michael, I'm loving this. Just like Mcdonald's. See you in the next video
where we are going to look at lip statements in statements me.
23. 3. elif Statements: Welcome back my fellow Python programmers to a
brand new video. In this one, we're going to be looking at elyph statements. Let's look at an
eliph structure. Let's say we have
some condition. Condition Number one, if
the condition is true, then we will execute the code. We've already seen this
in the previous video. Should be pretty obvious. But now what if we
don't want to just create a statement if there
is nothing else true? What if we have some
other condition like condition number two, L? If some other
condition number two, then we will execute
condition number two. If condition number one is not true and this code executes, we start off with
the first condition like we've saw before. If the condition is true, we execute this code. If the condition one is true, then some other condition
which is number two. If that one is true and
condition one is not true, we will execute the
following code. Let's go back into our code and let's see how this
looks in here. I'm going to add in here, Alif, we have g equal to 150. I will print out,
oh, and by the way, equal needs two equal sines. Because one equal
sine means that we are assigning a
value to a variable. Two equal sines means that
we are comparing two values. Lip age is equal to 150, we're going to say, and I
will add double quotations. Dumbledor, you're too
old for this party. That's how you write
Dumbledor. I think so. Now, I'm going to copy this, and I will add it
in here as well. Notice now what we need is we need this condition
to be not true. In order to execute
this line, of course, we need this one to be not true, and we need this
one to be true in order to execute
this line of code. If I right click and I run, and if I type in 150
and I hit Enter, you'll see that we have
a discrepancy in here. Now, we do get,
sorry, double door. You're too old for this party. But we only get it in the
second conditional statements, meaning that we get it in the second F
statements right here. While in here we don't get
anything. Why is that? Well, let me tell you something about how
the LF operates and something that you need
to always watch out for when working with
multiple LF statements. Right here at the top,
let's look at the logic. The logic says that if the age is greater
than or equal to 17, we will execute
this block of code. Now, what is the age? The age is 150, correct? So 150, is it greater than 17? Yes, it is. A is 150, it's greater than
or equal to 17. This entire condition is true, which means that we print out welcome to the
party, have a want. Also, when one
condition is true, that's it, we simply jump out. We don't continue going
through the lips, We don't continue
going through the Ls. And this should be obvious from the way that we are framing the if the furthest
condition is not true. Let's go back to the structure. If condition number one is not true and condition number
number two is true, then we will execute in here. It works. Why?
Because we are first checking if the age
is less than 17. If it's less than 17, we print out, sorry,
you can go 150. Is it less than 17? No, it's not. So this
condition is not true. We go to the Alif, we check, is the age greater
than 150? Yes it is. So we print out, sorry, umble door, you're too old. If I right click and I run, and I, for example, try 180, hit Enter, it tells me that I am welcome to the party
in both conditions. If now I type in 50 hit Enter, it tells us that we are
welcome to the party. And if I type in 12 hit enter, we are not welcome at both parties because
we are under aged. So this is just making sure that everything is
working correctly. So for example, at the 12 mark, I check if the H is
greater than 17. No, it's not. Is the age
equal to 150? No, it's not. So I go to the LS
and I print out, sorry, you're not
old enough in here. 12. Is it less than 17? Yes, it is. So we print
out, sorry, Mr. Potter, you're not old enough
And then we don't even check anything
else. That's it. One condition is true. We go through it,
boom, we exit out. This will be more obvious
in the next video. When we are going to be working with debugging and intelligent, you'll see how each and every single line
of code executes. But now it's time for
a bit of a challenge. Your challenge is
for you to create your own Lip statement inside
of our two statements. I want you to check if
the age is greater than 600 using an Lip inside the statements
that we already have. Print out a message
in that case and do it for both of
our statements. I want you to check if
the age is greater than 600 positive video right now
and go to the challenge. Okay, welcome back. How did you get on with that? In here, I will add an lip age greater than
600 and print out, you must be Nicholas Flamel. I think this is how
you write Flamel. Wait, let me Google search. I hope you know, and by the way, I'm using these references and I hope you have an idea
of who Harry Potter is. If you don't, that's okay. No worries. Nicholas Flamel? Nope. This is how you write it. I just Googled it. Oh my God. Can I please copy this? Yes. This is how you
write Flamel. All right. I will copy these two lines
and put them in here. Shift tab, right click, run. If I type in 800, hit Enter, the first one does not work, the second one does work
again. Why is that? I want you to take the time
to understand it on your own, and this works only
in the second one, because A is equal to 800. In here we check if the age is greater than or equal to 17, 800, Is it greater
than or equal to 17? Yes, it is. So this
condition is true. We print out, welcome
to the party and we jump out of the if statement. We go to the print in here, we check is 800 less than 17? No, it's not. Is
age equal to 150? No, it's not. Is age greater
than 600? Yes, it is. Which means that we print out, you must be Nicholas
Flamel and we jump out. We don't continue
until the L statement. Ladies and gentlemen,
I hope you enjoy it. In the next video,
we're going to be delving deeper and
we'll see how we can debug an intelligent
which will help us a lot throughout our journey. You're going to be
debugging all the time, where no matter how long
you stay with Python, debugging is going to be part of your journey and
it will help you tremendously throughout your
learning path or journey. So I will see you in the
next video. Bye bye for now.
24. 4. Debugging in IntelliJ: Welcome back my favorite python programmers to a
brand new video. And in this one we're
going to be looking at debugging in Intelligy. This is going to be a
very important lesson, a very important tool in your arsenal that will allow
you to carry on learning in a much better way
and going through iterations of your code to understand how it
properly works. So let's go ahead
and get started. First of all, you need to add something called
a breaking point. This breaking point is where
your program will stop executing and stop
at that exact point. So you can see
right here between the code and the number
of lines that you have, there is an empty space. For example, I can click on this empty space to
add this red dot. This is called a breakpoint. If I hover over it,
does it say anything? No, doesn't. But trust me, this is a breakpoint where
it suspends the thread. So it stops the code
from executing. Let me show you what I mean. I added the breakpoint
right here, correct? On the first if statement, I right click and I
debug if statement. And as you can see, we have something different
happening now. I'm asked, how old are you? Let's say I hit 150
and I hit Enter. And look at that, I'm not executing the code yet. There's nothing happening. There's no output yet. The debugger. Let me close this down and let's
work on the debug. You'll see a long blue line. This long blue line
indicates which line we are currently at in
our debugging process. Currently, we are on this line
we are trying to evaluate. You can see also all the
variables that we have. For example, right
now we only have one variable which
is an integer, which is age, which is 150. You can also see it
being displayed right here on the actual code in gray. You can even hover over it. Click on it, Set Value. You can change the
value if you want, if you want to play around with values and change
them up and see how program would respond
in that situation. But for now we are evaluating if age is greater
than or equal to 17. When I step into, you can see that I have many
buttons in here, but the most important
one is going to be the step into,
which is seven. If I step into Boo, you can see because this
condition turned out to be true, we evaluated it,
turned out to be true. We go into this line of
code which is welcome to the party Harry
we step into again, here have a want. And now look at what's
going to happen when we step through this
again one more time. As you can see, we jumped out
of the entire if statement. So we glanced over the lip, we glanced over the age, we glanced over the
Ls and then we went directly into the print in here. I will step into again, look at the console as well. Look at the console now. We have welcome to the party
Harry here, have a want. If I step into again, now we've printed out, we've executed this
line of code and we printed out our dashes.
Let's continue now. We are checking if
h is less than 17. If I step into and
notice H is 150, 150 is greater than 17. It's not less than 17. So what happens? We simply
jump over the print. We do not execute
that block of code. Now we're checking if the H
is equal to 150. Yes, it is. So we go inside of this line
of code, sorry, double door. You're too old for this party. Now, what will happen
when we step into again, I want you to tell me before
we execute or we step into as you can see, we finish and we print
out, sorry, double door. You're too old for this party. And what you should
have known is that we will not go
through this Lyp, we will not go
through this else, we will simply jump out. Let me show you another example. For example, in here, let's
say I type in 12 in here, hit Enter, and we step in. Okay, we stop right
here in the execution. What will happen now
with the blue line? I want you to tell
me we have 12. Is 12 greater than 17? No, it's not. So we go
to the next teleph. Is the age or 12 equal
to 150? Now it's not. So we step into and we
go to the next elif. We check is age greater than 12? Is 12 greater than
600? Now it's not. So we step into, but now focus
on what's going to happen. What we usually
did, we checked if it's greater than
we stepped into the lift and we stepped
into the next lift. But when we are
working with the Ls, we don't evaluate
anything on the Ls. Look at where the
line is going to go, but we go directly to the print. There's nothing to evaluate
if the first condition was false and the second elyph was false and the third
elyph was false. We can add as many
elyphs as we want. If all of these were false, we don't check
anything on the Ls. We simply jump into the Ls and
we execute the code there. Now as you can see, we
didn't have anything. We step into, we execute
blood line of code, it works. We step into, again,
is age less than 17? Yes it is, and we
have the same output. All right, well, good. So I hope you understood
what's happening. Now it's time for a
bit of a challenge. And I want you to test out
the debugger throughout your code and make sure
you understand how breakpoints and debugging work. For example, right now I
want you to try and see what happens when our
age is greater than 600. And try before you
use the debugger, always try to imagine
how the code will execute in your head
and then go through it, posit the video right now, and go do the challenge. Okay, how did you
get on with that? Now for example, if I
remove the breakpoint I added in here on this print, if I write click an
ID bug, for example, I type in 800, hit Enter on the console. You'll see that I already
went through this entire if statement and I only stopped
when I got to this print. This is what the
breakpoint does. It only stops the code
on this line of code, on the line that we've indicated for the code to stop
doesn't stop elsewhere. Let me put it back at the top. And debug this again. We can see what happens. So let's type in 800, hit Enter. Is 800 greater than 17? Yes it is. So we print
out, welcome to the party. Boom, we print out, here have a wand, and
now we print this out. Let's check 600. Is it less than
17? No, it's not. We go to the next lyp. Is G equal to 100? No, it's not. We go
to the next lip. Is H greater than
600? Yes, it is. So we print out, you
must be Nicholas Flamel, And when we finish with it, we simply jump out and we
don't need to go to the else. So ladies and gentlemen, this is a very crucial
lesson to understand. The debucker is going to be a tremendous tool
in your arsenal to make sure that you properly see all the variables properly, see how your code is working. You'll be using a
debuger no matter what you do in life when
it comes to programming. So please take the time to clearly understand
what's happening. And I will see you in the
next video where we will be delving deeper into
conditional statements. So bye bye for now.
25. 5. Deeper Into Conditional Statements: Welcome back my favorite python programmers to a
brand new video. And in this one we're
going to be delving deeper into conditional
statements. To better understand
conditional statements, we're going to be
creating a game. And it will be a guessing
game where we are going to be trying to guess
Nicholas Flamels, age. Let's go ahead and get started. We're going to create
a new Python file in here that I'm going to call Nicholas underscore Flamel. Underscore H. Boom.
First of all, we're going to
create the actual H which is going to
be equal to 665, then we're going
to print out what is La Mel's age, Wesley, and then give
him the old indicator. Then we're going to get the
guess which will be equal, or actually we don't
need this one. Since we're going to be
getting the input on a second or another line in here. We're going to have the input which is going to
have the sprant. Of course this needs to be
an integer because we will be comparing it to some numbers. We're going to be creating
the statements in here. If guess is less
than the actual H, we will print out, run guess higher
then elif, elif. The guess is greater than the
actual age will print out. Please run guess
lower. There we go. How will this work? Well, it should be obvious if the guess is less
than the actual age, which is 600, we are going to tell run to guess higher please. If it's greater than
the actual age, we will tell them
to guess lower. If I right click and I run, this was debugger right
here, we can close it down. What is f age 12? Please run Guess Higher. Click and run what is flames age 1,000 Please run Guess lower. All right, looks like our
code works correctly. The only problem is if I
type in 650 and hit Enter, still tells me to
please guess higher. Interesting. What is
the matter in here? I'll wait. I apologize. 665. Hit Enter. I don't get anything because we actually
got the right age. 665 is not less than the actual age and it's not
greater than the actual age, it's equal to the actual age. And we don't get any
answers, we don't get, hey, congratulations, we
don't get points for Griffendor. What is the problem? The problem is that I still haven't given you your challenge to do what if Ron gets it right? So print out a message of
congratulations if Ron, guess it correctly, past the video right now and
go do the challenge. Okay, welcome back. How did you get on with that? Some of you might have just
printed out this in here. Congrats, 10.4 Griffin Door. Is that how you write
Griffin Door? Yes. Right click and run 665. Enter ten points,
four griffin door. Only problem in here is if
I type in, for example, 12 and hit Enter, I still get congrats, which is not good. Now, the next people, or some of you might
have done the following, They said Lip, the guess
is equal to the actual H. Then added a tab in here in order to
create an indentation, it's part of the block of code. Right click and run 6665. Hit Enter, Congrats, run ten
points. Four griffin door. Excellent. If I type in 12, I don't get the answer. Nice. Excellent work. That is correct. That could work, but there is an even better way, because remember, when
we're working with an L, if we actually evaluate
the line of code, this is an extra evaluation that we don't really
need because, and I will click at the
end of the line and hit control forward slash
to comment it out. We can simply use an LS. If I write, click and I run 665, boom, Congrats run again. 1,000 guess lower.
Why does this work? Well, because if the
guess is not less than the actual age and the guess is not greater than
the actual age, then what is the guess? There's only one possibility, and that is that it's equal to the actual
age. There we go. I hope you understood. I hope this all makes sense. What I want you to
do now is I want you to run this
through the debugger. Take your time.
Use the debugger. Go through the code, try
all the possibilities. I will do it with you in 321. Add a break point right here. Right click debug. Close this down. What
is Flamels age 12. Hit Enter. All right, guess is 12, Is it less
than the actual age? Yes it is. Please guess higher. Let's strike the scan debug
1,000 Hit Enter, is it less? No it's not. Is it
greater? Yes it is. Please run on Guess higher, guess lower. We print out. Now if I right click
and I debug again, you can simply click on the
debug, right here at the top. 665 hit is less than
the actual age, is greater than the actual age. No it's not. Then we simply
jump into the print. We finish up with that. Now let me take this line back
and comment the L's line. Right click debug. So what is L H 665. Hit Enter. Notice
what will happen. Is it less than the
actual age? No, it's not. Is it greater than the
actual age? No, it's not. Then we have to
evaluate this again. Is it equal to the
actual H? Yes, it is. And then we print out, so you can see by using
an L, unnecessary LF, you can see that we just
add one extra evaluation, which is not something
that is recommended, even though this is
not a huge problem. At this 0.1 extra evaluation, you're telling me
like who cares? Like this is a few
milliseconds of extra work. But imagine if we
had a loop that does this 1,000
times per second. Just imagine it in
this situation. Of course it's not possible, but code optimization
is something that you have to be conscious
of even at this point. Using an L in here
does the same job as the lift without any further
or future consequences. Which means that
it's better to use the Ls just to remove one extra operation
like these operations. These comparisons take a few milliseconds
out of your code, And it's better to save on these milliseconds at
any point possible. Thanks so much for watching. I hope you enjoyed, and the next video is all about
giving people second chances. So I'm going to see you in
that video. Bye bye for now.
26. 6. Giving a Second Chance: Welcome back my favorite python programmers brand new video. And this is the season
of giving back. Of course, it depends on
where you are or when you're watching this
without any further ado. And we'll stop the jokes. Let's go ahead and get started. We want to give a second chance because he's a good
fellow wizard. What do we do in here? How
do we give a second chance? Well, this should
be fairly obvious. We need to get another
input in here. I will get guess equal to integer input and this
indicator right here. And then we of course
need to check if the guess was equal to the actual age we're
going to print out. Well done Mr. Wesley ten points or at this
point I think we should give him like five points
because it took him to try. So five points for
grid, right click, run. Let's say 5,500 Boom. Please guess higher. Oh nice. Now I get a second input. So I type in 665. Boom. Well done, Mr. Wesley. Five points. Four Griffin Door. Now, again, keep in mind
we're using two equal signs, which means that we are comparing the two values to
check if they are equal. When we're using a
single equal sign, it means that we are assigning
a value to a variable. Now the only problem in here is that if I
right click and I run, I type in 900 and hit Enter. I only get told to
get slower without any way for us to properly
get a second input. So what do we do in here? You should know by
now we should do the same thing for the lower. Now, if I write click and I run, I want you to also realize that. Let me add in here Mr. Ron. Just so we can distinguish between this print
and this print. If I write click and I run and
type in 900 and hit Enter, please get slower and
type in 665 Enter. There we go. Well done, Mr. Round five points
for Griffin door. This is the line of code, this is the print that's
executing and not this one. Why? Because we have 900, which means that this
condition is not true. That means that we go into this Lyp check if this condition is true
and because it's 900, it's greater than
the actual age. We go into the block
of code and we get another input and we check that the gas is equal
to the actual age. This is actually
called a nested if, meaning that this
is an if inside of another if even
though it's Santa Live. But it's the same
concept in here. We then print out the following. Now the only problem, and one more thing,
notice the indentation. Now we have a
double indentation. I told you a few
videos ago that we cannot have extra
indentations only in this case where
we have a block of statement inside of
another block of statement, Can we have these double
indentations in here? The only problem in here is
that if I write click Run, and I type in 900 and
then I type in lower, okay, 800, I don't get
anything printed out to me. At least they should tell me
that I'm not good at this. I'm dumb. I should
study more for the following tests to
know what Flamel he is. At least some indication
in here should happen. That is going to
be your challenge, to add an L statement to
our new if statements. And make sure you have the
right indentations for these. Pause the video right now and
go add an L to our new ifs. Welcome back. How did
you get on with that? In here, it's very simple. Simply add an L to these
if I'm going to print out wrong again, wrong again. And then in here I
will add an L and say you got it wrong again. When I write click and I run, let's type in 900, 800, you got it wrong. Again, this line of
code was executed. Let's run this 400, 500 win. This one is different. This is the line of code
that was executed. Thank you so much for
watching. I hope you enjoyed. In the next video,
we're going to be looking at testing operators. So we've seen some
of these operators already like the less
than, the greater than, the equal to, the greater
than or equal to, the less than or equal to, the less than or equal to. But it works the same way as the greater than and equal to. In the next video,
we're going to see another operator which
is the different than. It comes in very handy. I will see you in
the next video. Thank you so much for watching. Just as an extra challenge, as an extra homework, even though I don't
have it right here. Try to use the debugger
in various places in here to make sure that you understand how
everything is working. The only downside of
using a debugger when you have an input is that
sometimes it can go haywire. Like for example in here
if I step into yeah, and the console now it's
waiting for the input. If I type in 20, hit Enter, you can see that now it
doesn't step into correctly, like some weird things happen. Let me try this again, like 120, Hit Enter.
Okay, there we go. Now it works. You
have to use the step into my code as you can see, because it can get
hung up on going through the code
inside the input. This is something very
advanced, don't worry about it. When using the inputs,
use the step into, for example, in here
you get this, okay? Step into my code. All right, and then type in 300, it, I mean, step into again. All right, there we go.
This is how it could work. All right, ladies and gentlemen, thank you so much
for watching and I will see you in
the next video.
27. 7. Testing Operators: Welcome back my favorite Python programmers to a
brand new video. In this one, we're going to be looking at different
testing operators. As I told you in
the previous video, you've already seen a lot
of these operators and these are the operators
we have the less than, the less than or equal to, the greater than, the greater than or equal to, the equal to. Finally, the one that we
have not seen before, which is the n equal, which is an exclamation
mark followed by an equal. Very important to remember. Very important when using. Let's not waste any more
time and let's look at the use of these operators. If we go back into our game
that we've created in here, I want to write or have the same output. Let
me rephrase that. I want to rewrite
the code having the same output using
different operators. First of all, I'm going to select all of this
and I'm going to hit control control forward in order to comment all of it out. Then I'm going to say if the guess is different
than the actual he, I'm going to say if the guess
is less than the actual he, I'm going to print
out please run guess higher and
then else print. Please run guess lower in here. I'm going to say else print. Well done Mr. Ron or Mr. Wesley. Ten points, four
griffin door. Okay. So, how does this work? I want you to pause
for a second, and I want you to think of
how this actually works. First of all, we check if the guess is different
than the actual age. If it's not, meaning
this condition is false, we go into the else Correct, and we print out Well
done, Mr. Wesley. Ten points for Griffin
door. Let's test it out. Right click, and run 665. Hit Enter. Well
done, Mr. Weasley. Ten points for Griffin Door. Now, if it's different than the actual age only
then we go and check. If the guess was less
than the actual age, we tell the user to
please guess higher. If it's L, then we tell the
person to guess slower. Now, why did we not
say lip guess is less than or greater than the actual age in
order to guess lower? Think about for a second
why we didn't use the lip just like we did
in this case right here. I mean, in here we
checked if the lip is Lip greater than actual he. Well, it's for the same reason that we didn't use
an lip right here, and instead we chose to use an L. Because in this situation, we don't want to evaluate
this unnecessarily. And why is it unnecessary in here to check
if it's greater? Well, because we've already
established that the age or that the gas is different
than the actual age, It means it's either going to be greater or it's going to be
less than the actual age. After we made sure that it's
not equal to the actual age, we checked if it's less than the actual age because it is
less than the actual age, or if it's not less
than the actual age, it means that it has to be
greater than the actual age. There's no other way around it. It cannot be equal. If it's less than, it
means it's greater than, that's why we only need the
Ls in here for this to work. Of course in here we're using the different than expression. Yeah, the only problem in here is that we don't
get a second chance. So if I type in 100 or 900, please run guess slower but
I don't have another input. And that's where your
challenge comes in. Your challenge is going to
be to get a second input, get a second input
from the user. Check if the guest was
correct and if it's not, print out a message
based on the result. Should I give you a hint? Maybe I shouldn't.
You should only have one more input. Try
to think of it. Only one more input in here. Pass the video right now
and go do the challenge. Welcome back. How did
you get on with that? By the way, if you
love the scores, if you're enjoying my teaching, if you are learning something, please leave me review. It helped me out a lot. But anyways, what should
we be doing in here? Some of you might have
done the following. After we print out, we get the guess equal to input. And then in here, let me just add this extra
prompt and then we will what. Sorry. There we go. And then we will check if
guess equal to the actual age, print out well done, five points, L print
out wrong again. Then what you did is
you copy this and put it in the Ls that it
would actually work. Because now if I
write Click I run and I type in 500, 665. Well done, Five points,
excellent work. The only problem in here is that this is called
redundant code. Whenever you find yourself
copying and pasting code, you should immediately
start thinking, what am I doing? Alarm bells should start
triggering in your head that there is a better and
easier way of doing this. You should never
have to copy code. Of course there are exceptions, but most situations in 95% of the time where
you're copying code, you can avoid it. How do we avoid it in this case? Well, if I tell you
that we don't actually need to get a guess in here, we don't need to get a guess in this L statement shift
to take this back. We only need to get one guess. So if I write click
and I run 90665, well done, Write click
and run 30665. Well done. What did I do in here? Well, instead of putting this second guess
with its check for the actual age inside of this block of code where we check if it's
less than the actual age. Or in this block of
code where we check if it's greater, it doesn't matter. We can simply put
it on the outside. Notice this is not part of the
else, this is not part of. It's for a second if we
didn't give suggestions, if we had the following code. So as soon as you get
the guess incorrectly, you want to get a second guess. It doesn't matter
if it was higher, doesn't matter if it was lower. As long as it's different
than the actual age, we will have to get
a second guess. And that's the whole point. These two if
statements in here are just a guiding
point for the user, if they should be
guessing higher or they should be
guessing lower. But other than that, we
will have to get a guess. Either way, it doesn't matter
if we should guess higher, it doesn't matter if
we should guess lower, we should get a guess.
That's the whole point. I hope you understood
how this works. Some people really get confused, but you should take the
time to properly understand and learn why we have
this guess here. And not inside of the L, not inside of the F. Only
a single one works enough. Okay, thank you so much for watching. I
hope you enjoy it. And in the next video
we're going to look at writing ifs in a
slightly different way. So bye bye for now.
28. 8. If In A Different Way: Welcome back my favorite python programmers to a
brand new video. And in this one
we're going to look at ifs in a different way. So what we'll be doing is
we're going to be rewriting our program to guess the
correct answer first, and then we are going to
proceed and do everything else. And when we say we're going
to be rewriting the code, I mean you're going to be rewriting the code
and the best types of videos the best
kinds of videos are the ones that you start off
with a challenge, right? No. Okay. Please don't click off rewrite the code to check if the user's guess
was correct at first, write the code if the guess
equals to the actual age, and then continue
from there and make the necessary adjustments
to have the same output. Again, we want the same output. What I want you to do, in fact, is I want you to not
comment this out. Instead, I want you to
add a print in here. Of course, I want it
outside everything, and I want you to add
a multiplied by 50 and then proceed to write the code to have
the same output. But this time you'll need
to start with the gas being equal to the actual H. And I have a hint for you, If you don't want the hint, pause the video and
go to the challenge. If you do want the hint, 31, you don't need to
delete or add any code. Simply move some code around. Pause the video right now
and go to the challenge. Oh, okay, welcome back. How did you get on with that? First things first is we need to start writing the
initial conditions, which checks if the guess
was equal to the actual age. If it's equal, then what I want to do is I
want to simply say, great ten points
for griffin, right? Then I'll have an L. What should we do in the L? Exactly the same thing
that we did in this case. This is a simple moving
around of the code. We don't need to add anything. We don't need to change anything because we changed the
initial condition. All that we need to do is change the position of our code. Now if I write click, but you know the problem
with this is that we are going to get other
inputs in here. I mean, you know
what, Let's do it. So 300 hit enter, please guess higher, 665
hit enter, and there we go. Well done 5.4 griffin door, but in here, because
the guess changed. Why? Because the
guess in here was another input and it was 665. Doesn't really work, so we should in fact comment this out. Right click and run 300. Please guess higher 665. There we go. Well
done, five points. Okay, so it's the same output, it's the same exact code. We get the same results, we only changed the
operator at the top. So this is just a good
exercise in showing you that sometimes you can
have the same outcome using different codes. Sometimes it doesn't matter
which type of code you use, sometimes it doesn't matter what type of code you use or
what condition you write. As we saw in this video
in the F statement where we started with g
being greater than 17. And we've seen that
it's not as good as using age less
than 17 in this case. Sometimes it's better. So thanks so much for
watching. I hope you enjoy it. And I will see you in
the next video where we are going to be talking
about complex expressions. Meaning what if we have multiple conditions in here
on the same line of code, not on an LF, on the same line of code. I will see you in the next
video by bye for now.
29. 9. Complex Expressions using and, or: Welcome back my fellow Python programmers to a
brand new video. And in this one we're
going to be looking at complex conditions using, and so far we've only done
very simple conditions. What if, for example, we wanted more than one value evaluated, For example, age
greater than 17. Maybe if we want to check age being also less than something, that's where we start using
complex expressions using and we're going to
also be looking at and and or truth tables. Let's first of all create
a new Python file in here. So new Python file
and I'm going to call it plex expressions in here. First of all, we're going to get the input for a temperature. What we want to do is we have a gaming PC where we
want to play some games, but we can only
play those games if our GPU is at a
certain temperature. We're going to first of
all take the temperature, The temperature, that's
how you right temperature. Yes, Integer input. How hot is your GPU? Gpu stands for Graphical Graphical Processing
Unit, I think. Yes, I think so. That's the GPU. And then we're going to check if the temperature is
greater than or equal to 20 and the temperature is
less than or equal to 70, then we're going to say, great, continue playing
your game at 60. Continue to playing your gum. Eat nice 60 FPS. L print out, oops, sorry, you can't
play your game body. We forget that we are using single quotation
marks. It's okay. As you can see, first of all, we have a small
squiggly line telling us that we can simplify
chain comparison. This will be handled
in the next video, but for now what we need to understand is that in
here we're checking if the temperature is greater
than 20 or greater than and equal to 20 and the
temperature is less than 70, then we can play our game. Let's see how that looks
in the real world. When we run, how hot is your PC? 20 Hit Enter. Great, you can continue
playing your game. Why? Because 20 is greater
than or equal to 20. Keep in mind the equal
to is the keyword. Let's run again. 17 hit
Enter. Oops, sorry. You can play your game. Now, some of you
might be saying, wait, wait, wait, wait, wait. Michael, Michael, 17. It's not greater than 20, I mean. Okay, I'll
give you that. But it's less than 70. So what gives,
what's the matter? Well, when we are
working with an end, we have to have both
conditions true. So this should be true
and this should be true. Both of these conditions
should be true in order to evaluate the entire
condition to true, in order to go into
the block of code. For example, if I write, Click, and I run and type in 100, 100 is greater than
or equal to 20. The first condition
is true, great. But the 100 is not
greater than 70. It's greater than 70, It's not less than
or equal to 70. What are we going
to get in here? Oops, sorry. You can
play your game body. We need both
conditions to be true, in order to evaluate to true, in order to actually go into
the block of code in here. So with that out of the way, let me tell you a little
bit about the truth tables. So if we have a true and
true, we get a true. If we have a true and a
false, we get a false. If we have a false and
true, we get a false. And if we have two false, we get a false. Again, before we move on, like you have to
understand that we can add more than just
two conditions in here. We can add no matter
how many ones we want. If all of them are true, then we get true
and we can go in. If only one of them is
false, then we cannot go in. It's similar to when it's
like the veto, you know, the five most important
countries, or biggest countries, or powerful countries whatever, they get a veto vote. So for example, let's
say a US and Russia, and I don't know, France and Great Britain all say yes to, I don't know, fighting aliens. If then China decides
that they don't want to fight aliens and
they veto the decision, then we don't fight the aliens. It's the same thing in here. If everybody, if
all the conditions, the temperature is greater than 20 and the temperature
is less than 70. And something else. And something else.
And something else. And then one condition
is not true, this entire statement
would be false. And we would not go
into this block of code that's the end truth table. Now we also have
the Or Truth table. We haven't seen the Or. We'll see it in the next video. It will be a challenge for you. The truth table, we have
true or we get true. If we have or
false, we get true. If we have false or
true, we get true. And if we have false or
false, we get false. The truth table is different
than the end truth table, where we have to have
everything being false. If only one condition is true, then everything
else will be true. Okay? So that is everything
that you need to know about complex expressions
with the ends and the ors. Obviously, there's a lot
more intricacies to this. You will, it's not very common that you'll
find the ends and the ores, but it's very important
that you know them. They will come in handy
in many situations. They are a bit more specific
when it comes to their use. It's not very widely used. You can get around using
the ends and the ores most of the time, but you might, and you will, you probably will come across
the ends and the ores, so it's a good idea to
know how they operate. And the next video we're
going to be handling this squiggly line
in here that's telling us simplify
chain comparison. We can actually write this
in a more simple way. So I will see you
in the next video. Bye bye for now. Oh, and please. By the way, if you're enjoying
this, leave me a review. It helped me out a lot more
than you can ever imagine. If you ever have any
questions, please hit me up. I have my number
somewhere around. You can always contact me. You can contact your
dedicated instructor. And I will see you in
the next video. Bye bye.
30. 10. Simplified Chained Comparison: Welcome back my fellow
Python programmers. In this video we're
going to be simplifying chain comparison and we're going to have a very
confusing challenge. So very exciting times. First of all, let's look at the expression that
we've written in here. Intelligent is trying
to tell us that there's a simpler way of writing this
instruction for expression. If we write Click and we
click on Show Context action, you can see that we have
many suggestions in here. But one of the more
important ones, these are just for rewriting. But you have this light bulb. Usually the light
bulb is a good idea. You can simplify the
chain comparison. If we click on it,
you'll see that it changes our expression
to the following. This is written in
a different way, but it should probably
be more familiar to you. Where you can see
that the temperature should be greater than or equal to 20 and less
than or equal to 70, it should have the same result. So whenever you
change your code, always make sure to
test everything. And also always make sure
to test the extremities. What I mean by that, when I run, for example, 50
should work, right? But always test out 2070 numbers such as 71.19 Always test
the extremities. Always try to know
what would happen in the extreme cases with
that out of the way. Let's now take you
through the challenge. So what I want you to
do is I want you to use or I want you to change the condition
to use or instead of, and of course, make sure to make the necessary
adjustments to the code. And of course, this
should be obvious. We want to have the same output, we want to keep the
same knowledge in here. For example, we'll add a
print with I don't know, the dash is, again,
multiplied by 50. I want you to write the
code in here where we use an Or and we still have the same expression
for the temperature. Meaning for example,
if I type in 50, I should get yes, you
can play your game, if I type in 100, no, you cannot play
your games, et cetera. But this time using an Or. Posit the video right now
and go do the challenge. Okay, welcome back. How did you get on with that? In here, I'm going to
type in the following. If the temperature is less than 20 or the temperature
is greater than 70, then I will print out, you cannot play your game. I think this makes
a lot of sense. If the temperature
is less than 20 or the temperature
is greater than 70, you cannot play your game body. And then in the L
will print out, great, you can continue playing. I think this makes sense. I don't think it needs too
much explanation in here. If I write click and run, you cannot play your game 20. Great. You can play your
game 1971. You cannot. And there we go.
Everything looks to be working correctly. All right? Nothing
too much in here. Simply checking if
the temperature is less than 20 or the temperature
is greater than 70. Now notice the logic
that's happening in here. 66 is not less than 20. That's correct. Because
66 is greater than 20. So this condition
is false, right? But 66 if temperature and if temperature is
greater than 70, okay? So this is false and
this one is false. So we have two falls, and because this one is
false and this one is false, great, you can
continue on playing. So this entire expression
evaluates to a false. In here, let me show you, take you back to
the or truth table. We need to have both of them false in order to get a false. But for example in here if
I write click and I run and I say like 12, okay? So 12 is less than
20. All right. So this condition is true, but it's not greater than 70. So this condition is false. But because we have
a true and a false, or true or a false, we get a true. So this entire expression
evaluates to a true. It means we go, oops, sorry, you cannot
play your game. So before we move on, something very important to keep in mind about how
Python evaluates this. Python stops
checking the rest of the ends when it finds
one of them to be false. Because as I told
you, if we have 100 and conditions and 99% 99 of them are
true and one is false, then the entire
expression is false. What Python does
is it continues to check conditions
if they are true. When it finds one false, it does not continue looking
through the other ones. The opposite is true
when working with an or. It will look through
all the expressions in the re until it finds one to be true and it evaluates everything to be true after it. So I hope you enjoy it. I hope that made sense, and I hope you understood
how we're using the R. This is a bit of a
confusing challenge. For some reason a lot of
students find it very, very hard to wrap their
heads around this. Take the time, try to
rewrite it yourself, try to understand everything
that's happening. And in the next video,
we're going to be looking at the truth
value testing. Which is going to be a very
important and very fun video. So I will see you and the
next one by wife for now.
31. 11. Truth Value Testing: Welcome back my favorite
python programmers. In this video, we're going to be looking at truth value testing. And what do we mean by that? We mean by that where sometimes conditions don't
look like normal conditions, like when we're
comparing two things, but they still evaluate
to a true or a false. For example, a zero always evaluates to a
false. Interesting. Right, let me show you the following link and it
will be linked somewhere. Of course, if it's not,
please contact me. I always forget these
things in here. If I show you the following, as you can see, we have
the built in types. You can even look through
the built in types, Python, standard library
documentations, the typer, and to Google, you'll
find it very easy. The truth value testing
any object can be tested for truth value for
use in an F or a while. We're going to see the while in the next section condition
or as operand Hm. Of the bullion operation below. By default, an object is
considered true unless its class defines either bull method returns
false exactly, et cetera, meaning
that every object, if you just try
to set an object, it evaluates to a true. And I will show you what
I mean by that later on. But let's, let's look at a few objects that could
be considered false. For example, when we're
using a non or a false, we will see none in
the next section or the section after that. For example, zero evaluates
to a false 0.0 A float zero, j and it's an imaginary number. Decimal zero or fraction zero to one empty sequence
and collection. So if you have an empty string and you try to check for it, it would evaluate to
a false if you have empty parentheses,
empty square brackets. So these are lists and toupples. We will see them in
upcoming sections. There we go. You can also read, for example, this right here. This is where I did not create the table that
you saw a few videos ago. I actually got it from here. And as you can see, they have an extra thing which
we are going to use, which is is and the is not. Did we use it? I think we did use it in the previous section, but we're going to look
at it more this time. As you can see, the equal, the not equal and
the object identity where you try to
check if an object is the same as
another object not equal to is the same object. So we're going to
see that later on. But for now, let's test
out these theories and check if zero is actually
evaluated to a false. Back in our code in here, we're going to create a new Python file
that we're going to call the truth value testing. In here, I'm going to say if
zero I will print out true, l print out false. Even before we run this, look at what we are getting, we get a high light
over the print true. If I hover over it, it says
this code is reachable. Why? Because zero will
always evaluate to a false, which means this entire
expression is false. Which means we will go to
the Ls and print out false. If I write click
and again false, this will never change. This code is reachable. Now if we change
0-1 as you can see, now this code is unreachable
because one will always evaluate to a true
run, true, true, true. And it's not just the
one, if we type in whatever number we want or
anything for that matter, it will always
evaluate to a true. Anything other than zero
evaluates to a true. And the same holds true for 0.0 or will it? Oh,
yeah, there we go. It also evaluates to true. This is what we saw right here, 0.00 j, et cetera, et cetera. For example, if we
have a false in here, of course it will
evaluate to false, it click and run false. If we have none, which is something that
we'll see later on, we also get a false. This is the point
of value through testing it's values
that are not. You might not think that
zero would create a false, but it is considered as a false. Okay, so with that
out of the way, let me show you a
better example of this or a more practical
example of this. So for example, in
here I'm going to say name equals input. Give me your name,
give me your name. And then in here I'm
going to say if name. So I'm simply checking for name. I'm not checking if it's equal to something. I'm not
checking anything. I'm just saying if
name print out, hey, how are you else print, who are you? If I write, click and I run
and I type in Michael, boom. Hey, how are you Michael? Perfect. If I run this and I just have a space,
hey, how are you? Because space is also
considered to be of value. But if I write, click and
and I just hit Enter, it tells me who are you? If I don't type in anything, I just hit Enter, it
tells me who are you. Why? Because we don't have
anything on the name. And let me actually try to
print out name at the end. If I right click on, and I just hit Enter in here, as you can see, I
don't get anything. I just get an empty space. What's an empty
space? Where is it? It's this right here.
It's an empty string with nothing inside it
evaluates to a false. Before we continue
on, I have a bit of a challenge for you to check for an empty string change from a simple condition to check if the name is actually not empty. So should I give you a hint if maybe you didn't understand
what we want in here? So what we're doing
in here is because the name is empty and it
doesn't have anything in it, we just say if name we
want to change this. What does this expression mean? This is what I want you to do, to change this
expression to better reflect what we're
actually checking. Maybe you're still confused. If you want, you
can get the hint, but it's a bit of a
big hint if you don't, if you want to go search
for this on your own past the video right now
and go do the challenge. If not, I'm going to
give it to you in 331, an empty string. You need to check if the name is not equal
to an empty string. Pass the video right now
and go do the challenge. Okay, welcome back. How did you get on with that? The only thing that we
need to do in here, as we need to specify
that we're checking if name is different
than an empty string. This is what we are
actually trying to say when we write if name, we're checking if it's not
equal to an empty string. That's all that we needed to do. Let's run this. Hit
Enter, who are you? Run this type and anything else? Hit Enter, there we go. All right, so I
hope you understood in the next video we're
going to be looking at In and not in to check
for conditional statements. So I will see you in the
next video. Bye bye for now.
32. 12. Using in and not in in Conditional Statements: Welcome back my favorite Python programmers to a
brand new video. And in this one we're
going to be using and not in conditional
statements. I should really look
into changing the name of these videos in the lessons. Anyways, there are two uses, one for the loops and
one for the conditions. But this time we're going
to be simply learning about their use in our simple
small conditions. Let's go ahead and create
a new Python filing here. We're going to call the car, underscore checking
both in here. We're going to have a car
which is the BMW M three, nice, So this is our car. And then we're going
to have an input, which is going to be the
car name equal to input. And what car would you like? What would you like? And then I'm going to check if the car name is in the
car. I will print out. I will print out the replacement field car name is in the replacement field car. Else I will print out, sorry, we don't have a replacement field
again, I forgot to. I just got in the habit of using single quotation
marks before. I used to always use
double quotation marks. Now I always use single
quotation marks. And because I'm using
single quotation mark, I get these errors all
the time. I don't know. Force of habit, I just forget, you know, but it's okay. No harm, no foul. If I
write click and I run, I type in, what car
would you like? Well, I would like a BMW. Bmw is good. Bmw is in BMW, three. So everything turns
out to be good. But if I write Click and I
run and I type in Ferrari. Sorry, we don't have Ferrari. Hmm, not very good. Well, because it's not
part of the BMWM three. There is no sequence of characters in
here that is in BMW. So for example, if I write Click and I run and I type in B. Okay? B is in BMW. If I try this again and I
type in M3m3, is in BMW. But if I type in M space
three and I hit enter, you can see, sorry, we
don't have a M space three. So it should be the exact
same as we have it in here. The same sequence of
characters that we have in the car is used to check. If we have this later on, we'll be using this for
list as well and in loops, but for now, using it for conditional
statements is enough. Thank you for watching.
Before we leave, you have a challenge
to get another input. So you need to create another condition for
the if statement. Check if a string is
part of the car name available and instead
of the in using the in. So you need to use a
string directly instead of having this right here. So instead of car name, you need to have a actual string being used to check if
it's in the car name. Okay, positive video right now. And the more important part
is just to use the K in this challenge positive video right now and go
do the challenge. Okay, welcome back. How did you get on with that? I will comment this out and
what I'm going to do is I'm going to check if
BMW or excuse me, not in the car name
will print out. I will print out, sorry, we don't have a BMW BMW in the car name else. I'm going to print out.
Actually, I have it. I'm going to print out. Wait, not in that means
Ok. Now, it's all good. We are going to print out, we're going to say BMW
is in the car name. Right click and run. If I type in Ferrari. Sorry, we don't have
BMW in Ferrari. Makes sense then BMW. Bmw is in BMW. Everything is working
in the can't be both. There's a problem in here. If I write Click and I run, I type in BMW upper
case, BMW upper case. It happens sometimes hit enter, sorry, we don't
have BMW and BMW. The problem in here is that
characters that are in the upper case are
considered to be different than characters
in lower case. So for example, if I write BMW just one character in the
upper case and hit enter, sorry, we don't have BMW and B M. What's the solution for this? It's very simple.
There's something called a case fold in here, I can add case fold. If I hover over, it returns a version of the string suitable
for caseless comparison. Basically what it
means is it takes everything to the lower case. When I write Click and I
run F and B, hit Enter. Bmw is in BMW because we use the case
fold of the car name. Take it down to the lower
case and then compare it with BMW and everything
works perfectly. So thanks so much for watching. I hope you enjoyed. This is the last video of section
three, I believe. Maybe I'll add more later on
when we update the course. This master class will always be updated
from time to time. So maybe I'll add more projects, maybe I'll add more
lessons in here. If I deem it necessary or
something updates in Python, I will always be up
to speed with that. Thank you so much for watching. Congratulations on
making it this far. The skills that you've learned
so far are indispensable. In the next section, you'll be learning
a lot more about loops, about list stopples. You have a long
journey ahead of you, but it's a very, very fruitful journey if
you stick to it. If you're enjoying the
videos, if you're having fun, if you're learning, if you
like the quality of the sound. I'm doing my best
in here, I hope. If you're enjoying
all the quality of the sound, the editing, the everything, please
let me know in a review. Wherever you're watching
this or contact me, tell me. Wow, Michael, I am loving
this like Mcdonald's. Thank you so much
for watching and I will see you in
the next video, or next section, or wherever life takes
us. Bye bye for now.
33. Section 4 - Loops in Python | 1. Introduction To for loops: Welcome back my fellow
Python programmers to a brand new video and
a brand new section. And in this one
we're going to be looking at loops in Python. A lot of people
find this part of Python and programming learning in general very difficult. Where they have to understand this very new concept,
which is loops. Which is just having
the same code being iterated over and over every single time with a different outcome,
using different values. But I want you to
not worry at all. I've created the most
comprehensive way of learning loops
that I possibly can. Obviously, it takes a lot of concentration on
your part as well. You have to take your time, understand everything
that's happening. And I want you to really give
me your full concentration. You'll, for your full attention because the things
that we are going to learn are going to be very
crucial, very important. Not very difficult, but that require immense
concentration. So let's go ahead
and get started. And first of all, we need to
understand what are loops. Actually, loops can execute a block of code a
number of times, and that's the whole
basic thing of it. They just have the same block of code executed a number of times. Loops are handy if you want to run the same code
over and over again, each time with a
different value. So we have the same code
that we've seen before, just like we had codes and the F statements
that we've seen. But now we want to run
them multiple times, each time having a
different value. And you'll see what
I mean by that. Let's look at a general
structure of a four loop. So first of all we have four number of times
we want to loop, and then inside we want to do some stuff and the
code to execute. And of course, this
is a block of code, which means that it is indented. You can see the
indentation right here, four number of times
we want to loop. And then the stuff that
we want to do right here. Without any further ado, let's move on to
some examples and start looking at how
four loops work. First of all, let's go
into intelligent in here. We're going to create
a new project. It's of course going to
be a Python project. I'm going to put it inside
of the Python course. Inside of code right here. Yes, code and then backslash. And of course, you can
save it wherever you want. And I'm going to call this
loops in Python. Hit Finish. Yes. All right, there we go. So now we have loops and Python. First of all, we're
going to create a new Python file which is
going to be the four loops. And with an underscore
in between, we don't have to
do the underscore, but it's usually better
to have our file names all as a single word and
without capitalization, because capitalization
will be kept for classes later on
that's in the future. Don't worry about
it now. For now, let's just create this file which is four loops
and I think intel J. I will use the magic of editing to see
you when we freeze. Okay, welcome back. So first of all, I'm going to create a
very simple message. And I'm going to say that the message is equal to
the following string. I'm learning Python
as we've seen before. Each character is
an item of itself, meaning that each one of these characters has an
index attached to it. So what I'm going to
do is I'm going to go over every single one
of these characters. Meaning that I'm going
to say the following. Follow with me. Four
character in message, Colin, Print out the character. First of all, I want
you to think of what the output could
possibly be in here. If I right click and I run, this is the output that I get. Let me just stock it
right here. Look at that. I'm going over every single
one of the characters. And that also
includes the space. We've seen this before.
This includes the space. So I'm going over every
single character. I'm picking it out
of the message, I'm putting it in the
variable character, and then I'm printing
out character. Then I'm going back, I'm
going to the next character, which is the apostrophe. I'm putting it in the variable and I'm printing out character. I'm going back, I'm
increasing by one. I'm going to, I'm picking
out the character, putting it in the
variable character and printing it out the space, the L, E, A, et cetera, et cetera. By the way, we don't have
to name this character. We could name this x if we want. The output is going
to be the same. This is just the variable name, but I'm going to keep
it as character because it represents what we
are doing in here. I'm sure that at this
point you're still not entirely sure of how this
is working. Don't worry. Look at it carefully
and understand, first of all, at least
what is happening. You don't need to go
too deep in here. You don't need to
fully comprehend the minute small aspects
that are happening. Just know that we are going through the
message and putting each and every character into character and printing it
out at every iteration. Now at this point, once you've looked at
this breath, breathe out. I want you to do the
following challenge. And don't worry, the challenge
is not very complicated. It's just you using
the debugger, something that
we've done already. I want you to set up the
breaking point on the fore loop. And I want you to go through
your code and make sure you understand how this fore loop iterates over the
string message. Pass the video right now
and go do the challenge. Okay, welcome back. Maybe you've done the challenge yourself, maybe you're
waiting for me. That's okay. Let's add
a breakpoint in here. Right click and
bug our for loop. There we go. You can see that our message
is the following. Of course, it's using
the backlash for the special character which
is a single quotation mark. But now we are going to step in and you'll see that
the character is. If we step into again, we go back to the top and you'll see that on the
console we print out. Keep in mind this is
what's being printed out right now when I step into again now even though it says the back single
quotation mark, but it's just the
quotation mark. I continue. The
character now is M. I print out M. Now the
character is an empty space. I also print out
the empty space. This is not nothing,
this is an empty space. Now the character is L. I printed out the character
is I printed out. For some reason, this
is not refreshing. Let me check the message. I'm learning Python. But in any case, as you can see, we are changing the
character and clear all. Let's look at what happens. Okay, there we go. Now it's working again for some reason. But as you can see, we are going over every
single character. Let me terminate this and try to debug it again on your side. I'm pretty sure you're
not having this issue. If you are, there we go. We're printing out
the apostrophe. The, the space. Okay, there we go. Now
it's working again. I'm not sure what was happening. L, E, and again it's stopped. But as you can see, we are going through every and
each character. This was your
introduction into loops. Of course, there is
a lot more to loops, but what I want you
to understand is we are doing this code
multiple times. Let's look back
at the structure. So first of all, the loop can execute a block of code
a number of times. This is our block of code. Notice the intentation
that's behind it. Loops are handy if you
want to run the same code over and over each time
with a different value. We're running the print over and over and over every single time with a different value where the character is
changing the value. The structure of a four loop is just four and then the number of times we want to
loop right here, we start with the
four and then we have the number of times
that we want to look. Now we didn't define
or we didn't set the number of times that we
want to loop beforehand. We just said we
want to loop over this message because
message is a string and strings are meaning that
we can iterate over it. So we're going through
each individual character, extracting the information
from that string and putting it into the
character variable in here. And then printing
out the character. Then we're changing the
value and printing it out again, again and again. And we can keep doing that
until we get to the end. So ladies and gentlemen, thank you so much for watching. In the next video,
we're going to be looking at debucking loops
a little bit further. So I'm very excited
to see you there. Please don't be
petrified by what you, what you just saw.
Take your time. Breathe and breathe out
and trust the process. It's not as hard as
you think it is. So I will see you in the
next video. Bye bye for now.
34. 2. Debugging a for loop: Welcome back my favorite
python developers to a brand new video. And in this one
we're going to be debugging our for loops further. First of all, we
need to look back at an older project that we had. I'm going to create a
new Python file in here. I'm going to call it
data data separation. Let's just call it
dat coming in loops. I'm not the best
at naming things, okay, so let's just get
that out of the way. If you remember, in
an older project, we had the following
data coming in. Now mine might be different
than the one that you wrote, but the more important
part here was that we had the first a numeric number in
here and then a character, and then four numbers,
and then some kind of character and then four numbers and some kind of character. And what our goal was, it was to remove all the separators and
put them on the side. Or at least to print out all the necessary numbers without these special
characters being added. So the way we did that was
using the following code. We printed out the
data coming in from one to the end
with a step of five. So for example, if
I write click Run, this is the output that I get. I get all of these separators. And now I can use that
as a filter to remove all the unnecessary information and have clean
numbers coming in. Well, the problem
with that is if I tried to add just a
single number in here, let's say for example, three, now the distance
is no longer five. What I get is the following. This filter is bad. If I tried to use this filter, I would lose the two, the fours and the six and completely corrupting the
data that is coming in. How would we handle this? How would we make
sure that the data coming in is filtered correctly? How do we properly extract the separators to
create that filter? Well, for that we're
going to be using loops. Let's get rid of this code. Well actually let's comment it out just so we can always know
what happened in the past. Will build on top of it in here. First of all, I will add random
numbers and some random, let's just add, I don't know, a multiplication, a
percentage in here, and just throw things
all over the place just so we can see
how we can fix these. Of course, using
the data coming in and the slicing that
we've done right here, it's not possible to
extract this information because we have a
very defined step. The way to do this
is first of all to create a variable separators, sepa raters, and it's just going to be
equal to an empty string. We're just setting things up. Then we're going to go
through the data coming in. You should know by
now how to do this. I want you to take just a
few seconds to think about how we loop over each individual character
and the data coming in. We say four character, remember this is just
the variable name. We can call it whatever we
want in data coming in. Then in here I'm going to say, if not character is numeric, I'm going to say separators plus equals the character and I
will print out the separators. What is happening in here? First of all, I'm looping
over the data coming in, or actually it's
called iterating over the data coming in. Every single character is being put into the
character right here. Then I'm checking if this
character is not numeric, meaning it's not a number. If I hover over the numeric, you'll see it returns if the string is a numeric
string and falls. If otherwise, if it's six, then it is numeric,
this is true. True is false, which means that we don't go into
these conditions, or into this condition, or into this block of
code in the if statement. I hope you know your
conditions well. We've extensively looked at
them in the previous section. If the character is not numeric, so like let's say
the dollar sign, then this statement
in here is false, which means with a knot
behind it, it becomes. Which means that
we do go in here, and which means we append our separator with
the character, and our separators string
grows by the way, plus equals. I'm not sure if we
went on this before, but I will just do
it a second time. Separators equal
to separators plus character we are building
on top of our separator. So let's now run this and we are going to
dissect it further. I will right click
and I will run, and this is the
output that I get. As you can see, I have
all of these separators, including the space right here, all printed out properly.
So take your time. I want you to look at this. I want you to pause the video and understand what
just happened. Because I'm going
to add a line of code in here that will help
us understand this better. I'm going to print
out the separators at every single iteration so that you can see
what is happening. If I right click and I run, look at how this works. We start at the beginning, we have our six
right here we are. Going through the character.
We start with the six, we print out the separators. There we go. We
don't have anything. We check, if not is numeric, so is the six numeric, is it? Of course it is. This is true. Not true is false. Which means that we
don't go in here, which means we just
go back to the top. We don't append our separator, we print out the separators. Again, this is the line of code we are printing
out the separator. Now we have the the
character that is numeric. Is it a numeric number? I can hear you in the
back. No, it's not. Which means that this is false. Which means that this is true. Which means we go
into the statement and we append our separator
with the character. So our separator
grows with the comma. So that when we go back and
now character is at three, We print out the separators
which is just a comma. And then we check if
three is numeric. Yes it is. Then we don't
go into the condition. We go back to the top. We
print out the separators. We print out the separators. We print out the separators. And now we get to the dollar. Is the dollar numeric? No, it's not. So this
entire statement is true. Which means we
append our separator with the character and now we
have the commodellar sign. Commodellar sign.
Commodellar sign. Remember we're going
over all of these. Then we arrive at
the semicolon, boom. We append the semicolon, we arrive at the star, we append the star, we arrive at the forward and et
cetera, et cetera. And we keep growing this. So if you can get
through this properly, then you are golden. Now I have an
unofficial challenge, which is to add a
breakpoint in here and go through this code
again using breakpoint. And I want you to fully comprehend this
without any doubts. Okay, so I'm going to go
through this with you. So I'm going to be debugging
the data coming in. So let's go ahead and
see what is happening. I will close this down. We step into data coming
in is the character six. We print out the separators. Of course, the separators
is just nothing. It's just an empty line. Is the six a
numeric? Yes, it is. Which means not character
is numeric is false. Which means if false, we will not go into this. Then we go back to the top, Now we have a, we print
out the separators. If not, numeric is the common
numeric. No, it's not. Which means not character
is numeric is true, which means that we delve
into the separators. The separators, look at what's going to happen
to the separator here. Boom. Now it has a, we
go back to the top, now we're working with three. We print out the separators
and we have the coma at last. The three numeric. Yes it is. We do not go into the separators
plus equal character. We go back in here, boom, boom, six for the dollar sign, we print out the separators. Is the dollar sign numeric? No, it's not, meaning not. Character is numeric means
that this one is true, which means we do go
into the statement, which means we do append
our separators with the character and we add
the dollar sign in here. I'm going to stop the program. I want you to continue
through all of this and make sure that you
understand how it's working. That is your challenge. Before leaving, I just want to show you what
would happen if I just add an equal sign in
here and not a plus equals. Because some of you
might be thinking, what does it mean to append
using the plus equals? If I write Click and I run, this is the output that I get. I simply get the last character that is not numeric, the plus. My goal in here is to add
all of these together. I want to have a collection of these separators so that I
can then use them at the end. That's why I add
to the separator. I take the separator, let's say the separator
in here is the coma. I take the separator right
here. It's the coma. I add to it the dollar sine. Now I have coma. Dollar sign. And then I put all of this
into the separator again. Now the separator is
equal to the dollar sine. Then I find the semicolon. Now remember the separator right here is a coma dollar sign. I add to it the semicolon and, and I put this entire thing
back into the separators. So now I have a comma dollar
sign and the semicolon. Okay, so I hope that is clear. Thank you so much for watching. In the next video,
we're going to be looking at loops over a range which is slightly different than iterating
over a string. So I'm going to see you in the next video. By bye for now.
35. 3. for loops over a Range: Welcome back my favorite
python programmers. In this video, we're going to be looking at loops over a range. I'm going to create a new
python file in here that I'm going to call four loops. Underscore range. In here, I'm going to
simply say for I in range, that range is going
to be one through 30. I will simply print out in here the following to dots
replacement, field dot format. And then, by the way, I don't want to use
this format format. I'm not sure if
I've been using it before where I
changed it exactly. Because sometimes I update this course and
this master class, what I will use instead
is not the format, but instead inside of this, I will hit and hit Tab, and you'll see that a small F is added behind this with in here. Which gives us the same output as the format using
the replacement field. But anyways, look at the
output that we have. I said that I want I in the
range of one through 30, but when working with ranges, just like when we
were working with the slices, it's up to, but not including
I starts at one, but it ends at 29. Okay? That is very
important to understand. We are going up to
but not including. And that's the basics
of using a range. For example, I
want you to add a, let's also remove
one extra line. Let's add a debugger in here. Let's right click
and debug our loop. Right here, we step
into I equals one, I equals two, I equals three. And by the way, again, of course you should
know by now that I is just an arbitrary
name for our variable. You can call it
whatever you want, just like we did in the
previous videos where we had four character
in message. The variable name should represent what we
are going through. I in this case represents index, or generally in math
they use I, JK, or XYZ. So you can use whatever you
want of course in here. But as you can see, I
increases and we print out. So we are doing a
loop over this range. We are producing or
printing out or executing the same code every
single time with a different value
which is changing. This should be very
informative for you. I hope you understood
what we've done in here. I hope it's clear to you. If it's not, you have
a bit of a challenge, which is to test
out some ranges. So I want you to
play around with the ranges and I want you to experiment with
various ranges and see what works and
see what doesn't, just as a small hint. For example, you can
use the range of -5.0 I also recommend you
to go through ranges. Of course, in the next video, we're going to be delving
deeper into ranges on our own, but for now, I want you to test out these ranges yourself. Pause the video right now
and go to the challenge. Okay, how did you
get on with that? In here, for example,
let's say I want to start at zero, right
click and run. There we go. We start at zero, but it's also up to,
but not including. If I wanted to include the 30, I would have to go to 31 so
that the 30 is included. What if I try to do minus
six in here, to 31? What would happen? Do I start
at minus six or minus five? I start at minus six because
the beginning is included, only the end is not included. I hope you tried a
few things in here. For example, maybe if
I add an extra tab. Of course, this is not
part of the four range or the manipulation in here, but if you try to add a tab, you'll see in here that
you have a warning telling you that you've
invented a few things. Still works, but you have
over intented a few things. Yeah, that's the basics of it. In the next video,
we're going to be delving deeper into ranges. But understanding ranges is very important because
they are going to be not the main case
use of our for loops, but they are still
very, very important. So you need to understand
how these operate. Thank you so much for watching. I hope you enjoyed this
was a shorter video and the next one we're going to be delving deeper into ranges. So can't wait to see you
there. Bye bye for now.
36. 4. Deeper into Ranges: Welcome back my favorite
Python developers to a brand new video. In this one we're
going to be looking deeper or telving,
deeper into ranges. For example, what would
happen if I have this range? What do you think the
output is going to be like? If I write, click and I run, okay, This is the
output that I get. So when I don't
specify the beginning, I just start at zero. You'll see that ranges are
very similar or operate in a very similar way to
how slicing operates. If I don't specify
the beginning, I just start at zero. We can also provide in
here a step, for example, when I have three of
these, I start at zero, I go to 30, and I have a step
of two. What is the output? Think about it before we
run. Boom, there we go. We have 0246. A boom, boom, boom. We go at a step of two. And of course, if I have three, well it should be obvious we
go at a step of three next. What would happen if
I do the following? If I do 36, then minus two. You should know by now that
this is a step of minus two. What would happen in
this case, please? I want you to think of the
output before you run this. Boom. There we go.
We go backwards. Of course, we have the
starting 0.30 we have the end 0.6 and we have
a range of minus two. I want you to take the
time and play around with all of these
expressions and values and see what would happen if
you add a positive step with a beginning higher or
lesser, or whatever. Test out a few
ranges. Play around. Please make sure that
you understand this correctly before moving on
to the following challenge. Your challenge is
to use your range. So go back and find the file, complex conditions in
a previous project. And then use the
range instead of the operators to evaluate the condition on
the temperature. So if you remember, we created a mini mini project
where we would check the temperature of our GPU and see if it was valid
to play our game. I'm just going to add
this code right here. So I will create a new Python
file and I will call this the underscore complex range CPU temperature. And I will just
paste this code in here just in case you
don't have the code. If you remember,
this is what we had. And then we also simplified
the chain comparison. So now what I want you
to do is I want you to change the operators into a range to see how
ranges can also help us, not just in four loops,
but also in if statements. Pass a video right now
and go do the challenge. Okay, how did you
get on with that? In here it's very simple. We can simply check if the
temperature is in range 2071, why did we set it
to 71 and not 70? Because it's up to, but not including when I
write Click and I run, how hot is your GPU? If I type in 70, remember if it's
between 20 or 70, if it's equal to one
of these values, then we can continue playing. If I do 71, you can
see that I cannot play y because 71 is not
included in the range. It's up to but not including. And that is very
important to understand, Ladies and gentlemen,
I hope you enjoined. In the next video,
we're going to be looking at nested loops, which means we're going to
have loops inside of loops. So it's going to be like loop
seption or loop inception. If you didn't get the joke, I'm very sorry for making it and sorry for
that clap as well. I will see you in the
next video where we will be creating loops inside
of loops by bye for now.
37. 5. Nested for loops: Welcome back my favorite
python developers to a brand new video. And in this one, as I told you, we're going to be
looking at nested loops, meaning that we
are going to have loops inside of other loops. So let's not waste
any more time, and let's go ahead
and get started. The first thing we're
going to do is we're going to have the perfect
example of a nested loop, which is a calendar. So I'm going to
create a calendar. And why is that a
perfect example? Because we have years
which have months, which have weeks,
which have days, which have hours, which you
can start thinking up this. And it's a repeated cycle. Every year has 12 months. Every month has four
weeks approximately. And then every week
has seven days. Exactly. So we're
going to be working on the weeks and the
days in this situation. So first of all, we're
going to create the weeks, so I'm going to say four
week in range range. That range is going
to be 15. In here. I will simply print out
week to Dots, replacement, field and week if I write Click and as you can
see we get week one, week two, week three, week
four part of the month. But now what if I
wanted to print out the days that
are in that week? I would add another
four loop in here that is nested inside of
the previous four loop. I will say four day in range. And that range will go
one through eight again. Remember why are we using 5.8 Because this is up to
but not including. I will print out back. And do you remember what
the backslash T does? I want you to remember
very carefully. Backslash replacement
field, sorry, day replacement
field and the day. What does the backslash
D do If I write, click and I run?
Boom, there we go. It adds a tab behind
our day so that we can have this nice looking separation just
for the fun of it. I will also add a
print in here with these dashes multiplied by 20. And add a space in your right click run and boo, there we go. We have week one, day one, day two, day three,
day four, day five, day six, day seven, and
then we move on to day two. So how is this working? Well, I'm not going
to tell you how. I'm going to show you how I'm
going to add a debugger and I recommend that you do this
yourself without my help. And then re watch how I
do it and explain it. So I'm going to debug our calendar and we
start at the top. We start at week one. We print out week one, and now we are on the
days we have day one, we print out day one, but we don't go back to the top. We don't go back to the week, we instead go back to
the current for loop. We continue doing this for
loop again again and again, and again until we get to seven. And then when this
loop is finished, the condition in here,
it is no longer true. And when I say condition, it's just the condition on the range. Meaning the range is
one through seven, we are no longer at seven
or we went above it, we printed out seven, we
print out the dashes. And only then do we
come back to the top. We increase the week, Now we're in week two, and then we go back to the day. And the cool thing about
this is that we actually reset it to one and then
we continue on doing this. So I hope that is
clearly understood. I don't think there's
much more to say in here. Again, as always, if you
ever have any questions, please refer to me or your
dedicated instructor. Ask them any questions. They are available to you. So I hope you understood
what is happening in here. Now, I'm going to issue
you a bit of a challenge. Before you do the challenge, please take the time to clearly and properly
understand this because it is going to be crucial for the
multiplication table. The multiplication table is another good example
of using nested loops. Because we have two numbers, create a new Python file
called multiplication table. Use nested loops to print out the multiplication table
from one through nine. Your output should look
something like this. One multiplied by one is 11, multiplied by two is 234. And then we have two
multiplied by 122, by 242 by 36. And you have to do this
for all the numbers. I want you to start thinking
of nested loops in here, because remember, it's just like the weeks and days
that we worked on. You can imagine that
this is the week 1.2 on the left hand
side are the weeks, and then the numbers
one through nine on the right hand
side are the days. And then finally,
we have to multiply these together to get the
output. So take your time. And of course, this should
be 12 through nine, so all of the nine
iterations should be there. And also, I want you
to add these dashes. Pass the video right now
and go do the challenge. Welcome back. How did
you get on with that? I will create a new Python
file that I will call the multiplication
underscore table. In here, I'm going to
say four in range. And the range will
be one through ten. Because remember it's up to, but not including, we want
the nine to be there. Then inside I'm going to say four j in range and it's
going to be one through. Then in here I will print out that I have the
following replacement field. Then I hit tab for the
autocomplete multiplied by replacement field j equal to the replacement field
I multiplied by j. This is where most
people struggle. Then finally, where should
we add the print on which level? On this level? Maybe something that
I did not mention in the previous example
in the calendar. This print to which four
loop does it belong? Does it belong to this
one or to this one? Of course, it belongs to the following four
loop because it is not part of the block of
code of the first four loop, because everything that belongs to this four loop is indented. You'll see that this print does not have the indentation
for this loop. It has the indentation
for this loop. For example, I want you to
tell me what would happen if I do this print right
here on this level. Where will the dashes appear? There we go. We can see
that they will only appear at the end
because this print is no longer part of this
four loop. There we go. Now it appears in
the correct place. Back to the
multiplication table. This print belongs
to this four loop. When I write click and this
is the output that I get. There we go. This is our
multiplication table. One multiplied by
11 by 21 by nine, and then two by 22 by 32
by 93 by 13 by seven, et cetera, et cetera. There we go. So I
hope you understood. I hope you tried your best. Many people fail at creating this challenge or
doing this challenge, but if you were able to do it, it means that you are
on the right track. In the next video, we're
going to be continuing our use of the fore
loop and we'll see another very useful case. And we'll have our
first look at lists, which is going to be delved more deeply into in
the next section, but we'll just have to use them in these certain
specific situations. Thank you so much for
watching and I will see you in the next
video. Bye bye for now.
38. 6. Using continue in for loops: Welcome back my favorite python programmers to a
brand new video. And in this one we're
going to be using the continuum in our for loops and understand
what these are. But continuous are not enough in this video because
we are also going to be looking at lists or taking a small glimpse into
what lists are. So it's a collection of objects that are
of the same type. Now as I told you in this video, we're just going to be covering the surface level
information about lists. We have a complete
section dedicated to lists and couples and data
handling using these tools. But on the surface level it's a collection of objects
of the same type. They can be accessed
using an index, just like we can access certain characters in a
string using the index. And they have methods
available to them to access, sort, search, and modify. Now let's look at a
structure of a list. It looks something like this. So we have a list called computer items and
it's equal to, and we open up the
square brackets indicating that this is a list. We will learn that there are
couples that indicate or are indicated using parentheses. But for now, let's just focus on the lists which have
square brackets. And you'll see that we
have these objects, sometimes I refer
to them as items inside of this list and you'll see that they are all
of the same type. Now of course, later on when
we delve deeper, deeper, we will understand that they don't have to
be of the same type, but 99.999% of the
time that you will encounter lists or topples or anything for that
matter in your life, or the items are going
to be of the same type. Just like right
here, this is a list of strings with that
out of the way. Let's now go ahead
and test these out. Right here, I'm going to create a new Python file
that I'm going to call the Car
underscore dealership. I'm going to create a
car underscore list that is equal to the following. I will have BMW, Honda, Ford, Volk, Volkswagen,
and Volk Swagen. There we go. Sagain.
Yes, finally. Then we will have Ferrari. Then we will have Ad. That will be our
last car in here. We are going to iterate
over this car list, just like we've iterated
over the message right here. We can do the same for our list. I'm going to say four
car in car list. I will print out I
like driving my car. If you go back into the four, you'll see that in here
we are iterating over the message using the
character variable. The same thing
holds true in here, we are iterating over the car list using
our car variable. If I write click and I run, I get the following output. I like to drive my BMW, I like to drive my
Honda, my Ford, my Volkswagen, my
Ferrari I wish. And my Audi. Okay. How did I do that? Anyways, as you can see, we are iterating through the list and we are
printing it out. Now the next thing
I want to do is I want to issue you a
bit of a challenge. Your challenge is going
to be to drive all of them except
change the code to drive all the cars except for the Ford. I will
give you a hint. If you don't want
the hint, pause the video right now and
go do the challenge. If you want the hint,
then you need to create an F condition inside of the for loop, and
that's basically it. Pause the video right
now and the challenge. Okay, how did you
get on with that? As we've said, we are iterating over every single one
of these objects. What I want to do is
inside of the for loop, I'm going to say if the car
is different than Ford, only then will I print out I like driving my car if it's
different than the Ford. Now, if you use a
different code and you still had the same
output, congratulations. If not, I want you to start taking these challenges
more seriously. Take your time. Even if
it takes you 10 minutes, even if it takes you
research on the Internet. If you try to do these
challenges yourself, you will get a lot more benefit out of the solution that
I provide you with. Now if I write Click
and I run, there we go. You can see that I
like driving all of these cars except for the Ford. But there is a different
way of excluding an item from being
printed out in a list, and that is by using
the continue in here. I will change this
condition to be equal to what do you think we
should be writing in here? You should have a hint, which is the name or the
title of this video. It's the continuum. If I write, click and I run, you'll see that I
get the same output. What is the continue
doing in here? Let's not theorize about
what the continuum is doing, and let's actually try to use a debugger and see
how this is working. First of all, we start off at
the car list. There you go. Car is B, Is car equal
to Ford? No, it's not. So we print out, I
like driving my BMW. Honda is not equal to the Ford. Now, Ford is equal to Ford. And look at what happens. We go into the condition and
now notice which line of code is going to be
executed. Can you see that? Basically what the
continuum does is it entirely avoids the
rest of the fore loop. Everything else that's under
discontinue will be ignored. Everything that's left to do in this four loop will be ignored. Some languages don't
have discontinu. You're probably never
going to really the continuum during your day to day life Python development. But it's important
that you know that you have access to these tools. In the next video, we're
going to be looking at something that is
much more important, which is the break. And the break, unlike
the continue here, is going to be
very, very useful. I hope you enjoyed, I
hope you understood, and as I told you, please start doing your best
in these challenges. They are not just for skipping, they are not for you to just look at me how I
solve these solutions. You have to go out and solve
these problems yourself. Thank you so much for
watching and I will see you in the next video.
Bye bye from now.
39. 7. Using break in for loops: Welcome back my favorite python programmers to a
brand new video. And in this one
we're going to be using the break in here. If we change this from
continue to a break, what happens is we
only print out I like driving my car until
we get to the Ford. As you can see, we are not
driving anything anymore. And this is most useful
when you want to save memory when searching for a
certain item in your list. Imagine you're trying
to find the Ford. Once you find the Ford, you just print out the
information or anything. You just give the value, you represent that value and you stop searching through the list, so this can be very handy. And you will be
seeing a break a lot, not just during the scores, not during this master class, but throughout your entire programming career
going forward. Let's now go ahead and create
two more valuables in here. I'm going to say, first of
all that I have the car to drive and it's
equal to the Ferrari. I really, really wish. Then I'm going to have
car underscore index which is equal to non, and I'm going to explain to you later on why we're doing none. But before I do that
or actually there is a dedicated video to
understanding why we use none in here. Before we do that,
I want to just print something out
that we haven't seen. That is the length
of our car list. I'm not sure if we've
discussed length before, I'm pretty sure we haven't. But the length, basically
what it does is it gives us the length of the list or the
string that we have. For example, we have
123456 cars in total. So the length of the
car list is six, and that shouldn't be
any surprise to you. That is the length. That's
what length gives us. Now I want to do
something in here. First of all, I will
comment out this four loop. And then in here I'm going
to say four index in range. And the range is the
length of the car list. Then I'm going to check if the car list at the index is equal to the
car that I want to drive. I'm going to say
that the car index is equal to the index. What are we doing in here? First of all, what
does this mean? If you remember, when
we had, for example, right here back
in the for loops, we have this message, right? I can access, for example, a message at position 12012345. Let's say five. What do I get? I get because I have 101,234.5 I have at five. The same logic holds true
in the car dealership. For example, if I
want to print out car list at position
three, what is the output? Think about it before
testing it out. The answer would be Volkswagen
exactly right here. What I'm doing is I have the index and I have the range of the length of
the car list, which is six. What's the range over six? It's zero through five. Index changes 0-1
to two to three. And then I use that
index variable inside of the car list and I get car
list at position zero. Bmw, I check if it's equal
to the car to drive. If it is, then I set the
car index to that index. And then when I'm done,
I'm going to print out, let's just add a
replacement field in here. Is in the replacement
field position in here. We're going to have
the car to drive in. The index or the car index. Okay. Right click and run, and your Ferrari is in
the fourth position. 01234. Perfect. What I recommend you do is
have a mini challenge, it's not an official challenge. I want you to add a break point, and I want you to go
through this for loop. And I want you to clearly
understand what is happening. And I also want
you to tell me why this is not as efficient
as it could be. Right click and ID buck in here. I have the for loop. I start coming in index is zero. What's at index zero? B, B is not equal to the
car that we want to drive. We are at index one. What do we have at index
one? We have the Honda. The Honda is not equal to the
car that we want to drive. Index is two. It's four. It's not equal to Ferrari, Volkswagen, it's not
equal to Ferrari. Now we are at index number four. And what do we have at
index number 401234? We have the Ferrari car
list at index four, is now equal to Ferrari. And is it equal to
the car that we want to drive, which is Ferrari? Yes, it is. We step in here, we set the car index
to the index and boo. And now we have car
index equals to four. Perfect. The only problem is
we've already found our car, we are ready to drive it, but we still go into the four and we still
continue in here. And that is an issue because it might not seem like a huge
issue to you because, well, you can just say, okay, so we did one extra
iteration over the car list. What's the big problem?
What's the big issue here? The issue is, what if we found Ferrari at position number four, and we had 10,000 cars, so we would have to do 9,996
more cars unnecessarily. Keep that in mind unnecessarily. And imagine if each one of these iterations
required 0.1 seconds, multiplied by almost 10,000
that's 100 seconds more, I think if my math is correct. Or 1,000 seconds more,
1,000 seconds more. So imagine the pain at
1,000 seconds extra. Unnecessarily, what we do in here instead is
we add a break. Now if I debug this again, by the way, I have
the same output, but the only difference is when I get to index number four, I said the car
index to the index, I break out and
boom, look at that. I no longer go back
to the for loop, I just break out and
I do not continue. And if we had 10,000 cars and we found Ferrari at
the fourth position, we would have broken out
and we would have not had to wait for
1,000 extra seconds. So, I hope you understood
how the brake works. It's a very, very,
very useful tool, especially when we start
working with Y loop, which is not going to
be the next video, but it will be the
video after that. So thanks so much for watching
and I will see you in the next video where we will understand what this none is. It means nothing. But why do
we use it in this context? I will see you in the next
video. Bye bye for now.
40. 8. Why use None: Welcome back my favorite Python programmers to a
brand new video, and in this one, we're
going to be looking at why did we use none in here. So imagine that we were
looking not for my Ferrari, but for my BMW. If I right click and
I run, what do I get? I get zero position. Doesn't look very nice, so we can't just use the
car index that we get, we need to add a plus one to it. It makes a lot more sense. And I think we can or we can
not have the spaces in here. So now, it's in the first, the e doesn't look nice, but at least now we
have a better position. Let's just remove this
for the sake of clarity. So now, if for example, I'm looking for my Ferrari,
boom, there we go. It's in the five or in the five position or
in the position five. Maybe that would make more sense in the position
five. Okay. There we go. Now, it makes a lot more sense. But what if I had the lambo? So I'm looking for my ambo. If I click and I run, oh, I have an error. And what does that error say? It says that it's a non type. So the car index is of type. None means nothing. It's just a placeholder. You can call it if
you want, none is a constant that
represents nothing, and it helps us avoid
errors such as these. So now we can, for example, change a few things in here, create a condition. And that condition is going
to be created by yours truly. So you're going to create a condition that checks if
a car index is not none. Print out a message
based on that and add an L statement with
its own message printed. So, pause the video right now and go do the challenge Okay. How did you get on with that? So in here, I'm
going to check if the car index is not none. I will print out your
car is ready to drive. So now we avoid this issue. There we go. Now, we don't have any errors. And I'll add an L
statement in here that is going to say print out. Sorry. Couldn't Blah. Cool. Find your car to drive, right click and run. Sorry, couldn't find
your labo It's okay. No worries. Don't
sweat, you know? My lambos probably
somewhere. I don't know. Anyways, as you can see, using the noun is
very important. Now, some of you might
be saying, well, we could have used zero. But that's not good. Ba as you can see your lambos position
number one. Not good at all. Now, some of you
might have said, Why not use minus one? Well, as you can see, your
ambo is in the zero position, but you're telling
me that, wait, that is because we have not none in here because we're
checking if it's not none, and that's why the
condition is working. And that is indeed true. Now, we could have
used minus one, but in certain conditions, You might encounter
something like this. You might have Car
list minus one. And what do we have
if we try this, Car list minus one is the Audi. Because remember, in this
list, we can go backwards. So it's just a more
convenient way of using the n to avoid issues
such as these. So I hope you understood
why this is so important to use and why it's necessary
to have a placeholder like. We are going to see a lot more of this being used
down the line. In all of our projects,
and of course, you will see it a lot in your path through
Python development. Now, to be honest with you, all of this code is
kind of unnecessary. There is a much
better way of doing this or at least right
here with this for loop. If we comment this out, we can actually
do the following. We can say if car to
drive is in the car list. We can say that the
car index is equal to the car list dot index. Car to drive. And we're going to look
more at this code, and I understand it on a much
deeper level later on when we learn about lists
and tuples or in the upcoming section,
and boom, there we go. Now it's telling me, sorry, we can't find the lambo. But if I'm trying
to drive my ford, we should see that my Ford
is in position number three. Okay. So basically what
this does in here. First of all, it
checks if the car to drive is in my list at all, meaning that it goes through the entire list and
compares each value or each item and sees or checks if we have the car
that I want to drive. And if it does, then we set the car index to the
car list dot index, which if you hover over it, it tells us returns the
first index of value, meaning that let's say we
have we're looking for Ford. We send in Ford as the car
to drive to this index and it gives us the index and sets it to the car
index in here. So I hope you enjoyed this is a little bit
more advanced code. We're going to see it in
the upcoming section. But I hope you
enjoyed this video. I hope you understood why
using n is so important. And in the next video, we're going to be looking at loops that are very
similar to four loops, except for, it's a
conditional loop. So I'm going to see you in
the next video by by for now.
41. 9. Introduction To while loops: Welcome back my favorite Python programmers to a
brand new video. And in this one
we're going to be having an introduction
into while loops. First of all, what is
a wire loop in Python? Similar to four loops, It executes a block of code
a certain number of times. But the difference this
time that instead of determining the number
of times beforehand, we wait until a certain
condition is met. So that we can always redo the wire loop until
that condition is met, and then we jump out
of the wire loop. So let's look at a
structure of a wire loop. We say that while a
certain condition is true, we do some stuff, we
execute some code, and we keep doing it while
this condition is true. So that's the idea of it. While a certain condition
is true, we execute. So we don't know the number of times this wire loop
is going to execute. Unlike four loops where we
have a predetermined amount of times that we will execute the code in a
while loop, we don't know. We will keep doing this loop until a certain
condition is met. And let's go ahead and see how that is going to look like. First of all, I'm
going to go back into my code in here
and I will create a new Python file that
I'm going to call the Wi loops book in here. I'm going to issue
you a challenge. Not where it's not
a wild challenge, it's a simple four challenge. I want you to create a four loop that iterates over
a certain range. I want you to print
out the index at every iteration, and
that's basically it. Pass the video right now
and go do the challenge. Hey, welcome back in
here for I in range 26, I will print out I equals I tab in order to automatically
add the F behind it, which will allow us to
print zero through 25. Again, we've seen this before. You should have done this
challenge very easily. Now what I want to do is
I want to convert this into a Wiloop so you can
see how things work. First of all, whenever we
are working with a y loop, we always need to have a condition or an object
that we start with. Right here, you can
see that we set j20. We're going to say while
j is less than 26, that is the condition
that we're waiting for. I'm going to print out J
equal to replacement field J. Now if I write the
click and I run, what do you think
is going to happen? Well, as you can see,
this loop keeps going. What is the problem in here? Well, the problem is that
J stays zero, right? There's increasing J, nothing changing the
value of J anywhere. And what we end up with
is an infinite loop. Now, usually infinite loops
are extremely dangerous, and they are the main cause
of all programs crashing. But fortunately,
this is Intellij. It has a built in protection
for things such as that, meaning that it will
never go infinity. It will slow down and will
keep producing this output. But we never want to have this. We never want to have
an infinite wire loop, and this could be a big problem. So we need to have some way to change the condition
inside of this wire loop. So we have to have in
here j plus equals one. Now when I write, click on, you'll see that we stop at 25 and we started
with j at zero. These are the things that
we always need to watch out for when working
with a y loop. First of all, we have to have the initial condition
right here. We have j equals zero. You cannot start your y loop
without this condition. Of course, later on when
we expand on this example, we're going to see
more and more of this. But this is the main line that you have to toe when
working with a Y loop. Second of all, you
always have to have some kind of code inside of your Y loop that will change
your condition to false. Meaning that J right
now is less than zero. Less than 26, It's
equal to zero. So we print out J, and then we increase J by one. Then again, and
again, and again, and again and again
until we get to 25. And at J equals 25, we increase it by
one, it becomes 26. When we go back in
here and we check, is 26 less than 26? No, it's not, it's equal to 26. And that is why we jump out of the Wi loop because
this condition is no longer true right here. While a certain
condition is true, we do some stuff and
we execute some code. When this condition
is no longer true, we exit out of our loop. That's the big deal
about while loops. It's exactly like
four loops with a few caveats added
on top of it. Or meaning that we don't
have a predetermined number. Of course, in this case we have, but sometimes the conditions
will be different. I think in my opinion, while loops are more important
maybe than four loops, they come in handy in
a lot more places. They are more dynamic. So let's go ahead
and add a debugger. And I want you to
do this on your own and then come
back to the video. So I will right click
and I will debug. And actually, let me put this to five because I don't want to go through
all of these numbers. So I will debug the code. And let's look at what happens. J right here, you can
see it's equal to zero, while j is less than five. We jump in, we print out, we go back to the top. Now notice where we are going. We change the J. Now J is one, the condition is still true. One is still less than five, J 2j3j4. Now J is five. If we go into the wire loop, it evaluates it just like a normal if statement
and it's not okay, so we just jump out of it. Ladies and gentlemen, this is your introduction to why loops. In the next video,
we're going to be delving deeper into wire loops. We're going to see
how we can use the break and why
these two pairs, the wire loop and the break
are such a powerful force. I will see you in the next
video. Bye bye for now.
42. 10. Deeper into while loops: Welcome back my favorite
python programmers. In this video, we're going to be delving deeper into wild loops. Before we continue on and
create our new project, which is pizza toppings, our mini project, we need to understand a few things
that are happening in here. Even though we've
already covered these, I think it's important
for us to take a closer look to properly
understand what is going on. So first of all, as
we've said before, we always need to initialize. We always need to be able to change the condition in here. And we also need to make sure that this condition
actually ends. Now with this situation, we make sure that when it's while or while J
is less than five, we will continue
going through this. Now, some mistakes
that can happen. For example, if you
have right here the J shift at shift tab
in order to remove a tab. Tab. In order to
add an extra tab. You'll see right here, somebody might be looking at
this and be like, nice, I mean, I'm increasing J, what could be the problem? The problem is that
you're increasing J outside of the block
of code of our loop. So it's very important that you know that the J is inside, that the condition is
changing on the inside. Another thing that
you will see later on is that sometimes we
can say while true. If we have while true, it means that we will
keep doing this forever. And you might be telling me, okay, how's this forever? What do you mean by forever? I mean forever. J will keep increasing forever.
And how do we stop this? Well, in situations like these, we would have a condition
in here that would say if j is less than, or wait, if J is greater than, I don't know, 12,
we would break. If I write click and I
run, boom, there we go. When we get to j equals 12, this condition becomes true. Or actually, when
j is equal to 13, because 12, we actually
print this out, j plus equals one, and boom, now we get this one, it's
13 and we break out. There we go, because 12
is not greater than 12. It's equal to 12. You can say greater
than or equal to. And in that condition,
we would stop at 11. These are things that
you can play around. I do recommend that
you play around with these conditions in here
to properly understand. But as I told you, the true and the break work amazingly
well together. And we're going to see more
of that in the next lesson. But for now, let's delve
a little bit deeper. And let's start creating our
small little project in here which is going to be the
pizza underscore toppings. So we're going to have a
few available toppings available toppings. And they're going to be
equal to the following. We're going to have, and I will hit Enter so
we have more space, pepperoni duplicate
with control D meet the balls cheese, the greatest, one of all, the most controversial
one, pineapple. What do you think should
pineapple be on pizza? It's a question I ask the
students all the time. Should or shouldn't it be? Me personally, I don't mind. Why not have pineapple? Isn't tomato also on pizzas? Isn't tomato a fruit? That's also a very
controversial topic. To see what I did there, I'm going to create the
topic chosen and I'm going to set it to
just an empty string. Now we want to keep
asking a customer for a topping as long as he doesn't choose one of the
non available toppings. For that, I'm going to
issue you a challenge. Your challenge is to
create a wire loop. I want you to create a wire loop that keeps asking for an input. The input should only stop when the topping is in the
available toppings. You have to imagine what the condition on this
wire loop should be. We will, we will keep executing the block of
code that has input in it, while the topping it chosen is not in the
available toppings. And a hint for you is
the input should be inside of the wild
loop block of code. And I should have warned
you about the hint, but this is a fairly
hard challenge. Very rarely do some of the
students get this challenge. I think a hint is in order. Also, the condition
should be topping chosen, not in the available
topping positive video. Right now, I've given you
more than enough hints. If you didn't take the hints and you were able
to do this on your own, congratulations, you're
doing incredibly well. If you needed the hint and you were able to accomplish
it, that's great. If you use the hints and you were still unable
to create this, then I recommend that you focus more on the things that we are doing positive video right now and go do the challenge. Welcome back. So first of all, we need to say, while, I mean this
is the easy part, this should be done
pretty simply while the topping underscore chosen, not in the available toppings. I'm going to say
that the topping chosen is equal to input, choose a topping for your pizza. Then I'm going to say, hope you like
replacement fields, replacement field topping
chosen on your pizza. Now I will right
click and I will run and choose a
topping for your pizza. I want tomatoes, I potato. Okay, can I have some cheese? Yes, there we go. Hope you
like cheese on your pizza. So while the topping is chosen, which is right here, is not
in the available toppings, we will keep asking
this question until cheese which is in the
available topping, which means that this
whole condition is false. Which means we jump
out and we print out, hope you like topping
on your pizza. So I hope you understood
what is happening in here. Let's test it out again. If we, for example, type in meatballs, boom,
there you go. Meatballs are available in
the available toppings, or they are part of the
available toppings, which means that we can
actually select them, which means that we can
make this condition falls and we can jump out of it. As you can see, using
wire loops is a lot more dynamic than
using a fore loop. For example, we cannot create a fore loop to handle
something like this. We don't know beforehand how many times we want
to ask for the topping. We will keep asking as long as the customer does not select one of the
available toppings. So thanks so much for
watching. I hope you enjoy it. And in the next video,
we're going to be applying the strength and the power of the brake to our wire loops. So I will see you
then. Bye bye for now.
43. 11. Break in a while loop: Welcome back my fellow
Python developers. In this video, we're going
to be breaking a while loop. We've already seen how a
break in a Wile loop works, but we're going to be
delving a little bit deeper. First of all, what
we want to do is we want to give our user or our customer the ability to exit out of the topping
choosing process. Obviously, if they are
buying some kind of pizza and they type in a
few unavailable toppings, we don't want to force
them to keep going. We want to give them
the ability to quit. So what we're going
to do is in here, after they choose a topping
inside of the wire loop, I'm going to say if the topping
chosen is equal to quit, then I'm going to
print out bye bye. And then we will break out. We click and I run, we come into the store
like I want tomato, I want potato, I want a
bird, I want chicken. I don't know why I said bird. I want some meat. As you can see now, the customer is like,
okay, You know what? I don't want your pizza
to bye bye, quit. We can just leave. It tells us bye bye. Then what does it say? Hope
you like quit on your pizza? I mean, who likes quit on
your pizza? Nobody does. But before we fix this issue, there is another issue
that we need to fix. And that is if somebody is
doing the tomato potato, and then you know what
range they type and quit. You know, quit, quit. It doesn't allow them to quit. If they type and quit, it
doesn't allow them to quit. And even worse, if
they type in cheese, it's not working as well. Why? Because cheese
has an upper case, quit has an upper case Q. And we are comparing these two values or
string variables. The case is very
important in here. We can only select cheese
if we have a lower case. If we have even an upper
case or any letter that is, as you can see, it
does not register. We need to fix this. And when I say we, I mean because you need
to use a case fold, make sure that we can quit however we want without having
to worry about the case. Now, I do have a hint in here that will indicate
how to do this, but I recommend that you
posit the video right now and go do the research to
find how to do this. There are different
ways of doing this, three to one use case fold. Now, through your research, you might find some
different method, Both work. Use
whatever you want. Posit the video right now
and go do the challenge. Welcome back. How did
you get on with that? The important thing
in here is to use the case fold right
here on the topic. We will use the case fold, and now I right click. And if I type quit in range
with all upper cases, it actually quits
out of the program. Now the problem. Now some of you might have found lower, which lowers everything. Both good, both are the same. I prefer using case fold. If we run this again
and for example, I type in cheese, you'll see that it
still doesn't work. What should we do
in here? Exactly? We can use the case
fold right here. Now if I right click and
I type in cheese, boom. As you can see we
have this working. But there is a very important
lesson in here that we can take advantage of even though
two methods work the same. And I'm not talking about
the case for all the ord lower you can use whichever one you
want, it's the same. What I'm talking about is that even though
we can add a case fold here and a case fold here
in order to make it work, a better way is to add a
single case fold right here, a single case fall on the input. Now if I run this, you'll see that I can quit, I can select cheese. Instead of using two case falls, I can use only a single one. And you'll see that
it's not capital, which looks even
better in the output. You need to start thinking about efficiency
and effectiveness. Even though you can
use two case folds, it's not as efficient
as using a single one. Now of course, this case fold in here is not
going to change the world. But still, when you're saving a few milliseconds over a loop, it makes all the difference. I want you to really hone
in on this idea and think about it next time
you're trying to write any coding program. Now obviously there is still one problem in here
and that is that we actually get quit on our
pizza and not good at all. Don't worry, we will come
back to this later on when we learn about something
called the Ls in a loop. And I will see you in the
next video. Bye bye for now.
44. 12. Random Number Generator and Importing: Welcome back my fellow
Python developers. In this video, we're
going to be looking at random number generators and also have an introduction
to importing. If you remember, we had
created a guessing game a while back which involved guessing the Nicholas
Flameles age. So we're going to use the same prospect or
the same example, but we're going to be
expanding on it because as you remember when we were working with the Nicholas Flamel age, we already kind of
knew what the age was. And we had a very limited amount of tries that we can apply. Now we're going to have
an infinite amount until we finally get it. And on top of that, the age is going to be random. I'm going to create a new
Python file in here that I'm going to call Nicholas Flamel. And boom, I will right click on Nicholas Flamel
and close other tabs. Which will close
all the other tabs and all the other projects. And just keep this one. First of all, I'm going
to import random. When I do this, it
means that I am importing something
called a module. The random has an entire
library and you can even hold control and click on random to
open that library. Now when I say library, it's a few lines
of code of a few, maybe almost 1,000
lines of code. And as you can see in here, we have classes and
functions and many, many stuff that we
can use from random. Instead of typing
all of this just to use maybe and range for example, we can simply import
random and now we have access to everything
that's in that random. A module is something that
is already pre created, pre coded for us to use. Next we're going to
create this actual he, we're going to have actual
actual underscore h equal to random dot and in 120, if I hold down control
and go to rand int, you'll see that we
open the random pi, the module that
we just imported, and you can see this is the
rand in that we are using. Let me find the function. Where is it control? Let's try to find random, boom, there we go, returns a random integer. Let me open this up, actually,
let me close this down. Rand end returns a
random integer in range B, including
both endpoints. So this is something very
crucial to understand. When I wrote 120, it means that the
20 is included, so we're going to
get a random number 1-20 Both are going
to be included. Before we continue,
I need to provide the highest H that this
could possibly go to, and I'll tell you why. The highest
underscore H is going to be 20 instead
of 20. Right here. I will type in highest H. Next, I'm going to print
out what is lamely in, here's what's Flames Weasley and I will give it
this indicator to where the player
type in the result, or actually we just
have a print in here, we'll have the input
in another place. I apologize. In here we are
going to say that is between one and the highest
age that the user, because remember, this
is a random number. The user needs to
have some indication, just for our own sake, so that we don't spend
hours trying to guess this. We are going to print
out the actual age. This, of course, is going
to be simply for testing. Now that we've
printed out or asked the user to provide
us with the name, I'm going to issue you
a bit of a challenge. Now you already have the code, so this shouldn't be a
very hard challenge. All that you need to do
is you need to create a wire loop that keeps
asking our players, or our player for inputs until
he gets the correct age. Keep the F statement inside
the Wi loop and test if the player
should go higher or if the player should go lower. Pass the video right now
and go do each challenge. Okay, welcome back. What is our goal? We need to create a wire loop
that keeps asking our player for an input while
their guess is not correct. Which means that the
condition should be while guess is different
than the actual H. The issue in here is that
we don't yet have guess. And this is of course
natural because as we said, whenever we're working
with wire loop, we need to initialize the guess, and in here, the
guess will be none. And I will compact these
a little bit because they are all over the
place. There we go. While the guess is different
than the actual H, this is the first thing
that you should think about next in here. Keep the statement inside
the wire loop, okay? Test if the player should
go higher or lower, okay? The next natural thing to do is to actually get
the guess input. So we're going to say
guess is equal to input. That's it. We're going
to have the input and just a small
indicator in here. But the problem
with this is that actual H is a random integer. And when we do this
input, it's a string, we need to convert it into an integer before we can
compare it with the actual H. Now that we have that,
we're going to say if the guess is equal
to the actual H, we should print out,
you guessed correctly, ten points for griffin door. There we go. Else we're going to check if the guess
is less than the actual. He will say, please guess higher L or else actually in this case
we can simply use an L. Oh, sorry, print. Please guess lower
is that correct? Yes, it is correct. There we go. Now, if I write, click and I run what is Flamel, age 12, please guess
higher, 13141615. There we go. You
guessed correctly, ten points for griffin door. And as you can see now we have an infinite amount of tries, unlike before where we
had two or maybe three, I'm not entirely sure. But now our code works 100% And it's
actually a good game. It's actually a game that you
can give somebody to play. It's not like they have
only one or two guesses, they have infinite guesses
until they finally get it. Now, if you haven't
done the challenge, because it was a hard challenge, I'll admit I want you to do the mini challenge that I'm
going to tell you right now. I want the player to
be able to go out of the game if they press
the number zero. How would we stop the game
if somebody presses zero? Positive video right now. Well you don't have to,
but I recommend that you do this in here, just simply anywhere
that you want. You can say if G
is equal to zero, what do we do out? Hard luck, break now. Right click and run. 101126 00:00 P.M. hard lock, and we break out. Thank you so much for watching. In the next video,
we're going to be starting a new big project, which is going to
be the high Low. We're going to be learning a special algorithm just
for that high low project. The next video, we will
just be setting things up. Then we will learn bind research algorithm
and we will create a really nice game where we
will create sort of an AI. Not a complete AI, but it will be a program that
will guess the number that you're thinking of in
less than ten tries. How cool is that? So
thanks so much for watching and I will see
you in the next video. Bye bye for now.
45. 13. High-Low: Welcome back to my favorite
Python programmers. In this video, we're
going to be setting up our High low project. Let's go ahead and create
a new Python file. New Python file. And I'm going to call this
the High underscore low book. I will close this down for now. And I'm going to be
typing in the following. First of all, the
low is equal to one, the high will be equal to 1,000 We're going to print out first of
all, the following. We're going to say
that choose a number between low and hopes high. Then we're going to
have the input which is going to be just press
any key to start the game. Press any key to start the game. Actually, let's say
think of a number. Think of a number 1-1 thousand. Now the player of
our game is going to think of a number 1-1 thousand. The PC or the computer is going to try and guess that number. With a little bit of help. We're going to say, while true, I'm going to say that
the underscore by underscore PC and what is that? The guess by PC is equal to low plus high minus low
divided divided by two. Now you might be thinking, wait, Michael sub sub sub, what
the heck is even this, Don't worry my
fellow programmers. I'm going to explain
everything in due time, but for now, we're
going to get the high, low underscore input and
it will be equal to input. This is the computer
talking to us. I guessed replacement field. Then in here I'll also say press L to guess lower back. In here we'll also
add a backslash N because we want to
go to a next line then H to guess higher back, see if the guess was correct. And of course in here
we're going to be replacing with the guess by PC. And this is the input
that's coming in. I'm going to make it caseful, just in case the
user tries to press the upper case or upper
case or upper case. We always have those options. First of all, the player,
which is me and you, or whoever is playing this game, will think of a number
between the low and the high, which is 1.1 thousand. Then they are going to be pressing a key to
start the game. So they press any key
and they start the game. So they can start
with the wire loop. We have this equation that I'm going to explain
in the next video. And then we have
the high low input. I guess this is the guess by the PC after they
do this equation. My guess is this guess. So let's say you're
thinking of a number, 800. The PC guesses 500, you have to tell it
L to guess lower, H to guess higher, and see if they got
the number correct. In our example. If for
example the player was thinking of 800 and
the PC guess 500, then the player
should tell them H. So the PC can guess higher. If the PC guesses 800, the player says C, they
guessed correctly. If the PC thinks
of or guesses 900, then the player tells
them L to guess lower. Now what's left to do is to actually create
these conditions. And when I say it's time to
create these conditions, it means that you should
set the Lph conditions. First of all, create an F and
Lip for each of the inputs. And the inputs I'm
talking about, of course, are the LH and C. You don't need to
write anything inside, just make sure you check
for the inputs in the LF. Keep these empty. We're going to add
the code later on. If you want, you can add
something called a pass inside. Just type in BSS and
it will help you, especially if you have
errors coming up, but don't worry about that. The three options are L to guess lower and H
to guess higher, and see if the guess is correct. Pause the video right now
and go do the challenge. Okay, welcome back. How did you get on with that? This should be a pretty
simple challenge. We type in F high
low input is equal to h. Then in here we
are going to pass. What the pass allows
us to do is it allows us to write this if statement
because an if statement, let me just remove
this, you'll see. And we hover over
the error in the expected or it just says that
it's expecting some code. You cannot just leave your if statements and your loops empty. You can add a pass just as
a temporary placeholder. If the high low is H, L high low, high low
input is equal to L pass. And then finally, live high low is equal to C. But finally, I apologize, we also
might need an else in here just in case they write something
completely different. But for now, I will
keep it as it is. What? Let's just add
the else right now. And I will print out, Please choose one of the following LH or C with
a few exclamation marks. There we go. If I write, click and I run, think of a number, 1-1 thousand, press any key to start. Just hit Enter. I guessed 500. If I hit L, nothing happens. If I hit H, nothing happens. If I press, nothing happens, We just go through
the wild loop again. And finally, if I hit
three, for example, it tells us, please choose
one of the following LHC. One more thing in here
is I would like to add a space just so it's not crammed with the
correct next to it. Okay, so also right
here if we add, So let's see how that
would look like. I just want to make sure
that the output looks good. So press any key at edge. Okay, 12 maybe. Okay, so I think this
would look very nice. Okay, there we go. Now
at least we know where the prompt is for us
to press the key. Ladies and gentlemen,
we've just set things up. This part of the code should be very simple for
you to understand. This part of the code should also be very simple
for you to understand. The only thing that is
weird is right here. And this is going to be part of the binary search algorithm
that we are going to learn. In the next video, I will see you then.
Bye bye from now.
46. 14. Binary Search Algorithm: Welcome back my favorite
python programmers to a brand new video and kind of a hard one where I will require your
full concentration. You might need to watch
this video multiple times before you fully comprehend
binary search algorithm, But that's the name of the game. You always have to show me complete concentration because I always need you to be on point. What is binary search algorithm? Let's imagine we have
a class right now. We have eight students, I think, yes, eight students. But let's imagine
we have 50 or 100, or 1,000 or 1 million. So we have this lovely teacher that wants to hand
out report cards, so she has all the
report cards in order. We have Abby Ben Sell, Pat, R, S, V, Z, so they are all ordered
in alphabetical order. So what we want to
do is we want to start giving these
report cards out. So let's say we want to
give van or Sam or whoever. Let's say somebody out of
these three right here maybe. Let's say van. We want to
give Van the report card. How would the teacher
go about finding van? Well, the teacher
knows that all of them are ordered in
alphabetical order. What the teacher
can do is she can start taking out Abby, then Ben, then sell, then Pat, and start going one name at a time until she
finally gets to Van. Now this is not a huge problem because we only have
eight students. But again, imagine if we
had 1 million and Van was in the position
600,000 something. 600,008 So imagine
the teacher has to go through every single 1,600,000.7 times in order to
finally get to Van. Not very practical. And of course I'm taking
things to the extreme, but there are
situations like this. Like for example, trying to
guess a number 1-1 thousand. So what the instructor
does instead is something called a
binary search algorithm. And binary search algorithm
is something that we do on a daily basis without even knowing
that we're doing it. What the instructor
does instead is the instructor cuts the
report cards in half. So she takes the
Abby Bansal and Pat to one side and read Sam
Van Zac to the other side. Now she doesn't
select the numbers, she just separates
them into two piles. And then she looks at the
last name in the first pile. So she sees Pat, so she thinks, okay, so P is the last one. Which means that there's no way that van is in the first pile. So she discards the first pile. She's like, okay,
great. This is amazing. Now let's look for Van. She does the same thing again
with these report cards. So she discards tan Sam. Oops. And then she
sees Van and Z. And she's like, oh, there
we go. We have van. So instead of having
to go through Abby one bend to sell three
pad 45 Sam, six. Instead of having to go
through six report cards, all that the teacher had to
do was discard the first half of the pile and then the
second half of the pile. So it only took her two tries in order
to finally find van. And the same logic applies if we have thousands
of students, just like we have
in our example of the high low 1-1 thousand. Instead of the computer
having to guess, let's say you were thinking
of the number 800. The computer will start
with a guess of 500, so it will split
down the middle. What you can do
is you can create a program that just adds
one every single time. So 501, 5025035004567. And imagine if the player was thinking of a number,
let's say 825. The computer would need to
guess and the player would need to press 800 or no, actually, 328 times
500501502503. Imagine that It would
take very long time. And it's not practical. And it's not a fun game,
there's no thinking in it. But if we use the binary
search algorithm, we can make our lives
much, much easier. And that's where the
equation comes from, because it always cuts in
the middle. If I show you, you'll see that this equation always has whatever
guess that we have, look, we have 1.1 thousand, so we guess 500. And you'll see this better when we start actually
implementing it. But now I've created
a small scale example to fully comprehend
binary search algorithm. Now again, now I need
your full concentration. Put your phone down,
put everything down. I want you right here, right now, with me. So let's go ahead
and get started. First of all, we have two
rules that we need to follow. We will, plus one to the mid and make it the new low when
we should guess higher. Okay, We add a plus one to the mid and
make it the new low. When we should guess higher, we minus one to the mid and make it the new high when we
should be guessing lower. These are the two rules
that we need to follow. We are looking for number seven. This is the formula
that we'll use. This will always guarantee
that we cut in the middle. We start off with,
in the beginning we have the low is one,
The high is ten. We start in the beginning. The low being 1110, being high. The high is ten minus below, minus one divided,
divided by two. What is divided?
Divided? Why aren't we using a single division? Well, for the astute students that still remember
the first section, when we use divided divided, it means we are disregarding everything after
the float point. We are simply getting integers. When we use the divided divided, we don't want floating points, we want concrete
numbers in here. We have high is ten, low is one, and the low is one. We have one plus ten minus one divided divided by
210 minus one is 9/2 It's 4.5 Because
it's divided, divided, we disregard the
floating point and instead of 4.5 we get four plus
one equals five. Okay, Now we need to look at
the rules. What is the rule? We got five plus one, the mid, and make
it the new low. When we should be
guessing higher, we're looking for number seven. Should we be guessing higher? Yes, we sold because we are
looking for number seven. We got five plus one, the mid and make it the new low. What's the mid? It's five. If we plus one to
it, it becomes six. We make it the new low. Six will become the new low. That's exactly what we do. Again, I will re explain this because it's a hard concept for people to grasp, but I will not explain it
again, I will have to move on. We have the low
one, the high ten. We apply or replace these into the variables and we get
510 minus one is 9/2, is 4.5 because we're
using divided, divided, we get four plus one. It's 5.7 is greater than five, which means we should
be guessing higher. If we look at the rules, we plus one to mid and
make it the new low, when we should be
guessing higher, plus one to the mid. The mid is five after
we do the equation. And by the way, the mid
is also the guess by PC. I'll add a comment in here. This is the mid as well, we plus one to the mid, it becomes six and we
make it the new low. Now we reapply the equation, we have low being
six, high being ten. We do ten minus six
divided divided by two. Which gives us what?
Ten minus six is 4/2 It's two plus
six, it's eight. Now, should we be guessing lower or should we
be guessing higher? Of course, we should be guessing lower because seven
is less than eight. When we should be guessing
lower, what do we do? Minus one to the mid. This is the mid.
We do minus one. What's minus one? It's seven and we make it the new
high. There we go. Now we have six as the low
and seven as the high. But now again we
apply the equation. Seven was the high,
six was the low. Seven minus six, It's one, yes, Divided by two at
0.5 which means it's 00 plus six
is equal to six. What should we be doing? We got mid. 66 is
less than seven, we should be guessing higher. Plus one to the mid, and we make it the new low. And now we have the seven
being the high and the low. Now we finally
calculate seven plus seven -7/2 It's equal to seven. The correct answer is 7.7. Is the high, low. Some of you
are dumbfounded Right now. You're looking at the computer, you're looking at your
screen and you're like, what have I gotten myself into? I recommend you go through
this video slowly. You think about
every single step and if you have any questions, always refer back to one of
the instructors or to me. Thank you so much for watching. I hope you enjoy. And I will see you in the next video
where we will be completing our game using the theory that we did
right now. Bye bye. For now, please make sure to
understand this because you will have a challenge.
Keep that in mind. You don't have a challenge now, but you will have a challenge. Next video. Bye bye for now.
47. 15. Completing our Game: Okay, so now it's time to replace our pass
with some real code. First of all, we need to change this pass or we need to fill
in the information in here. We need to understand
what we are doing. Just like we saw in
the previous video. Let me take you
back to the rules. We plus one to the
mid to make it the new low when we should
be guessing higher. And we minus one to the
mid and make it the new high when we should
be guessing lower. Our main goal is to translate this or these two
rules into code. How do we do that? I want you to take a moment and try
to do this yourself. You should be, you
should be able, I will be so proud of you. If you can do this
back in our code, I hope you made me proud
back in our code and here, first of all, we
need to handle what happens when we should
be guessing higher. Remember here,
plus one to the M, plus one to mind. And make it the new
law when that's it, when we should be
guessing higher. Okay. In here, first of
all, we take the mid. And again, I told you
that the mid is the gas by PC plus one. We make the new low. Now the low is equal to
the guess by PC plus one, when we should be guessing
lower minus one to mid, and make it the new
high is that correct? Let me double check.
We should guess. We make it the new low. Yes,
and we make it the new high. Okay. In here we get
the guess by PC. We do a minus one and we
make it the new high. Then in C or LF, we type and we simply print out, I guessed it, with
an explanation mark. Also, we should break because we don't want
any more guesses. That is basically it. I hope you were able to do this. If not, it's okay. As long as you clearly
understand what is happening, let's go ahead and
test this baby out. If I read, click Run,
Think of a number. Let's think of 720. The 3,700.23, Let's
start the game. 723. You should guess
higher, huh? 750. So you should guess lower, 625 guess higher
guess, higher guess, higher guess, lower guess, lower uh huh, guess
higher, lower, 23. 723 hit. Nice. I guessed it very nice. So how many times did
it take it to guess? So this is the first guess. So 1-234-567-8910 And there we go. So it took our PC ten
guesses to finally get it. Imagine if we were simply
increasing this by one, we would have needed or 723
-500 that's 223 guesses. Instead, it only took ten and you want to
know something crazy, the maximum amount of times
that it needs PC to guess, the number is going to be ten. To prove that, I'm going
to issue you a challenge. And your challenge
will be to create a counter count the number of times the PC tries to guess, create a variable outside the wire loop and
initialize it and increase it every time
the PC doesn't guess correctly and print out
the number of guesses. Pass the video right now
and go do the challenge. Welcome back. How did
you get on with that? First of all, we need to
create the number of guesses, and we do that
outside of the loop. In here, we'll say
number underscore, underscore guesses, and
it's equal to zero. Then we need to increase this number by one
every single time. And where do you think
we should do that? Try to guess. Well, we should do it anywhere for that matter. Some of you might
think, well, we should do it here and here. But it doesn't matter as
long as we take a guess. It should be in here in the number of guesses
plus equals one. So let's go ahead and
test out 723 again. Where do we printed,
where do we print it? I guessed it in replacement
field number of guesses. Of course, we should do it here when we actually get
the correct answer. Right click and run 723. Let's go higher,
lower, higher, higher, lower, 23, lower, lower. Boom, There we go. I
guessed it in ten, choose any other number, Let's try something low. Let's try 300 or 250. 250 is very simple, because 500 divided, for
example, let's say 250. Boom, there we go.
Just took it to. Let's try something
a bit more complex. Red and red and 68, I guess. Lower, 168, higher, lower, higher, lower, higher, 68, higher, lower, boom. Ten guesses. How cool is
that, ladies and gentlemen? Thank you so much for watching, but there is something extra in here that we still
haven't finished with. I will tell you next time because we have one
more lesson to do, and that is the L
statement in loops. And then we will use
this L statement in a very powerful way. It will blow your mind, at least it bloom my mind
when I first did it. Thank you so much for watching. I will see you in the next
video where we will learn about L statements in
loops. Bye bye for now.
48. 16. Else statements in Loops: Welcome back my favorite python programmers to a
brand new video. And in this one
we're going to be talking about the L
statements and loops. Let's go ahead and
create a Python file. A new Python file, and we're going to
call it lo in here, I'm going to create a list. And that car list is going
to be the following. I'm going to have BMW car. Come on, I'm going
to have Ferrari. I'm going to four car, I'm going to have a car and the Tesla car.
Nice. There we go. This is in no shape or form. We are not sponsored by Tesla, we're not sponsored by anyone. But if they do watch this video, I'm always open to suggestions. I will change all of my
examples to accommodate your car without
any further ado, Let's go ahead and create a for loop that will go over
all of this list. Car list, I'm going to
say car. Watch carefully. If the string car not in car, I will print out this
list is acceptable. If we don't have car in every
single car in our car list, then this list is unacceptable
and we will break out. What do you think the output is going to be as soon
as I run this? If I write, Click and I run it, tells me, sorry, this
is unacceptable. And by the way, when I tell you, what do you think the
answer is going to be, Please take the time and actually don't just run
and look at the answer, think of what it is going to be. So, as you can see, if we run, it is not working and we are
breaking out. Why is that? Because Ferrari in here
does not have car in it. But if we add this
car and we write, Click and we run, excellent, we don't see anything. And that's not good because
there's nothing being output, we don't even know
if this car is, this list is acceptable. You might be thinking, well,
you know what, Michael, I can just add print this list
is acceptable right here. The problem with this is if I didn't have the
car in Ferrari, I would have, this
is unacceptable, this is unacceptable, and
this list is acceptable. There's a cognitive
dissonance in here. What we have is something
called in L for our four loops. So if we don't break
out at any point, then we have this printed out. Or if we finish normally
through our list, then we go into the
Ls and we print out or execute whatever
code is inside. For example, right now if I run, you'll see that we only get, sorry, this is unacceptable, Why we don't execute the Ls? Because we've broken
out of this list. If we have car in here
instead, in the Ferrari, you'll see that it
tells us that this list is indeed acceptable.
Why is that? Because we went through
the entire list. We haven't broken out of it, so we go into the and
that's basically it. There's nothing
too much in here. Just remember that if the
loop finishes correctly, then everything works good. Thank you for watching. Now
as a small challenge in here, I want you to go back into into where is
our pizza topping, the pizza topping in here. I want you to add
an L statement to this while loop in here so
that we don't print out. I hope you like
quit on your pizza. How would we fix this? I hope you tried your best in here. I will add an L. I will
add the indentation. What happens in here if
I right click and I run, choose a topping for your pizza. Let's say we want
kale, doesn't help. Tomato. Uh huh. There we go. Still doesn't work. Cheese. Boom. Hope
you like cheese on your pizza because we haven't broken out of our while loop. We just go into the else
the oil has done its job. If I now try, for example, tomato potato. You know what? I just want to leave quit. It just says bye bye. And we don't have hope you
like quit on your pizza, which just sounds weird. Nobody likes quit
on their pizza. So thank you so
much for watching. I hope you understood. In the next video,
we'll be using our high or we'll be using the
L in our high low. And I think it will be the
last video in this section. Congratulations on
making it this far. Please leave me a review
wherever you can, and I will see you
in the next video. Bye bye.
49. 17. Else in High-Low: Welcome back my favorite Python programmers to a
brand new video. And this one we'll be implementing
the L in our high low. Let me take you back in time to when we were explaining
the high low. In here, you'll notice that we start off with
a low and high. We find the mint,
we increase by one, We get a new low or a new high. We get the mint, we get the
mid, et cetera, et cetera. And then at the end, sometimes we have the school feature, if we don't guess the
number beforehand, if it takes ten guesses, we actually have the
high equals the low. And this is called the high low. And when we have a high low, we have the answer, so we don't have to
guess more than that. What we can do is we can create an L statement in some
way or modify our code in order to have an AI that will be always checking if
the high is equal to the low. If it is, if we have the
high equals to the low, it means that the answer is the correct answer
and it's equal to either the high or the low. I want you to use that information in order to
do the following challenge, L to a while. Change the condition
on the while loop to stop when the high
is equal to the low. This is something
very important. You will have to figure
out the condition. You should stop when the
high is equal to the low. Add an L statement for
when the loop finishes. I'll give you a small hint. If you don't want
the hint and you want to conquer
this on your own, pause the video right now
and go to the Challenge 321. The while condition should
be high different than low. Pause the video right now
and go do the challenge. Okay, welcome back.
So first of all, let's go back into our high low. The condition in here is
not going to be just true. It's going to say while the high is different than the low, we're going to be
doing all of this. Then at the end, I'm going to keep the break in here
because it's still required. Maybe the computer guesses your number without getting to the ten in here.
I will add an L. I will say print out you were thinking of
replacement field the high because
it doesn't matter. We can either use the
high or the low in here, it doesn't matter at all. We will also print out it took me replacement
field, number of guesses. If I write click
and I run in here, I'm going to say 500. Let's think again to 723
because it took us ten guesses. High, low, high, high, high, low, 23, low, high, low. Look at that. I didn't press C, and it told me that you
were thinking of 723. As you can see, this is magic. But the only problem in here is that it says that it
took it nine guesses. If we count them
and remember it is, then let's just double check. 1236789. There we go. 123-45-6789 The last one is not a guess. Keep in mind the last
one is not a guess. It just told us that you
were thinking of 723. This is not incorrect. It just, it didn't guess, it knew that you were
thinking of 723. Let's try a different number. Let's try 628 high, low, high, low, low, low. There we go. Now, it guessed 728 before
it guessed it on its own, because it was less than ten. I guessed it in eight. Let's go back and count 1235678. And there we go. So
ladies and gentlemen, I hope you enjoyed This is a very fun game that we created. It's a very complicated,
not complicated. It's a fairly
complicated program or project that we made. Thank you so much for watching. Thank you for sticking with me until the end of the section. Later on, we will be appending the section with more examples, with more projects
down the line. I will always keep this course
and master class updated. I will see you in the
next section where I think where we will be
looking at lists and couples. The things that we
already kind of looked at when we were
working right here. But in much more in depth. You'll see that this is
a very powerful tool. Thank you for watching
and I will see you in the next video. Bye bye for now.
50. Section 5 - Lists and Tuples | 1. Introduction to Sequence Types: Okay, so let's go ahead and
start creating our project. First thing we'll do
is on this window, I'm going to click on New
Project, right here at the top. I'm going to go to next. I'm going to call this
Project List and Couples. I'm going to save it. Inside of code, I will write
click Create a new folder, and I shall call this
Lists and Couples, Okay? And save it in there. Once we hit Finish, we should
see the following window. Before getting started, let's understand what sequences are. We said that this
is an introduction to sequence types and lists. Let's start by understanding
what sequences are. What are sequences? A sequence is a
collection of items. We've previously seen something related to that when we
talked about strings. These are also
collections of items. In the case of a string, the items are just characters. In the case of lists, it could be anything. The items could be strings, the items could be integers. The items can even be lists. So it could be a list of lists, and we'll see that later on, that is called Nest blists. Next, we know that each item has a position and items
are in an order. Just like when we talked
about strings where we had the first element indexed to number zero or the
index was equal to zero, the second element was index
one, et cetera, et cetera. The same things hold true when we are
talking about lists. Each item has a position
and they are in an order. You can refer to any item in the sequence by using the
index number, Meaning, let's say we have a sequence
that is called S. We can access the item at index zero using these two
square brackets. We can access the second item which is on index number one. The same way in here. This is not something that's
completely new to you. You've already seen
how we can access the individual items
using a string, using the square brackets. I will continue on, and let's also understand
that in Python, the sequence also
starts at index zero, not at index one. This is very important
to remind you of sequence types
could be lists, byte arrays, strings, topples, and ranges, and bytes. Now we will see
couples later on. We've already seen strings, we've already seen ranges. But you might not have known
that that was a sequence. But it is. We will see bays
and bytes in later sections. Finally, Python
classify sequence types as mutable and immutable, and we're going to learn what these two things are and
understand that later on. Let's go ahead and
get started to properly understand
how lists work. I'm going to go back
into my coding here and I'm going to create a
new Python file that I'm going to call lists
Underscore Intro There we go. First thing I'm going to do is I will close this project
down to have more space. And I'm going to create the color underscore
parts equal to, I will start with wheels just in order not to have a
very long string in here. I'll just add enter
and then enter. And I'll just try, start
writing things down. I'm going to duplicate control D. I'm going to have
tires control D. Seats control D. Doors
control D, and stereo both. There we go. And unlike other languages where if you're
at the end of your list, you are not allowed to
add a comma in Python. Because as I told you, this is a very versatile
programming language. You can actually just leave the comma there in case you
want to add another item, or if you want,
you can remove it. I personally, personally like to keep it because
in my experience, since I was like a kid and
I've been programming, it's always been a
freedom issue for me. Like why can't I
leave a comma now? I can, so I will, then I'm going to create a four loop to iterate
over this list. So I'm going to create four. Part in car underscore parts and I'm going to
print out the part. If I right click and I run, this is the output
that I will get. I'm going to dock it right
here on the right hand side. As you can see, the
fore loop using the part variable
iterates through every single item
that we have in our car parts list and
then it prints it out. As you can see, wheels, tires, seats, doors, and stereo. Nothing too much in here.
We've already seen this. We weren't using lists, but we were using strings. It's the same
concept if you want, I encourage you to go through
this using the debug. Next, I'm going to go ahead and add a
small print in here, just an empty line. And I'm going to print out car parts at
position number two. Now before I run, I want you to take
a moment and try to guess what the
output is going to be. I'm going to write
click and I will run. And there we go, I get seats. Because if I go and
look at the car parts, I can see that we have
wheels at zero tires at one, and seats at position number
two or at index number two. To be more precise. My warnings, as you can see, that is
the output that we get. We get the seats. All right, so I hope you understood
what is happening here. If you have any questions, you can always leave them in whatever section
is available. I'm going to issue you a bit of a challenge to
do on your own. So you'll need to print out
a slice because remember, just like we can print
things using their index, just like we saw right now, or print items out
using their index, We can also slice them just
like we did with our strings. So this should be
simple for you. Use slices to print out the first three car
parts that we have. Print out the last car part
using two different indexes. And that's it. That
is your challenge. Pass the video right now
and go do the challenge. Okay, so how did you
get on with that? First thing I will do. Okay, sorry for that. First thing I will do
as I'm going to just add an empty space and
I'm going to print out the carport at positions going from
zero to dots three. So if I write Click and
I run, there we go. As you can see, I printed
out the first three items. Now some of you might
have done the following. You did not specify what
the starting position is, so naturally it will start
at index number zero. If you did that, I
congratulate you. You've been paying attention
to the score so far. Next, I'm going to
print out the car part. As we said in the challenge, we wanted to print out the last car part using
two different indexes. The first index would
be pretty obvious. So we have 0,123.4 at
index number four. I should see stereo. There we go, it works. Now, what about
the other method? Some of you might have done the other method before
this first method. Some of you are
adaptive like that, but the other way around, and if you haven't
figured it out, I do recommend that you try to go back to the
previous project where we were accessing items or to be more specific
characters in a string, because this is a
very fun challenge. So we can use the minus one. If I do minus one and
I run look at that, I also get the word stereo. And I will duplicate
this just so we know that it is
indeed the same. Look at that. Stereo and stereo. So just like with strings, we can access items using
negative indexes in a list. It's basically the same thing. Strings are actually
sequences as well, but the difference is that
strings are immutable. And we're going to see what
that means in the next video. I hope you enjoyed
as a small homework, I recommend that you go through this for
loop using AD Bug. And I will see you in a few
seconds, hope you enjoy it.
51. 2. Immutable Objects: Okay, so as promised,
I told you that. I'm going to tell
you or explain to you what are immutable objects. Let's go into our
slides and let's talk about immutable objects. Immutable is when no change
is possible over time. That's the actual meaning
of the word Python. If the value of an object
cannot be changed over time, then it is known as
immutable object. Once created, the value of
these objects is permanent. They will stay with the
same value forever. Let me give you an
example of what an immutable object
would look like. I'm pretty sure that you are
going to be very surprised. First of all, an immutable
object is numbers. Like integers,
floats, or bullions. We cannot change an integer
object once it's created. When I say object, I
also mean a variable. Another thing that is
immutable are strings. Strings once created
cannot be changed. Now, I think some of you
right now are thinking, oh my God, wait, wait,
wait, wait, wait. You're telling me
that we've been changing strings the whole time. For the past, I don't
know, like four or 5 hours we've been changing
strings and now Michael, you're telling me that I
cannot change strings. You're telling me that
strings are immutable. This has to be some bull do. I will show you how strings can't be
changed in just a bit, but before we do that,
we also need to know that couples are also immutable. And we will learn more
about topples later on. Let's go into our code and start creating
immutable objects. I'm going to go back into my code in here and
I'm going to create a new Python file that I'm
going to call immutables. Now, before I start
talking about immutables, I need to show you something
very important in here. Let me search for what is ID in Python or what is
the ID function in Python. Right here you'll see
the Python ID function returns the identity
of an object. The identity of an object is an integer which
is guaranteed to be unique and constant for this object
during its lifetime. Two very important keywords
in here, unique and constant. Unique and constant,
which means that no two objects can
ever have the same ID. And that the object, once it has an ID, it will stay constant
during its lifetime. It will not change, meaning that this
will identify that we are indeed talking about
this specific object. It's very important for you to remember unique and constant. Let's go back into our code. In our code, I'm going to
type in the following. I'm going to say that we have a value that is equal to six. I'm going to say that we have another value that
is equal to value. In here, I'm going
to do the following. I will print out
the idea of value. I will say ID value. Duplicate this line
and the idea of another value and
then another value. Let's see what the output
is going to look like. If I write Click and I run, look at that, I
get the following. And I'm actually going
to remove the spaces in here because when we're
providing multiple arguments, multiple arguments, because
we have a comma in here, it adds a space on its own. So when I write Click, that looks a bit cleaner
with only one space. So as you can see, we have this ID number that is unique to both
of these variables. Well, you might be
saying, wait, wait. Didn't we say that
the IDs are unique? Well, yes, they are
unique to each object. Which means that these
two things in here, or these two variables, or objects to be more specific, are indeed the same. Now these are random IDs. You might be getting different
IDs than what I'm getting. As you can see, every single time I write click and I run, I get a different ID. Now you might be also
asking yourself, where does this ID
even come from? I'm not going to delve
too deep into what all of these IDs mean, but
what you should know, it's a combination
of a random number and the space that each
variable takes out of your Ram. Rams have like 2 gigabytes, 4 gigabytes, 16
gigabytes, whatever. Every single time you
create a variable, you get a small
slice on that Ram. That slice has an ID of itself. It's combined with
a random number and you generate the following. On your ramp, there is a
specific place for integers, specific place for a strings, specific places for lists and arrays and so
on and so forth. But this is outside the scope of what we're learning today. All that you need to know is that both of these
have the same idea. Which means that they
are the same object. But now I'm going to
try and change this. And remember I told you that the integers are immutable,
they cannot change. I'm going to print out just
an empty line in here, and I'm going to say that
value is equal to four. And I'm going to print
out the following. I will duplicate this line of code and I will move it down. I moved it down, holding
down control and shift. Now look at what's
going to happen. I will write click and I
will run and look at that. As you can see, this ID is different than the
one we started with. Look the last two
numbers in here. We have 88 and here we have 24. Oh my God, what happened? Well, we try to change value, and when we changed value, the ID changed. And
what does that mean? That means that value now is a completely
different object, because integers are immutable, which means they cannot
be changed over time. When we actually try to
change them, it works. But as you can see, we get a totally different ID, which means we get a
totally different variable, a new variable, value
has been created. There you go. If I try to
print out another value, take a few seconds,
pause the video. Or if you want, just think about what the output will look like. Don't, don't run it. Think about it. If I right
click and I run, there you go. You can see that the
idea of another value stays the same as value
and another value. Because remember now value is a completely different object, so it should make sense. Okay, let's continue on, and let's test it
out on a string. Because you might be
saying, well, yeah, actually you said value
is equal to four. But what about, let's say, when we append something that shouldn't affect the strings, I'm going to print out
just an empty line. I'm going to say message
equals to correct. Because you are correct, I'm going to say underscore
message is equal to message. Then I'm going to print out, or actually I'm just going
to duplicate these lines. I'll move this down and
I'm going to say the idea of duplicate this message, another message. Now when I write Click and
I run, as you can see, we have different IDs for the message and
another message. Obviously they start, they
might look similar for the first few couple of numbers, but obviously they
later on change. So you can see right
here, 880, right here, you can see 368 and
so on and so forth. Nothing to wind in here. The idea of the message is the same as the idea of
another message. And that was expected, but now we are going
to break this. By we, I mean you, because you will need
to add to our value, append the value of our string. Do that before printing
out the idea again. And then run and look at
the result that we get. What does it mean? You
should know by now. I will give you a small hint. If you don't want the
hint and you know how to append the
string yourself, or you want to look it up, then go ahead and
do the challenge. If not, I'm going to
give you a hint, 321. Boom. To append, you
can use the plus equals pause the video right
now and go do the challenge. Okay, welcome back. How did you get on with that? As you can see in here, we
have message equals correct. We printed out the ID's. Now, I'm going to
try an appendix. I will print out appending the message now with three dots. So that in the output we can see like, wow, what's happening? But now nothing's
actually happening. We'll just have a print in here. I'm going to print out, sorry. I mean, say that message
plus equals ish. So you are correct ish. I will print out message, so what it has become. And I will also print
out the idea of message. Let's go ahead and print out
the idea of another message. Why the hell when I
write click and I run, I got the ID in here
where it's 2398064. Then I said appending
the message. Now it's correct, is now
the ID ends with 61128064. As you can see, the ID changed
when the variable changed. And what does that mean? Let's say it altogether. Yes, exactly. A new object was created when we tried to
change our strings, because strings are immutable, When we changed the
result or the value, Python actually
created a new string to accommodate this new value. I hope you understood
what this is all about. I know it might look
like freaky black magic. This is Python works, and you'll see that this
has a lot of benefits, especially when we start
working with mutable objects. In the next video, I
hope to see you there. I hope you enjoy, and I'll
see you in a few seconds.
52. 3. Mutable Objects: Okay, so now it's time to start talking about
mutable objects. What are mutable objects? Mutable is when something is changeable or has the
ability to actually change. In Python, mutable
is the ability of objects to change their
value during round time. Which but does that mean? Which means that their
ID should stay the same. These are often the objects that store a collection of data. Just like lists that store
a collection of data. Example of mutable
objects would be lists, sets, and dictionaries. And we're going to
learn about sets and dictionaries in later sections. But for now we're going
to focus our attention on lists and see how they
are actually mutable. If you go back into our code, I'm going to create
a new Python file. And sometimes if you
don't see the file, you can click on the
actual code in here, go to file and create a new Python file that I'm
going to call the mutables. The mutables, I'm going to
create a shopping list. A shopping list is a great example of an object that we
would like to change. Because I don't know if you go shopping yourself or
if you just order. But the same thing holds
true when you're ordering items from Amazon or the
supermarket or whatever. You start adding items, but then you also might
want to remove these items. So there will be
a lot of change. A shopping list is a
perfect example of an object that we would
like to be mutable. I'm going to have milk. I'm also going to set
it on a new line, and this new line
doesn't look nice. Shift up until the
end. Duplicate this. Now with the milk, I'll get
pasta and some eggs, maybe. Maybe I'll get spam bread. I hate spam, by the way. And rice. There we go. This is our shopping list. I'm going to say that we have another underscore
shopping underscore list that will be equal to
our shopping list. I'm going to print out the ID of shopping list. List two.com ID shopping
list. Duplicate this. Another shopping list ID,
another shopping list. If you right click and we run the same output
that we were expecting. The same ID is there for both the shopping list
and shopping list, because they are the same. We've set them to be
actually the same. So I'm going to give
you a challenge. Your challenge will be
to append our list. So you'll need to append
the value of our list. Print out the ID. Again, run and look
at the results that we get or the result that we get and
what does it mean. But before you start
your challenge, I should give you a hint. If you want to go
and understand how to add or append
a list yourself, I do recommend that you
try it on your own. You will find that
there could be some freaky stuff
going on in there, but my hint is 321 to append use plus equals and not just the normal
double quotations, but with the square
brackets around them. Pause the video right now
and go do the challenge. Okay, welcome back in here. What I'm going to
do is I'm going to append my shopping list. I'm just going to
print out and then print out adding cookies. Is that how you write cookies? I hope so. Adding cookies with three dots. And I'm going to get my shopping list and
say plus equals. Now this is where most of
you might have messed up. Some of you, if you didn't look at the hint and
you tried it out yourself, you might have a cookies
like this in here. I will print out the
shopping list again. So print out shopping
list and I will duplicate this and take
it down to the bottom, the idea of the shopping list. So I'll actually jag this
and put it at the bottom. If I write, click and I run, look at what I get. So I get milk, pasta, egg, spam, bread, rice. And I also get C, 00 K, E. And what the
hell is happening? Well, what is happening
is that cookies, as we said, is a string. And as we alluded to earlier, strings are also sequences. What that means is
that C is an item, O is an item, is an item, k is an item, is an item, et
cetera, et cetera. When shopping list,
which is a list, is plus equal this
other sequence, it thinks that it should take each individual character and consider it an item and
add it to its list. Instead, what we should do
is we should tell it that cookies is an item on its own. So now if we write
and click and we run, you'll see that we actually
have cookies being added. I hope you understood why that is the case,
how this changed. But the more important
thing in here is the ID. What happened to the ID? The ID started off
as 24588, whatever, and then 792, and
then it stayed 792. Oh my God. What does this prove? This proves that
we were actually able to change or
pend or whatever, changed the value of our
shopping list, of our list, the ID stayed the same, which means no new
object was created. Which means that a list
is a mutable object, while strings,
numbers, bullions, et cetera, are all immutable. If you try to change them, the value of the ID will change, which means a new
object was created. So I hope you understood
the difference between an immutable
and immutable object. I hope you understood the benefits of having
mutable objects, and the benefits also of
having immutable objects. I'll tell you the benefits
of having immutable objects. And just a bit, I actually have a table in here that
I almost forgot about. Immutable objects are quicker to access because you know that this object
will never change, it will always have
the same position in your data based on the Ram. I'm not going to
go into specifics, but because it doesn't change, it's easier to access. Mutable objects are recommended when there is a need to change the size of our current
content of objects. Meaning if we have a list of groceries that we will
definitely change later on. Extend, shorten, then mutable
object is the way to go. Immutable objects are expensive to change. Why do
you think that? Take a moment to think about it, because if you try to
change an immutable object, you actually have to create another immutable object
which is heavy on the system. You might think like, yeah,
what are you talking about? Like I just changed
the list or changed the string and it happened
like instantaneously. But when you have a program that is thousands
of lines of code, when you have, I don't know, like millions of
objects being created, it's going to take it stole. So knowing which object
to use is very important. Mutable objects are
easy to change, unlike immutable objects,
which are expensive. And finally, when we talk
about immutable object, a change involves the
creation of a new copy, wh. When we talk about
immutable objects, change can be done
during run time. That is the benefit mainly
of using immutable objects. They are quicker to access. If you have an object
that shouldn't change its value over time, using an immutable object
is the better option. So I hope you enjoyed, I hope you understood
what this is all about. I do recommend that you go and look yourself into these things. I might even attach
some homework, some quizzes to these videos.
We'll see what happens. So I will see you in
just a few seconds. When we talk about binding
multiple names to a list, what is that even? So I'll see you in just a bit.
53. 4. Binding Multiple Names to a List: Okay, so let's look at binding
multiple names to a list. Now, this is not
a role in Python. This is just an experiment
to show you what happens when you have
mutable objects. Just as a small introduction, what I want to do in here
after printing out the idea of shopping list is that I want to actually out another list. I'm going to print out in here. And I'm going to say
this is another list. I'm not printing out the
idea of another list. I'm actually printing out the entire another
list, another list. Let's just call it
another shopping list. I think you are going to be a little bit shocked
of what you will see. I'll also copy this
pasted in here, and I'll say that this is the shopping list and
another shopping list. Okay, there we go. Let me move this up a bit and I will just print so that
the ID is separated from. Oh, and also, let us
why not print out the other shopping list
ID since we're here. If I write Click and I run, look at what we get. So we are adding cookies, and remember we added cookies
to our shopping list. We did not change
another shopping list. And notice what we
get in the output. This is another shopping list, and what do we have at the end? We have cookies. Oh my God, what is this all about? Well, remember,
another shopping list is pointing to shopping list, which means that they
are the same object. We've already
established that when we changed or when we
checked the ID. But now as you can see, when we changed
the shopping list, because another list is
pointing to shopping list, they have the same ID,
they are the same object. And we said that
shopping list is a list, which means it is mutable, which means when it changes, another list will
change with it. As you can see, the ID has stayed the same for
the shopping list. For the another shopping list. Every single time
you make changes to shopping list or
another shopping list, the change will
be on both lists. Kind of crazy, I know, but this is how Python works. So just to hone in the idea, I'm going to issue you
a bit of a challenge. Your challenge is going
to be to add bananas. So you need to first create another four lists and set
them as the another list. So a lot of students
make the mistake of creating list a and then
list B, and then no, you should say a
equals b equals equals D equals equals F. No matter
how many lists you want, equal to another
list, then print out, then let's see, append
another item to one of the four
newly created lists. Use the pen with
something inside. This is a different
way of appending. If you don't want to
use the plus equals, print all of them out
and what do you see? You should be already familiar with what
the output should be, but test it out for yourself. Pause the video right now
and go do each challenge. Okay, in here I'm going to go ahead and
create a few more lists. I'm just print out
an empty line. I'll say a equals
b equals equals equals equals f.
I'm going to say that all of these are equal
to another shopping list. Then I'm going to print out
list just for the heck of it. I'll then say that I
want to add bananas. I'll actually add bananas. First of all, is that
how you write bananas? If I write click Show
Context Bananas, it only needs one on each side. Bananas adding
bananas to a list B. Just so we are clear on that, then I'm going to say B end. I will add bananas with one
on each side and print out, print out, print
out another list. Print out the original
shopping list. Print out whatever you. Because when I write click
and I run, as you can see, bananas after we've
added it to only the B, all of them became the same. Because these are mutables, they are linked
to the same list. Which means when we
add banana to one, we add banana to everyone. So as you can see, when one list changes,
all of them change. So I hope you enjoyed, I hope you understood. And in the next video, we are going to look at some common operations that
we can use on our sequences. See you in a few seconds.
54. 5. Common Sequence Operations: Okay, let's continue on and let's look now at common
sequence operations. I'm going to open up a link
in here that I'm going to provide you
with. Here it goes. This is the documentation, Python.org library, STD type, I think it stands for Don standard library
and the built in types. Once you get to the link, I will do a control to
find and I will search for common sequence operations. There we go. Now some of these operations you
might have already seen. If you look in here, you can
see that x in returns true. If an item of is equal
to x l, we return false. We've already seen
this used many times in if statements when
comparing two strings. We also have the
X naught in which returns false if an
item of is equal to x. We also have concatenation, just like we were able to add two strings together
to concatenate them. We can also add two lists
together with the plus sine. We have the multiplication which creates or
multiplies the sequence, which in our examples were always strings multiplied
by an integer, would just duplicate that string multiple times, as
you can see in here. We can also access an
item with the bracket. We can slice, slice our sequence using
the square brackets. We can slice the sequence using a step using the
square brackets. We have the length, I believe we've already seen that one. It just returns the
length of the S or the number of
items that we have. Keep in mind that this does not consider the index
starting at zero. We don't count them like 012. If we have, for example, a sequence that goes 0-7 that
means we have eight items. Next we have the minimum which
returns the smallest item, the maximum which
returns the S. And this overcomplicated
index thing, which if you just take
out everything on the side and just leave index x, you provided with the item x. And then this method,
or this function, or this operation
to be more precise, returns the index of the
first occurrence of x in. Finally, we have the S
dot count operation, which returns the total number
of occurrences of x in. How many times did we, let's say we're
looking for banana, how many bananas are there
in this shopping list? You would use the doct. Okay, So pretty simple.
Not too much in here. I recommend that you
go through them. You understand every
single one of them. We've seen them before, and now we're going
to look at a few of them in our program. I'm going to open up
by lists and doupples. I'm going to go into again, the Python is there, so I click on the
code Python file new, and I call this the
numbers underscore lists. Let me close this one down. I'm going to create random
underscore numbers, and it will be equal to 162-51-2068 I will duplicate this and change from a
small to big numbers. And the numbers
that I will have in here are 695-41-2365 7,584, And by the way, these
are just random numbers. Just recommend you find
high random numbers, or big random numbers and
small random numbers. Then I'm going to print out the minimum of the
small numbers. I will duplicate this and
change it into the maximum. I will then select
these three lines including the empty space, and then duplicate that as well. And then we will use these
for the big random numbers. All right, so with
that out of the way, let me write click and run, and there shouldn't be
any surprises here. The smallest number in the
random small numbers is one. The biggest one is 68. The smallest one in the
random big numbers is 365. And the biggest one or
the max number is 7,584 Nothing too important in here. We simply used a very
common operation that gives you the
minimum and the maximum. This was just a demonstration. Now, with that
knowledge in hand, it's time for a bit of
a challenge for you. You need to test out other methods or
operations I've used. The word operations may be, print out the output of the method length on
our two sequences. Print out the output
of the method. Do count on the string with the same letters
appearing multiple times. What do I mean by that? Ferrari. Ferrari has the letter R
appearing multiple times on it. You need to use this Ferrari because remember a string is a sequence as well. You will use the count
on Ferrari and count how many times we
had occur in there. Pass the video right now
and go do the challenge. Okay, welcome back. So, how did you
get on with that? The first part of our challenge was to print out the length. So I will print out
length of small numbers, print out the length
of random big numbers, right click, run,
and there we go. We have five by five. Notice 16 would be at index
number zero, correct. Then 123.4 But in this case, even though index stops at four, we have 12345 elements. 12345 elements. Just to test this out, I'm going to create
an extra element. So we should see
that the length of random big numbers
should become six. There we go, we get a six. For the other part
of the challenge, I'm going to add an empty print, and I'm going to
print out Ferrari. Do and I will count the
number of Rs that I have. If I write, click and I run, I should see that we have
three R's in my Ferrari. Maybe some of you created
like something like this message equals Ferrari. And then you message
in here on the dot, that is the same exact thing, but I decided to
use it explicitly. Explicitly means I don't
store it in a variable, I immediately the count
on it explicitly. All right, so a small
trick before we leave. This is a very simple I
think, lesson in here. So I'll give you a
small extra challenge to mess with your head if
I try to do the following. If I want to print out Missy P dot count and
I one account SSI. Notice that we have
MISSI on here and also we have SSI on this side. How many will it count? Will it count two or
will it count one? If I write click and
I run look at that, it only counts one of them. Because if you look closely
into what this says, the total number of
occurrences of S, even though it doesn't
explain it really well, once it finds one of them, it doesn't consider
the second one to be part of it as well. Meaning that it
counts this one and the other one would
be just an S I. If you wanted, you could
have done the following. Now, this should count
or return at least two. There we go. So just
something to keep in mind. I hope you enjoyed
this was, I believe, a very simple lesson,
I hope you enjoyed. Operations will come and will
be useful in the future. In the next lesson, we're going to learn about operations on mutable sequences. And a pending our lists
where we will actually start creating a very
elaborate and nice project. I'll see you then. Thank you for watching.
55. 6. Operations on Mutable Sequences plus Appending to a List: Okay, time to start doing operations on mutable sequences and also learn how
to append lists, even though we've
already appended lists, but never at this scale. This is also going to be the
start of a project that we are going to do over maybe
four or five videos. So let's go ahead and
start the journey. First of all, I'm going to
go into file and create a new Python file that's going
to be called Creating car, or building underscore car. There we go. First of all, I'm going to create the
current underscore choice. I'm going to say that
the current choice is just equal to a. Then I'm going to say
that car underscore parts is equal to an empty list. This is going to be just to create an empty list that
we will fill later on. What is it nagging me about? I think it just needs an extra
line. Yeah, there we go. Python doesn't like
you ending at the end. It always likes to have
one extra empty line of space. Don't ask me why. Then we're going to create
a while loop in here. And we are going to be
doing the loop while the current choice is
different than zero. And by the way, this is why we set the current
choice to be a. Because if we set
it to be a non, this will cause an error because you cannot
compare non zero, you need to have some
kind of value again, we will check if the current choice is
different than zero, then we're going to check the
current choice is in 12345. If the current choice is in this string that
we have in here, we are going to
do the following. We are going to print out adding replacement field format
and the current choice. Then in here I'm going
to say else print, Please add option or
please add an option. Please add an option
from the list below. And I'm going to print
out the following. I'm going to print out 12
dots or column wheels, Boom. To lights duplicate,
front wings duplicate. Oh no, seats, duplicate windows finish. And then we'll have 345
and the Almighty zero. Then I'm going to say current choice is
equal to the input. Your choice here. All right. So once you are done
with this code, I recommend that you
look through it very carefully to properly
understand what is going on. Go through it line
by line so that you can clearly see what is going. Because I'm going to be
explaining this to you. First of all, I want you
to mind the indentation. So the current choice, we are always getting an input inside of this
while loop in here. Once we get that input, we are checking if the current
choice is in 1234 or five. If it is, let's say
the person chooses 11 will be inside or in this current string
that we have in here. If it is, we are
going to print out adding one or adding
two or adding whatever. But if the user presses
a number like eight, let's say, or 510, for example, we're going to go into the else and we're going to indicate to the user of our
program that no, please choose from the options
that we've given to you. Don't go wild in here. And then regardless
of what he picks, unless he picks zero, of course. Because remember, while
the current choice is different than zero, we keep going through this loop. If the person chooses
five, or four, or ten, or 11, or one, or 19, or 500,000 we are going to ask for a
current choice again. If you're still not
sure how this works. Again, I recommend
going line by line, understanding properly
what is going. I will right click
and I will run, and I will move
this to the side. What happened in here? First of all, we have the
current choice as a dash. We checked the
condition in here. It turned out to be true, which means we go in here, We checked if the current
choice is in 12345. No, it wasn't. So we went into the Ls and we printed out everything in here. Boom, there we go. Once we
finished with the printing, we jumped out of the Ls and
we had the current choice. Because remember, the
current choice is not part of the block
of code of our Ls. We're here on the
current choice. Let's say I pick eight. What do you think
the output will be? Think about it before
you actually hit Enter. There we go, because
eight is not in 12345. We printed out the Ls in here and we got
all of these options. Now I'm going to pick one of these options.
I will hit one. Boom. There we go. It says adding one, because one is part of
the 12345, then 2345. If I hit zero, there you go. You can see that the
program is terminated. Again, I recommend you test
it out, you play around, You understand exactly
how this works. Now we want to start
actually adding these numbers into
our car parts. After we say that we're
adding something, we're going to do the following. We're going to check if the current choice
is equal to one. We're going to call up
the car parts pend and we're going to add
wheels. How about that? But if it's not one, we're going to check LF, current choice is equal to two, then car parts a pend, It's going to be lights. I will hit Enter and I
will duplicate this, 345. I'm going to have
34.5 I will add front wings, seats, and windows. What is happening in here? Obviously, if you haven't
finished the code, pause the video,
finish the code, and come back so you
can clearly understand what's happening in here. What we have is
we're checking if the current choice
is equal to one, then we are going to
be adding wheels. If the current choice
is equal to two, we'll be adding lights. If the current choice
is equal to three, we'll add the front
wing to the car parts. We're appending the car
parts just like we were appending the list
of where is it? Right here, just like we
were appending list B with bananas or like we were appending the shopping
list with the cookies. Now, obviously we could have used the plus equals as well, but using the dot append is more sophisticated.
Shall we call it that? We are doing the exact
same thing in here. I'm going to remove the empty
lines that we have around. Now that you've
understood everything, I will add an extra space. And once we jump
out of our Y loop, I'm going to print out the
car parts that we have. Actually, let's just
add a space in here. If I write, click and I run, I want to add Wheels. It tells me adding 123,335.0 Before I press zero and before
you do it on your side, please think of what
the output will be. Always do that, never just
hit Enter and try to analyze. Think before you
actually press Enter, think of what the
output should look like and there we go. Let's look carefully
at it in here. As you can see, we pressed
one, which was wheels. We pressed two,
which was lights. We pressed 33 times, so we got three front wings, you can never have
enough front wings. And then finally
we pressed five, so we got windows at the end. As you can see, we are building our car by adding one
component at a time. So I recommend that you
test out this entire code, make sure that everything works
as you expect it to work, Add all of the car
parts and whatnot, and make sure that you
understand how the sequence of events and the
outputs looks like. Because once you
have all of that, I'm going to issue
you a challenge. Your challenge is going
to be to add an item, so add the stereo as an option or as one of the items that
we can get with our car. And make sure to look
for all the places where we need to make
the modifications. Test it out. Make sure you can add
that item as well. Very important to
test it out past the video right now and
go to the challenge. Okay, let's go ahead and get
started with the challenge. You might have done
it and you might have found why this
is so cumbersome. First thing we need
to do is we need to add it as an option. I'm going to add a six, I'm going to add stereo Next, we need to actually
be able to append it to our list in here. I'm going to add an extra line
and we'll duplicate this. There we go, because I'm lazy, I will make this six. This will be a
stereo. There we go. Now if I write click
and I run look at that. I get the option
to add a stereo. But if I hit six and I
hit Enter, Interesting, it doesn't tell me that
we're adding a six, even though I have it in here. If I try to just finish, I still have an empty
list. What gives? Well, there is one more place
that I need to add a six, which is right here, so that this condition
can actually trigger. Now I right click and I run and I try to hit six
and another six, and maybe another front wing. Why not hit zero?
And there we go. You can see that I got a stereo. You might be thinking, well, that wasn't that bad. I mean, we just added
a few lines of code, A few words here and
there, no problem. Well, what if somebody
comes along and tells you, you know what, This car needs? A few more parts. So they hand you 500 parts
that you need to add. Imagine that for a second. Imagine having to
add 500 more parts. First of all, to
display them in here, so that's 500 more prints
that you need to add, 500 more L ifs that
you need to add. And this is not even possible. You need to go up
to 500 numbers, so you have to account
for 678-60-7080, 125, 350, whatever. So a huge, huge blunder here. That is a problem that
we will fix next, next time in a few seconds,
when you watch the video, which is called
iterating over lists. So, I will see you then.
56. 7. Iterating Over a List: Okay, now it's time to start optimizing our
code using lists. The first thing that we
need to do is we need to type in the following
code at the top. In here I'm going to add
two spaces and I'm going to create a list of
the available parts. It will be equal
to the following. We are going to have
the wheels control D, to duplicate the lights
control D. Front wings control D. Seats control D. Windows control D.
There, there we go. Now we have the list of
the available parts. The next thing we need to do
is we need to use this list in order to print out
the following lines. I'm actually going
to comment them out because you are going to have the challenge of
doing that yourself. Print out our available parts. Create a four loop over the
available parts we have. Use it under the else. Print out the index
of the part and the name of that
part next to it. You will need to use the index that we learned about in
the common operations. I don't know how
fast you're going through the scores
a few videos ago. It should look identical to when we hard coded in the
previous lesson. Meaning it should look like
12 dots wheels, the same. We should have the same
output as in here. And finally, I will
give you a hint. If you don't want to
look at the hint, I recommend that you pause
the video right now and go to the Challenge 321 used index. Oh, well, yeah. Sometimes, I don't remember exactly what the challenges
entail, but there we go. That was your hint,
You already had it. If you pause the video, went and did the challenge and
came back and turned out the hint was
something you already knew you pretty disappointed. But anyways, pause
the video right now and go to the challenge. Okay, welcome back. How did you get on with that? I hope you at least
tried your best. The first thing we want to
do is we want to create this fore loop that goes over
all of our available parts. I'm going to say four
part in available part, two dots and there we go. Now we go over all of our
available parts one by one. Next I'm going to print
out the following. I'm going to open up my
replacement field in here, and this is the new way
of using the dot format. I'm going to put in here
the available parts. Do index and notes. When I hit the tab,
it autocompleted and added this small behind it. I believe we've already
talked about that. But because I'm recording
Sam cut that out. We can see that the F
was added automatically. We've already talked about that. I'm using the dot index on my available parts and
I'm looking for the part. Then I also need to add
a plus one in here. Mm hmm. Why do you think
I added a plus one? That will be a small
challenge for you to figure out before we finish up when I hit the part in here, because I want to print
out the part when I right click and I run look at that, I get the same exact input. So let's talk about why we
have a plus one in here. Well, if we don't have that
plus one in here and we right click and we look at
the output that we get, we get zero wheels, one lights. The dot index gives you the index of the
first occurrence of the item that you're looking
for when you type in part. For example, part when we're at the first part which
is the wheels. Uh huh. Look at that. We
get wheels, its index zero. Good lights. It's index is one, front wing index is
two. That's correct. But as the user, as me for example, I'm using this program, I'll
come in here and be like, oh, nice look at that. I want to add some wheels, hit zero, hit enter. And I'm like, what, what's that? What kind of sorcery is this? I'm trying to add
wheels and you just throw me out of my own program. Yeah, not a good way
to impress your boss. So we need to add a plus one in here so that it adds
one to the index, and now the user
can actually press on one and it tells
him it's adding a one. Hit zero. There we go,
we get the wheels. That was the challenge. Now we can easily and seamlessly add an
extra item in here. Let's say I wanted to
have a DVD player. I just type it in right there at the top when I right
click and run. Look at that. Now we
have a DVD player. I can add whatever
more parts I want. I'm not going to add them right now because this
code isn't done. Now, if I press
seven, I hit Enter. Yep, it still doesn't work. I have to add it in here
next to the current choices, and I also need to accommodate for it
with an Lip statement. But we have started
optimizing our code. Next time we're
going to learn about enumerating over a list. And we'll see how that
is going to help us with reducing this entire
block of code in here. And this one as well. I will see you in the next
video where we will learn about enumerate
in functions. See you then.
57. 8. The enumerate Function: Welcome back my fellow
Python programmers. In this video, we
are going to be learning about the enumerate. And we'll also be
using the enumerate to upgrade our project. So let's go ahead
and get started. First of all, we need
to understand what the enumerate is all about. First of all, the enumerate
function in Python converts a data collection object
into an enumerate object. Let's delve a little bit deeper. Some concepts will be confusing at first,
but don't worry. We will have examples and that will allow us to
understand everything. It returns an object
that contains a counter as a key for each
value within the object. When you enumerate over a list or any sequence
for that matter, or in this situation we
call it any itteruble. Which means we can
iterate over it, like when we do
with the four loop. We iterate over a string, or we iterate over a list. When you put ble
into the enumerate, it returns two things. It returns the key and it returns a value
associated with that key. What do all of
these things mean? This also makes it
easier to manipulate our data collections where
such things are possible. For example, I can enumerate
over my available parts, which returns the part and an
associated number with it. That associated number
will be the index. But I still call it an associated number
or an associated key. Because if you enumerate
over something that's not a typical list or
a string or a topple, you will get something
other than just the index. And we'll see what I mean
by that later on when we learn about
dictionaries and sets. In our current situation, we will always have the
key being the index. You can even take it as a rule. But keep in mind that the key will not
always be the index. Without any further ado, let's see a few examples to clearly understand
what all of this is. You can then come back
to the slide and re, read the theory part
of the enumerate. Trust me, it's a very easy
concept that's not as complicated as you
can see in here. If you go back into
our code in here, what we want to do is
we want to enumerate over our parts right here. As you can see, when
we create a for loop, we go over our available parts, that's why it's
called an itterble. A list is itteruble
because we can't get it iterate over it. We're going to do the same, but this time using
the enumerate. First of all, I'm going to
comment these lines out, now I'm going to
delete the prints, but I recommend that you
keep them or you copy the code and put it either
below or in a new Python file. Because then you can see the
progression of our program. In my case, I'm going
to delete them. I recommend that you
don't tell J crashed. Okay, we're back
after a small crash. I commented these
lines out in here. I'm going to create the
following for loop. I'm going to say
four number part in enumerate available parts. Notice I have two items in here instead of
just one in the part. I'm saying number and part to be even more precise and in parallel with the
theory that we learned, we can even call this the key. Now that I have this, I'm going to print
out the following. I'm open up the a
replacement field in here. Inside I'm going to type in number our key because
I changed it to key, type in key and hit Tab so
that the gets autocompleted. Right here on the
left hand side key, two dots open up the second replacement
field and the part. Let's see what the output
is going to look like when I write click and
I run. Look at that. As you can see we have the key which are
keys are the index. And again this is only in this situation when
we're using lists. Now again, let me
reiterate this. About 80% of the time the
key will be the index, but in certain situations
it will not be. That's why I'm emphasizing
this as much as possible. We have the key in here, the numbers associated
with the parts. Now you can begin to
understand what a A counter is you have a key for each value
within an object. Where is it object into
an enumerate object. The enumerate object
has two parts in it. It has the key and has the actual part which is part of the available
parts that we have, that is the key part pairing. Now you'll notice that in here, wheels start at zero. Obviously, we don't
want that very simply. We can simply add a plus one. Run this ball. There we go. I hope you understood
how this works. I will remove the
following two lines. Again, I recommend that
you keep them so we can see the progression
of our program. But now we have a
very clean fore loop that prints out all of
our available parts. I hope you understood
how the enumerate works because you
have a challenge. Your challenge is going to be
to enumerate the alphabet. You'll need to create
a new Python file and call it the alphabet
enumeration, Or obviously, whatever you want inside
enumerate over a string, that is the alphabet, a string, not a list of strings. You will have a string which
is the alphabet ABCDEFG, whatever that will
be the alphabet. And you need to enumerate over that string and print out each value with its
associated number. Pause the video right now
and go do the challenge. Okay, there we go. In here I'm going to say
four index character in enumerate and I'm going to
send in the alphabet A, B, C, D, E, F, G, H I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y and Z. Yeah, there we go, That is correct Inside, I'm simply going to print out
the index, the character. Notice that in here I
called the key index. I will refer to it as
the index going forward. But again, you have to know that it's not always the index. But in any case, if you want, you can start using it as
an index from now on as, but later on you'll see that
that is not always true. But anyways, when I write, click and run, there we go. You can see that we start
at 0123, 43d, Nice. 56, et cetera, et cetera, until we get to 25 Z.
I hope you enjoyed. I hope you understood the importance of
using the enumerate. And I'll see you in the next
video where we actually use this new found power to
improve our code even more. I hope you enjoyed. See
you in a few seconds.
58. 9. Improving our Code: Welcome back my fellow Python programmers to another
video where we will be improving our code back
in the building car. And here as you can see, we've already made
some adjustments where instead of going through a hand
manually printing out every single available car part, we now do it very easily
using a for loop. This had many benefits. The first benefit was that
it made our code shorter. The second benefit was
it made it more dynamic. Meaning that or when we
add more available parts, they automatically
get displayed. It also made our code easier to debug and easier
to find issues in. Now we need to improve
this even further. There was an issue
with this program. Some of you might have found it, but some of you might have not. The issue is on the
following line number 15, where we check if the
current choice is in 123456. What is the problem? It's
working fine in here. If I type in three, there we go, I'm adding three. If I type in, for example,
eight, there we go. You can see that it's not there. Now one of the issues is obviously that if we
add, for example, a DVD player on
key number seven, not registered, but that is
only part of the problem. This is a small
problem that we can easily solve by adding a
seven right here at the top. The other problem, and the much more drastic
issue in here is that if you type
in 12 and hit Enter, it actually says
adding 12. Oh my God. If I type in 23, it also says it's adding 23. Now if I type in
20, there we go. You can see that it tells us, please add an option
from the list below. So what is the problem? Take a little bit of
time to understand. So for example,
if I type in 123, it also is adding 123. So look at the code,
look at the condition, What is the issue in here? Okay? So if we look closely, we'll see that we're checking if the current choice is in 1234. Now this is an entire
string of its own. It means that we check
if the current choice, for example, 123 is in 123456. So for example,
if I type in 456, it also tells me adding 456, if I type in 4536, there we go. Because the five of what? 4536 is not in 123456. So that is a big, big issue. That is the first thing
that we need to handle. So what we're going to do is, or we're going to
create a list of all of the valid choices right here before we actually start going through the Wi loop and getting the current
choice and whatnot. We're going to do the following. We're going to create a
list of our valid choices. We're going to say
that for I in range, with the range being one on the length of the
available parts plus one. We're going to get
valid choices, append with an STR of and print out the valid
choices, weird, weird code. What is this all about? First of all, I want you
to take a few seconds past the video and try to understand
what this code does. I do recommend that you do it. And then after that, I recommend that you add
a break point so that you can try and go through this
code again so you can see, all right, what's happening
after you do that, try to make another prediction of what it's going to look like. Finally, we will run the
code. Take a few minutes. Okay, welcome back. For me, nothing has changed. I hope you tried this
mini mini challenge. When I run this program, you'll see that this is
the output that I get, 123,456.7 And you'll
see that each one of these are individual
items inside of a list of the valid choices. As you can see, there's no complete one single string of 1234 all next to each other. Now we have a clear list
of the available choices. Let's look at the code and
what it actually does. First of all, created
an empty string, an empty list.
Nothing much in here. Then we created this fore loop. Now we have the I being the variable that is
going to be increasing. Nothing too special in here. Then the special thing is
the range that we have. The range is going
to go from one throughout the length of the
available parts plus one. And then at every single
point in that range, we're going to get valid
choices and append it with, but it's going to be
converted into a string. Why are we, first of all, let's think of the length
that we have in here, or actually the entire range. Let's consider the entire
range and what's happening. Our goal is to have all of the following numbers match the parts that we have
right here, as you can see. In this case they do, they go one through
seven in my range. What I'm trying to do is
I'm trying to associate one with wheels and the last number which is
the DVD player with seven, this should be 123,456.7 That is why I start
at a range of one. Makes sense, right? Because
I want to start with a one. Not a zero but a one. But what that means is that if I want to go to the end
to the DVD player, not only do I have to
go through the length, because remember
if we do length, it will return seven. If I print out the length of the available
parts, I get seven. Now you might be saying, okay, so why not just
use seven in here? Well, young grasshopper,
you cannot use seven because in
ranges it's up two. But let me hear
you say it again. Up two but not including
that is why we have to add a plus one right here at the end to accommodate
the last element. Because if I remove this plus one and I write Click and I run, look at that, I only get to
six because it gets to seven, but it's not included. I have to add a plus one. I'm going to remove
this line of code. This was just for
debugging purposes. If you want, you can
simply comment it out, put it in another file
to clearly understand. I hope that was clear. The last thing that
we need to understand is why we're converting
it into a string. In here we are
converting this because remember in range is an integer, we want to convert
it into a string because the current choice
that we get in here, obviously, these valid choices
will be used somewhere. It's going to be a
challenge for you, but it will be used somewhere in here to check if
the current choice, I gave it out. But okay, it is in
the valid choices. And remember, when we're getting an input for the current choice, it is a string, that's why we convert
it into a string. I hope that was understood. I hope there was no ambiguity. If you have any questions, leave them wherever
that's possible. That out of the way, it's time
for a bit of a challenge. Your challenge is going
to be to print out the choices in the while loop. Check if the current choice
is in the valid choices, then print out that we
actually added that choice. Use the current choice input as an index to get the chosen
part from the available parts, Append our car parts, and test it out on the last
part and see if it works. This is a tough challenge. I think it's one of the harder challenges because there are a lot of
things to do in here, a lot of things to think about. It's not an easy, but
you'll have to use the current choice as an index to get the chosen
part from the available parts. There's no hints in here, it's not an easy thing, but read carefully, read it, slowly, dissect it,
and understand. Because the current choice
will be used as an index, which means it has to have
something happen with it. After it's used as an index, you can get the chosen part
from the available parts. And once that happens, you can append your car parts. And the most important
thing is you need to test it on the last part because there's a
small trick in here. Past the video right now
and give it your best shot. Okay. So how did you
get on with that? Please, If you were able
to do the challenge, post it somewhere
wherever you can. Maybe in the question
section or wherever you can. Posted there, posted on social media tag
me, I don't care. It's a great achievement
if you were able to do this challenge on your
own, I congratulate you. You are becoming a great
Python programmer. If not not a problem. As long as you did your best, that is the most
important thing, because if you try it, you will encounter
a lot of problems. And once you encounter
all of those problems, you will see the solution
much more clearly. Because the first thing
that we need to do is we need to remove this part and say that the current choice
is in the valid choices. Now if I write Click and I run, If I type in 12, look at that, it no longer works because my valid choices are
one through 7123, et cetera, until
seven and then eight. It does not work. One to three, no longer works. 45 no longer 56 no longer works. We only work with the valid
choices that we have in here, which is amazing.
That's the first part. That was the easy part
of the challenge. The other part is to use the current choice input as an index to get the
chosen parts from the available parts in the whole premise is to comment these lines out and replace them with a much simpler code. Now, if you weren't
sure at any point, if you find yourself, oh, that was the key that I needed
to finish this challenge, then pause the video
again. No problem. Try to do the challenge again. No problems in there. In here, as you can see, we're
saying that we're adding the current choice or
whatever, adding that choice. Now we need to use the index. We need to use the
current choice as an index to the chosen part. First of all, we need
to have the index. The index you might be thinking should be just
equal to the current choice. But the issue in here is that the current choice is a string, the index has to
be an integer we converted into an integer. Great. Then we're going to get the chosen underscore part. I'm going to say that the
chosen part is equal to the available parts
at the index. There we go. Pretty simple. We get the current choice, let's say it's four seats, we convert it into an integer, we send it into the
available parts, and we get the chosen part. But that's not all because
we also have to append our car parts with
the chosen part, and that was the challenge. It's still not over. There is a small hiccup in here
I haven't talked about, but let's say this is what we got to because there's
a small detail in here that can easily
go unnoticed. Notice that one of
the last points in the challenge was to
test on the last part. Test it out on the last part. Let's go back in here.
If I write Click and I run your choice. Let's say two for the lights, three for the front wings. Let's add three front wings. You can never have
enough front wings. Let's do seven. The last part, what is that list? Index out of range. Hmm, that's weird. Let me try this again
without the last part. Let's try lights and three front wings and
hit zero to finish. What didn't I just order a
light and three front wings? I did, but the problem was
that my current choice was two When I convert two into into an integer and I put it as the index and I use
it on the available parts. What is two in the
available parts? It's not lights because
we start at 012. Instead of having lights,
I get front wing. And instead of instead
of three front wings, I got three seats. And that is why it's
very important to always test out your code. Even if you think that you've
done everything correctly. Even if you might not have
any immediate errors. It's important to test out all of the
limits in your code. So how do we solve this problem? Take a few seconds
to think about it. Yes, exactly. In here we do a minus
one on the index. Now whatever we press, we will remove one
from it and then it will be used to look
through the available parts. I right click, run now,
what do you want to add? Six, boom. Adding 63. Boom. Adding 33. Or
four front wings. It zero. I got a stereo. And four front wings. We haven't tested out
the DVD player 77750. There you go, ladies
and gentlemen. We now have a very nice code. Look at how many lines
of code we were able to save using our
new found knowledge. There we go. Now there are still a few improvements
to be made. We will definitely
be coming back to this project to
improve it even more. But for now, I hope you enjoyed. I know this was a long video, but I think it was full of
very, very useful information. I recommend that you
go through it again, Understand exactly what is happening in these three
to four lines of code. And in the next video, we are going to be
learning how to remove items from a list. So I hope you enjoyed and
I'll see you in a few.
59. 10. Removing Items from a List: Welcome back my fellow
Python programmers. In this video, we are going
to be learning how we can remove instead of add
items to our list. Now, how or what will
be the context of our removal of items were
well in our program, in here, as you can see, when we add seven, it tells us that
it's adding seven. When we add another seven, it adds another seven. So what we're going to do is
just simply when somebody adds seven and then
removes seven or I mean, if they press seven and
then press seven again, instead of adding
two DVD players, we're going to be
removing the DVD player. I know it's not the most
fancy program ever. I'm going to give you a small
homework that you can maybe do on the side to improve
the program later on. But for now we just want to implement removing
items from a list. So let's go ahead and get
started to start off. First of all, right, here, after I get my chosen part, I check if chosen part
is in the car parts. If it is, I'm going
to get my car parts remove chosen part
and that is it. L car parts append
the chosen part. I could have actually moved
this line, but it's okay. I'm just going to
remove it. There we go. Now we can test
it out and see if we're actually removing items. I'm going to right
click and I'm going to run now the chosen part, let's say it's 123, and then I hit two again. Now if I hit zero, there we go. You can see that we first
of all added wheels, great. We added lights, great. We added a front wing, great. But then we press two again, which removed or
removed the lights, which means that we only have
wheels and the front wing. But you can clearly see that
there is an issue where it says we are adding 22
problems with this. First of all, we're
saying that we're adding two even though
we're moving to. The other problem is we're
saying that we're adding two. We should be saying we're
adding the chosen part. We're adding seats, we're adding front wings, we're
adding wheels. So we want to actually print
out what we're adding. And that's going to be
a challenge for you. Your challenge is going to
be to print out removing, adjust the code so that
we print out removing. When we're removing an item, this should be sorry. And adding when we're adding an item with the item
that we removed, of course with the actual name. Pass the video right now
and go to the challenge. Okay, welcome back. So, how did you
get on with that? It shouldn't be that
hard of a challenge. I'm going to remove
the print from here. Instead I'm going to print
something else in here. This is where we are removing. I'm going to print out, open up the replacement
field with the chosen part. I will duplicate this, hold down control shift
and slide it down. And then I'll say adding, okay. Now as a rule of thumb, this is not very
important right now, but it will be important when we start creating databases. It's better to actually
print out after we've appended or removed items from a list or a database. It's more important than
databases because let's say this line of code
does not work and it errors out or it breaks
or whatever happens. We don't want the user to see that we've actually
removed the part. So it's better for the program to break on this line of code, not add the chosen part, and not have not having the program print out
that we've removed the part. So the user like, oh great, we've removed the part but
in actuality it didn't work. So it's better to print
out that we've removed or added something after
it was actually added. Just a small extra hint of
knowledge in there for you. But that out of
the way, we right click and we run your choice. 1233210, Boom. As you can see, adding wheels, adding lights, adding front wing, and
then removing front wing. Removing lights,
removing wheels, and all that we're left
with is an empty list. So I hope you enjoy it, I hope you understood
how from lists work. We're going to delve a bit deeper into removing from lists because it might not be
as easy as you'd think. This is very simple concept, sometimes it's much harder
removing items from a list. Now, as I told you, a
small extra homework that you can do on your own, it's a very simple one. Instead of just removing an item if it's
in the car parts. A good rule of thumb would be, or a good program practice would be to actually ask the
user the question, would you like to remove
this part or would you like to add
more of this part? If the chosen part is
already in our car parts, you could, for example say that, hey, would you like to add this? You already have this chosen
part in your car parts. Would you like to add more or would you like to remove it? This will be a
challenge for you. It's pretty simple. I think you can figure it out. There will be no
solutions for this. But I do recommend
that you always try to dabble and
improve the code, Copy it, paste it
somewhere else, the good version, and
then try to change up. So I hope you enjoy it, I hope you understood
everything. And I will see you in the next video where we will be talking about sorting lists. So very exciting stuff.
60. 11. Sorting Lists: Welcome back my fellow
Python programmers. In this video, we are going
to start learning how we can sort lists without
any further ado. Let's go ahead and get started. First thing we'll
do as we always do, we're going to create a
new Python file and we'll call it underscore lists. There we go. So first
thing we do is we have random num one. And it's equal to 124,269.81 I will then duplicate this
line and I will have random number two where I'm going to have the
following numbers, 314, 2,067.92, Now that we have those
two random numbers lists, and keep in mind
these are integers, what I'm going to do is
I'm going to combine them together to
make one big list. To do that, I'm going
to have random number one extend random number two. Now if I print out
random number one, think for a second what the
output would be like or will look like when I write click and I run.
This is what I get. As you can see we have
list number one which ends at 81 and then list number
two starts after it. We've basically extended
random number one list with random number two. But as you can see, all of the numbers are still scrambled. What we want to do is we
want to sort them out. So in here I'm going
to do the following. I'm going to do random
number one sort, I'm going to print out
random number one. If I write Click and I run, there we go, Look at that. Now instead of the numbers
being all scrambled around, they are sorted from the
smallest to the highest. If we hover over the sort, we should see that we
get the documentation. I recommend that you do this for every single new
function or method, or anything that we use. You can also go to Python.org
If you click on this, it will actually take you to the website where
we have the sort, you can understand the keys. You can, for example,
using the reverse, something that we will
use in just a bit, you can read up on how
all of those things work. This method sorts
the list in place. As you can see, it actually sorts out the
list, random number one. So let's try to use the reverse. As you can see, this
is called a keyword. We will delve deeper
into keywords later on. We will be using keywords
from time to time, but we will not really delve into them until later
on in the course. But for now, we can set
reverse to be true. Now, instead of sorting them from the smallest
to the biggest, we will sort them from the
biggest to the smallest. That's basically
how the sort works. Keep in mind that this does
not create a copy of a list. It simply rearranges the items in the list that
we already have. This could be very useful
and lifesaving, okay? Not to that extent,
but very useful when you have a list that
could be several gigabytes. So imagine if you have a list that's several gigabytes and you have to create an entirely
new one that is sorted. It's going to take
you some time. This is a much more
efficient way. I hope you understood there's
nothing too much in here. Again, I do recommend that you go through the documentation, but for now I have a
challenge for you. Your challenge is going
to get another number. You'll need to create another numb and set it as
the random number four. Before it is sorted you'll
need to print it out as well. And then print it out
after we've sorted random number one, is
there any changes? And what does that mean
again, another number. It should create another number, variable it before random number one is sorted right here. Then I want you to print
out another number again and tell me what
the output looks like. Pass the video right now
and go to the challenge. Okay, welcome back. How did you get on with that? So the first thing that
I'm going to do is I'm going to set
random number one. I think we can set
it right here, another number to
random number one. Underscore numb will be
equal to random number one. I'm also going to print
out another number. When I write click and I run, we should see that we
have another number which is equal to the
random number one. Not too many things
to talk about here. Now I will add a print just so we can distinguish
between the two lines. And I'm going to print
out another number Again, I hope you always think
of what the output is going to be like
before you actually run. Let's see what's
going to happen here. When I right click and look at that number was also sorted. Oh, my magic, isn't it? Well, if you've been following
the past a few lessons, you will know that
lists are mutable. Another list or another
number points to random number one when random
number one was sorted. Because it is mutable, it means that the object
actually changes, which means that everything pointing to that
object also changed, which means another
number also was sorted. So I hope you enjoyed, I hope you understood
how this works and why another number
was also sorted. In the next video, we are going to look at sorting things, meaning that instead
of sorting a list, we're going to just be sorting things that
are inside of it. I'll see you in a few seconds.
61. 12. Sorting Things: Welcome back my fellow Python programmers to a
brand new video. And in this one we are going
to start learning how we can be sorting things as always. First thing we do
is we go into file, create a new Python file and
call it underscore things. Now I'm going to create a message that a lot of
Hobbits are familiar with. It's going to be, one does
not simply walk into mordor. There we go. If you
didn't understand that mean or that sentence, then congratulations,
You've probably had much more social
encounters that I have. But anyways, what I'm going
to do now is I'm going to say that letters is equal to sorted. And I'm going to send the
message as a parameter, and then I'm going to
print out letters. Notice again, just
came to my mind, we always keep an empty
space below in here. If I write click, I run, look at what I get. Let me just log this right here. Look at what I get. I get some weird stuff in here. Weird, okay. But then I have
M cool and then I have A D, D, E, E, I, I, K, L, L, M, N Op. All right. There we go. I'm not going to say every
single letter, but as you can see, there are a few things in here. First of all, the most important thing that
you need to know about what happened here is
that we've created a list. You can understand that this is a list because of the
square brackets that are around this
collection of items. Next inside, we have each
individual character that was in the message sorted out from the smallest
to the biggest. The spaces are
considered the smallest. Then we have the
upper case letters. Only then afterwards do we
have the lower case letters, the sorted. What does it do? If we hover over it again, you'll see that it returns
a new list containing all the items from the
interbal in ascending order. Again, we can always open the documentation
in here as well. You can see it also has
its own reverse key. You can go and see how it works. Again, I recommend that you
spend a little bit of time in the Python documentation
and get acquainted with it. You will definitely
see it in the future. If this is the career path
that you are going down to, as you can see, sort creates a list and sets everything
in ascending order. But it doesn't need to only
be on a specific message, It can also be on
a list of numbers. If we have a list of numbers, and we have 2.34 0.58
0.73 0.19 point 2.1 0.6 Here I'm going to say that underscore numbers is equal to numbers If I print out sort numbers and if
I print out numbers, now you might be thinking, why are we printing out numbers? Again, this will be important
in just a bit because if I write the click and
I run the first thing, I notice that the sorted
number that I printed out is that number was a list. And we used sorted
on the numbers and sort numbers is still a
list that we have, number not sorted out. And it's
important to realize this. Why? Because in the
previous lesson where we had sorting lists
and we used the sort, notice that another
number actually changed. It was actually sorted, but when we're using
the sorted method, here we are setting
it in a new variable. We're creating a new list. And we're setting it there. Numbers in itself is
not being sorted. We are sorting numbers. And we're setting it, or putting it into the sorted
numbers variable, we're creating a
completely new list. And this is a very
central point and that's the main difference between
the dot sort and the sorted. For example, if I
do the following, if I do numbers sort, what do you think the output is going to be of the last line? When I write click and I run. Look at that, you'll see that
numbers was also sorted. That is the main difference. Sorted actually
creates a new list and leaves the
original one untacked. It assigns it to a new variable, or to be more specific, we assign it to a new variable, and that is the main difference. A new copy is created
with the sorted. I hope you understood, I hope it wasn't
too complicated. Now what I'm going to
do is I'm going to give you a bit of a challenge. Your challenge is going to
be to do the wrong thing. You need to create
a variable and set it as number sorted. Create a variable,
pretty simple, and say that it's
equal to number sort, print out the numbers, print out the actual numbers, and print out the variable
that we created at 0.1 Pass the video right now
and go do the challenge. Okay, How did you get on with that pretty
simple challenge? Nothing too much in here. I'm simply going to say another numbers is
equal to numbers. Sort look, even before
we try to do anything, I'm also going to say
that I want to print out another number even before we try to do anything
or run the program. We immediately have a
small warning in here. Now, sometimes
these warnings can cause errors or cause a problem with the
project or program, but sometimes they don't. In this case, they won't
cause any problem. But there is going to be some weird unexpected
output which is just none. If we hover over this error, it will tell us that
function sort doesn't return anything that is true. And sorting in here, sorting lists, if we
hover over the sort, it sorts the list in ascending
order and returns none. And when we say returns none, it means we don't
return anything. We will delve deeper into functions that return
functions that don't return, what's none, et
cetera, later on. But for now we need to know that sort doesn't
return anything because it actually sorts out the
list it's being used on. So that is the gist of it. We cannot set another
sorted number equal to numbers sort because just
doesn't return anything. It just sorts out the
list and that's it. All right, before leaving, I want to show you
something really cool. We're going to create the
missing underscore letters. And I'll say that
it's equal to sorted. And inside I will type
in the following, the quick brown fox jumps over. Lazy I will print out
the missing letters. I'll also just have
a print in here. If I read Click and I
run, look at what I get. I get the empty spaces being set at the beginning,
pretty typical. Then I'm going to have A, B, C, D, E, F G H I J K L M and O P
Q R S T U V W X Y N Z. So what have you noticed
about the output that we got? Well, what you should
notice is that we have all of the letters
in the alphabet, and the quick brown
fox jumps over. The lazy dog is a sentence that is called a pangram sentence. Which means it contains all
the letters from the alphabet at least once before we move on. I know I've said it before, but one small little thing
in here that we also need to keep in mind is that if we
call our variable just sorted, regardless of this error in
here we have a warning which is called shadows built
in name sorted, whatever. This is something in Python
that you need to know. It's not very friendly
to create variables with names of things or functions
that are built in in Python. Meaning we already have a
function called sorted, so you wouldn't really
want to create a function. Later on we'll learn how
to create functions. You wouldn't want to
create a function, you wouldn't want to
create a variable that is called sorted. It calls shadow built
in name sorted. Just a small lesson for the
future ladies and gentlemen. I hope you enjoy it. I
hope you're having fun. In the next video, we are
going to learn how we can do case sensitive sorting. Because notice in here, the T is not in
its correct place. It should be next
to this right here. So we're going to
learn how we can do this without any
case sensitivity. Thanks so much for watching. I hope you enjoy it, and I'll
see you in a few seconds.
62. 13. Case-Insensitive Sorting: Welcome back my fellow Python programmers to another video. In this one, we are going to be creating case sensitive sorting. Let's go ahead and get started. First thing I'm going to
do is I'm going to make sure that when I sort
out the letters in here, that I have the T in
the proper position. It's very simple to do
that simply in here. On the sorted function,
I will add a, and I'm going to add
a keyword which is key equal str case fold. But keep in mind
that in here, look, we immediately have an
error or a warning, unexpected type SDR SDR. The thing that you need
to know in here is that you need to remove
the parentheses. Why are we removing
the parentheses? Well, because you've
seen that case fold is actually called. It's a function
that gets called. But in here we don't want
to call this function, we just want to use it
as it is, as a keyword. When you remove the parentheses, it means that the
function is not called, which is what we want. Now if we write
Click and we run, you'll see that we have
all of these empty spaces. And on the, there we go, you can see that the capital gets placed before the small. It's not because of its order, I think it's just because
of its order in here. Where's the capital T? Oh, yes, it's because of where
the T is actually placed. The big T is the first, that's why its
order is that way. The next thing that
we're going to do is we are going to try and sort out a list of names. I'm going to create the
list of names in here. First of all, I will add a empty print and I'm going to say that names are equal to, we'll have John, Ned Brand. Come on Robert, and hold. If you don't, you don't. These are the names that
we want to sort out. I'm going to issue
you a challenge to actually sort
these names out, you need to The names, print out the sorted list. Now, inside of the
parentheses on the send in the case key. Pass the video right now
and do the challenge. Okay. Welcome back. So I'm going to get
the names sort. I will print out the
names when I write. Click and I run. There we go. You
can see that now. Aria is in the beginning
then John, Ned, Robert. But the issue in here is that brand and holdor are at the end, even though brand
starts with a B, which means it should be here
behind J and hold as well. For that reason, we use
the key STR in here. I'm going to add key
equals SDR case fold. When I write Click
and I look at that. Now brand and hold are in
their respective position. Using the R case fold is very helpful unless we
obviously these are names. Brand should have an
upper case holder, should have an upper case H, but some situations
will have this problem. Sometimes when you're
working with databases. This could be an issue where
someone hasn't capitalized their name or you didn't create the proper methods
and uses for it. So using the case fold
would be helpful. It's good to know
these kinds of things. So thanks so much for
watching. I hope you enjoyed. And in the next video
we are going to look at creating lists. You might be thinking, wait, we've been creating lists
for a very long time, but we're going to delve
a little bit deeper and see what's happening
under the hook. So I'll see you
in a few seconds.
63. 14. Creating Lists: Welcome back my fellow Python programmers to another video. And in this one we are
going to be learning how we can create lists
in different ways. Let's go ahead and get started. First thing I'll do
is I will create a new Python file and call it
creating underscore lists. Hit Enter and close this down. For now, I will create the first list which
is going to be equal, which is going to be
called e equal to 2468. I will duplicate this and
call this odd and have 1,357.9 and add three spaces. As you can see,
we have two lists of the even and odd numbers. Nothing too special in here. Next I'm going to get numbers, and I'll say that it's
equal to even plus odd. Then I'm going to say
that print numbers. If I write click and I run, I should get the following. As you can see, 24681357. This is the first way that we
can create a list by simply concatenating or adding a plus between two
different lists. Meaning we create a third one. Okay? So that is the first way of creating a
list. Nothing too special. We're just going to go over a few methods of creating lists. The second way is
using the sorted, because remember, when we
use the sorted method, it returns a list as well. Meaning it creates a list. I'm going to call this
the underscore numbers, and I'll say that
it's equal to sorted. And inside we'll send in numbers and I will print
out sorted numbers. Again, if we have our
over the sorted method, it returns a new list
containing all the items. This is another way
of creating lists. When I write click and I run, this is the output that I get, a completely different
and new list. Let's also test it
out on a string and see what happens if
we use it in here. I'm going to say that
I have digits and the digits are equal to
sorted inside of the sorted. I will send in 12 or actually
15 978-632-1324 I mean, these are all nine numbers. If I print out digits, what do you think the output
is going to look like? Think about it for a little
bit before running, okay? So if I write Click and I run, this is the output. You can see that this string
was converted into a list, but it was a list of strings. Meaning that when we create
a list from another object, the content of that list
will be of the same pipe. For example, using the, when we created the sorted
numbers out of the numbers, it was already a
list of integers. The list that was created was
a list of integers as well. But in here we had strings, so it was a list of strings. Okay? Now what we can
also do is the following. I'm going to duplicate
this and comment it out, and instead of sorted, I'm just going to
use list in here. Now, this is not
a method per se. It is a method, but it's also a constructor. We're going to look more
into constructors when we start learning about classes. But for now, all that
you need to know that you can consider this
a normal method. When I write Click
and I look at that, it creates a list
that is not sorted, but it's still a
list of strings. Because what we're
trying to create a list out of our strings. Finally, to look at
and make sure that the list is actually
creating a different list, I'm going to say that more numbers is equal
to a list of numbers, and I will print
out more numbers. Let me also just
have an empty print in here, more numbers. And I will print out the ID of numbers first and
then more numbers. Let's see if they match. If I write Click and
I run, there we go. Look at that, we have two
completely different ID's. As you can see, it means that we have two completely
different lists, which means that list
actually creates a new list. So with all of that
out of the way, this is a very simple lesson. I don't think we need more
explanation than that. I'm going to issue you
a bit of a challenge. And your challenge
is going to be, is this the same number? So you'll need to print out the bullion value of the
following two statements. Number is the same
as more numbers. Numbers is equal
to more numbers. Now, a lot of
students get confused on what is the
same and is equal. This is something
for you to find out, but I'm going to give
you an indication of what it means to print out the bull value
because this is not something that we've
specifically talked about. It means that if we want to
print out the condition, so similar to how
we were checking if let's say some kind of variable is equal to another variable, and we would use it
in the if statement, we want to use it
and put it instead inside of the print
arguments in here. Post the video right now
and go do the challenge. Okay, welcome back in here, I'll keep this empty print
and then I will print out numbers is more numbers. This was the first part of
the challenge that checks if these are actually
the same object or not. When we say numbers
is more numbers, we're checking if they are the same or to be more specific, we are comparing their ID's. I will duplicate
this and check if they are equal two equal signs, if numbers is equal
to more numbers. When I write click and I run, I can see that they are not the same because the
output is false, but they are equal
to each other. They are equal in
terms of content, in terms of items, but they are not the same. They are two completely
different lists. Before we move on, I still have a few sticky
ways of creating lists. The first way is
to use a slice in. Wait, let me actually
comment this out. Duplicate it. And
comment it out, I don't need to print, We'll just work on the more numbers. Keep the last line
in here, in here. I'm going to, let
me move this up, control shift to move up. Instead, I'm going to say that more numbers is
equal to numbers. Open up the two square brackets and simply add a column inside. When I write, click and I run, you'll see that I create
a completely new list. Do you remember what
this is exactly? For some of you, this
is called the slice. And when I don't present with the beginning or the
end point of the slice, it just slices from the
beginning until the end. When you slice, you
actually create a new list. The last method that I want to show you will be the following. If we say more underscore
numbers equal to numbers, copy, and this basically
creates a copy. This is the easiest one, there's nothing too much to it. There we go, you write
the click you run, you create more numbers, and they have completely
different IDs. And you can see that
they are not the same, but they are equal
to each other. So these are the basic
ways of creating lists. It's important to
know these ways. If you ever encounter
some of them, you can immediately
pick on them. So thanks so much for watching. I hope you enjoyed
and I will see you in the next video where
we will learn how we can start replacing
slices from our lists. See you in a few seconds.
64. 15. Replacing a slice: Welcome back my fellow Python programmers to a
brand new video. And in this one we're
going to learn how we can start replacing
slices as always. We're going to create
a new Python file and we're going to call it replacing slices here. I'm going to create
the following list of car underscore parts, and I'm going to say that
it's equal to wheels, lights, or front wing seats. Come on Windows and stereo. There we go. Now what
I will do later on is I'm going to drag the output and put it in here and make
it slightly bigger. As you can see, it obscures
our view of the list. Instead of writing it like this, I'm going to hit
Enter to separate each one on its own
line. There we go. Also something to keep in mind, and I love this about Python, is that you can add
a coma at the end. Most programming languages
will not allow you to do this. It will start telling you like, no, that's it, you
finished the stereo. You cannot add another coma unless you have another object. But Python is very helpful. It considers you as an adult. It thinks that, all right, this guy or this Gal
knows what they're doing. So they can just or not
a complete freedom I, because I've spent
years programming in different languages and not
having the ability to add. So now that I can I always add a. Anyways, that's
beside the point. Now that we have our
list of car parts, I'm going to print
out the car parts. If we write, click and we run, this is what we get. A list of car parts. We can see that it's
a list because of the square brackets that
we have on each side. Obviously it's a list
of strings because of the single quotation
mark that we have. Again, obviously
we could have used the double quotation
marks for any of these. If I write, Click and I run, you can see the output
stays the same. Single quotation marks, it doesn't matter. Use
whatever you want. Just like we were able to access specific characters in a string using the square brackets, we can do the same to access
specific items in a list. What I mean by that
is if I want to print out car parts at
position number three, what do you think the
output is going to be? Think about it when I
write, click and I run. I get seats because
wheels is at position 0,012.3 I get seats. If I try to print out four, think about it again
before boom. There we go. Windows. All right. Now that we have
that out of the way, I will print out cars
again, normally. Now what I want to do
is I want to replace one of my car parts with
a different car part. Meaning that I'm going to
say car part or car parts at position three is
now equal to rents. And I'm going to print
out the car parts. I right click and I
run. Boom, there we go. You can see that now instead
of the seats, I have rims. Excellent. Nothing
too much here. We're simply replacing
a single item. Let's continue on,
and let's look at replacing an entire slice. I'm going to comment
this line out and I'm going to say that car parts at position three until the
end is equal to rims. If I right click and I run, look at what I
get, I get wheels, lights, front wing,
and then I get R I MS. So what is the problem in here? The problem is that, well, first of all, let's
look at the obvious. We don't have any stereo
windows or seats. If you don't remember
how slicing works, I recommend that you go
back to section number two. I think where we learn
all about slices. But basically what we do is we go from three,
from number three, which is seeds, until the end, and we replace it with
whatever the output is. The issue in here is that
string is a sequence, which means that Python
interprets it as, let's say in between
quotation marks. Kind of a list with R IS
being individual items in it. So when you say car parts from three until the end
is equal to rims. Now it just thinks that R is
an item that we need to add, is an item that we need to add. M is an item that we
need to add and is an item that we need to
add four separate items, replace the three items
that we had in here. This is an issue, obviously, this is not something
that we want. We want to just add
or replace seats, windows, and stereo with
single item which is brims. But it's going to be
a challenge for you. And your challenge is going
to be to replace a slice. Replace an entire slice with another car component or part. Use a string, strictly a string. Same way as we did with
the individual items. Print out the resulting list. Now, instead of replacing
it with a string, replace it with an entire item
and then check the result. Now you might be thinking,
wait, wait, wait. What does it mean to
have an entire item replace a specific slice? I'm going to keep this as a
guess for you to think about. You can also go look for
it online or something. It's going to be very fun. Try it out, do your best, and I'll see you in just a bit. Okay, welcome back. So how did you get on with that? I'm going to stick with rims. I'm not going to use
another component in here. What I'm going to do
to make sure that this is interpreted as an item to a list is simply add square
brackets around the rims. Now this is an
item that contains a or an item of type string which contains
rims or is of value rims. If I write click Run, look at the output, now
it's completely different. Instead of having
individual characters being part or individual
characters items, now we have the entire
item which is rims. I hope you enjoyed, I hope you
understood how this works. In the next video, we are
going to learn how we can start deleting
items from a list. Even though we've seen
removing items from a list, we'll see that deleting is a
completely different beast. I'll see you in a few seconds.
65. 16. Deleting Items from a List: Welcome back my fellow Python programmers to another video. And in this video, we are
going to learn how we can start deleting
items from a list. Now you might be thinking, wait, we've already removed
items from a list, and this will be
definitely different. Deleting items is going to have its own intricacies and
we're going to see them. First things first,
we need to create a new Python file
that I'm going to call deleting underscore items, underscore from
underscore lists. I'm going to create the inputs
underscore, underscore in. And the inputs coming
in are going to be 01, 234-567-8910, Wait 11, 12, 131-415-1617, There we go. So these are our
inputs coming in. I take your time, write
all of these out. You didn't think you would
be doing math to day, right? That was bad. But anyways, now what we want
to do is we want to delete some of the
inputs that are coming in. So I'm going to hit delete. So then inputs I'm
going to delete going 0-2 then I'm going to print out
the inputs coming in. Now if I right click
and I run as expected, we should see that the first
three elements get, sorry, the first two items get
deleted because remember when slicing the end
is not included, we delete from zero
until 10.1 are deleted. There we go. You can see
this is our new formed list. So now I'm going to
issue you a challenge. And this challenge is
going to help you to see below the surface
of what's happening. So your challenge is going
to be to delete a slice, So similar to what we did now. So you'll need to
delete everything from position 16 and up. Do this after the
first deletion. Keep the current
deletion that we did, which is 0-2 Keep that. And then afterwards delete everything from 16 and upwards, print out the inputs. What does the result mean? I'm pretty sure you're
going to have some kind of weird result and maybe
an unexpected result. Pass the video right now
and go do the challenge. So how did you get on with that? Well, what I'm going to do is I'm going to select
these two lines, copy them, paste them in here. And then I'm going to delete
everything from 16 and up. Meaning I'm not going to
provide with the end result. If I write the click
and I run, huh? Interesting. I got the
same exact result. Well you probably had the
same thing happen to you. What does this result mean? What does it mean when we
try to delete from number 16 and upwards and it's
not provided to us? Well, let me show you what is happening
below the surface. I try to print out
the following. I'm going to create a forward Now you don't have to do this, I'm just showing you this
to prove to you the point. If you want, you
can write the code. I'm going to do four I
in inputs coming in. I'm going to print out, or actually know what
to make it even better. I'm going to have an enumerate over the inputs coming in and I'll have the in the value. I will print out index value. When I write a click
and I run, there we go, you can see that I
have zero at 01, at one to two until
we get to 17. Pretty obvious, nothing
too strange in here, but if I copy this and
I put it right here, and I'm actually going to create a print
inside of the print, I'll just create this
multiplication symbol and multiply it by 20 so that we can have a
clear difference between where the indexes are. Now if I run, look at that now because we've deleted
the first two elements. Zero, or index zero has a
value of two. Look at that. Index one has a value of 32435
and et cetera, et cetera. When you and I, when we tried to delete from
position 16 and upwards, what happened is Python went
into this inputs coming in. It looked for position 16 and
it did not find anything. That is what you should start thinking
about when you are deleting items from a list. The list actually
shifts and changes, and empty spaces are filled with the values that
are after the indexes. This is very important
to understand. I recommend that you clearly look at the outputs that we got. Again, even though I said you
shouldn't write the code, I do recommend that you
write the code if you want. You can also go through
this with AD Bugger. You can add a debugger here or anywhere you'd
like and slowly go through the program to properly understand what is happening. As you can see, the list shifts, we've removed two items, two indexes were deleted, and all of the list
shifted to the left. That's why when we
try to delete from 16 and upwards,
nothing happened. Let's see a more
intricate example to understand this fully. I'm going to comment
out everything in here. Never delete code, always
comment the code out because you might want
to get back to re, understand what
happened in here. I'm going to create the in underscore valid and I'm
going to say that it's equal to five and I'm going
to have the max valid and I'm going to say
that it's equal to 12. The minimum value that
we can have will be five and the maximum valid value that we can have will be 12. I'm going to create
a loop in here, four index value in
enumerate inputs coming in. I'm going to check if the
value is less than the minimum valid or the value is
greater than the max valid. I'm going to delete the inputs
coming in at the index. Finally, I will print out
the inputs coming in. What is happening here? First of all, we're
creating index and value. We're getting it
from the enumerate. Same thing as we did in here. Same thing as we did
in video number nine, if I'm not mistaken, which was called the
enumerate function. You can go back to that video
and rewatch it in here. We get the index,
we get the value, and we value that. We're extracting the value at
every single point in here. If the value that we're
getting is less than the minimum valid or the value is greater
than the max valid, I'm going to delete the inputs
coming in at the index. So let's say we start at zero, We have index zero. Value zero we check is value less than the
minimum valid it is. Then I'm going to delete the inputs coming
in at index zero, which means I will delete zero. Then let's say we are at index
15 right here. Index 15. Value 15 is the value
less than the max valid? No, it's not because 15 is not less than five or value is
greater than the max valid. Yes, 15 is greater than 12. So we will delete the inputs coming in at the
index number 15. So we delete this number. So we should have, in theory, the inputs coming in
from five until 12. If we write click and re run, this is the output that we get. We have 130 and
2.4 were removed. I mean that's the start. I guess we have 1356, all the numbers are normal. Then we have 12, 14, 16, which means 1,315.17
were removed. Okay, what is happening here? Now use the information
that you got from this old code and apply it to the code
that we have in here. And think about what happened. If you're thinking that the list is shifting as we're
deleting items, you are correct what
is happening here. Now I recommend that
you try on your own, adding a debugger here and going through the list to properly understand
what's happening. After you've tried
understanding and if you can't figure it out,
amazing, congratulations. If you let me take you
through the explanation. What is happening here? I need your full concentration. This is not an easy concept
to wrap your head around, but once you do, you are golden. We have the inputs coming in, 0123 until 17, and we
also have the indexes. Everything in red below these values is going
to be the indexes. We have 0123 until six until 17. We are going to delete
if it's less than five. Let's go ahead and
create the four loop. You can see in here that
we have at position zero, at the index on the loop zero, we have the following list. What we do is at zero, we check that we have
value zero, correct? So we're going to delete zero. What happens to the list
after we delete zero? This is what happens.
Now the list is 123456. No one is at index 02, is at index 13, is at index two, et
cetera, et cetera. The indexes don't accommodate
the actual values. The indexes will always start at zero and go and
increase one by one. But what does the four loop do? The four loop doesn't care what you're doing
inside of the four loop. It will just add a plus one. And now we're working on index one and what's at index one? At index one we have two. We delete two, we skip the
one. What happens to the list? Now we have 13.4 The loop
doesn't care what we did, the loop increases by one. Now we're working on index two. What do we have on index two? We have four. We delete four, and now this is what
we are left with. We are left with 1356
and this is what we got. And same thing happens
on the other side. Sorry, I might have
been a little bit fast. Take this in, go through this again step by step and
understand what's happening. Once you do, let's move
on to the other side. If you did figure out what happened on the left hand side, take the time to,
again understand what happened on the right hand side, because once we get
to index number ten, we have 13 at index
number 1013 is greater than 12, we delete 13. What happens? All of the list shifts a
little bit downwards. And by the way, the index
in here ends at 14. Why it should be obvious? Because we've already
removed three elements. 17 minus three equals 14, that's why 17 is at index 14. Remember we removed
three elements in here. Again we remove 13. Now we have 14 at
position 1015, at 11. Again, the four
loop doesn't care. Plus one, we get
11. What happens? We delete 15. This is what our list now looks
like, 14, 16, 17. The four loop doesn't
care. We go to 12. What do we have at
12:17 We delete 17, and this is the list
that we are left off. That is where we got our weird output Of
the inputs coming in, we have 1,356,789.11 12, 14, 16, just like we got
with our output in here. Some of you will be like, oh, this makes so much sense. Others might be looking
at this and being, wow, what the hell
just happened? Some of you might be okay. Maybe I need a little bit
more time to understand this. All of these are valid. This is not an easy concept
to wrap your head around, but it's important to
understand what is happening. In the next video, we are
going to learn how we can safely remove
items from a list. And then we'll even learn a
much better way of removing items of a roll when they're not even in a proper sequence. Because look, right
now we have 0123. We know what's happening. Later on we will learn what happens when it's
much harder than this. Thanks so much for watching. I hope you understood. I do recommend that you go back. Watch this again.
Understand properly how the slides are working. I'm going to provide you with the slides so you
will be able to go through the animations
on your own and fully understand
what is happening. Thank you so much. I'll
see you in the next video.
66. 17. Safely removing values from a list: Welcome back to my favorite
Python developers. In this video, we are
going to learn how we can safely remove
items from a list. As you saw, removing
items from my list is a very dangerous occupation. So we need to find
a way to remove these items in a more
efficient and well overall, just remove them properly
because we don't want to have all of the
issues that we've had before. So let's go ahead
and get started. First thing I'm going
to do is I'm going to remove the code in here. Again, not remove, we
will comment things out. We want to have the progression
of what's happening. I even recommend that you
start adding comments and say, this method we used, et cetera, et cetera, add some description
for you to understand. We're going to keep the minimum
valid and the max valid. We are going to keep using
the same inputs coming in. But now we're going
to start doing things a little bit differently
because first of all, we're going to process the
low values in the list. Let me add a space. We're going to start processing
the low values. I'm going to say
stop equal zero. This is a variable,
I'm initializing it, I'm going to say
four index value in enumerate over the
inputs coming in. I'm going to check if the value is greater than or equal
to the minimum valid. I'm going to set the
stop to be equal to the index and I'm going
to break out interesting. Then I'm going to
print out the stop. This will be purely
for debugging. For debugging, then I'm going to delete inputs coming in from the beginning
until the stop. And I will print out
the inputs coming in. So I'm going to run this, but before I do, I recommend that you
go through the code. It's not very complicated. It's definitely less complicated than what we've done before. Try to understand
what's happening. Obviously I'm going to
explain to you what happened. And then we will continue. I'm going to write Click, and I'm going to run
and look at our output. How nice is that we've deleted all the items from
zero until five. What is happening in here? First of all, we initialize
the stop at zero. Then we created an enumerate, we got the index and the value. And we're checking at each incrementation of the four loop, we're checking if the
value is greater than or equal to the minimum
valid, which is five. We're checking is it greater
than or equal to five? No it's not. Then
we will postpone, we will not set the stop and we will go back in the four loop. We start at zero, is greater
than the minimum valid. No, it's not. The move
to one, is it greater? No, we move to two, to three, to four and then we get to five. So once we got to
five, we looked at it, is the value was five, is five greater than or
equal to the minimum valid? Yes, it was. It was equal to. We entered into the code, we set the stop to be
equal to the index. Now, stop is equal to what? Yes exactly to five. And then we broke out
of our fore loop. We printed out the stop. We deleted everything from
the beginning until the stop. And keep in mind the
stop is not included. This was inputs coming in from the beginning or from
zero until five. But five is not included. It's up to but not in, and we printed out the output. I hope you're not too confused. This is not a very complicated, it's definitely less complicated than what we've done before. If you're having a
hard time again, go through it again,
use the debugger. As always, it's very helpful. The important thing here
is that we don't change or delete data of the
list inside of a loop. Only when we finish the loop do we start changing the data. Okay, it's very important to not change the data
inside of the loop. After we've done
this, it's time to handle the high numbers. I'm going to add
two spaces in here. I'm going to create another
comment which is process the high values in the list. And I wrote high incorrectly. Very nice. I'm going to set the
start equal to zero. This one will be slightly
more complicated. I'm going to say
four index range. The range is going
to be the length of the inputs coming in minus one, minus one, minus one. And you're like, what
is happening here? I'm going to check if
the inputs coming in at the index is less than or
equal to the max valid. And it's not allowing
because it's less than or equal to, yep, sorry, the max valid. I'm going to set the
start to be equal to the index and
I will break out. Once I do, I will print out
the start for debugging, delete inputs coming in, start until the end, and print out the
inputs coming in. If I now right click and I run, this is the output that I get. As you can see, the
index that start or that I start at is going
to be equal to seven. And we delete everything
from the start, which is seven until the end. So how did we come up with this? If we look, remember
that the seven represents the index in
this list that we have. The list where we've already
deleted if you items. So we have five at
zero, so 012345, 67a7, we start deleting and
we delete everything upwards. Now you might be
already thinking, wait 12 is the max valid. Of course, this is going to be an issue for you
to solve later on, but before we can solve it, we need to understand what
is happening in here. I'm pretty confident
that you know what's happening in
these three lines. There you go. If you were
confused now you know. But we need to understand what's happening in these four lines. First of all, we know
the break. That's good. We know the start equals
index, that's good. Now, what's happening
in these two lines? Inputs coming in at the index
is less than the max value. We're just checking the inputs
coming in at that index. Remember, the index
is a variable. It's changing inputs
coming in at the index. If it's less than or
equal to the max valid, we'll set the start equal
to the index and break out The more important
and pressing thing that I think you might not be very familiar with
is this range right here. This range. What is
happening in this range? I'll just add a small
comment in here, and I'll say we're
using minus one because the last
value isn't included. Actually, you know
what? That's too long. I'm going to copy this. Cut this in here. What's happening? First of all, we need to understand
how the range works. Just like we have the
slices and the ranges, you can see right here, we have the starting point. The starting point is
going to be the length of the inputs coming in minus one. Why are we doing this? Because we want to start
at the last element. In this case it's 17, or to be more precise,
in this case it's 17. We want to start at the end. How do we start at the end? First of all, we get the length of our entire inputs coming in. The length of the inputs
coming in is going to be more or one more, than the indexes that we have. Because remember we
start at 05, is at zero, the length is going to be
0123, 4567, 8910, 1112. There are 13 elements in here, It would have been
easier for me to just say 17 minus 1234517, minus five is 12. We have 12 elements, the length is 12, but the index is
going to end at 11. So we need to do length
of the inputs minus one. And then the value
that we want to get to is going to be minus one, because we want to go until the first index because we
don't know where this ends. And finally we have the step
which is going backwards. To better understand this, what I'm going to
do is I'm going to set value underscore. We underscore our, underscore, please our at a. This is really unnecessary. I'm just going to
say value equals to the inputs coming
in at the index, I'll just print out the value. This is simply for debugging purposes. You don't
need to do this. If you want, I will red
click, I will debug. Actually step into value, print out the value. What do we get on the console? Let me drag this and put
it in here, see better. All right, there we go. The first value was 17. We started at the end at 17, then we step into, again, we go back,
we do minus one. Remember we're going backwards. Now we check what is the value. It's 161-514-1312 And now once it's 12, we set the start to be
equal to the index, because remember what
index are we at? We are at seven when we
step into again, boom, we want to break out and we will print out the
start, which is seven, and we will delete
everything going from the start until the end. There we go again. I recommend you go through
this one more time, a few more times to
fully understand it and you'll even have the chance
to understand it even more. I will comment these
two lines out. These were purely for debugging because you have a challenge. Your challenge is going to
be to not remove the start. Remember, we don't
want to remove the 12, we want to keep the 12. Find a way for us not to remove the first
item at the start. I will give you a hint. If you don't want the hint, go to the code and
do the challenge. We need to add a plus one. We can do that in two places, find one of them. There is one place, or there are two places where we
can add the plus one. We need to find one of them past the video right now and
go do the challenge. Okay, welcome back. So how did you get on with that? There are two places
where we can do this. Let me just close this one down. We can either add a
plus one right here. Now when I write click
Run, look at that. We start at 12, because remember we just add a plus
one to the start. But I find it much better
to put it in here. We increase the index by one. There's no real inherent
difference between these two. Both of them are the same. But if you had to choose, if you had to choose, it's better to add it right
here as a rule of thumb. It's not very friendly
or user friendly, let's call it just not a
very good programming habit of actually changing the start. It's better to change the
way the start is used, if that makes sense to
add the plus one here. Not change the value but
how the value is used. Again, if you ever see anybody doing the plus one
on the actual index, it is 100% correct. I'm just saying if
you just wanted a small thing to tip the scales, this is
what it would be. Ladies and gentlemen,
these two lessons were very hard to understand. I know, but they
are very crucial. I hope you understood. In the next video, we are
going to look at removing items from a list
going backwards. I'll see you in the next video.
67. 18. Removing Items from a List Backwards: Welcome back my favorite
Python developers. In this video we are going to understand why iterating
backwards over a list. To delete items from it
is better long headline. But you'll get the point
when we talk about it. When you iterate over a list forwards and delete
items from it, the index of the
remaining items shift down each time you
delete said item. Just like we saw in the
previous examples we had, whenever you delete an
item in the beginning, all of the list
shifts downwards. This can cause you to skip over some items or process the
same item more than once. In this situation,
we're deleting an item, but what if we were doing something like maybe
getting passwords, maybe changing the
location of passwords? This can cause a lot of
trouble, a lot of confusion, and can sometimes destroy entire companies and databases.
Maybe not that much. But you get the point, it's a dangerous thing to do. Iterating backwards over a list. Delete items avoids this issue. Because you are deleting items from the end
of the list first, which means you don't
affect the indexes of the remaining items just like
we had the zero through 17. If you delete 1701234 are
not going to get affected. You've just deleted
from the end, the numbers in the middle and in the beginning are
not affected at all. Their indexes have not changed. That's why deleting from
the end is so much better. Finally, overall,
iterating backwards over a list to delete
items is considered a safer approach because it helps you avoid
unexpected box in your code whenever
you have something to do with changing
the values of a list. Of course, to certain
extent in this situation, it's when you're deleting. Obviously when you're
changing values, it's also better to
iterate backwards. Let's see one final example, just to hone down all
of this information you've just seen the background into what's happening
behind the scenes. I'll call it, maybe
I should create a video of how all of this
happens behind the scenes. Tell me if you're
interested about that. Let's go ahead and create a new Python file
that I'm going to call backwards and maybe just add underscore
between go backwards, hit Enter, and I'm
going to have a set of data that will be 104-10-1410 5, 308-103-5107 100 3 061-061-2108 These are our values. And again, I didn't
want to write them on a single long line
of code so that we can always see
what is happening. And the reason why I chose this seemingly random set of numbers is because
up until now, the numbers that we were
working on were in order. I don't want them
to be in an order. I want to show you how we can do this when they're not
properly ordered. I'm going to have the
minimum valid equal to 100. I'm going to have the max
underscore valid equal to 200. And I'm going to check four index in range length
of the data minus one. This is to start at the last element at one
oh eight minus one. That is, so that we get
to the first element minus one is the step to
actually be going backwards. Then I'll check if the data
at the index is less than the minimum valid or the data at the index is
greater than the max valid, I will print out the index. I will delete the
data at the index. I will print out the data. Keep in mind, I'm printing out the data inside of the
for loop so that I can see things changing
at every step of the way. One more thing, before we
actually run this right here, when we were doing the following right here
on this if statement. As you can see, we
said value minium, valid and value or value
greater than the max valid. And I used the
parentheses in here, while in the go backwards
I did not use parentheses. The reason why I
used parentheses here is just for the
sake of explanation. They were not needed. I just wanted you to
understand that these are two completely different
set of bullions. One does not depend
on the other. They are both independent, but they are used to set the proper definition
on this statement. It's less than or if
it's greater than, when it comes to comparing the data to the minimum
and the maximum. With that out of the way, let me right click and run. And there we go. So
this is what happens. We start from the end, correct. So we check the
minimum valid is 100, the maximum valid is 200. So we shouldn't have
any values that are less than 100 or
greater than 201. Oh eight is good. One oh two is good. What is the first value
that should be removed? 36. So right here, 123. All right. There we go. So you can see 36 was removed, and if we go through this, so we go 1-234-567-8910, sorry, 012-345-6789 I apologize. There we go. You can
see that we get 36. The next value would be five. So on this line, we shouldn't see five. We do see a five, but
it's the other five. Keep that in mind, I should
probably change the example. But yes, in this case, we shouldn't see
one of the five. So we have 0123456, and there we go at index
six, we've removed five. The next number is 38. It was removed five was removed
and the rest are valid. So I've taken you through
the process of safely deleting and removing items from a list. I hope you enjoyed. I hope you understood why iterating over a list
going backwards and removing items is so much
better than going forwards. Thanks so much for watching. I hope you enjoyed. This
will be the last video. I know it was a hard
path to go through, but you got to the end. Congratulations.
And the next video, we're going to learn
about nested lists. It means when we have
lists inside of lists. So I will see you
in a few seconds.
68. 19. Nested Lists: Welcome back my fellow
Python developers. In this video, we
are going to be learning about nested loops. Let's go ahead and get started. First thing as always, we will want to create
a new Python file. I'm going to go into file new, create a new Python
file and call it the nested underscore
lists in here. First thing I'm going to do
is number one is equal to, I'm going to have 23, 416-098-2201 We'll
just start a new one. Number number two,
we're going to have 20, 131,575.94 These are two
distinct lists of integer. Now I'm going to create a third list which is going
to be called numbers. And I'm going to say
that numbers is equal to the following list, number one. Come on, number two and I'm going to print
out the numbers. Now again, I want you to take a deep breath before you run
this program and tell me, tell me, just tell
yourself what you expect the output is going
to be in here. If you notice that we have
number one and number two as individual items inside
of the list numbers, which means we should have two items inside of
numbers which are lists. This is a list of lists, just like we have items inside of this list which are integers, which makes this a
list of integers. This is a list that has
its items as other lists, which means this is
a list of lists. If you figure that out, tell me if you can
figure this one out. What if I do the following and I say number underscore list in numbers and I print
out numbers list? What do you think the
output is going to be? Well, if you guessed individual
numbers, you're wrong. If you guessed that it will be just two separate lists,
then you are correct. Because remember, when
we loop over a list, we get each individual item. We put it in the numbers list variable or whatever
variable we've created. When we print, we simply
print out that item in here. This list is consisting
of two items, and these two items
are the following. And you can double check that
if you do the following, if I wanted to print out
the length of my numbers, what would the output be? If you guess two, you
are correct because we only have two items
inside of numbers. Numbers is made up of two list. Oh yes. It is made up of two
lists and it's made up of two items. All right. If we wanted to get indiumbers, individual items from inside, what would we need
to do in here? I'm going to, if you want, you can take a second
to try and guess. Okay. So I'm going to create a four individual underscore
numbers in numbers list. And I will print out individual numbers if you
were able to guess this, congratulations you are on the way of crushing
Python development. If not, no worries, start paying more attention. I'm going to right
click and I'm going to run and look at the
output that we get. So we get individual
numbers out of our lists. There we go. Now with that information done, if you're still not
sure how this works, again I recommend that you
add a breakpoint in here. And you slowly debug
this four loop, which has a four
loop inside of it, so that you can
see how each item is being extracted from there. With that, out of the
way I'm going to add, I think I'm, I will
comment all of these out. Now let's comment
everything out. Okay, And I'm going to
create a new list of lists. So I'm going to create a
list underscore core lists, and I'm going to say that
it's equal to the following. I'll have 268, and here I'm going to 10, 181-316-1819 Again, I'm going to have 2618, 8065 0450 2808 and again 2065. 0280 4909, 1115, 1877. 1516, 1960 2203. And I think I should speed up this part because it's useless. Mr. Editor please
speed up the process. 63 18 skin 8450, 2181, 8511, 8808, 74.51 All right. There we go. We're
done. And as always, I'd like to add the
come up because I can. This is a list of lists. As you can see, we
have individual lists all being added into
one enormous list. Let's go ahead and print out the list on the lists that
don't have 18 in them. I'm going to create
this for loop for list, list of lists. I'm going to say if the
18 not in numb list, why doesn't it like numb list? Because in word to, to numb list we'll just start and underscore between list. If 18 not in numb list, I will print out list. If I write click and I
run, this is what I get. We only have two lists that
don't contain 18 in them. As you can see, all other
ones contain 18 somewhere. Now let's also print
out the lists with 18 and how many
times they occurred. We are checking if 18 we are
going to print out the list. Else we are going to print out, I'm going to have my
replacement field in here and I'm going to
print out the numb list, has 18 appearing
replacement field, numb list count 18. We've already seen the dot count and how it works and
we've already seen the use of this kind
of replacement field with an F on the other
side when I write, click and run, there we go. This is our output. We have this list that does
not have any 18 in it. We have this list that
has 18 appearing twice. 18, 18. This list that has 18
appearing on this one, having 18 appear on
this one having no 18, and the last one having
18 appear entire times. I hope you understood. If you're still not sure
how this code works, again, I recommend
you go through it. You can use the debug, you can find everything
that's happening. Because once you do, you have a challenge
of removing 18. You need to create a
new loop where you loop over the list of lists inside. You need to create a loop going backwards over the range
of lists you are in. If the item on the list is 18, delete it from the list and print out the list
of lists at the end. Not an easy challenge. Hard, You need to combine a lot of things that we've
learned before, but I believe in you pause the video right now and
go to the challenge. Okay, welcome back in here. First thing I'm going to
do is I'm going to create a for loop with the numb
list in list of lists. Actually I'm going to comment this in here or
actually you know what, I'll also hold control and shift and move this up,
it's at the top. I'm going to say four index in range and the range
is going to be the length of the numb list. Minus one, because I want
to start at the last one or at the last item. And remember what
we're doing in here. We're going forward
using our lists. So we're looking at each individual list one
by one because it doesn't matter if we start at the last list or
at the first list. The items that we're deleting
are not the actual lists. They are items inside the
lists that are inside list. Get what I mean. For example, it doesn't matter
if we start with the last list or
with the first list, but when we get
to the last list, it's important that we
start at the end of it. That is why we have
a normal four loop. And then on the
second four loop, we start at the end. We want to get to minus one. We want to go until
the first element and our index is minus one. In here, I'm going
to say if num list at index is equal to 18, then I'm going to delete
the numb list at the index. Print out numb list. I'm also going to
print out numb list. Not on the if, but
in this situation, every single time I
finish with a list, I'm going to print it out. Mind the indentation when
I write click and I run, this is what I get. First of all, we have 268. It stays the same because
obviously there is no 18 there. Next thing I'm going to do is on this following
list, I had 218. Now I have zero. In this list I had
118. Now I have zero. And this one I had 118. Now I have 000 in here. We had 418, if you
remember correctly, and now we have none of them. I hope you understood
how this works. I hope you are beginning to feel how important it is to
go backwards in a list. We did not disturb any of the other elements because
we were going backwards. Before we finish off,
I'm just going to show you another
way of doing this. I'm actually going to
comment this out in here. I'm going to say four number or four list of lists for number. Numb list. If number
is different than 18, I will print out the number and we'll just have a
print in here and I write Click and I look at that, I'm printing out all of
the numbers and I've removed or I did not print out the numbers that
are equal to 18. I mean, it's what you can do is you can start appending
your lists in this case, but this is just another cheeky
way of not having the 18. It's not a different way of
handling this sort of thing, but you can actually then add these numbers into
a list if you want. Append different lists.
I hope you enjoyed. I hope you are not overwhelmed with all
of the information. The next video will be
the last video on lists. You will become a
master of all of these. We will learn how to use the
join and the split methods, and afterwards, we
will get into topples. I hope you enjoyed. See
you in the next video.
69. 20. Join and Split method: Welcome back my fellow
Python programmers. In this video, we are
going to be learning about the join and the split method. Let's go ahead and get started. First of all, I'm
going to go file new, create a new Python
file as always, and call it underscore. Underscore method. I'm going to start by
creating my car parts. I'm going to say that car parts is equal to the following. First of all, we have
the hood, the wheels, the mirrors, then we have seats, then we have motor, then we have stereo. And at the end, oh my God. Here, first thing
I'm going to do is create a variable
called the separator. Separator is equal
to just a separator, and I'm going to add
a space on each side. Next, I'm going to say that
the output is equal to the separator join
and I'm going to join over the car
parts and I'm going to print out the car parts. Or print out,
sorry, I apologize, I meant print out the output. If you hover over the join, we'll see that it cactinates
any number of strings. And the strings whose
method is called is inserted in between
each given string. The result is returned
in a new string, the join we provided with the. And it should return
a concatenation of all of the items that are
inside with the separators. In between when I
write click and I run, this is the output that I get. We get the hood,
wheels, mirrors, seats, motor and stereo with these
slashes in between them. We specify the string that we want as a separator
inside of the join, and then we use the join
to create all of this. Nothing too weird in here. Nothing too complicated. I think it's a
very minor method. Let's move on to the split. I'm going to go into file, a new Python file and call
this score split core method. Boom, In here I'm going
to have a message. The message is going to be, learn Python is easier
than you think, but apparently not
grammar learning Python is easier than you
think I'm going to say. Words are equal
to message split, then I will print out the words. If you think I'm
moving too fast, Positive video way to write all the code and
then look at it again, I'm not doing anything
special in here. Let's hover over the split
and see what it's all about. If we hover over the split, it says that it returns
a list. Uh huh. Before the joint would
return a string. Now we're returning a list
of the words in the string using sepp as the meaning
right here, this variable. And we're going to learn in the upcoming section what these arguments are
and how to use them, which is the separator as the delimter can see right here, the limiter according to which
we split the string, none. The default value means split according to any white
space that you see. And discard empty
strings from the result. This is the documentation. If you want to go even further
into the documentation, you can click on this link. It will take you to Python's documentation, which is very, very complicated but
definitely very useful. Another resource that you
can use is W, three schools. In here, I could type
in the following. Let's say I want
the split method in Python, three schools. The split function, you open
three schools and boom, look at that, you find all of the resources that you need. I've obviously
covered this before, but this is a great
example just to remind you of what
you can go through, because obviously
I cannot teach you every single small
detail in Python. It's impossible. The course
would be thousands of hours, so some gaps you need
to fill on your own, like the split for example. Nothing too much. The split is very simple. If we go back into
our code in here, when I write, click and I run, you'll see that now I
have a list of strings, which was each
individual item in here separated or split
over the empty space. So every single word
is a item on its own. The next thing I'm going
to do is I'm going to have the message equal
to the following. I'm going to have apple, banana. By the way, this is an
example that you might see on W three schools,
cherry and orange. I will print out the message, split over the hashtag. What do you expect
is going to happen? Pause the video, think
about it before you run. There we go. We can
see that we've split our message over the hashtag. Now, if you would have
added a space in here, for example, what
would the output be? Come on, think about
it. There you go. You'll see that
these spaces will be added to our item
strings as well, or to our string items as well. I think it's pretty
self explanatory. There's nothing
too much in here. I'm going to continue on. Let's now work with a
join and a list together. First thing I will do is I'll
simply add a print in here. And then I'm going to
have a number list. And I'm going to say
that the number list is equal to the
following in here. I think is a great
moment for a speed up. Okay, welcome back. After you've typed in this list. As you can see, these
are individual items. I've just separated
them with extra lines. The difference between
this and this is not, you could have just
written it like this, but I wanted to write
them in this situation. And you'll understand
why in just a bit. In here I'm going to
do the following. I'm going to create
values equal to. I'll have join the numbers list. The number list, I'm going
to print out the values. What do you think the
output is going to be? While you're thinking
of the output, I'm going to do the following. I'm going to have sttocosco values equal to values split. Then I'm going to print
out list of values who think about what's
going to happen based on what we learned
about the join method. By the way, what we said
about the method in here, or by searching for the split, you can do the same for
the join, by the way. So keep that in mind. Think about what
would the output look like if I right click and I run? This is what I get.
I get one space, seven space, 843 space, et cetera, et cetera. This is when I used the join. I joined over this
space in here, similar to what we
did right here. We use the separator
which is just, I think it's called the
pipeline character, if I'm not mistaken. We use a space,
we use the space, pipeline space, and then we use the separator that join
the car parts in here. We did the same, We have one, then the space which
is right here. Then we had 007
and then a space, and then 843 space in
between each character. We just had a space in
between each character. That's why we have
a space in here. And then we got this output, and then we split this output
over its empty spaces, so we created a list of numbers. Now what would happen if
I had a space in here? Think about it and tell me. I will write the
click, I will run, and this is the output. So you can see we get one, then we have a space, and then we have a space, and then we have a space. What is happening in here? Well, first of all, in between each character, we also have a space. But when we get to
an actual space, we have to add a space on the left hand side and
on the right hand side. That's why you see
these big gaps in here. It's very important that you understand what is happening. I will take this back
before we move on. Before we go into the topples, I'm going to issue you
a bit of a challenge. You'll need to
convert to integers. I want you to
convert the list of values we have into integers. Should I give you a small hint? If you need the
hint, wait for it. If you don't, and you think
you can do this on your own, what we basically want is to
convert this into a list. This needs to be
converted into a list of integers with these numbers
instead of being strings, because notice they are strings. They need to be integers. If you need the hint, I'm going
to give it to you in 321. Go through the list and
at each index convert the value into an integer.
That's basically it. Then put back every
single value into a list. This is how you could do it. I know it's on the nose, but pass the video right now
and go do each challenge. Okay, welcome back in here. I'm going to do the following. I'm going to say that four in the range is going to be
the length of the values, or actually, sorry, I apologize. The list of values, I'm going to go over
all of the list of values at each index. The list of values at each
index is equal to integer. List of values at the index. There we go. And
that's basically it. There's nothing more than that. Finally, we will print
out the list of values. And what is it nagging me about? Index. If we hover over it, unexpected, let's run it
and see what happens. Okay, it works. But
what is the matter with this unexpected type or types? It's waiting for an integer and we've provided
you with an integer. So what is the matter in here? It's not complaining
in here, it's coming. All chalk it off to a
hiccup in the system. As you can see, we have
this properly working now. You might have done
it in another way. We could have said value
underscore list of integers, j is equal to an empty list. I'm going to say four
values in list of values. I'm going to take the
value list in integers, pend with the integer, all values, print out the
value, list integers. So instead of converting
the actual list of values, we will create a separate list and put all of the
integers inside. Now I right click and I run. There we go. You can see, let me get the same output,
ladies and gentlemen. I hope you enjoyed this video. I hope you enjoyed Lists. It was a long, arduous journey, but you got to the end
of it and now you have a of more knowledge. When it comes to list, you
basically have everything, all the knowledge
regarding lists, you probably now know more
than 99.9% I don't think so. No, no, I do think that you know more than 99% of the
world's population enlists. Congratulations, It's an
amazing accomplishment. And the next video, we
will move on to topples. And I'll see you then. Take care.
70. 21. Tuples: Welcome back my fellow
Python developers. In this video, we are going to start learning about topples. What the heck are topples? They are used to store multiple items in
a single variable. Not too many changes
from our original lists. It's a collection which is
ordered and unchangeable. Mm hmm. Unchangeable, Those
are the two key words. First of all, ordered, meaning that they have indexes, they are in an order
and unchangeable. Unlike lists where we can change the items in
couples we can't. Which means that
they are mutable. Correct. So couples are
written with round brackets. Couple items are indexed
starting with zero. You can create a tuple
with only one item inside. Tuple is one of
the four built in data types and Python used
to store collection of data. The others are lists,
sets, and dictionaries. We've already looked
extensively at lists. We are going to see sets and dictionaries in
upcoming sections, but that is the basics of it. Let's go ahead and start using
tuples back in our code. In here, I'm going to
create a new Python file, and I'm going to call it
tuples underscore Intro here. I'm going to say
t equal to a, a. And I will print out, if I right click and I run,
this is what I get. Look at that. I have a, B, C, and I have round
brackets around them, which indicates to me
that this is Apple. But this is not the most
correct way of creating Apple. And by the way, we
need an extra line, we need to add parentheses around these to properly
indicate that we have Apple. And I'll tell you why Python allows us to do something
like this where we don't have the two
parentheses in here. Again, if I right click, we get the same output. Simply add parentheses
around them and you will get the output as a couple. That means whenever
you want to pass a literal of a couple
into any function, it must always be
in parentheses. We'll see what I mean by
that sentence later on, what it means to actually send
a couple into a function. Let's go ahead and continue on, and let's create some fruits. So I'm going to have
fruits and I'm going to say that they are equal to
the following. Oh my God. We're going to have, oh my God, why can't I write
apple, banana, cherry? Something went wrong
with my fingers. What else do we
have? Another apple? Yeah, sure. Why not? Apple, ma, and another
cherry. Why the hell not? Go ahead. Very
creative fruit names. And I will print out the
fruits and I will print out fruits at position two, what do you think the
output is going to be? There we go, pretty simple. We have a couple of our fruits, and if we print out fruits at position number
two, we get cherry. Because just like lists, we start at 01.2 we get cherry. Also, tuples are immutables,
as I've told you. Meaning that they cannot change. And I'm now remembering,
maybe I said mutable, I hope I did not. But in any case, in here, we know that couples
are unchangeable, which means that
they are immutable. Which means if I try to do the following cheeky
thing in here, fruits, and then I say that
fruits at position zero is equal to pineapple. Look at that. Even
before doing anything, even before I tried to run this, it immediately gives
me a huge highlight. And if I hover over
this highlight, it tells me that couples don't
support item assignment, meaning you cannot
assign anything to it if I try to now
print out fruits. When I write click
and look at that, I get an error because
it's a type error. Topple object does not
support item assignment, you cannot do these. I should comment this out. I'll also comment this one out because I don't
really need it. We can also convert
topples into lists. For example, I can say fruits. Two is equal to a
list of my fruits. Let's print out fruit. Click and run. And look at what we get in here. What did we get? I was so
confused, like what the hell? We converted it into a list and it doesn't seem like a list, but we were printing
out the fruits, fruits to when I write click
and at that I get fruits, fruits two is a list. Now we can also convert
this back into a topple, so I can say that fruits three now is equal
to fruits two. Excuse me, fruits two. Apparently, the heck cup
is not just in my fingers, it's also in my
brain or my eyes. I will print out fruits three, right click and run
and look at that, we've converted it
back into a topple. So that's the basics of topple. They are immutable, they
have round brackets. And we'll see more uses to our topples in the next videos. But before we go, you need to deal the impossible
in your challenge. You need to change
the unchangeable. You'll need to destroy
the undestroyable. Find a way to change an item inside of the immutable topple
that we've created. That is an impossible
challenge, I know, but there is a way
when there's a will, Should I give you a hint, or would you like to
do it on your own? 321, Convert the
topple into a list, change an item in that list, and then convert it
back into a couple. Obviously, this is
something that we will never need to
use in real life, but you never know
when you might need to change a
value in a couple. Pass the video right now
and go do the challenge. Okay, welcome back in here, what we want to do
is the following. When we change
fruits into a list, I will also say in here, print out changing, changing apple to pine apple. In here I will say
fruits, fruits two. At position zero is
equal to pineapple. And then I converted
back into a topple. And now we should have the
following, boom, there we go. So we've actually changed
our congratulations. Obviously, this is
a very cheeky way. We would never want
to do such a thing. But it is, everything
is possible with Python if you
really believe so. An example of the use
of couple would be, let's say, date related events. You wouldn't want
to have a list that indicates when the event
is happening because somebody might come and
change these dates and ruin your whole event medicine that somebody should take should
be definitely a couple. What else may be money in a
bank account for example? Oh no, The money and back and
cap actually would change. What wouldn't change would be the transactions that you made. So you wouldn't want to change the amount that you made
in a certain transaction. So after a few years, you just have a
list and you go in, you remove things,
you continue on. These are a few examples I hope you enjoyed. I
hope you understood. In the next video, we are
going to be looking at unpacking topples and what
it even means to unpack. Thanks so much for watching. See you in the next video.
71. 22. Unpacking a Tuple: Welcome back my favorite
Python developers. In this video, we are
going to be learning all about unpacking topples. Let's delve into it first
things first, File new. And we should find the Python
file and call it unpacking. Let's just call it
unpacking topples so we know what the heck
we're even talking about. I'm going to have x, y, and z, and they are equal to 12.3
If I try to print out x, y, and Z, right click and
run, and there we go, we get 12.3 Basically
what happened in here is called unpacking
because as you can see, we have 123 that are a topple. It's the same thing that we
did in here when we had ADC, just without the
parentheses around them. Xyz are three different
variables that were each assigned a
value from that topple, meaning that we unpacked
the topple, okay? That's basically it. We simply unpacked the topple. If you want to make
sure that this was indeed a topple
that was unpacked, you can do the following,
and the output is the same. We can also unpack any
sequence that we would like. For example the following. If we have a data underscore
list and it's equal to 123, we could say that we have P Q R equal to this data
list and we can print out P Q and right click and run. There we go. The only
problem with unpacking a mutable object is that
if any changes happened, it could really
damage our unpacking. If any changes happen to this data list and
we try to unpack it later on into let's say
the following variables, we could see that
we do get an error. Or let's say for example, we try to unpack a
data list that has, for example, like four elements in it, right click and one. You can see that
we get an error. Or if we append the
data list at any point. Let's now look at a more
practical use of unpacking. I'm going to comment these lines out and I'm
going to do the following. I'm going to say that we
have the alphabet and it's equal to ABC D E F G H I, J K L M N O P Q R S T U, V, W, X, Y, and Z. There we go. We got them all. Now I'm going to say four in
enumerate over the alphabet. Oh my God, you're telling
me right now, whoa, whoa, Michael, you've clearly
done mistake here. When we say enumerate, it returns two things. It returns the index, and it also returns the value. This is clearly
not going to work, but what you might not have
known, young grasshopper, is that what happens in here is that the enumerate
actually returns apple, and that couple is unpacked
into two variables. That is what was
happening all the time if I just keep it as a single variable,
that's why I call it. By the way, look at what we get. We get a topple. I don't know if you
feel cheated or not, but this is what
happens under the hood. That's why we always have to
delve deeper and understand what's happening in Python. As you can see, this is apple. We can unpack it. Actually, you are going
to be unpacking it. Your challenge is
going to be to unpack the index inside the loop. Unpack the topple
into two variables, the index and the character. Print both of them out
at every iteration. Pass the video right now
and go to the challenge. Okay, welcome back very easily, just like we've done
for all of these years. Index character equal to t. Then in here we can
say index character. That's basically it. In
here we are unpacking the topple into the
index and the character. And when we write
click and we run, we get this output. Unpacking is very
simple, very easy. There's nothing much to it. We will see a lot of examples of unpacking tupples
down the line. Not specifically for unpacking, but in situations such as
with the enumerate where we are unpacking tupples without actually knowing that
we're unpacking tupples, I hope you enjoy it, and I'll
see you in the next video, where we will learn about
nested topples and lists. I will see you then.
72. 23. Nested Tuples and Lists: Welcome back my fellow
Python programmers. In this video, we're
going to learn about nested tupples and lists. Meaning that we are going to
have lists inside of lists, or actually tupples inside of lists or tupples
inside of topples. We're going to see
what's going to happen, we're going to mesh everything
up and see what comes out. I'm going to create a new
Python file that I'm going to call movies Nested Couples. And I'm going to
do the following. I'm going to have movies in here and it's going
to be equal to the following and
magic in 321. Boom. I'm not going to sit down
and write everything, I don't want to make the
video unnecessarily long, but as you can see, we have individual items inside
of the list of movies. We have the name of the movie, for example, Sha
Shank Redemption. Amazing movie by the way, the producer or director
is Frank Drabont, and it was made
in the year 1994, Silence of the Lambs, Seven, The Shining,
and Deer Hunter. All of them amazing movies
except for deer hunter. I don't know why, I just
didn't like it that much. But anyway, if I
try to print out the length of movies
before you run, please think of what the
answer is going to be. If you thought five,
you'd be wrong. There are 15, because
notice that there are no indications of a list or no indications of
a topple in here. In order to fix this, we need to make all of
these into okay, wait. Into a topple. There we go. And as we're creating or
making these topples, why would we want the movies to be topples
and not lists, if you said? Because the name of our movies are never
going to change and the directors of our
movies are never going to change and the year
that the movie came out is never
going to change, then you would be correct, because we will never change
the name of the movie, never change the director, and never change the
year it was made unless there is some
unforeseen consequences. I don't know the name of the director turns out to
be wrong or something. Regardless, we would
always have the same year, same name, and same
movie director. That is why having a topple
is a good idea here. Now if I rightly, can
I run look at that. I get five instead of 15. Now we want to dissect this. I'm going to create a four
loop and say four movie in movies and I'm going to
print out the following. I'm going to have a
replacement field, first of all, I'll have name
replacement field inside. I'm going to have movie
at position zero, Mm Hmm. Then director to Dots
movie at position one. And then year two, Dots placement field movie at
position two. There we go. Now when I write
Click and I run, this is the output that I get. Let me also jag it right
here, we get the following. We get name Shashank Redemption
director Frank Arrabon, year 94, name Silence of the
Lamb director Jonathan Demi, the year 1991, et cetera, et cetera, et cetera. But as you can see, it's not very clear what the information is that
we're trying to extract. What I mean by that is
like what is movie zero? What is movie one? What the heck are we
even doing in year? A better way of doing this is instead of
having movie zero, I could have movie name underscore name
instead of director. I could have underscore
name instead of the year. I would like to have
just hear all I meant. Instead of movie two, I would
just like to have the year. But obviously, the keen eye the viewers of you would have noticed that we have
an error in here. Yes, the three big
huge lines under the variables probably
gave that away. But as you can see, we
cannot simply do that. We need to actually
have the variables. And it's going to
be a challenge for you because I'm
feeling lazy today. You will need to fix the errors. First of all, you need to find
a way to fix the error in the most efficient way
possible, Unpack the pack. And there are two
ways of doing this. Should I give you the ways? If you don't, you can just go right now and do the
challenge if you want. This is sort of a hint, the two different ways are 321. Boom. Inside of the loops using variables or in
the actual loops, similar to the enumerate, pass the video right now
and go do the challenge. Okay, welcome back. So the first way is
inside of our loop. So we simply say that we have the movie copy,
copy, movie name. Come on, director name
here equal to movie. And we simply unpack this, because remember this is a
topple that can be unpacked. Now when we say
name, movie name, we know that we are
getting the movie's name. We're trying to print
out the movie name. Not just movie at
zero or movie at one. We know what is
being printed out. When I write, click on, look at that,
everything looks fine. But this is not the
most efficient way. The most efficient way is
doing it directly in here without having to go through
the movie just right here. Four movie name,
director name and hear. Similar to what we did
with the enumerate, right click run,
and there we go. So this is the basis
of nested loops, I mean nested tupples lists, as you can see, we have
movies, we have lists. This is the almost last video. In the last video,
we are going to look deeper into nesting. I'm very excited
to see you there, and I will see you
in a few seconds.
73. 24. Deeper Into Nesting: Welcome back my fellow
Python developers. In this video, we are going to start looking a little
bit deeper into nesting. The first thing that
we want to do is we want to upgrade our
movies. How about that? We want to have also a list of actors before we start thinking of how to add
them and whatever. We want to have a
mini challenge, it's not written
down, it's something for you to think
about on your own. What would we use
to hold the actors? Should it be a couple
or should it be a list? Or could it be a list of
couples or a couple of lists? I'm just going to tell you
that what we'll do is we're going to have actors with
a number next to them. We will have the name
of the actor and next to them we'll have
the number attached. This number is going
to be the ranking of the actor based on his
popularity in the movie. Think about it. Should be a list of couples, couples of lists. Just Apple, what do you think? Let's see. I'm going to go into file new and
I'm going to create a new Python file that I will call Nested underscore data. Inside of this nested data, I'm going to do magic
copy and paste. Oh wow, Where did all
of this come from? I'm going to provide
you with these. I'm not going to leave you
hanging if you do that, do not find these right here and you don't want to
write them down yourself, please contact me over any way that you can or
you can go into discord. I think you'll have access
to that discord, please. Whenever you need, whatever
you want, let me know. So in here as you can see, we have the Shaw
Shank Redemption, we have Frank Daramore, and we have 1994. And we also have
a list of actors. And these actors are
individual toupples. Now why is this a
list of toupples? First of all, we would like
to have them as stupples. Because as always, this is
not ever going to change. Now you might be thinking, well, maybe the popularity
of Morgan Freeman will wane against the
popularity of Bob Gunton. But we're just going to assume that this is
not going to change. You know Morgan
Freeman is never. Do you even know who
Clancy Brown is? I dare you, I double dare you. Anthony Hopkins will always be more popular
than Jodie Foster, even though that's debatable. But definitely more popular
than Brooksmith, Brad Pitt. I mean, come on, and
then we have Jack Nikon. No debate there.
But in any case, let's just imagine that these
will always be the same. This should be a topple, And because we might want to add other actors to this list, that's why we've made it
into a list and not Apple. That is the
explanation of why we should have a list of topples. Next thing we want to
do is we want to print all of this information
out properly. I'm going to say four
name direct year actors in movies. I am going to print
out the following. I'm going to have name two dots, replacement field with name
inside director to dots. Director, this is
called a column, two dots, this is two dots. When you have two
dots like this, maybe I should stop calling them at least vertical dots
or vertical two dots. And finally, actors column. And we'll have the actors. We've basically unpacked the
top, which is the movies, into the name director I might not have
mentioned in here. Notice where the topple
begins and ends. If you click on one
of the parentheses, you'll see where its
other brother is. Right here, the Shashank
Redemption, Frank. More comma 1994, the list. And then we have
the topple ending. We have the stopple
closing down. Right here when I
write Click and I run, this is what I get the name, Shashank Redemption director Frank Ramre Year and the actors. And you'll see that the actors are printed out in this way. Not a very nice way, but we get the pot. We can have multiple
actors in here as well. We can access any
particular movie and get the information from it. What I mean by that is, for example in here I'm going to print out and I'm
going to say that we have a particular movie equal to movies at position number
two and I will print out. The movies, I print
out the movie. So when I write Click and I run, this is what I get
at the bottom seven. David Fincher 1995 and
then the list of actors. But what if we wanted to
access individual actors? First of all, let's
say I want to access the actors. I would
do the following. I would say a equal to
movie at position one. Keep in mind I have access to the movie
which is a topple, and then I access actors. Or I say actors equal to
that movie at position one, because I have, excuse me, it should be at
three. Very nice. Move Michael in, here's 012. And then three, we
access these elements. I flint out the actors, right click and run and boom. There we go, We have our actors. Now I want to access
one of the actors. I would say actor equals actors. And then I would
access number one. Now I will print out the
actor right click and run. And there we go, we
get Morgan Freeman. Or if you want, you
can get Brad Pitt. You can even get Kevin Spacey. There we go, bit. Now I have a challenge
for you that you've seen how we can
unpack the topple slowly, and by the way, if you want, you can also print
out the actual name. For example, in here,
underscore name equal to A at position one, and we print out the
actual actor name. Now we exactly have Brad Pitt without any
parentheses or any columns. I hope you understood
how this works, because now you have
a very fun challenge, which is to find and
print out the actors. Print out the
following three names, Danny Lelloyd, Tim
Robbins, and Scott Glenn. You'll need to use the
same method that we've used right now to print
out all of these actors. Post the video right now
and go do the challenge. Okay, welcome back. So, let's go ahead
and get started. First of all, we
have Danny Le Lloyd. Le Lloyd. Is that
how you write it? Yes. First things first, we need to find this man. Where is Danny? Danny?
Danny, Danny, Danny, Leo. The man is in the Shining. Which means it should be movie equal to 012. How
many movies do we have? Let me check, 0123. All right, movies at three. Next we want to get the acts, which means we need movie. Keep in mind movie movies, 012.3, There we go again. Three. Then we need the actual
actor, which is actors. Then we need 012. All right, two. Finally the actor
underscore name is equal to act at position, which one was that one, I think. Yes, one. The 321 print out. Ace. This works?
Yes, there we go. We get Danny Lee Lloyd. Now we need to go
to the next name, which was, what was the name? Tim Robbins. But
before I do that, I want to show you a much
easier way of doing this. I can say that I have
Danny underscore Lee Lloyd equal to
movies parentheses, three parentheses,
three square brackets. I mean, square brackets, two square brackets, one. If I print out Danny Le Lloyd, right click, run, look at that. I can go and delve deeper into my list using these or multiple brackets,
one after the other. Let's find Tim Robbins. Tim Robbins is Tim Robbins is in the Shawshank Redemption. It should be zero. Then we will have actors
at three, always. Then we have Tim Robbins at one. And then 10311 in here, I'll say Tim underscore Robbins
is equal to movies 080. Oh my God, please. 03. What did we say Tim Robbins
was one and then one, and we'll print out Tim Robbins. Let's see if this works. Yep. There we go. Tim Robbins And the last name was Scott Glenn. Where are you squat? Scott Glenn. Scott Glenn is in the movie where Scott then
do we even have a Scott? There we go. Here it is. In the
Silence of the Lambs one, it's 13012344 is that correct? Yes, it is. Because
these are number one. They start at one, which
means this one is definitely 4,134.1 The last or these two numbers
never change in here. I'll say Scott Glen equal
to movies. What did we say? 1341. There we go. Scott Clam. Ladies and
gentlemen, I hope you enjoyed. I hope you got to
the last video. This has been an
amazing journey. We have finally finished
lists and topples. You are slowly but
surely becoming an amazing Python programmer. I hope you're
enjoying the scores. You're getting tons of
information out of this. And I will see you
in the next section where I believe we will start
talking about functions. Very important section, very important lessons
we're going to take. So I can't wait to see
you in the next section. Pat yourself on the back. You are doing incredibly well. I will see you then.
74. Section 6 - Functions | 1. Defining a function: Welcome back my favorite
Python programmers to a brand new section where we are going to start learning
all about functions. So we're going to be
defining functions, understanding parameters
and arguments. We'll understand what
calling functions is. Returning values, not
returning values, handling invalid arguments,
et cetera, et cetera. So without any further ordo, let's go ahead and get started. First of all, let's
explain or let's define what a
function actually is. So what the heck is it? A function is a
block of code that performs a specific task. Just like we had blocks of
code in our statements, just like we had blocks of
code in our four statement. Now we have blocks of code
inside of a function. You can pass data through, or known as parameters
into set function. A function can return
data as a result. A function only runs when
it's actually called. Functions provide
better modularity for your application and high
degree of code re using. What do we mean
by the following? First of all, we can
pass data to it. So imagine a function being like when you try to
sum a few things. When you want to
sum two elements, let's say 2.5 you're providing data to a
function that is sum. You provide it with a two and then you
provide it with a five. And the function
adds them together and the function can also
return data as a result, meaning that you
provided it with a two, you provided it with a five. It adds them up,
it gets to 7567. Yes, that's right, and
it returns that result, meaning that it gives you
back data, which is seven. A function can only run
when it's actually called. Meaning that let's say you
have this some function. It will not be called on
its own unless you tell it, unless you specify that you are actually trying to
call this function. And finally, functions provide better modularity
for your application and a high degree of re, using, meaning
that first of all, modularity means it's a
technique of splitting a larger program into
tasks that are smaller, more separate, and
easier to manage. Let's say instead of having to use plus every single time, you can just create
a function that you can use whenever you need to. This will allow you to make one small change in order to fix all of
the issues that you. We'll see where
this becomes very helpful and you also can reduce it many times.
We've already said that. Let's look at a
functions structure. This is the typical way that
we would create a function. We define it using the deaf. We have the function
name, the argument, the function body,
and a return value. Deaf is the keyword used
to declare the function. Function name is the name of the function or the name
given to that function. Usually, the
function name should reflect what that function does. The arguments, it's any
value that is passed to set function and the return
which could be optional, which returns a value from that function after all of
the code has been processed. As I said, you can
sometimes return things. You can not return things
if you don't want. And it's very important to also know that you need
to leave some spaces. I'll tell you what, that with that small introduction
into functions, let's actually get started. Last time we were in here, I'm going to create
a new project. Now, I might have changed code updated
course, I don't know. Some things might have
changed. Don't worry. Go to project, make
sure that it's Python. I'm going to call
this one functions in Python and I'm going to
select the appropriate file, so it should be in
D Python course. In the code. In the code, I will create a new folder
which is going to be functions in Python code it. Okay, let's finish up. Yes, this window, I'm going
to create a new project. New project. And right here, make sure
that it's a Python project. And I'm going to save it
inside of Python course. Inside of code, I will create
a new folder for this. Call it functions in Python. Copy this, okay. Okay, and also copy it in here. It's not changing for
some weird reasons. Again, let me make sure that we've selected
Python functions. Okay, finish up this window. There we go. We should have
everything working properly. Let's go ahead and get started. First things first,
we're going to create a new Python file. We click again in here. If it's not showing,
let's click on this. Python file. We're going to call this intro underscore functions. Let's go ahead and create
our first function. Our first function is going
to be a very simple one. We're going to define
addition in here. I'm going to have the
result which is equal to 10.5 plus four and I am
going to return the result. Then I'm going to close down the project so
we have more space. And I will have the answer equal to just addition and
print out answer. A few things to note. First of all, we have
this squiggly line. If we hover over it, it
tells us step 8305 expected two blank lines after a class or function
definition found one. What they're talking
about is this empty line. We always need two lines. When we hit enter, we have
a space. There we go. Whenever you define a
function or a class, we'll learn later
on what a class is. You always need to
have two spaces. Then we define the
actual function. In here, we said the def keyword addition
to round brackets. Result equals 10.5 plus four
and we returned that result. Finally, we actually
called this function. The function will
not work on its own unless it's actually called. When I write click and I run, this is the output that I
get, 14.5 Pretty simple. Nothing too much in here. Now what we want to do is we're going to issue you
a bit of a challenge. Your challenge is going to
be to do the following. Create your own
personal function. Create a function with
the multiplication. This function should multiply two numbers of your choice
and return a result. And call it in your body. In the body of your code. When I say body of your code, it means anything
that's outside of the definitions of functions
that we have at the top. Print out the result. Pass the video right now
and go do the challenge. Welcome back. How did
you get on with that? In here at the top, I will define multiplication. And I'm going to have the result equal to 10.5
multiplied by four. And I will return the result. And we also need to
have two blank spaces between our functions as well. I'm going to change this from
addition to multiplication. Now when I run,
this is what I get, 42.0 You'll notice that
even though it's 42, we also have the zero, meaning that whatever
the result is, what it will return. The result is a float. It returns a float. That means the
answer is a float. That means we print out a float. So I hope you understand
how this works. As a small homework, I recommend that you add a breakpoint right
here next to answer, so that you can see how the
program actually functions. So answer calls multiplication, we go to the multiplication, We go through the result, and then when we return, we go back to this exact line. So this will be like
a small homework that you can do to make sure you understand how
Colin functions works. Functions are not that
hard, as you've seen. There are a few things that
we need to know about them, but everything will be fine, trust me, don't worry.
So I hope you enjoy it. And I will see you in the next video where
we will look at parameters and arguments
and understand them fully. So I will see you
in a few seconds.
75. 2. Parameters and arguments: Welcome back my fellow
Python developers to a brand new video. And in this video we're
going to learn all about parameters and arguments. Our current function
isn't really useful since we can just
avoid using the function. In this case, what we want
is we want to actually start adding parameters
and making it more useful. Not only that, we are
just adding two numbers, ten point 5.4 or multiplying
these two numbers, which is not really efficient. We want to be able to add, for example, two numbers that the user would provide us with. Let's go ahead and do that. To start changing this, we're going to go back
to our function, which is the multiplication, and we're going to
provide two parameters. The first parameter
is going to be x. The second parameter is
going to be y in here. Instead of multiplying
10.5 with four, I will be multiplying
x by y. There we go. And then I will be
returning the result. Now whatever values we provide will be used
in this function, multiplied together and set to the result and then returned. Now notice as soon
as we do this, this no longer works. If I write click and Iun I get an error because it
tells me there's a type error
multiplication missing two required positional
arguments, x and y. So we have to provide it
with these arguments. I'm going to provide it
with ten point 5.4 So basically we haven't
done anything but we did provide
it with the numbers. And now there shouldn't
be any error. And now we get 42.0 Now I can change this to let's say a 6.8 And I right click
and I run, look at that, 27.2 I can change
the four to 12, right click and run
81.6 So as you can see, we've croof created a really effective
multiplication function using a few arguments
and parameters. Obviously also what
we're doing is we are providing this function
with a float number, which gives us a float
number in return. But if we provided with an integer number or in
two integer numbers, we should see that we
have an integer output. That's the basics of
having two arguments. Nothing too much in here. I'm going to give
you a challenge to help you better
understand how this works. I'm going to show
you in the slid, you have to create
looping functions, create a four loop
over a certain range. This should happen in
the body of your code. Again, concentrate
body of your code. Use the value in the
loop as an argument. In the multiplication function, you have the value
that's increasing or decreasing or whatever you
want inside of your range. The value that is
changing needs to be used as an argument in
the multiplication function, Print out the resulting
answer every iteration, and that's basically it. Pass the video right now
and go do the challenge. Welcome back. How did you
get on with that in here? First of all, I need
to create a four loop. So I will say four valve, meaning value in range. And the range will be 1010, we are going to go
from zero until nine because remember it's always
up to, but not including. And I'm going to say table
underscore value is going to be equal to
multiplication to valve. Then I will print out the
following two things. I'm going to say two x which
stands for multiply with the replacement field of val will be equal to replacement
field table of value. So what we should see is we
should see two multiplied by zero equals zero multiplied by one equals to multiply,
blah, blah, blah, blah. Right click run,
and there we go. It works two multiplied
by 02 multiplied by 12 multiplied by two until
two multiplied by nine. As you can see, providing
parameters is very helpful. A function that does not
have parameter can still have its own place in existence, but it's not that efficient. Before we move on, let's go ahead and
create some debugging. Let's do some debugging
for our values. So I'm going to first of all, add a debugger in here, or maybe I should
add it right here. It doesn't matter. I'm going to write the click and
I'm going to run, sorry, I'm going to write the click and I'm going to debug. Boom, This is where we start out on the multiplication.
On the answer. Now if I step into, look at what happens, I go to the top, into
the multiplication. Pretty obvious, if you've
done the homework, the small homework that
I gave you before, you should be
familiar with this. So let's see what
happens when we step in again. Oh, sorry. Before we step in again, look at what happens in here. We have x six and y 12. So they go to their
respective positions. So the first argument
is going to go to x, the second argument
is going to go to y. We step into again, there we go. The result is 72, and
then we go back to the multiplication to set
the result to the answer. If I step into again, look at that, answer becomes 72. But notice something very
important that happened when we actually went out of the multiplication function
x and y disappeared. Why is that? Well,
because in this case, X and Y are just
temporary variables. They're not set to anything, they've not been properly
created or defined. They are temporary.
Once the function is done, they are deleted. And what I mean by
that, and it's very important to know
this distinction, because now if I try
to, for example, print out x, look at that, there's nothing,
there's an error. Because x does not exist
in the body of my code. It is only defined inside
of the multiplication. It only exists in this boundary and does not exist on
the outside, okay? So very important thing to note. You cannot use your variables, your parameters outside
of the actual function. To whom, who, or I don't
know where it belongs. Okay? So I hope you understood
parameters and arguments. It's not that hard,
it's kind of easy. I recommend that you also,
as a small homework, you can use the debugger
right here on this for loop. Go through it, make sure you
understand what's happening, how these values are changing, and how they are also
disappearing and cannot be used outside
the bounds of the. I hope you enjoy it. I'll
see you in the next video where we will be creating
a word reverser. That should be fun. So I'll
see you in a few seconds.
76. 3. Word Reverser: Welcome back my fellow
Python developers. In this video, we are
going to be creating another function that will demonstrate how we can actually, we use functions in a
more meaningful way. Because currently
the multiplication that we've created and the addition are functions
that already exist in Python. So we want to create
one that's unique. The first thing we're going
to do is we're going to go into file new and create a new Python file that we'll call word underscore reverser. Reverse sir. First
thing I'm going to do is I'm going to
define the reverser. I'm going to provide
it with an argument. It's going to be the string underscore two,
underscore reverse. Then I'm going to say that the reverse underscore string is equal to the
string to reverse. And we are going to slice
it the following way. And then I will return the reversed strength,
and that's basically it. Can you tell me what
this does right here? I want you to take a few
moments and remember how slicing works and
this exact slice does. After passing the video
and thinking about it, you've probably concluded
that what we're doing in here is we are starting
at the beginning, going until the end, but we're doing a
step of minus one. We're going back through the string that we
would like to reverse. When we have a
step of minus one, it means that this is the end
and this is the beginning. Basically what we're
saying is that the reversed string is equal to a slice of the string
that we want to reverse, but when it's going from end to the beginning, and
that's basically it. But because we don't
know the size of our current string or the
string that we want to reverse, we do not specify what the
end and the beginning or we just tell it that we want to go from the end until
the beginning. And then we return
the reversed string. With that out of the way, I want to show you
one thing that we could do in here to make
this more efficient. Instead of setting
the string to reverse with its slice in a variable, what I can do is I
can comment this out. Remember I can
comment out a line with the control forward slash. I think I've already mentioned that before, but no worries. And I can simply return the
reversed string directly. This doesn't change anything. The function will work the
same way it did before, but it will definitely provide a easier to read and
more efficient function. Now that we have that, let's
go ahead and create word, which is going to be
equal to an input. That input is going to tell us. Please enter a word
you'd like to reverse. The word that we would
like to reverse will be added and finally
we will print out your word was two dots
replacement field with the word when reversed, it is two dots
replacement field. The reverser provided
with the word. There we go. We obviously
should add an extra space. If we write click and we run, Please enter the word that
you would like to reverse. I would like to
reverse. There we go. Looks like it doesn't
work because, look, your word was rotator and
when reversed, it's rotator. Well, actually I made a mistake, but I deliberately chose a word that actually
is the same, going forwards and backwards.
A small joke in here. No worries. It's April fools. I'm kidding when
I'm recording this. So let's try any other word. Let's Michael, there we go. Look at what we get.
A I don't know. So as you can see, the word reverse
or works properly, the only problem
with it is if I try to enter the following
word rotator. But with a upper case R, you'll see that I get an
upper case R at the end, which doesn't really make sense. It just doesn't look good. To fix this, I will
issue you a challenge, which is going to be
to mind your case. Reverse the word
without having to worry about the case meaning, Make sure the returning value is independent of the case
of the characters. Pass the video right now
and go do the challenge. Welcome back my fellow
game developers. So how did you get on
with this challenge? This is a very
important challenge because some of you might
have done the following. You might have used case
fold in this situation so that you can lower the case on the input directly,
which would work. You might have used
the fold right here, which would have taken the reversed word and
lowered the case, which would also be good. But the best place
to put the case fold is if you haven't put
it in the correct place. Thank a little bit,
it's actually here. What we want to do is
we want to reverse the word and then apply
the case fold to it. Now you might be
asking yourself, why isn't it good here? Why isn't it good here? Well, because later on we
might use the reverser again. Do you think we should
apply the case fold again to when we're printing
out the reversed word? I mean, we can, but
what if we're calling the reverser 1,000 times? Well, now we'll have
to make sure that we type in case fold
every single time. And those 100 times, 100 or 1,000 times, this is where the power of
functions come into play. This is what we meant when we said reusability and modularity. Instead of having to
call the case fold every single time you try to
print out a reversed word, you can now simply
use it one time inside of the function
and it will always work. I will copy the rotator, Run paste the rotator. Hit Enter, and look at that. Rotator is printed out
with the lower case R. Now let's just make sure that
it works also for Michael, for example. There we go. You can see that no big
M, which makes sense. So I hope you enjoyed. The most important
part in all of this video is for you to
understand the importance of using a function and
how easy it is to modify code that you might use repeatedly throughout
your program. I hope you enjoy it.
I will see you in the next video where we
will learn about functions. Calling functions, you can call it functions inception
if you want. All right, I'll stop here and I will see you
in a few seconds.
77. 4. Functions Calling Functions: Welcome back my fellow Python programmers to a
brand new video. In this video, we
are going to see how functions can
call other functions. Let's go ahead and get started. First thing we're going
to do is we're going to go into file, new file. I'm going to call this underscore
calling functions here. I'm going to define multiply. The multiplication is going
to be between x and y, and it will simply return
x times y. Pretty simple. Nothing too much in here. Now the other function that
I'm going to create is going to be define get
underscore power. Underscore two. We're also going
to have x and y. Remember, these two, x and y, are independent of each other. The get power is
the best example of a function being called
inside of another function. Because when you try to get
the power two of something, you multiply it by itself by the time that
you've provided it with. That came out completely wrong. Let's say you have two
to the power three. You would multiply
two by two by two. Usually the symbol of
the power two would be this means that
it's equal to, actually let me
comment this out. It's two multiplied by
two multiplied by two. What is happening in here? The multiplication function
is being called three times. First of all, it was
two multiplied by one. To make it more obvious on
how this is going to work, one multiplied by two, then two multiplied by two, then two multiplied, or the entire answer
multiplied by two. Again, the get power
is a very important or a very good example of
using a function or calling a function inside
of another function. First thing we're going
to do is we're going to create the result
which is equal to one. This is just to set things up. Then I'm going to
say four in range, and the range is going to be y, so it's going to be
x to the power y. We're going to multiply x by the results that
we are getting, y times four in range y. The result is equal
to multiply result x. I will print out the result. This is purely for
debugging purposes, purposes that
purposes yes, it is. Finally, outside
of the for loop, I will return the result. Now in here, after
two lines of code, I'm going to print
out the following. I will say five to
the power three is replacement field
and then get power 53. If I write Click and
I run, there we go. Five power three is 125. And that's true because
five times three is 25. Then multiplied by three again, multiplied by five again, I almost lost it. There is 125. I want you to look
closely at this, get power, and truly
understand how it's working. Basically what we're
doing, as we said, if we put back our example
of five power 35 to the power three is equal to one times five times
five times five. The result is one. We take one, we multiply it by five. We say that the result
now is equal to multiply result
is one axis five. We go to the multiply, This is where we're calling
the multiplier function. From another function,
we get five. Now the result is equal to five. We go back through the loop, we check is less than y, which is three. Y is three. And remember, the range is
up to, but not including. We started at I equals zero. At I equals one, no, it's still less than y. We have the result equals five. We say that result, the
new one is equal to multiply result which is
five to the power three, the power five.
Now we have this. We set it back in the result, now the result is 25. Now we go back and we do
the same thing and we have a function calling
another function. It's pretty simple.
Nothing too much in here. You might be thinking,
how is this simple? I didn't understand anything. Once you understanding
understand it through the next challenge, you'll tell yourself, wow, this was indeed easy. Because your
challenge is going to be to use the debugger
and understand this. Use the debugger to go
through the code and see how the logic is working. Pass the video right now
and go do the challenge. Okay, welcome back. How did you get on with that? Pretty simple. Nothing
too much in here. I will add a break
point right here, exactly on the print. And I will debug the code. And let's look at how
everything is working in here. I will step into, there
we go, we go to the top. As you can see, x
is equal to five, y is equal to three. We step into again,
the result is one for I in range is equal to zero. Look at what's going
to happen when we execute this following line. I will jump into the multiply and look
what we have in here. Return x multiplied by y, something that we
might not have seen before or you might
not have realized when you're debugging your
code when working with a function is that we don't
hang up on the function, we immediately go inside of it. Something that might
be obvious to you, but something very
important to realize. Just like when we
skip over the ls, we don't execute the ls, we go inside of it and execute
the code that's inside, return x times y. Notice when we come back, we don't come back a
line to the front. We don't go back to the print, we stay on the result. And this is something
that you've probably seen as your debugging your code in the previous sin
or two videos before. Y equals three, x equals five. Now we have the
result equal to five we printed out in the debug. Now y is one, result is five, or result is equal to multiply. Now what do we have
the result as? Boom, there we go. This is
five multiplied by five. We come back, it's 25. Now when we go back to
the top, there we go, x is 25 multiplied by five
is the return of 125. We print out the result and
we go back. We increase I. We see that it's no longer exactly less than Y or
less than the range, and we print it out. I
hope you enjoyed it. If you're still not
sure what's happening, go back through the
code debuckt again, understand everything
that's happening. And I will see you in the
next video where we will look deeper into
returning values. So I will see you
in a few seconds.
78. 5. Returning Values: Welcome back my favorite Python programmers to a
brand new video. In this video, we are
going back in time. We're going back in time
to this following program, the old Nicholas Flamel. The problem with this is that
if we use a string in here, we would get an error. Don't believe me. If
I write click and I run what is flames H, I could type in a number
that I already know. But if I type in, for example, high and hit Enter, look at that, I get an error. What is this error all about? Well, the problem is
that we are trying to convert whatever the
input is into an integer. But if you provide
it with a string, as you can see,
you get an error. Because how do you
convert high into an integer doesn't
make any sense. In this video, we're
going to learn how we can create a
function that can help us a lot because we're going to create
a new Python file. This new Python file
is going to be called, what shall we call it, Nicholas? Underscore flamel. Underscore underscore function. Or why am I calling
it just underscore function it in here. The first thing that
I want to do is I want to define a new function. I will define the get
underscore integer. This integer will
ensure that what the user is providing
is indeed a number. In here, I'm going
to add an argument, which will be the prompt. The prompt, The prompt is
the following, right here. When you say, let's say in here, I want to get input. Provide me with a
gas, for example. This is called the prompt. We are providing the get
integer with a prompt. You should answer me by
the time we're done. Why we're providing
the prompt to the get integer next
we have a while true. We're going to keep
on with this while. We're going to have Tamp, which is a temporary
variable Tamp input prompt. We're going to have
the input with the prompt inside of
it and we're going to check if stamp
dot is numeric. Do you remember this function? Very, very old function. I told you we're going back
in time in this video. Return in and then temp. Look at this and tell me what is happening in this
function. Take your time. Now the only thing that
might be weird about this is there's
no break in here. This is a wild true, It
will keep going forever. What's going to make
this wild loop stop? Well, it's going
to be the return, because remember when
we return a variable, we jump out of the function, which means we will effectively jump out of our wire loop. So this is a great way of
avoiding the use of a brake. We can simply use the return. Now that we have that down, I'm going to get this code and I hope you can find it
somewhere in your project. I honestly, I can't name which section
it was in right now. You'll have to try
your best to find it. I apologize. It should be somewhere in here
in the project. Go to file open recent and find the project
that you're looking for. What I'm going to
do is I'm going to copy all of this right here. But to be fair, do we
really need all of this? Yes, we do. Let's go. No worries. So I will
add all of this in here. The import, what is it, level Import at the
top of the file. All right, so there we go. Import should be at
the top and then have two spaces and then
only have two spaces. Okay, eight. I've
given you anything. I've subjected myself to your
wills to all of your needs. I in your highest
101 actual age one, and the highest
guess, none. Okay. Everything should be true
except for this right here, where we say that the guess
is no longer equal to the input is going to be
equal to get integer. The prompt should be
just the following, because remember we're printing
out what is Flamels age, Mr. Weasley right here. Now we could do it
inside in here, but I just want to keep
the code as it is so that we just make the little
changes that are needed. If I write click and I run. Let me just duck
this right here. What is Flam Mel's age? If I type in, let's
say 20, it tells me, please guess higher
if I type in high, Look at that, There's no error, but it does not work. Michael Python. Can I please play? Nope. It will wait for
another number which is 53. I think it's 53. As you can see now we have
a functioning program, or at least we have a
error free program. The question that I asked you, why do we have a prompt in here? Well, because of
the last lesson, you should know by now
that we are going to be using the get integer
in a lot of places, not just in this
situation right here, because we're going to be
using it in a lot of places. We're going to have
different prompts. Let's say for example, we use it right here just
for this forward slash. But what if we change our mind, and now we want to print
this instead inside. This completely changes
everything, right? But what if we use the get
integer in another place? Providing the get integer with a prompt is a good idea because now we can use it dynamically wherever
we want in our code. Before we leave, there's one more thing we
need to do in here, or at least you
need to do in here. And that is tell the user, because you'll need to add a message to the
function that tells the user the input is invalid and what he
should be doing, he or she test it out and make sure that
it works properly. Basically, as you've
noticed when we try to add Hi or Michael or
can I please play, the user just doesn't know why the game keeps
kicking him out. Help the user. This
challenge is very important to know where you should be
Adding this in your code, Pass the video right now
and go do the challenge. Okay, welcome back in here. If we have the under the Ls
we are going to print out. Please enter a value. There we go. What is the matter with
this expected two dots. Did I seriously forget
a colon in here? When I write click and I run, What is age? It's Michael. Please enter a
numeric value, Hi to. All right, there we
go. So my game works. Thanks so much for watching. I hope you enjoyed the video. I hope you understood the importance of using
the prompt in here and you are beginning to really feel how important
functions are to us. In the next video, we
are going to look at returning none or
returning nothing. Thanks so much for watching. See you in a few seconds.
79. 6. Returning None: Welcome back my fellow Python programmers to a
brand new video. And in this one we're
going to learn what it is that is returning none. All the functions
that we've seen so far have always been
returning a value. Like right here
we have a return, right here we have a return
like the word reversal. We're always
returning something. But what would happen if we don't and would it really
help us with anything? Let's create a new
Python file in here and call it non underscore. Returning underscore
functions. By the way, you can call these Python files whatever you want as long as they are in line with what's going to
happen inside of this. Let's define again the multiply. The multiplier is
going to have x and y. The multiplier will
get x times y. And we will actually, let's turn the x times y. There we go. Everything is
good in here. Life is amazing. And I will simply print
out, or first of all, I'll say answer equals
to multiply four by 16. And then I will print
out the answer, Life is good,
everything is good. When I run, there
we go, we get 64. Hopefully, that is the answer. Now, what would happen if I
decide to comment this out? Well, first of all, I'm going to have an error because you can't just leave
a function empty. We have to provide
it with something. So I'm just going to say
that the result is equal to x times y. Okay, There we go. Now, no more problems.
What do we have in here? Multiply doesn't
return anything. Uh huh? The multiply does
not return anything. Setting this,
nothing that's being returned to a variable is
not really smart, is it? We need to figure out a way to make this a
little bit better. How? Well, what would be the use of a function that
does not return anything? First of all, we would probably not want to set any
variable to it. Second of all, I will probably
remove the print in here. But what would we do
in this situation? What is the multiply good for? Well, I'm going to tell you that the multiply in this
situation is not completely useless because you can use them to perform certain actions like you're going to learn this challenge
could transition, I don't know, no result.
Still get something. Since we're not
returning anything, we still need to get
something displayed. Which means what should we do? Should I give you a hint? If you don't want
the hint and you want to try to solve
this on your own, it's a bit of a weird challenge, but you can go and
solve this on your own. Simply print something out directly into the function,
and that's basically it. If the function does not return, we want to print something
out of this function, pause the video right
now and go do the. Okay, welcome back. How did you get on with that? I think this is very simple. I can simply say the result of the multiplication is
replacement field result. And that's it. Now when
the multiply is called, it will multiply these
two numbers and then print out the result directly. So not returning anything
has its uses sometime. I hope you enjoyed this
was a very short video. In the next one, we will be
handling invalid arguments. Meaning what if I provide high, high, high, theoretically. Can I run well in this case, there we go. Look
at what we got. But what would
happen if we didn't want to get this if we
don't want a string? We'll see that in
the next video. See you in a few seconds.
80. 7. Handling Invalid Arguments: Welcome back my fellow Python programmers to a
brand new video. And in this one we
are going to look at handling invalid arguments. I've already told you about what happens if we provide
this with a string. We get an unexpected output. But this is not as bad as
if we have the following. If I provided with this, if I provided with two strings. Now when I write clicking
on look at this, I get an error. This is not good at all. We don't want something
like this to happen. We're going to look at
how this is fixable. The first thing I want
to do is I want to uncomment returning x and y
and comment out the print. Then in here I'm
going to print out, give me or give us two
numbers to multiply. In here, I'm going to
say that a is equal to an input and then a two dots
and B is also an input. Before I continue, I'll just
make them into an integer. Now I know we've learned that this is not the most optimal way because the user can
still provide a string. But for the purposes
of this video, we'll just assume that the user knows he should be
providing a numeric number. So now instead of number, if we try a string,
we get an error. Obviously, this is because of the integer that we are
providing this with. But what if we wanted to
create our own kind of error? For example, let's say we can
only multiply everything. Or we can multiply only
if x is less than ten. Let's say this is what we want out of our program or
out of our function. This is exactly what
you are going to do in the challenge of creating
your own type error. In the multiplication function. Multiplication
function, make sure that the numbers meet
a certain condition. Example x or y are
greater than 100. Use the raise value
error if they are. Otherwise, calculate the
result and return it. Google it and understand how to actually use
it so you can type in value error W three
schools to really see how you can use
the raise value error. Pass the video right now
and go do the challenge. Okay, welcome back. How did you get on with that? Let's say we want
to only multiply x and y if they
are less than 100. What I'm going to do, and
I hope that you looked up the raise value error in here, I'm going to say if x is greater than 100 or y is
greater than 100, I'm going to raise value
error and I'm going to say one or both of the numbers. Let's just make
it a legit error. Numbers one or the both are greater than the max size 100. And there we go, that
is what we need. And then finally
in here we'll have an L and we'll just
tab everything. So now we have our own error. Ladies and gentlemen,
if I right click and I run and I provided with 506, I don't get anything
for some reason. What is the issue
in here? Uh huh. Well, the issue in here,
ladies and gentlemen, is that my tired head has
forgotten to do multiply a B. Very nice work. Very
excellent work. Again, we try to run. We provide 506, and there we go, one or both of the numbers are
greater than the max size. If I write click and I run and I try 6.10 there we go, we get 60. If I try, for
example, 103 or not, let's try 10.110 or 1010. There we go, One of these
or both have an error. 200, 500, we also get an error. So as you can see, we have a way of handling
invalid arguments. I'm also going to show
you the following link. So you should open it up. You should have access
to it somewhere somehow. It's called the
built in exceptions. You can go through
these to clearly understand all of the
exceptions that we can create. For example, the base
ones or the Args. There are exceptions.
Exceptions. We will be looking deeper into exceptions when we
get to the SQL part. Right now, you just need
to know the surface level. Let me try and look
for value error, let's see if I can find it. No error Summary. There we go. We have type error, we have value error
in here. There we go. Exception raised
when an operation or function receives an argument that has the right type but
an inappropriate value. There we go. X and
y are integers. That's good, but they have an inappropriate value.
I hope you enjoy it. I hope you understood this is the link If you want to
go through it or you can search built in except
Python documentation. And I will see you in
the next video where we are going to be talking
about default parameters. So what if somebody doesn't
provide a parameter at all? What would we do? We'll see in the next video. See you soon.
81. 8. Default Parameter Values: Welcome back my fellow
Python programmers. In this video, we're going to be exploring default
parameter values. Let's go ahead and get started. First of all, why would we
need a default argument? It's an argument that
assumes a default value. If a value is not provided in the function that requires
an actual argument. For example, in here with the multiply x and
y, as you can see, we need two arguments
in here, the x, y, let's say we
don't provide this. Let's say we just provide
the notice that we get an error if I hover over
the small highlight in here. Well, not an error,
but just a big, big warning sign In here, you can see performing Cod Inan. One weak warning found and then one huge warning found
when I hover over it. Parameter unfilled. If I right click and I run here. If I type in 42, 40 had entered. There we go. We get an error because missing one required
positional argument y. The problem with this is
that we've required the y and we just provided
it with the x. In this situation, it took
the x as the first argument. How do we avoid this problem? How do we avoid having
errors such as these? Well, we provided it
with default arguments. For example, let's say
in here we have x and y. In some situations where
y is not provided, I can say that y
is equal to one. And notice that in here
I did not add spaces. As you can see, again, we follow the P eight rules. It says 251 unexpected spaces around keyword
parameter, whatever. These are called
keyword parameters. We will look deeper
into them later on. But for now, as you can see, y equals one, we have no
errors in here at all. Now, if I provide 42.10 the
answer is ten. Why is that? Well, because we've
provided correct only B. We did not provide anything
else which means is set to X. There is an order to this, as you can see, because
Y was not provided. We set Y to one and we
just multiplied by one. We can change this to
two just so you can make sure that this
is actually working. 40 12, boom, there we go. 24 12 was multiplied by two. We can also present default
values for the x as well. In here I can say x
is equal to three. Now when I write
click and I run, oh wait, in here I can now
provide nothing at all. So now when I write
click and I run, I can type in whatever I want, 42, and then 50. And the answer will
be just six because we simply multiplied
three by two. Whatever you type in in here, whatever the number is, I can type, of course not that kind of number like this
one. Boom, there we go. The answer will always be six. So as you can see, having default arguments
is very important. Later on, we will
always be having default arguments
because we want to avoid these kinds of errors. But before we move on, there is a slight thing that
we need to learn. And notice when we
hover over multiply, what we get in here, this
is called the doc strings. And we will learn more
about doc strings later on. How we can display our
own thing in here. The clerk equals three equals to whatever. One more
thing in here. What if for some
reason I wanted to have x be set as
the default value? Or or having x use
the default value. For example, if I provide a, I want a or Y to be set to a. How would I do that? Well, this is going to be a
bit of a challenge for you. Set only the y currently. When we provide
only one argument, it's being set to x and y
is using the default value. Find a way to make sure that when we provide one argument, the y is the one being set and x is the one that
uses the default. I recommend that you go search, you go try and find
this answer yourself. But if you don't, you
can have this hint in 321 specify which argument you are setting when
calling the function, say y equals to the thing
that you want to set, the value that you are sending. Pass the video right now
and go do the challenge. Okay, welcome back. I hope you did the
challenge in here. Let's see, multiply a. If I right click and I
run the problem in here, that we're always going to
consider that x is equal to a. So we're always going to
multiply a in here by two. As you can see, we get 84. What if I wanted to
multiply a by three? Meaning I wanted y to
be set to a. I could simply say y equals
a. And there we go. As you can see, parameter
y is going to be set to a. Now, whatever a is, it will be multiplied by three
because x is not provided, I'll multiply 30 by 310. Boom, there we go, we get 90. We can specify which argument we will be setting the value of. Thanks so much for watching.
I hope you enjoyed. In the next video,
we will be actually creating a Fibonacci function, which is a very
interesting thing. We will also be learning
about Fibonacci numbers. I recommend that
you look them up. Thanks so much for watching, and I'll see you
in a few seconds.
82. 9. Writing a Fibonacci function: Welcome back my fellow
Python developers. In this video, we
are going to be writing a Fibonacci function. Before actually we start
writing our Fibonacci function, we need to understand what
a Fibonacci function is. I'm going to follow
the following link, H. Interesting choice of words. And by the way, you
can simply type in Fibonacci sequence into Google and just look up Fibonacci. This is a mathematical
sequence that is very popular in most
mathematical fields. Or you will see the
sequence almost everywhere, you might have seen it
before in this form. The spiral that you see like where everybody on
Instagram pretends like, wow, look at this picture. Oh my god, it
follows the spiral. Yes, that is indeed the
Fibonacci Nerdy sequence. The Fibonacci sequence
is actually very easy. Basically what it's all
about is summing up two numbers and
then setting it as the third number and
doing it forwards. For example, we start off with a 0.1 These are two
arbitrary numbers. We just start off with 01, and then we have zero
plus one equals 11, plus one equals 22, plus one equals 33, plus two equals 55 plus 38851313 A 2,121.13
34.1 and so forth. Very simple sequence.
Again I recommend you can find math is fun.com. Numbers Fibonacci sequence. You can follow this link. I will make it
available somewhere, but also make sure that you
do some research yourself. You understand
what is happening. Now you can see right here, we have the rules or the equation which this
Fibonacci Sequence follows. It's very important that
you go through it as well. You check out what is
happening and how this works. For example, right here,
let's say we want to get x at n. Let's say we want
to get the number, or the Fibonacci number. And our function will be a function where we
presented with the n, let's say we want
the number at 11. We presented with 11, the function will return 89. How does this work? Right here, the rule is, let's
say for example, you want x8xn is
equal to x minus one, x seven plus x N minus two, which is x six. And that is the rule that our function is going to follow. We're going to have a
small four loop inside. And we're going to be replacing things because look
at what happens. First of all, we start off with 0.1 then we have the
result, which is one. But then we have a
change up in here, meaning that n minus
two right here, n minus two becomes n minus one. The values are changing, and so on and so forth. So that is what we are going to try and implement
in our program. Once we create the program, I will have a slide
where we explain this further and we will
see how it properly works without any further ado. Let's go back into Intellig. I will create a new Python file that I will call the fibo Naci. We'll just count Fibonacci. Fibonacci has two C's, that's why it's pronounced she. I'm not Italian,
but that's what I think they would
call it as in here. I'm going to define
the fibo naci. Fibonacci is going to take
in the end that we want to produce the number at which we want to produce the
number of the Fibonacci. First of all, we
need to make sure that if the end that the user is trying to provide us
with is either one or zero, we want to just return the n, because right here, look at
n equals zero, we have zero. At n equals one we have one. Only when we get to n
equals two do we get a one. If the user inputs one or zero, we will simply return back the making our
lives much simpler. We have zero less
than or equal to n less than or equal to one. This basically makes
sure that n is in 0-1 And keep in mind that the user will not
be inputting any floats. Meaning that it's like saying if n is equal to zero
or n equal to one. But it's easier to
write it like this. We will return and now we need to have an
else in here as well. With that out of the way, now we need to start
creating the n minus one and the N minus two. I'm going to say that we
have underscore minus one. Underscore minus
two equal to 10. We are packing apple in here. If you're not sure
what we're doing, we have the couple 1.0 and unpacking it into n minus
one and n minus two. Now we're going to
create a four loop. Four in range, And the range
is going to be N minus one. I will tell you what
this range is about, you'll try to figure it
out on your own once we write the block of covets
inside of this four loop, I'm going to say result is equal to n minus
one or N minus two, to be more precise,
plus n minus one. Then I will say n minus two
is equal to n minus one. N minus one is equal
to the result. Finally, we return the result that we get after going through. Let's test it out, make sure
that it actually works. And then we will explain
the code in here. I will print out Fibonacci at, let's say seven in here. As you can see, the result
has a small warning. Glo may be referenced
before assignment, okay, so it's just worried that
we might not go into the fore loop or we might just return
and here, don't worry. I believe that this will not
cause any error at seven. Right click and run
the output is 13. Let's check this
number at seven. Yes, we do get 13. Let's try 13 back in the code. If I try 13, right click, run, it's
233, which is correct. What is happening
in our coding here? First of all, we've said the
n minus one and n minus two. These are already established. When I say n minus one, I am referencing to this number right
here at N minus one. So we set it as 0.1
N minus two is zero. N minus one is one. Then we have a four
range, N minus one. Now why do we have
this weird range? Well, because we've already
done the first two numbers, which means we don't want
to go through them again. We want to continue
on from there. You might be thinking,
well, why is it not range N minus two? Well, because as
always it's up to, but not including
the last number has already been taken out, which means we only need to
have a range of N minus one. And we won't even
get to n minus one. We will get to n minus two. We need a range of
n minus one because the first two numbers have
already been dealt with with. Then what we have is
result is equal to n minus two plus n minus one. Similar to what we have in here, just the numbers are
in a different order, x n minus two x N minus
one and x n is the result. And then what we have is n minus two is equal
to n minus one. And then n minus one
is equal to result. Because remember what
we have in here. Let's say we're trying
to get three, correct? We have n minus
two, which is one. To be more precise, we have
right here, we have one. N minus one is one. And the result is two, because we have one plus one. Now when we try to get n four, the result should be three. What we have is n minus
two becomes n minus one. And then n minus one becomes the result that we got
previously confused. I know, let's move
on to the slides. How does our function work? Let's take an example and try to calculate Fibonacci
at number seven. We have n minus two is equal to zero and minus one is
equal to one. Right? This is how we start off. I want your full
concentration right now. The result is equal to n
minus two plus n minus one. We start off we have
n minus 20 minus 11. This is at two, because remember we already dealt with the first two ones, that's why we dealt with zero, Dealt with one
where f equals two. So right here, n minus two, N minus one, what do we have? We have the result
being set as N minus one and n minus two being
set as n minus one. We continue on from there, we have a three, now we have n minus two as one, N minus one as one.
The result is two. We set n minus one as two, N minus two as one
as n minus one, not just one as n minus one. We continue on from there, now we have the result
equals to three. N minus one is set to three, N minus two is set to two, which was previously n minus 10. This is four. At five, we have the result equal to
five because remember we had 3.22 plus three equals five. Again, n minus one is set as the result and minus two
is set as n minus one, which is three. We
do the same in here. Now we have 5.33 plus
five equals eight, the result, n minus one
is set to the result, and minus two is
set to n minus one. Finally, Okay, this
should have been six, I apologize for that.
But you get the point. We have 567 and we get
the result which is 13. Okay? So I know it's
a bit confusing. I recommend that you
go through it again. I even recommend
that you try and add a breakpoint
in here somewhere, maybe on the print,
go through it slowly, understand how everything
is working correctly. With that out of the way, I'm going to issue you
a bit of a challenge. Your challenge is going to be
to bring me the Fibonacci, You need to print out the
first 36 Fibonacci numbers. Use only two lines of code. If you want to get a hint, you can wait for the hint. Or if you want, you can pass the video right now and
go to the challenge. Use a four loop over a range and call the function
with the parameter. Simply create a four loop
in the body of our code. Meaning outside of our function, this four loop should
go over a range of 36. At every iteration, you should print out the index that
you're currently at, and use the Fibonacci with the index that is looping over. Pass the video right now
and go do the challenge. Okay, welcome back. How did you get on with that? In here I will just add a print, and I will say four in range, and the range is 36. Then I will print
out a Fibonacci I. That's it, because remember our function, basically
what it does, you send it, it gives you
the number you send it, it gives you a number. What we're doing in here is
we're just sending all of the numbers from
zero through to 25. Because remember 26
is not included. Right click and run, and this is the
output that we get. Let me dock it to the right. So 0, 0, 1, 1, 2, 1, 3, 2, 4, 3, 5, 5, 6, 8 is are these number correct? Let me just double check. 55. Yes, it is. Eight until look at that. At 35, we have 9,227,465 So this is not easy
to get on your first try. If you understood it,
congratulations, that's great. I love it if you haven't, again, I recommend that you look closely at the function
that we have in here. Look closely at how
our function works. I recommend that you go
back through the video and watch again each and every step and how
it's happening. I think the explanation
is pretty clear, except for this mistake
that I did right here. And you can also
use the debugger. This is like a homework for you. Use the debugger,
rewatch the video, Understand how the
Fibonacci function works, because once you
get how this works, you intermediate plus level
when it comes to Python. Okay. Also make sure you understand what the range
is all about in here. Thank you so much for watching. I hope you enjoyed.
And in the next video, we are going to be looking at function annotations
and type hints. Because currently, for
example, the user can, I don't know, provide us
with 13.5 What would we get? We would just get an
error because while object float object cannot be
interpreted as an integer. We'll see how we can
provide a hint to the user that please
use the integer here. Don't use a float. Thanks
so much for watching. See you in the next video.
83. 10. Function annotations and type hints: Welcome back to my favorite
Python programmers. In this video, we
are going to be looking at function annotations and type hints a subject much
easier than the Fibonacci. And I know, again, I reiterate this if you're
still not sure how it works, leave a comment or leaving a question anywhere
that you can. And I will try to answer
it as best as possible. So with that out of the way, let's now look at annotation. And tyto to annotate
means to indicate to the programmer what is the type of parameter that is
needed to this function. And also we can tell
that programmer what is the return value of the
function that we're calling. For example, in here, as I showed you when
we use 13.5 and then we are using that same thing right
here in the range. It just creates an error, but the user has no
idea for example, or the programmer that's
using your function. Because later on
you'll find that it's not only you that's using
functions like the Fibonacci. You can provide functions
much more complicated, obviously, than the Fibonacci to other programmers to use. Just like we use, for example, the print right here. We don't know how the print is written, but we just use it. Maybe you have your own
function later on in a company and then you provided to one of your colleagues. You need to indicate to the user of your function
what should be provided. If you have over the
Fibonacci in here, you have the end that
you need to provide. So you can see that the
documentation is not really clear in here on how
to use the Fibonacci. What I'm going to
do is I'm going to annotate to indicate that
this should be an integer. And the way I do this is by adding a column and typing in. Now when the user is typing in the
Fibonacci, look at that. Can you see the indication
right here if I hover unfilled and you can see that
the n should be an integer. Now sometimes IntellJ
does this by default after you run the
program several times, or if IntellJ recognizes what's happening
inside of the code, it sees the N being
used in a range. It immediately knows
that a way, there we go, this needs to be a, an integer. But as you can see, we
can unnotate like this. We can also indicate what
the return type is going to be if I do the following,
boom, there we go. It also indicates what the
return type is going to be. As I said, this was already
present before because Intelligent recognized
that the return type is going to be a integer. Either way, it just
flat out for us, but we can enforce it. Maybe we want some
different type, who knows. But now we can know that
when we're typing the code, the user is like, oh, it needs an integer. Okay, I will not use a float
and I'll just strike 14. All right. Click
run. Problem solved. Of course, this does not stop the user from actually
typing in a float. He can do it. But as you can see,
immediately they get a warning even before they run. It's expected type integer
got a float instead because we specified that we want
an integer not a float. It does not stop the
user from actually, or your fellow programmer from actually using a float
instead of an integer. But at least he will
have a warning and he will use the float
at his own risk. There we go. Pretty simple,
nothing too much to it. For example, we can look
at any function like this. If I hold down control
and go to print, maybe no, this is
not a good example. Let's see if we can
find some function, some function where we use it. I'll think of a function
in the meantime, I recommend that you check, maybe also not a good example. End also not a good example. In the meantime, I have a
challenge for you to annotate. Go back to the
multiplication function in one of our previous videos, in one of the older files, go to the multiplication
function and annotate the two argument
and tell them that it should be a float number. Indicate that the function
should return a float as well. And now try to annotate
the arguments and set a default value
to them as well. Meaning that you need to annotate the function,
set the function, or set the arguments
to be flawed, but at the same time, you will need to set a
default value to them. It's a small trick. You
can Google it if you want. It's not that hard, but
it's about the arrangement. Should you set the default value first or should you annotate
the argument first? That will be the trick in here. Pause the video right now
and go do the challenge. Hey, welcome back. How did you get on with that? I did actually find how you
can do something like this. For example, in here,
if you hover over the input and you hold
down control and then Q, then Q, wait, sometimes
it's not working. I hover over control, let's go. So it gives you the
definition in here, and as you can see, it has the annotation that it
does return a string. Now, I cannot seem
to find it in here. It's not done. I don't know why. Later on, there are
many examples of this. We will find one
somewhere down the line. But let's go back to our
multiplication in here. The multiplication
in the introduction to the functions in here, we want to indicate that
this should be a float, float, x y float, and the return type
will be float. Now, in here, answer is
equal to multiplication. If I'm typing in multiplication, what is it waiting for? However, over it, there we go, a float and float, okay? Even if I type in
2.6 for example. In here, there's no problem. When I write, click and I run, look at that,
everything works fine. We get a 12, but
it's just float. There we go. Now, what would we have to do in order to
also set a default value? Now, some of you might
have tried the following, but the ones that
have actually tested things out or found it on
the internet, there we go. We simply say this is how
we set the default values. Now I can simply not
provide anything actually, because these should be floats. We will have a 0.0 0.0 to
indicate that this is a float. Now if I run multiplication, I should get an answer of two. This is how you can annotate. And at the same time, I
think it's better if we just remove the spaces or does it not like that
missing white space. Okay, sorry. I apologize. There we go. We do need the spaces. So ladies and gentlemen, this annotation is
very important. I recommend that you
always annotate, even if I don't get in
the habit of annotating, because it's great
habit to have in programming and your
fellow programmers will love you for it. I hope you enjoyed. I'll see you in the next video
where we will be printing in style. I
will see you then.
84. 11. Printing with Style: Welcome back my fellow
Python developers. In this video, we are going
to be printing in style. So let's go ahead
and get started. First of all, I'm going to
provide you with a link. That link is actually a
Google search and that Google search is NC color code, some called NSI or C. You can select whatever
you want in here. If you go into the
anti escape codes on the Github or on Wikipedia
or I don't know, anywhere you want
for that matter. You can see that we
have certain sequences for specific colors that
we can use right here. Let me scroll down until
I find, for example, black foreground, color 30, bright black. You
can see in here. It's takes a little
bit of time to properly understand how
these equal sign work. You can also go on Wikipedia and read all about how
the NC codes work. But basically what we're
going to do is we're going to be using them directly using the assembly that
I found right here. Also we can find all the
foreground colors in here, Black, white, and so on
and so forth somewhere. I'm going to provide
you with it. But first of all, we need to create a new Python file that we are going to call the
color underscore print. These are our colors. Boom, There we go. You should find it somewhere below.
Somewhere around. Basically, what we said is
black is equal to this number, Red is equal to this number, and so on and so forth. We also have something
other than just the colors. We can first of all, reset. We can set it to bold, we can underline,
and we can reverse. How do we actually use these? Well, very simply,
we print out yellow. And then I can say, hi there, Drake, how you doing red? Click and run, and
look how cool that is. Now we can actually
print out in yellow. That's super cool. But keep in mind
that this is like dipping your pencil
into a specific color. Because now if I
try to print out, is this still yellow? If I try to print this out, you'll see that it stays yellow. That is because as I told you, it's like dipping your
brush into the color, and then you always paint
with the same color. But if we want to stop
it, what can we do? Well, we can use the
Reset, for example, in here I can say reset
on boom, there we go. It's simply resets.
Or even better, you can use the Reset
immediately on here. Boom. Look at that. And now it just does this following line in yellow and it resets
everything else. Let's try a few other things. We can also stack them
on top of each other. For example, in here
I can add bold. Now when I write
Click and I run, it's yellow and it's bald. If I duplicate,
are we still okay? In here I will also underline, look at that now, bald,
underlined, and yellow. Finally, I can also
print out reverse. This is getting out of
hand book. Look at that. It's reversed, bold
yellow, and underlined. I can, for example, change the color so I can
change it back to. Maybe can. Okay, there we go. We've used a single
quotation mark. We'll make it into a
special character. Right click and run.
And there we go. As you can see, this is
how we use our colors. It's not very hard. I'm going to, for one last time, show you something
that's interesting. First of all, I
will print out and just reverse everything
from here on out. We should have
everything normal, let's just check right click
and does not work like that. We need to actually
apply the reverse. We should do the reset. Reset. Let's check.
Okay, there we go. So the reset does work, and notice that it
creates an empty space. That's why we also have a small space in here because
we need to accommodate for the extra variable or the extra argument that
we provided in here. For example, what I can
do is the following. I can add a replacement
field and then that format. And then I can provide it
with manita for magnetat, how you call it, right click. And you can use a
replacement field in here. In this situation, using the replacement
field allows you to just have no spaces behind it. Obviously, we don't
need to use the format, we can simply use magneta like
this run and there we go, it works. I hope you enjoy it. I hope you understood how
this works before we move on. A small function that you
need to create in order to tie into the main theme that we're working
in this section. Create a function called
print with color. It should take two
string arguments, the text and the effect that
you would like to have, and use replacement fields to create a string with the color, then reset the color and
print out the string. Basically, the goal of this function is to
send in some text, send in the effect. And for that effect to only be applied to the sentence
that we want to print out. Meaning that we don't want any other sentence to be
affected, only this one. And I already showed you
how you can do this. Pass the video right now
and go to the challenge. Okay, welcome back. How did you get on with that? Right here at the top. I'm
going to print or define my print with color. It will take two arguments. The first one is the text, which is going to be an SDR, stands for string, and the effect which is also
going to be an SDR. And it will return non, meaning nothing in here. To do two dots again. The column, I'm going to have the output underscore string and it will be equal
to the following. I'm going to first of all have replacement
field for the effect, we start off with the effect. And then a replacement
field for the text, and finally a replacement
field with reset inside of it. And then we will print
out the output string. So the whole challenge was
in providing this reset, because we apply the effect we apply to the text and then
we actually reset it. And then we print out the
string because we don't really want anything printed
out now in here, I can, for example, let's say I want to
print with color. Hi there, Mr. Crowley. There we go. I don't know. Crowley. Crowley. Okay. Anyway, Mr.
Poppin. I don't know. And then we had a comma, and then we want it to
be bold, just an effect. And then in here,
I will print out I still bold when I right click
and I run look at that. Hi there, Mr. Poppin.
I am still bold. And this is because we've actually let me add
a reset in here, so we can clearly see
what's happening. Boom, there we go. So it's
only applied to poppins. Now, if you want, we could have gone
even the extra mile of adding a reset
right behind it. Now whatever we had previously
will not be applied. So now we can remove
the reset from here. And I'll right click
and run. There we go. We can see that it only
prints out with color with the exact effect
that we want in here. I can change this to
print with color. Maybe the function name is not really good
because print with color seems like you can
only print with color. But we can print, for example, with an underline right
click run. And there we go. I hope you enjoy it. I
think this is a fun program or a section or lesson
in this section. I hope you enjoyed
in the last video and probably the last one. Maybe we'll add more later on. But for now, the last one is
going to be the star arcs. And we're going to learn all
about that and how we can provide multiple arguments to a function or as
many as we want. I will see you then.
85. 12. Star args: Welcome back to my favorite
Python programmers, and in this video, we're going to be learning
about the star Args. Let's see, first of
all, what it does and realize that we've already
used it a lot of times before. Even in this video right
here in the color print, if you've noticed right here, we were using yellow. And then hi there, Drake.
What you're doing? Bold. And is there anything
yellow or whatever? We sometimes even added a reset in here and we could
also even add, let's say red for example. As you can see, we can add
many of these arguments. So now when I write click and I run, look at what happens. We reset and then we
make it red and then there's an underline
and so on and so forth. Print, just like the print
with color is a function. But notice that the print with color can only be
provided with two. If I try to add a comma and say red or reset or whatever,
look at what happens. I get an error if I
have not an error, just a very serious warning
where I hover over it. It tells me that
unexpected argument we're providing more
than the arguments that we've said there should be. We just said we need the
text and the effect. But in here, for some
reason we have more than that and it's totally
normal. How is this working? Well, if I hold down control and I go to
the print function, you'll see that we have
something very special in here called the star arcs. I will explain what
the self is later on when we start learning about object
oriented programming. As you can see, there
is the star arcs. There is also the separator. I'm not sure if
we've used before. I forget honestly the
end and the file. And we'll see the
file also in one of the upcoming sections where we have input outputs of files. But for now, the most important
part is the Star Arcs. What is the stars? Let's go back into our slides and explain
what are star orgs? So first of all, star orgs
are a special parameter that allows you to pass a variable number of
arguments to a function. Keep in mind a variable
number of arguments, meaning one argument, 23172100. When you use the star arc, all of the arguments passed to the function are
packed into a topple. We'll see what that
means later on. But something to keep in mind, if they're packed into a topple, it means that we can unpack them if we want or we
can iterate over them. You can access the
arguments in the topple by iterating over the
star or variable name. The star arc can be used to make your function more
flexible and reusable, just like the print
function where we can make it more
flexible if we want to print out one
word or ten words, or five sentences, or one
sentence for that matter. Or maybe we want to add some effects and so
on and so forth. The star arcs are
very important. They are very useful. Let's look at a
way of using them. I'm going to go back
into my code in here and create a new
Python file that's going to be called
the car. Hit enter. Now in here I'm going to define fruit,
underscore function. I'm going to have
the, by the way, it doesn't have to
be actually stars. We can call it star fruits, we can call it star, Michael. We can call it whatever we want, but it's the conventional
name of calling it stars. And in here we're going to say four arg stands for argument. In args, I'm going to
print out the arc. Then in here in the body of
my code, the fruit function. I'm going to have
apple, banana, cherry. Now if I write Click and I run look at that
apple, banana, cherry, I could add a
comment and say pineapple. There we go. We just prints
out pineapple that easily. Again, as I said in here, we could have called
this the fruits. Now in here we would fruits. This would be the fruit. There we go. It would
work exactly the same, but it's better to call it or it's the conventional way and will help other developers
read your code properly. Okay, if somebody
sees star fruits, they're like, what
are you doing? I can't you just use orgs
like a normal person. In this situation, maybe it's
better to have it as fruit, but I just called it be. You have the or, which
are the arguments. And then you have
the g, which is a argument if you want to
extract information from it. Before we move on, this is just a very simple lesson just so you know the
possibilities that we have. But I want to also
print out the type of G. I also want to print out this is the Args. Then I will use a replacement
field for the Args. Duplicate this, I'll
say the or, whatever. This is the star. Star Args. When I write, click and I run, this is what we get. First of all, the Args in itself is just a topple right here. You can see that the type of is, if we try to print out
as we've seen before, we know it's apple because of the parentheses that
we have around it. But if we check the star args, you'll see that
it's been unpacked. We have them printed out, unpacked. That's basically it. There's nothing
too much in here. I recommend you go
through this again if you need more
information, more examples. But I honestly think
that's enough. We will see real world
examples of using the star args later
on in our sections. But for now I have a bit of
eight challenge for you. And your challenge is
to sum up the squares. Create a function that takes
any number of integers. The function should
calculate and return the sum of the squares
of all the arguments. As an example, let's say we
have this function is called, or I call it the sum of squares. Then we provided with 1234. And the return value should
be one to the power 22 to 23 to the power 24 to
the power two equals 30, and we simply return 30. Pass the video right now
and go do the challenge. Okay, welcome back. So in here I will create
a new Python file. So going to file new
and I'm going to call this the sum of squares. Enter in here I'm going to
define the sum of squares, star args and then we will
have the square underscore sum equal zero and then four
R. I will go through, say, wait, I will say that the square underscore
sum is plus equals to the arc
times times two. This might be the part of
the challenge that you forgot how to make it square, or to the power of any
number for that matter. Then finally, when we
go through everything, we will return the
square sum in here. I'm going to say that the
returned underscore sum is equal to sum of squares,
and I will fight that. 1234 56k 54. And then we will print
out the returned sum. I will also have
another return sum which is equal to
the sum of squares, and it will be 12.3 This is just to
demonstrate that we can provide any number of
arguments that we want. So that when we write Click and we run, this is what we get. I'm going to add maybe ten in here just
for the fun of it. Look how dynamic and
flexible our functions have become with the star
arcs. I hope you enjoyed. I believe we are at the
end of this section. As I said, maybe we
will upgrade this. We are going to always be
constantly updating the course, so you'll be always able to go back to
it and check it out. But for now, I think this is the end of section number six. Congratulations on
making it to the end. You now know more than 97% of the world's
population in Python. And this is something to
be proud of, definitely. The next section we are
going to be looking at object oriented
programming in Python, which will really expand the
horizon of knowledge that, you know, I can't wait to see you there and I'll
see you in there. Well, I don't know when
you want to continue. I wanted to say like in a
few seconds, but who knows? Maybe you want to
continue on in a week. You want to take a break? You
deserve it. I will see you.
86. Section 7 - Object Oriented Programing | 1. OOP 101: Welcome back my favorite
Python developers to a brand new video and a brand new section
where we are going to be learning the most exciting
part of all of programming, not just Python, which is object oriented
programming with classes. I'm very excited
to teach you this because once you know object
oriented programming, you have officially expanded your horizon of understanding. Once you understand and fully comprehend object
oriented programming, there is no language in the world that you cannot learn
in a matter of two weeks. It will just be a matter of understanding the syntaxes
around certain languages, for example, Java or C
plus plus or I don't know, whatever you go to learn. If you know object oriented
programming, that's it. You are golden forever. So I want your full concentration,
your full attention. I will try to explain everything
as deeply as possible, but it also requires
attention from you. So let's go ahead and get
started. What is Oop? Oop stands for object
oriented programming. It is a programming
model that uses objects and their interactions
to design applications. We will expand on
that idea later on. It is a way to, of organizing
and structuring code that focuses on the objects in the program rather than just the functions
and procedures. So up until now, everything that we were working on were variables that we would apply to functions that we would use certain operations on. But now we have a
more organized, more structured approach to the objects that we
are going to be using. Almost everything is Python is an object with its
properties and methods. Every single time we
would create an integer, it would be an object every
single time we create a list, a string, a topple. These were all objects
that have been created, and you'll see what I mean
when we start actually creating our own classes
and objects in Python. Object oriented programming
is supported by several features
such as classes, objects, inheritance attributes,
et cetera, et cetera. And we will see all of these. Let's now look at
a class structure. A class is like a blueprint
of how the objects should look like and
what they can do, and the objects are
instances of that set class. If you've ever been
building a building, that sounded, if you ever
construct a building, if you ever have
a certain project that you need to create, you need to create
a blueprint of that project that then
you give to the engineer, and the engineer
follows that blueprint, and then he can add and change
and maybe expand on it. There is a certain blueprint that the engineer
needs to follow. The same thing holds
true with the class. The class is a blueprint of what the object
should look like. You don't have to use
every single thing an object has to offer. You don't have to use every single thing that
the class has to offer. But you need to adhere
to certain rules that this class or blueprint
provides you with. Every object that
you create from that class is called an
instance of a class. This is the class structure
that we would see. First of all, we
have the keyword. This keyword is used
to define a new class. Just like we have the DEF de, when we start
creating a function, class is used to
create a new class. Then we have the class name. The name of the class. And this starts with
an upper case letter. You've seen that when
we're creating variables, we need a lower case letter. When we're creating functions, we start with the lower case. When we're creating final names, we start with a lower case. Only when creating a class do we start with an upper case. This is what differentiates a
class from everything else, and I recommend that you
follow these eight rules. Next we have the class object that we created at the bottom, which is equal to the class
name with parentheses. And we'll see later
on how we can assign certain variables that will be assigned to attributes
inside of the class. Obviously inside of the class, we have the constructor, we have attributes,
we have methods, we have a lot of things. Without any further ado, let's go back into
Intelligent and start working on our classes. File new and new project. Once we hit New project. Yes, Python, We're going to call this object oriented
programming. And I will copy this. It's in the Python course. Object oriented programming. Yes, finish and this window. Okay, there we go. Now we have a new project. I hope you have it
up and running. As I always say,
your UI might be different based on the new
intelligent that comes out, but 99% of the things
should be the same. Let's go ahead and create
a new Python file. Let's click on this right here, a new Python file. And I will call this, oop, oop, Underscore Intro Okay,
we're back from the freeze. I will close down
the project and I will start creating my class. The class is we'll start
off with the keyword. I will call it new class. And the new class will
have simply x equals 23. And with spaces around, just like with functions, we need to leave out two spaces between the class and the
main code of our body, or the main body of
our code, I think. Okay, the main body of our code. In here, I'm going
to say we have the object new class and
it's equal to the new class. There we go, I will simply
print out object, new class x. Notice in here we did not provide the object
new class with an x. We did not set it as anything. We just said that object, new class is equal
to a new class. This is the instance of the
new class and it's an object. Notice now if I write
click and I run, I get 23 because the new class inside of it has this
property or attribute. Later on we will see the names of these small detailed things, has x equals 23. When we create an
instance of that class, it immediately receives
that property right here. Object of a class has something inside
of it that's called, that we can actually
check out and see. This is the structure that
we were talking about. This is the model, this is
the blueprint upon which we will start building
everything going for. But obviously, this is not
a real practical example, like having a class
that has x equals 23 only is not really
something that's, as I said, viable or practical. We're going to look
at a deeper example. But before we do
that, we need to learn something called
the constructor. Which is the underscore,
underscore in it, underscore, underscore,
and then self inside. This is a constructor
method which allows us to construct objects. For example, right now
with our new class, we were forced to
have x equals 23. But what if we wanted to have x be different for every
single object that we create? We would use a constructor. It's a special method
that is automatically called when an object of
the class is created. When you create a new class, the underscore,
underscore in it. When you create an object of a class or an
instance of a class, what I mean by that is when
you actually say object, new class equal to a new class, you're creating a object. When you create an object, this method is
automatically called. It is used to initialize
the objects attributes. And we'll see what those
are in just a few. But for example, x equals
23 is an attribute. The self parameter is a reference to the
object being created. So the self references the
actual object that we have. And additional arguments
can be added as needed, depending on the attributes
that the class should have. So we'll see if we
have two attributes, we will need two arguments. That's not necessarily
the rule here. We'll see that
there are different scenarios for this case. But yes arguments are sent to certain
attributes that we have. Finally, it's a convenient
way to ensure that all objects of a class have
a consistent initial state. And I will tell you what
that means in just a bit. But just know that this is the constructor.
It's very important. And the other very
important lesson is that the self references the
object that was created. Let's go look at an
example of that here, I'm going to comment all of
this out. Hey, welcome back. So don't you just
love when you have a very well working program and then it insists
that you update it, and then when you update it, it keeps freezing every
couple of minutes. Uh, uh, about that. I love it. That's why I never like
to update anything. That's why I still use Python 3.9 even though
there are updates, just like I found a stable
Python that works, that's it. I don't want to
upgrade to anything. As long as obviously what I'm teaching you
right now holds true. In the future, I'm going
to create a new class. And I commented everything
out by selecting all of it and hitting control
forward in here. I'm going to have
class person in here. I'm going to define the int. I always recommend that you use the autocomplete the tab to
autocomplete all of that. Just like we said before, this is a method we need
to use the def t in here. I'm going to add and
we'll have ph now. I'm going to have self name. Equal to name and self h equal to h as
you can see in here, The self, as I told you before, self is the parameter that
references the object itself. Which means that when I say, for example, in here, underscore Michael, and
this should be underscore, not stands for person, underscore Michael
equals person. Open up the parentheses and send in Michael with the age of 27. When in here, self means
underscore Michael, and we've provided
it with the name, which is Michael and
age which is 27. Now you might be thinking,
where's the self? Shouldn't it be right here? Well, the self is taken from the underscore Michael that now when we mention
underscore Michael, we know that its
name is name and its age is that
we've sent before. That's basically it.
This is the constructor. It allows us to
construct a method just to show you that it's
called automatically. When an object is created, I will print out a new
person just created. When I write click and
I run, look at that. A new person was created
in here as well. I'm going to print out, print out underscore Michael. Do name underscore Michael. Right click and run And look
at that Michael And 27. I hope you understood what
is happening in here. I know at first sight
it's like whoa. Oh, everything is new.
Everything is weird. But don't worry about it
as we take more example, as we do challenges, as we progress
throughout the course, it will become
easier and easier. So with that out of the way now your challenge is going to
be to create a new object. So create a new object
from the class person. That person should have
a name and an age. Of course, make it different than the one that
you currently have. Print both out on
separate lines, the name and the H. And
that's basically it. Now, once you do the challenge, you will fully appreciate
the power of having classes. So pose a video right now
and go do the challenge. Okay, welcome back. How did you get on with that? In here, underscore
someone will be equal to person and that person will be someone with the age of 42. So if I print out
underscore Michael name, sorry, underscore someone,
name, duplicate this age. When I write, Click and I run, look at that, another
new person was created. Look at that, the constructor was called and then
we have someone. And 42, I will comment
this out for now. And I will just
have it like this because now that
we've established that this works, it will work. As you can see, classes
are very important. It's a blueprint, a structure of a object, and
how it should work. Every object has its own name, has its own age, has they
share the same attributes? But each object has different values for
those attributes. So I hope you enjoy it. I hope you're not too confused. In the next video, we will look, or we will take a deeper look, into classes, instances,
and so on and so forth. So thanks so much for watching, and I'll see you
in a few seconds.
87. 2. Deeper Into Class: Welcome back my favorite Python programmers to a
brand new video. And in this one, we are
going to be delving a little bit deeper
into classes. Understanding instances,
constructors, the self, and more in Python. As I told you before, every type is a class. This is something
that you need to keep in mind as we go forward. Back in the person in here, I'm going to create
another method that I'm going to call deaf. My underscore height. The height as you can see, as soon as I type in
the left hand bracket, you'll see that the self
gets autocompleted. I'm going to provide it
with another argument which is going to be of type. I'm going to print
out the following. I'm going to say
replacement field, I'm going to have name is
replacement field self height. Or we can actually we have
to use height directly. And I'll tell you why
just a bit centimeters all unless you are in
the Imperial System. Again, we need more
place in here now. I'll just keep person
for now in here, what I'm going to do is
I will add a print and then I will say underscore
Michael height, height. Now I can provide it with 172. I'm not sure if that's
my height, honestly. Maybe it's more, they tell me it's definitely more Pero,
I've never measured it. Anyways, right now, we can
call a method on an instance. Python provides the
self automatically, but you can provide it
yourself if you want. For example, we can
do the following, person height and
then provide someone. And then 188, for example. When we say underscore
Michael might, just like with the constructor, the self is the underscore Michael and 172 is
set to my height. Now if I write, click and
I run, Boom. There we go. Michael is 172, centimeter
stall, someone is 188. You can see clearly
how myself or my Let me talk this right here so we can see
everything fully. You can see how someone is self and set the 188 centimeter. Pretty simple. Nothing
too much in here. Now I'm going to
issue you a bit of a challenge to add
another method. Create a method inside of our class that prints
out the person's weight. It should have an
integer argument, that is the weight. And add the way to one of our person objects and
display it properly. Pause the video right now
and go do the challenge. Welcome back. I hope
you tried your best. It's pretty simple. Just like we had my height, we're going to have
underscore weight. Oh my God, I cannot weight.
Is that how we write weight? I don't know,
weight, self weight. And I will print out, boom, what's the
problem in here? Method? My weight may be static. Okay, we'll see what they
want Later on in here, I will have a replacement
field and self name is replacement field
weight, 100 kilograms KG. Okay. So down here again, I'm going to add underscore Michael my weight and
I'm also not sure. I think it's 72 as well. Okay. And I will just add a print so that we can
separate Michael from someone. Right click, run,
and there we go. Michael is 72 K's Now let's go back right here
to my weight and my height. You'll notice that when I tried to use an attribute
which is right here, this is one of our attributes on the name, as the dot name. And by the way, I didn't
need to name it name. I could have named
it name of person, you know, I could have
called it whatever I wanted. But it's a convenient
way of calling the attributes the same as the arguments
that are being sent. So this is the attribute name, and this is the argument
that's setting, or that's the value that's
being given to the attribute. And we usually name
the attributes the same as the arguments that
are being given to us. You'll see it a lot in examples of creating
classes later on. But you can name it
whatever you want. Now notice in here we were
able to use self dot name, for example, when we said
underscore Michael height. I called my height but
the self was Michael. Self name. It looked for the name
attribute of the self. Wasp underscore Michael, it
found the name was Michael. That's how we were able to
print out Michael here. That's why we were
able to print out someone here is height. Now notice on the height, we don't have the
self dot height. That is because we
have height not as an art attribute but just as an argument inside of
my height function. It's not an attribute. Everything that's in
here is an attribute. Everything that's self
dot is an attribute. We will look deeper into
attributes in the next video, but you have to know
the following rules. Before we finish off, I want to show you another way
that we can set my weight. I'm going to scroll down
in here and I'm going to say underscore someone weight. You'll see that I
can add a weight. I'll just add 42.
Now that's too low. 142, someone is
getting out of shape. Right click and run. And there we go, 142 kilograms. But now look at what
I can do in here. I can say underscore someone
weight is equal to 100. What is happening in here? If I print out, I can say
a placement field in here. I'm going to say someone name has a change of weight. Now the mouth now they are replacement
field, someone weight. Interesting. Where
did that come from? How are we able to
access weight even though we don't have
anything in here? When I write, Click and
I run, look at that. Someone has a change
of weight now. They are 100 weird. Let's try this on Michael. Let's see if I try to print out underscore Michael weight. I get an error even though in here someone
does have weight. Right click and run. Person
object has no attribute. We wait, wait, wait. But someone has weight. How is that possible? Well, as you can see, if we try to force an attribute onto an
instance of a certain class, an attribute gets created, but only for that said instance. For example, for the
underscore Michael weight, there is no attribute weight. We haven't created one. There's no weight in
the actual class. But for P someone, when we said underscore someone, that weight a weight
was actually created. This shows the flexibility
of Python that allows you to actually create an attribute from inside
the body of your code. I know this might be a
little bit confusing, but later on you will see how it's just like everything
that we learned in Python. It might be confusing at first, it might be like this
doesn't make sense. But later on with more
and more examples, it will be more. So I hope you enjoyed it. I hope you understood what
is happening in here, even though it's
a bit confusing. In the next video, we are
going to look deeper into class attributes and maybe get a better idea of
what's happening. Thanks so much for
watching CUNFU.
88. 3. Deeper into class attribute: Welcome back my fellow
Python developers. In this video, we are going to take a deeper look into class. Attributes are classes, or I mean what are
attributes really? Attributes are
variables that hold the state or data of an object, just like we have the
name and the age. Those are states and data about the objects
that we're creating. They are also known as
fields or properties, and they are defined
within a class. If you ever see
somebody refer to attributes as fields
or properties, don't get scared, just know
that they can be used. They can have different names. An attribute can be
any type of variable, even another object of a
different class as we've seen. We can have strings, integers like the
name and the H, but the type of the
attribute could also be from a different
class entirely. When Python attributes
are defined within the constructor
method, which is the in it, and attributes can
be accessed and modified directly
using the notation, just like we saw when we were modifying the weight
of the person. And we'll delve deeper
into that later on. But back to the line
where we printed out the weight in here where we
had print Michael weight. It shows the dynamic nature of Python that allows you having two instances of the same class, but that end up having
different attributes. So let's go ahead and now create a different type of attribute
that we haven't seen yet, which is a class level attribute
at the top right here, just under person, I'm going to create a variable
which is the number. Let me just make the smaller
I feel clustrophobic. The number underscore of limbs
and I will set it as four. This is called a class
level attribute. Class level attribute number
of limbs. Four, right? We have four limbs, two
legs, two hands, whatever. Every single person
has these four limbs. Let's go ahead and
print all of that out. I'm going to comment
this for now. I will just have an
empty print in here. I'm going to print out the
following replacement field. I will have persons name. Okay, has replacement field. What's the problem in here? Has replacement field and
then person number of limps. I will duplicate this
to change right here, underscore Michael, Michael. Duplicate this. Someone, someone, Okay. If I right click and I run
look at the output that I get. First of all, at
the bottom in here I have some weird
thing because I did not say name on
Michael and someone, and this should be better. There we go. So as you can see, a class attribute means that all the instances and even
the class has that attribute. So person underscore, underscore name returns the
actual name of the class. You can even go to
the documentations to make sure that that
is exactly what it does. Because remember, person as
a class doesn't have a name, doesn't have the attribute name. It's given to the instances
through the constructor. Michael has the name,
someone has the name, and all of them have
the number of limbs. Because it's a class
level attribute, it's not specific
to any instance, it's to the class
level attribute. But we can also change the
class attribute in here. I'm going to do the following. I'm going to just
have a simple print. And then we will print
out changing into, when we change into an octopus, I will say person number of
limbs is now equal to eight. I will copy the code and
I will paste it in here. Now if I write Click and I
run, look at what I get. I'm changing into an octopus
access per number of limbs. And I change it to eight. As you can see when play and go around with the
class level attribute, I actually can change
it for everyone. What if I changed this
person number of limbs? What if I changed the
class level attribute? Not directly on the class notes. Right here, I accessed
person number of limbs. What if I did it to
a specific instance or object of that class? Well, you're going to
find out in just a bit because you have a challenge
to change the class level. So you'll need to change
the number of limbs, but this time only to
one of our instances, either to Michael or to
someone. Afterwards. Print out the number of
limbs for the other persons. Print it out, just
like we've done always for person class, for Michael and for someone. Are there any changes? And what does that mean? Pause the video right now
and go do the challenge. Okay, welcome back. How did you get on with that? I'm going to copy these lines. Put them in here from octopus, changing into an insect. And we're going to
have in here six. And I'm going to actually say changing Michael into an insect. And underscore Michael has
the number of limbs changed. We haven't changed it
for the actual class, we simply changed
it for an instance. What do you think is
going to happen if you haven't weren't able to do the
challenge for some reason? What do you think is
going to happen now? Will the number of limbs change for everyone or will
it just change for P? Underscore Michael, If I write Click and I run changing
into an octopus, we changed it on the
person everyone changed. But now when I'm
changing it on Michael, underscore Michael
number of limbs, you'll see that
person stays eight. Someone says stays eight, but Michael has six limbs. Now, as you can see, when we change a
class level attribute for a specific instance, only that instance is affected, the other instances, and even
the class stays the same. When we change it on a class, it changes for everyone. Again, we're delving deeper
and deeper into things. In the next video,
there is something that we will have
to watch out for, that I will tell you about. But for now, I hope you're understanding what's happening.
I hope you're enjoying. If you have any questions, leave them wherever you can. Ask me wherever I'm
available or the instructor, that's you and I will see you in the
next video where again, I told you we're going to see something that we need
to watch out for. Thanks so much for watching
See you and a few.
89. 4. Something To Watch Out For (__dict__): Welcome back my fellow
Python programmers. In this video,
we're going to look at something we
need to watch out for when developing our classes and working with attributes. Also looking at that thing that we need to watch out
for with the underscore. Underscore, underscore,
underscore. What is the underscore,
underscore, dict? Underscore, underscore.
Okay, I'm going to stop. Attribute is a dictionary that holds the attributes
of an object. Now, we have not yet
looked into dictionaries, but we will definitely be
looking at them later on. But for now, it just
is a key value pair. The dictionary is
a key value pair. And I'm going to explain more when you actually
see the output. So it allows you to
access and manipulate an object's attributes as if they were items in a dictionary. Again, don't be freaked out
by the words dictionary. We are going to be looking
extensively at dictionaries, but it's very important that
we look at the underscore, underscore dict right
now before we move on. Because we need to understand
what's happening under the hood of our workings. It's created automatically when an object is created and it contains a key value pair for each attribute
of the object. Where the key is the
attribute name and the value is the
attribute value. All that you need to
know for now about the dictionary is that it's
a key value pair list, sort of, Okay, let's
see it in action. And I will tell you
what the keys are, what the values are, and
what the dictionary is. If we go back into
our code in here, I'm going to actually
comment all of this out for now, boom. And then right here, where it, where is it? Where I have name. And then two, let's see, where we add weight. We have someone weight. Okay. I think in here
it's a good place to, for example, print it out. I'm going to print out underscore Michael,
underscore underscore dict. And I will duplicate this line and use someone underscore
underscore dict. If I right click and I run, let's look at the
output that we get. As you can see, as
I promised you, these are key value pairs. It's a list of key value pairs. The key is this right here on the left hand
side of the column. And it's the key which is the name of our
attribute, the name. Then we have the value of that attribute,
which is Michael. Then we have another key pair, which is the H. This is the
key, this is the value. Again, don't worry too much about what's
going on in here. Once we learn dictionaries, it will become
much, much easier. The only thing that
you do need to worry about is look at what
we have in here. On Michael, we have the
name and age, correct? Pretty simple, pretty
self explanatory. Nothing too much in here,
but if you look on someone, you have name, age,
and then wait. Hmm. Where did that
weight come from? Well, if you remember, when we were working with
Michael and someone on someone, we had this line
of code on line 34 where we actually added
weight equals 100. And what happened
when we did that? We were able to
access the attribute, but when we tried to
print it out for Michael, look at that, there
was an error. Remember that is because of
the flexibility of Python. We've already talked about it. When we had someone
weight equals 100, the attribute was
actually created. And you can look at all of the attributes using the
underscore underscore dict. Again, I recommend
that you open up the documentation right here. There we go. Python
standard library. Everything is available there. You can look for the
documentation of control. Underscore underscore ****. And for some reason
it's not available. Let's try **** mapping
type, Let's click on there. Okay. No, it's just talking
about the dictionaries. You can type in underscore, underscore, underscore,
Underscore. In Python, you can find all resources delving
much, much deeper. But basically, it
represents a dictionary or any mapping object
that is used to store attributes in an
object. There we go. That's everything
that you need to know about the dictionary. It shows you all of the attributes that
you've created so far for your objects. Thank you so much for
watching. I hope you enjoyed this was just to show you how we can create attributes out of thin air and very,
very flexibly. In the next video, we
are going to be delving deeper into methods
on our classes. So I'm excited to see you
there. See you in a few.
90. 5. Deeper Into Methods: Welcome back my favorite python programmers to a
brand new video. And in this one we're going to be delving deeper into methods. But before that I want to tell you about something
very important. That is the doc strings, for example, in the print. If I hover over the print, I don't know if it will give
me too much information. But there we go, You
can see it gives me the values that I
have to give it. It gives me the
various types that should be given to it
and it's return type. But right here you'll
see that we have this description of
the actual method. So it prints the values to a stream or to the
system, dot out whatever. By default, optional
keyword arguments ya. So it gives you information about what this actually does. What if we wanted to have the same thing for
the person in here? Just calls the base
class of the class when called exceptional
arguments, whatever. So it's not really
descriptive of what the person is or what we
need to provide it with. Instead, we can create
something called a dog string. Basically the dog string
are what's called three quotation marks right
here and we start typing in this is the person class, provide it with a name, a H. And you can
use two methods, underscore height and
my underscore weight. That's a very basic doc string. Obviously, later on
I'm going to show you, oh my god, how many
mistakes that I make. Anyway, I'm going to show you a more extensive way of
creating doc strings with better looking
attributes display and better method display. But for now, if I
hover over the person, look at what it gives me. This is a Person class provided with a name and age and
you can use two methods, my height and my weight. We've actually added a bit
of description to what this. I can also add
description to methods. For example, in actually strings for example
in here prints out the name and the height provided actually
doesn't actually set the attribute height. For example, now if I
hover over my height, there we go, prints out
the name of the height provided doesn't actually
get attribute height. Okay, so that is
the dock string. From now on, I'm going to try to use it as much as possible. So the doc string is a string that appears at the
top of the class, or a function, or a method. And it's used to provide
documentation or information about the
code that you are going to be using or any other programmer that takes over your code
is going to be using. But for now, let's
go deeper into method and the first thing
that I'm going to do is create a new Python
file and call it the Bitcoin underscore wallet. Once we have that, I'm
going to create a class, call it the Bitcoin wallets. And I will add a dog string
in here and it will be wallet to hold your Bitcoin in. There we go. Then I'm
going to define the in it. It will have a seed. Oh my God. It will have a seed. Underscore name and the balance. Then in here I'm
going to do name equal self balance
equals balance. I'm going to create a method that will allow us to deposit. Define the deposit. Open this up and
we're going to have the amount underscore
two, underscore add. Then we're going
to very important, we're going to the to add
is greater than zero, then we're going to self balance plus equal
the amount to add. Then we'll define the withdraw. The amount to subtract. Subtract, Is it
written incorrectly? Subtract. Oh my god. Subtract the amount
and withdraw. What's the matter with you?
Withdraw may be static. Okay, this warning always up. It will be resolved once we actually finish
typing everything. We want to make sure that the attract greater than
zero but still less than the self balance because
we need to make sure that the amount that we want to subtract is actually available. And here we need
to add the column, and then we're going to say self balance minus equals
the amount to subtract. Last but not least, we're going
to have the show balance. This will not take any
argument and simply print total amount of BDC replacement field self
balance. There we go. If you're still not with me
on the same level in here, take your time, pause the video, write everything out, make sure you understand
what is happening. These are very simple methods. In a very simple class, we simply have the name
that are two attributes, the name and the balance. We have three methods. The first method where we deposit and we provide
the amount to add. We make sure that
the amount to add is greater than zero and plus equals to the attribute
balance withdraw is the same, the amount to subtract. And then we make sure that the amount to subtract is
less than the total balance, but greater than zero and minus equals the
amount to subtract. And the final one is
simply a definition that allows us to
show the balance. Let's go ahead and create here. I'm going to create wallet
underscore Michael. As always, you don't
have to create Michael. You can create your own wallet, whatever your name is
on the other side. Create the wallet in your name, it's just going to
be called Michael. Now some of you that know a
lot about Bitcoin know that the seed name or seed phrase
shouldn't be that small. But just for the purposes
of this example, we're going to have 100 Bitcoin. Some of you are like
yes, 100 Bitcoins. And obviously we don't have
a cap on the 100 million. Let's not worry
about that for now. Let's just work on using, I just thought it would be a good example to have a wallet. All the examples that you
find on the Internet are always like bank account
and balance and whatever. Let's do something more fun. Let's not be centralized
now that we've created our Bitcoin wallet
with the seed named Michael NA balance or
initial balance of 100. I'm going to get
Michael wallet and show the balance when I
write Click and I run, there we go, Total
amount of BTC is 100. Now I'm going to
do something else. I'm going to get the wallet of Michael deposit and
I will deposit 122. Then I am going to
duplicate this line again. Hold down Shift Alt
and move it below. Now when I write, click
and run, there we go. Look at that. They were
added to each other. Let me copy these
past them in here. Add an extra space and withdraw instead of add and withdraw 30. Now when I write, click
on, boom, there we go. 192 for example. If I try to withdraw -130 look
at that, it doesn't work. We simply print out
the show balance. As you can see, everything
works exactly as we need it. Though there is a
slight problem. Obviously there are still
a lot of problems in here. But the main one that
we want to fix right now is that every single
time we make a change, we actually have to call the
show balance every time. I mean, it's very cumbersome. Let's say we make
like hundreds of deposits and hundreds
of transactions. We just have to make
sure that we always show the balance very good, not very efficient
use of our time. So a better use of our time
is giving you a challenge. And your challenge, Oh my God. And your challenge is going
to be all about transparency. So print out the balance
every time we make a withdrawal or we add money to our wallet,
and that's basically it. So you need to
find a way to show your balance every
single time you make a withdrawal
or you add money. So pass the video right now
and go do the challenge. Okay, welcome back.
This is something new. We've never actually
use the self to call a method that
is within the class, but it's very simple right
here on the deposit, after we add some money, we're going to say
self show balance. We are obviously going
to do the same in here. We will only show
balance when we actually do make a withdrawal or when we do actually
make a deposit. In here, I no longer
require these lines. There we go. Every
single time we make a deposit or a withdrawal, we should get this
printed out to us. For example, in here, if
I add or I remove 32, I should get 190 at the end. Everything works fine. Everything works good. As you can see, we
can call methods within other methods
that are in our class. I hope you enjoy it.
In the next video, we're going to be looking at the warnings that
we keep getting, telling us that we might
have a static method. Well, in the next video, we are going to be looking at static methods and create
our own deliberately, so can't wait to see you there. I see you, I will see
you in a few seconds.
91. 6. Static Methods: Welcome back my favorite
Python developers to a brand new video. In this one, we're going to be learning about static methods. What we want our static
methods to do is we want them to keep track of all the transactions happening. We will need a way
to keep track of the times and the
dates that we want. I'm going to go back
to the slide later on. For now, let's go
back into our code and let's set things up. First of all, in order to
use the time and the date, we need to import two
important libraries. We will need to import the date, time, and we'll need
to import PY tz. Don't worry, you're going to see some freak code right now, but don't get too frustrated
or anxious about it. The code will be
explained and will be self evident once it's working. Now for some of you the YZ
might not be very apparent. You need to right click. And in show context, you should see somewhere in
here where it tells you to install or download or
whatever. Just click on that. If it doesn't work immediately, close down intelligent,
open it back up. You should be able to
download or install PYTZ. No. The next thing
we want to do is whenever we create a
new Bitcoin wallet, we want to create a
list of transactions. So self dot transaction
transaction Z list. This will be a list of
all of the transactions, whether they are depositing
or removing or withdrawing, I mean a list of transactions. And notice we don't really
need to give it any argument. We just can set it as an empty list just
to initialize it. Now, the next thing is
whenever we make a deposit, we need to provide it with the following information
in the deposit. After we show the balance, we want to do the following or actually as a rule of thumb, it's better to do it in here before we actually
show the balance. I'm going to do self
transaction list append. I'm simply appending it and now look at what's
going to happen. Again, I told you,
don't freak out. I will open up the parentheses and write pytZuTc localize. Then open it up again. I'm still inside of the
localized daytime daytime UTC. Now, scary. I know. Then come on the amount to add
what is happening in here. Unexpected argument. All right? What is the issue? This one is closed, This
one is closed as well. Okay. I think in here an extra one and then
in here I have to. Okay. There we go. Okay. Okay.
Okay. So this one is in here. So we're providing
where appending our transaction
lists with a couple, and that couple
has two elements. The first element is
going to be the time and the second element is
going to be the date. Let's go ahead and
test this one out. I'm going to create a method in here that's going to show all of
our transactions. So I'm going to define show underscore
transaction and then I'm going to say
four date amount in self transaction list. The amount if it's greater than if amount is
greater than zero. I'm going to set the trans
underscore type to be equal to deposit else we're going to set the transaction type to
be equal to withdraw. I'm going to do amount
multiplied equal minus one. Again, this will
make sense later on, but for now we just have to
do it. You have to trust me. Then finally in here, I'm
going to say that I want to print out a
replacement field. Inside of the replacement field, I'm going to have amount and then another replacement field where I will have the
transaction type, Then another replacement field or on another replacement field and that replacement field will be open up, these parentheses. Local time was
replacement field date as time zone does not always give you the
suggestions, but there we go. As you can see, we've
created all of this. Let's go ahead and
try and test it out. I'm going to duplicate these deposits and
make like 2223565. Then, I'm going to do
to underscore Michael. Oh, it's wallet. I forgot we're
working with wallets now. In here I'll just
print out line, show transactions, and
add an extra line. As you can see, we've
made these deposits. These deposits are being appended every single
time we make a deposit. It appends to the
transaction list with the following weird code. And the amount to add Apple
that has these two items. Let's see what this looks
and then we will break it down when I write Click and
I run look at what we get. Actually, I'll just
Doug it on the bottom. We've made all of the addition
of the transactions and we made one withdrawal
as well in here, 122, deposit on 2020, 3669, date at 01:22 48 plus this
weird number plus 00. This is the Greenwich time. And then finally, we have the
local time which was 42248. So, this is my local time time that I am currently
in right now. Now, if this number is
just too big for you, what you can do is you can do the following amount in here. We can add two dots and six when I right click and
I run. There we go. It just adds a few spaces on here to the left
hand side so that we, as you can see, first
of all right here, the date time zone just gives you the date in my
current time zone plus three. Then in here on the UTC. Now it simply provides the
time that is right now, but we need to use P YZ module. We will delve deeper
into all of these, but for now just
know that it simply provides you with the
time that the transaction was made of and the amount
of money that was deposited. So we extract or we unpack
the couple that's coming in of the date and the amount
or into the date variable. Into the amount variable, and then we print
all of that out. The next thing we
want to do is we want to actually not have to write this entire
thing in here every single time we
want to make an append, because writing
this is cumbersome, especially if you're trying
to append it multiple times. A better thing to
do is to actually have something called a static method that
would handle this. What is a static method? A static method is a
method that belongs to a class rather than an
instance of the class. When we were working
before in the person, for example, where we had my, my height was applied to the actual instances to underscore Michael to
underscore someone. But now we have a method that is static that belongs
to the actual class, not to individual instances. It can be called on the class itself rather than on an
instance of the class. Even though we can call
any method on the class, we have to provide it with the instance on which
we want to make the transactions or the
modifications of whatever. For example, when we did
person my height inside, we had to provide the self
on which we were working. But now with static methods we can actually
simply apply it to, for example, the Bitcoin wallet. And we're going to see
that in just a bit. A static method is defined by using the at static
method decorator. I will show you what the
decorator is in just a bit. It does not take the
self, obviously, because it's applied
to the actual class. Let's go ahead and create
a static method that will return the current
time back in our code. In here at the top, even before or at the
top above the it. Because this is a static, we're going to do the following. I'm going to say at static. Static, okay, it will
not show up right now. Wait. Let's first of all
define underscore current. Underscore time, I will remove self from here and I should see static method
being suggested to me. I will tell you about
why we're using underscores later
on in this section, but for now I'm
going to say that UTC underscore time is
equal to date time, date time UTC, exactly what
we were using in here. And then I will return
yz localize UTC time. There we go. Now we
are actually returning this long line and we can
remove it. Boom. There we go. And move this as well. In here I can simply
type in Bitcoin wallet, do the current
time. There we go. So we've made it
much, much simpler. Look, we are actually calling the current time on the class. That's what makes
this a static method. When I write click and
I run, there we go, I get the same output but now with a slightly
different time. I hope you understood
the freak part. Is this right here, what's the UTC time date And oh
my God, so confusing. Don't worry, these are
standard things that are used. We will later delve
deeper into them. But as always, these are things that we need
to understand. On the surface, of course, if you are more interested into understanding
these right now, you can always go to
W three schools or just search for whatever
you want on Google. But now with all of
this out of the way, the next thing to do is obviously to also
show the withdrawals, because currently we
only have the deposits. Your challenge is going
to be to append again. Whenever we withdraw
from our wallet. We want to append the
transaction list as well. Make sure to call the
current time static method. Also provide the
amount to st subtract, which should be sent negatively. Very important part
of the challenge. Pause the video right now
and go do the challenge. Okay, welcome back. So how did you get on with that once we do this challenge, this line of code right
here which is the multiplied by minus one
will make a lot more sense. First of all, on the withdrawal, just like we did before. We're going to append
our transaction. We're going to have
selfsactlistpend. We are going to have the
Bitcoin wallet current time, the amount to subtract. And as I said, it's going to be
minus, save that. Now if I scroll down and
let's make a few withdrawals and move them in between the
deposits and withdrawals. And actually, I will make
something like this and I will remove 243. I think that's too
much. 120? Yeah, I think we're removing
too much in here. Let me deposit like
50. I don't know. And let's just remove five and
then we will withdraw 200. Okay. So I think
that's good if I right click and I
run, let's see. All right, there we go. So let's see if they match
what we've done. So 122 deposit, 50 deposit, withdraw is five, withdraw. 120 deposit, 235
deposit and withdraw. So everything matches up
exactly as we did before. I think this is pretty
self explanatory, there is not much to it, but what we finally need to explain is this amount
multiplied by minus one. So we've created the
show transaction that would handle transactions, whether they are withdrawals, whether they are deposits. If the amount that we have
from the transaction list, let's say it's right here. Okay. On the deposit, if we get this item in
the transaction list, we will check for
the amount to add. If it's positive, it
means it was a deposit. If it's negative, because notice the amount to subtract needs
to be greater than zero. So we send in the negative one. It's an LS, which means
the amount is negative, it will be a withdrawal. And we will multiply it by minus one in order to get
a cleaner output. So instead of seeing in here
-234 or -65 or whatever, I -120 and minus five
doesn't really look neat. It doesn't look good and it
also doesn't make any sense. -120 withdrawn. Mm, You know, 120 with drawn, there we go, makes
a lot more sense. So that's why we have
this amount multiplied by minus one and we display
all of that out. So thanks so much for watching.
I hope you enjoyed it. I hope it was not too confusing, especially with these
lines of code right here. I know something new,
something crazy. Everything that we're
learning is new. But that's why I
told you the section requires a lot of
your concentration. Thanks so much for watching.
I hope you enjoyed. In the next video,
we're going to be looking at attribute
accessibility and understanding why
this static method has an underscore behind it. So I will see you in a few.
92. 7. Attribute Accessibility: Welcome back to my favorite
Python developers. In this video, we're going to be learning about attribute
accessibility. But before we do that, we need to look at a
glaring problem that we have in our program that might have not been
apparent before. I'm going to scroll down
in my code in here and I'm going to remove all of these
deposits and withdrawals. Or maybe I'll just comment them out just to keep
them on the side. Let's just leave
them. It's okay. We can add whatever
we want later on. What I'm going to do
is I'm going to say that wallet Michael deposit 100 and then I'm going to say wallet Michael withdraw 150. So why is this a big problem? Well, if I write Click and
I run, look at what I get, the total amount of
BTC is 50, sorry, is 200 and then the total
amount of BTC is 50. But if you look at
the transactions, you can see that all that
we did was we deposited 100 on this date and then we
withdrew 150 on this date. So the issue in here is if somebody looks at
your bank statements or at your Bitcoin statements, at your deposits
and withdrawals, they're going to see that you've deposited 100 and then
you withdrew 150. So how is that possible? Something doesn't add up and obviously you're
thinking right now, well, that's because we had
an initial balance of 100. But it does not show right here. It does not show on
our transactions. And it should show, we should be able to see what
happened initially, what was the initial balance. So this is going to be
a challenge for you to deposit the initial deposit. So make sure that as soon
as we create a wallet, we have a transaction added
to the transaction list. If you want to go and conquer
this challenge on your own, it's not an easy challenge. You will have to think very creatively about
what you should do, but try your best, test it out, see what
works, see what doesn't. And then if you need the hint inside of the Inet constructor, transaction list should not be initialized as empty currently. If you go into the code, you'll see that the
transactions list is initialized as two square
brackets facing each other, meaning that there's
nothing inside. It's an empty list, but we don't want
it to be empty. We would rather have
the current time, again using the static
method that we created last time with the balance sent
as the first element. The first element
should be a couple, with the first item
in that couple being the current time and the second item
being the balance. Just like we did with any normal deposit positive
video right now. And go do the challenge. Okay, welcome back. How did you get on with that? It's not an easy challenge
for those of you that tried to do it without any
hints. I congratulate you. It's very important to
try without any hints. The ones that saw the hint
and were able to do it. Also very good if you
weren't able to do it. I want you to focus
very correctly. So the whole idea is
that we replicate what we are doing right here on
the transaction list append. We want to start off with the transactions list
not being empty, but with the Bitcoin walled current time
and the amount to add. I will simply copy this
and paste it here. But instead of the
amount to add, I'm going to have the balance. This should make sense. If I write, Click and
I run, look at that. 100 deposited on this date, 100 deposited on this date, and 150 withdrawn on this date. Now if somebody sees your Bitcoin statement or looks at the block chain to be more
precise, they see, okay. So there was a 100 deposit. 100 deposit, and then you
withdrew 150. All right. Then 50 is the remaining
balance that this person has. So great, congratulations. But there is still a
massive problem here that we have not addressed or we
have not tried to break. If I do the following, I say, wallet underscore Michael
balance is equal to 360, then wallet Michael
show balance, look at what we get. Where is it? Where is it? Uh huh. Look at that right here. Just before we show
the transactions, I actually have 360. And if I duplicate
this code and try to run it after the transactions,
it's even worse. Because look at that. I made a 100 deposit. Another 100 deposit, I
withdrew 150 and somehow I came up with 360
Bitcoins At the end crazy, this is definitely not something that we
would like to have. We don't want people to easily be able to access our
balance and change it. The even worst part is
that I can make this -360 which is like
completely breaking everything that we know about
money, about everything. So obviously we don't
want this to happen. We need to make sure
that nobody can access these attributes
through any instance. And to do that, we need
to make a small change. And that is adding an underscore behind
the balance right here. Once that's done, obviously you can see that there are
a lot of places that we need to make changes before
I go and do the changes. For every single one, I will double click on the
balance and hit Control. Or you'll see that now all of the balances everywhere
are selected. Now I will simply copy this, paste it in here, and
make an underscore. Now I can select, replace all, But there are a few of these
that I want to exclude. Like this one and this one. This one for example. This one. This one. This one. That's
it. There we go. Now I can replace all,
boom, there we go. And all of them
have an underscore. You might be thinking, well,
how does this help us? Well, first of all, I'm
going to remove these. We forgot to exclude
these ones and well now let's say somebody is trying to access our
balance and modify. He'll do like Michael, and then he will
type in balance. He doesn't see that we have
the underscore balance. Let's stride this again. He tries to do
underscore balance. He thinks he's smart, but again, nothing shows up. Now obviously, if he does this, he does eventually
break our code. This is not a perfect solution. There we go. So if I right
click and I run, there we go. You can see that they
still can access. But at least this underscore has the ability to
hide our attributes. Now some of you might be
laughing at this point. I've had students
that make fun of this strategy of hiding because, yeah, this is not going to
stop like some amazing hacker. Obviously, there are
other checks and balances at this point
that can be used by a developer to make sure that a person or a malicious person
does not access the code. But this is a quick, easy fix that hides the functions or the
attributes that you have. The sensitive
attributes that you don't want other
people accessing. Such as the underscore
behind the current time. So I promised you I would tell you what this does,
and there we go. You can see that current
time we have the underscore. It has the same meaning as
the one behind the balance. For example, you can start
adding multiple underscores. Three underscores the person
that's trying to access. How many underscores
does this person have? Crazy? So there we go.
I hope you enjoy it. I hope you understood the importance of
having an underscore. From now on, we will
probably have many of our sensitive attributes all having underscores behind them. Thanks so much for watching.
I hope you enjoy it. And I will see you in the
next video where we will be importing and manipulating data using getters and setters. Maybe I'm not sure still at this point I'm playing
around with the course, checking what's good,
checking what's not. Thanks so much for
watching and I'll see you in the next video.
93. 8. Importing Manipulating Data: Welcome back my fellow
Python programmers. In this video, we're
going to be delving deeper and seeing
the real power of object oriented
programming by having multiple files communicate
with each other. The first thing we need to do is we need to create a new project, which is going to be
our game in the file, I'm going to go to new project, I'm going to go to next. And in here I'm going to
call this the oop game. And make sure to select
the proper file. And then hit Finish. Yes, this window. There we go. The first thing
I'm going to do is create a new Python file. That's going to be the player. Hit Enter, there we go. Make sure to call
this file Player with a small P because
we're going to create a class inside that has a big P which is the player. But we're also
going to make sure to type in object in here. Now if you don't type in object, it will not cause any errors, it will not cause any
problems in your code. But we need to get
used to seeing this. This is called inheritance. And we're going to look
closer at inheritance in later videos but for now we just want to inherit
player from object. But to tell you the truth, every single class
that we've created so far inherits from
the class object. This is not necessary, but I just wanted
to show you how inheritance will look like and just start working with it. You can even check out the
object class by holding down control and clicking on this class to go to
the class object. And this is the base class
of the class hierarchy. When called it except no
argument, et cetera, et cetera. You can see functions such
as the in it are inside of this class and other functions or other methods that we use. Let's close this down and
let's go back to the player. In here, I'm going to
create the constructor, define the It, and the player
will simply have a name. Then we're going
to have self name and it's going to be equal to the name lives equals to three. The player will
have three lives. Self level is going
to be equal to one, and self Xp will
be equal to zero. There we go with
that out of the way. Now that we have established
this class player, I'm going to create
another Python file that I'm going to call the main. And this will be the
main body of our code. We're not going to write any classes in this
file right here, but we are going to be importing the classes
from outside. Let me show you what
I mean by that. First of all, I'm
going to import, I've imported the file player. That's why it was very
important to make sure that the file name is with a
small P or lower case P and the class name is with a big P. I'm importing the file here, then I'm going to say
player, underscore Michael. And again, you can name your
player whatever you want. You don't have to
name him Michael. And we're going to say, I'm going to send in
Michael. There we go. What we do in here
from the file, I'm getting the class player
and sending in Michael which is going to be
the name which is required on the
constructor in here. Then I'm going to
say that I want to print out player name. To do then player Michael duplicate this player level. And this is not work unless
I say, because I believe. Can you allow me to do this? Yes, player level. There we go. And I'm going to remove the art because level is an
integer, it's a number. That's why we will need
a replacement field. If I write click, there we go. Player name is Michael, Player level is one. We've established a few things. But we can also change
the way that we're importing the file by
typing in the following. Instead of importing
just player, I can do the following. I can say from player import. Player. Now, I don't need to
type this every single time, I want to create a new player. I can just say player Michael. Now what we can do
is we can start creating massive classes
in separate files, and then simply executing
them in the main file, which will save us
a lot of space. Next, we want to modify
some of our attributes. In here, I'm going to
print out the following. I'm going to have a
star multiplied by 50. I'm going to print out
player lives left to dots, replacement field, then
player Michael lives. Then I'm going to say my player Michael
lives minus equal one. And then I will duplicate this, line control D, shift Alt. Move it down so that we
can see what is happening when I right click and
boom, there we go. Players lives left is three, then players lives left is two. But the issue with this is
that if I do this many times, so if I select these two lines or three lines
and duplicate a few times, you probably know what's going
to happen at this point. If I write, click
and I run, boom, look at that, I get
lives minus two. Obviously not something
that we want, something that we
would like to fix. Something that we could fix, for example, with an
underscore behind lives, which will deter the person that's trying to
access our lives. But there is a much better
way of handling this, and that way is through
using property. So in Python, unlike
other languages, you have the ability to access attributes without
getters or setters. In other languages,
this is frowned upon. But in Python, you are considered to be a
responsible adult. So they think, okay, even though the user has
access to the lives, they will not go through it. But sometimes the user
does go through it, he does use the
attributes directly. They are not responsible adults, so we do have a way
to mitigate this. That way is going to
be through properties, and getters, and setters. First of all, let's understand
what is a property. Properties are a way to define methods that are accessed
like attributes. So similar to the way that we're accessing lives right now, we can create methods that can allow us to access them
the way we access lives. They allow you to define a
method that is invoked when an attribute is accessed and another method that is invoked
when an attribute is set. When I say invoked, I mean called upon or you
call a function but a method, but in this situation it's
called invoke, called. We can have two methods, one to access the attribute
and one to set the attribute. Attribute that is accessed
is called a getter. And an attribute that is
set is called a setter. Properties are defined using the built in property function. We're going to see
how that works. And they are assigned to a class attribute using
the ad property decorator, Similar to the static decorator
that we've seen before. We also have the at
property decorator for example, in our game. It would make sense for us to create a setter and a getter for our lives because
we never want to add too many lives
to our player, nor do we want to
have negative lives. A setter in this
case would allow us to set the values properly. So the first thing we need
to make sure of is that our value for the setter and the cater,
which is the lives, is slightly hidden back in
our code on the player, the lives will have an
underscore behind it, so it's slightly hidden. And again, as I told you, this is not a way of preventing someone from
accessing the attribute. This merely hides
it from appearing easily to the user or
other programmers. The next thing we
need to do is we need to create the setters. And the getters in here, I'm going to define underscore get underscore lives and it will just have the
self and we will return self, underscore lives. Then we are also going to
define the underscore set. Underscore lives in here. We're going to have the
self and also the lives. Now I can say self dot
underscore lives is equal. To lives. Now we need
to create the property. After we've made these
two definitions in here, I'm going to say that lives
just lives, Not underscore. Lives. Just lives is
equal to property. The property has this
parentheses and we will get lives and set lives. Now you'll notice in here
that we have a warning. And this is a serious warning because we don't want to
have these parentheses, we need to remove them. Now, why do we sometimes have these parentheses and why
do we sometimes don't? As a rule of thumb, whenever
you have these parentheses, it means that you're actually
calling the function. In this situation, we're
not calling the function, we are setting the property. We're saying that whenever
the user tries to use lives, they are actually using the get lives and
the set lives if they're trying to receive the information they're
using the get lives. If they are trying to set the information they are
using the set lives, the setter and the getter. Let's go ahead and test it out. If we look back in our code, you'll see that we
don't have an error, even though we change this from a lives to
an underscore lives. And we've seen that
when we do this, this should not work any longer. But it does in the main code, we still have
everything working. If I write click and I run, look at that, everything
works perfectly fine. But there are extra steps being taken in order
to get to this point. And I'm going to
prove it to you. First of all, I'm going
to remove a few of these. I will just have these
three lines in here. I'm going to say that
I want to print out, hey, I'm in the getter. Hey I'm D setter. When I write click and I run, look at what I get in here. First of all, let's
go line by line. When I said print
player lives left, player Michael or player
underscore Michael lives. First of all, when I arrived at this point and I said lives, we went into the player class, we scrolled down and
we found that lives as a property and we're trying
to get the information. So we called upon the get
lives and that's how we got, hey, I'm getting
I'm in the getter. We retrieved the information, we sent it back,
and we were able to print out player
lives left three. Then we had this
player underscore Michael dot lives minus equal
one. What happened here? Well, what happened is
we have getter setter. And then we had the getter and placed the player lives left to this line of code
belongs or has these two. But the dot lives
needed these two lines. So it first needed
the getter and then it needed the
setter. Why is that? Well, because we first of all needed to get that information. When we set player
underscore Michael Lives, we got the information, We went to the getter, we
received the information. And then we did a
minus equal one and we sent it to the
setter right here. Okay. I know it's
a bit confusing. This is not an easy concept
to wrap your head around. I even remember
having trouble with this myself years ago when I started learning about
decors and the setters. I'm like, okay, this doesn't make sense. How does that work? When you do it once, twice, three times, you
finally get used to it. It's very important to know
how these things work. That's why I had these prints
for debugging purposes, but for now I'm going to comment them out with a
control forward slash. But keep in mind that this
works perfectly fine if I try to duplicate
these several times. As you can see, it all
works perfectly fine. Now we do have a warning
here, cannot be set. It's a bit confused, because even though our
code is still the same, it's a bit confused. But no worries, everything
works perfectly fine. But there's still
the issue of having minus one and minus two lives and even zero. The
player should be that. At this point, I have a challenge for you
to set the setter. Make sure that the lives
never goes below zero. Test it out in your main,
that's basically it. Where should you
make sure of this? You should make sure of
this in the set lives, in the actual setter
that we've created. Pause the video right now
and go do the challenge. Okay, welcome back. As you can see in here, we have the definition
of our setter. What I'm going to
do is I'm going to, first of all, this one I'm
going to move to the bottom. Actually, I'm just
going to delete it. I don't want it anymore in here. I'm going to say if the lives that we're trying to
set underscore lives, if lives is greater than zero, then I'm going to set the lives strictly
greater than zero. I mean, you could
say greater than or equal to because at zero
you're actually dead. But we haven't
accounted for that. But that's okay for now. We're just going to
say greater than else, meaning that if we are
definitely in the negative, I'm going to print
out lives cannot be negative and self
lives equal zero. There we go. Notice
that I said self live. I'm referring to lives that is right here.
I'm setting it. If you go back into
our main and right click and we run,
look at what we get. Lives cannot be negative, lives cannot be negative twice. When we tried to do
minus one and minus two, this did not work and we
received a printout that lives cannot go below zero. The last thing I
want to do in here, even though this
video is very long, thank you for bearing with me. And that is the underscore
underscore SDR. So if we wanted to print out everything about our
player in a cohesive way, like the name, and the
lives, and the level, and everything with it, We
can do something like this. You can create the
underscore underscore SDR. Boom, in here we can
return whatever we want. I'm going to return name to
dots, replacement field. I'm going to show you something that's a little bit weird. I'm going to say
zero name weird, isn't it? It's going
to make sense. Then I'm going to
say lives to dots, zero lives replacement field. Then I'm going to say level to dots replacement
field zero level. And then P two dots
replacement field zero Xp. And then at the end I'm going
to say format and self. This is simply the
replacement for the self. The self is replaced in here and then we're
using the dot name. The zero represents the self
in here every single time. This is just a small short cut, something that I
wanted to show you. If we cover the SDR, we can go through
the documentation. It's basically whenever you
want to print something out. Now for example, instead
of saying all of these things or instead of trying to print out the name and then the level on
separate lines, I can simply do the following. Print out player Michael. Boom. And look at the output. Okay, what is the problem? Two lives, no attribute XP. What is it called? Xp, small
p that I write in Big XP. I apologize. Let's run it again. Okay, no issues.
So there you go. Name lives, level, and XP. Ladies and gentlemen,
I hope you enjoyed, I hope this was
not too confusing. Sorry for the long video, but these are very
important stuff that we are delving into. I'm going to see you
in the next video. Hopefully, if your brain
hasn't exploded so far, where we will be looking at data management and structuring, which means we are going
to delve deeper into properties and data attributes. I will see you in
the next video.
94. 9. Data Management and Structure: Welcome back my favorite
Python developers. In this video, we're going
to be looking deeper into data management and structuring
as you've seen before. Now we have a set lives and a get lives that will allow
us to avoid certain problems. I'm going to remove
these for now because we already know
that everything works. But again, as we've said, this does not prevent somebody
from doing the following. Doing underscore
lives, for example, and setting it to -13 Then
if we print out Michael, there we go, we'll see
that lives is -13 Again, this is a problem, but only for someone looking to really break into your code. When you see an underscore while trying to
get an attribute, you should realize that the developer put it
there to protect it. And if used directly, could cause problems somewhere
down the line in the code. But now let's look at
creating more properties for our player to make the
class more dynamic. And when I say let's
create some properties, I mean you should start creating some properties by getting
and setting the XP. Create a getter and
a setter for the XP. For the setter of the XP, we want to increase the level
every time XP goes to 100. Make sure to add them to the property and test
it out in your main. Okay, pause the video right
now and go do the challenge. Okay, welcome back. So how did you get on with that? So the first thing
we need to do is back in the player, let
me close this down. The XP should become
underscore XP. We need to protect
our experience. And then I'm going
to scroll down, right here to the bottom, and define the underscore, underscore P and return self Xp. Then I'm going to define
the underscore set. Underscore xp, it will
only have the self, the xp, underscore two. Underscore, I'm going to have self xp plus equals
to the xp two. Now if self dot underscore
xp is greater than 100 than self self level set level plus equal one and the self x
will be minus equal 100. Now why do we do the
minus equal 100? Because obviously we
want to remove 100 P. Then in here we're
going to do the following. I'm going to say that X P, big X and Big are equal to
property on the property. Underscore get X P.
Underscore set P. There we go. We've created the getter and the
setter for our XP. The first one simply returns
the XP that we have. The second one takes
in an argument, which is the XP to add, and adds it to the
self underscore XP. Now you'll notice that
these two setters are slightly different, whereas in here, we would
simply set the underscore lives to be equal to the lives directly
that's being sent. While in here, the
self underscore XP is done with a plus
equals to the XP. To add that is the two different ways that
we can create a setter. For example, in here, player
underscore Michael lives, we would have minus equal one. We would actually get
the property and then remove minus one from it and then send it
to the set lives, and it would set the
underscore lives to that. But now we're going to do things a little
bit differently. First of all, let me, I
will comment these out, everything in here,
I will comment it out and move
it to the bottom. Then in here I'm going
to start removing Xp. I'm going to say
that Michael Xp. And actually know what
having a big X is, a bit cumbersome in here, small x, let's just
make it small Xp. I think it's better in here. We'll have Xp equal 20, then we will print out Michael. And then we'll have a print. If I click and notice
in here I didn't say plus equals or minus equals,
like I did with the lives. I said it's equal. Now this 20 will
be sent to the XP. To add, it will be added
to the underscore P, and then we are
going to check if the underscore XP is greater than 100. So
that we can level up. When I write click and
I let me add this right here to the right hand
side. There we go. We can see first of all, player underscore
Michael x equals 20. I don't need to
print this one out, I just want to make
everything makes sense. There we go, p 20. Now if I duplicate
this three times, maybe add a little bit
more. So in here 32. We'll duplicate this again. In here I will add 88. If we write click and we run, look at what we get. As you can see, first of all, we added the 20. Here's the 20. We added another 20, so now we have 40. We added 32, we have 72. Then when we added 88, we had the following 72 plus 88, boom, 160, And then -100 we leveled up and we
are left with 60. So everything seems to be working correctly for
us. So there we go. Ladies and gentlemen, we've
created the XP as well, and we've seen a different
way of creating the setter. Let's now look at
a different way of actually creating the
getter and the setter. If I go back in here, I want to obviously make
sure that the level is also protected
with an underscore. And then I'm going to
scroll down in here and I'm going to
say at property, this is the property decorator
that I told you before. I'm going to define
the level self, which will return self
underscore level in here. I'm going to say
at level setter, I'm creating the setter. Define level level in here. I'm going to say self
underscore level is equal to the level. The reason I'm seeing equal in here and
not plus equals is because of the way we are increasing the level and
here with a plus equals one, similar to how we did it
with the lives as well. Okay, hope that makes sense. It is a little bit
different in here. Now notice these
are the same get which returns the and for
the set are the same. Remember when we were trying
to access a property like P, we would simply say
player Michael, and automatically
the program would know whether our Python would know whether we should be using the getter and the setter. The same principle
holds true here. We have the same name for
our setter and getter, but they do different
things based on what is provided to them or
how they are used. Now if we go back
into the main code, right click and run, we should have the same output if we try to do the following. Michael level equal
to six, for example, print out Michael, right click, run, and there we go. So we are actually setting it directly and we don't
need the print here. There we go. Level is six. So we're actually setting it. We haven't increased it. We've actually set it. Ladies and gentlemen, I hope
you enjoyed this video. Sorry if that clap
was very loud. And in the next video, we are going to be looking at inheritance and how it works, and why it works, and why it's needed and why
it's so important. And we are going to continue building the project
that we have currently. And you'll see at the
end that this project can really be expanded upon. We're just doing
surface level things to understand
everything properly, but you can always
increase your knowledge, expand the projects,
expand on everything. Thank you so much
for watching and I will see you in
the next video.
95. 10. Inheritance 101: Welcome back my fellow
Python programmers. In this video, we're going to
be looking at inheritance, which is a very important part of understanding object
oriented programming. You're going to see
inheritance all the time. Now in this video, we're not going to be
creating inheritance, We're going to be understanding inheritance and
setting everything up. And in the next video, we'll be creating the
subclasses and so on. But for now, what is
Inheritance? And Python? It's a mechanism that
allows a class to inherit properties and methods
from a parent class. If you create certain
properties, certain methods, certain attributes in
your initial class, you can then give them to a child or a subclass
down the line. So you can inherit, see, that's where
the word comes from. A child class is defined
by inheriting from a parent class using the child
class parent class syntax. Similar to the way we
created the player. If you remember, we said in between two parentheses that we inherit from object class. The same holds true
when working with any child class parent
class relationship. The child class can also define a new properties
and methods, or even override the ones that they inherited
from the parent class. So let's say the child
inherits from the, from the parent class. They inherit the family name, for example, but they can
override the name, right? They can have another name. This is just a very
simple example. They can inherit the money, but they can override or add methods on the way that
they spend that money. That's just a broad example. We will see a lot more
of this later on. Inheritance allows
for code reuse and reduces the amount
of code duplication. So let's say you
have a class where, I don't know, maybe later on we'll see an
example in just a bit. So let's say you have a
class that is a mammal, for example, that a
mammal gives birth. What the normal way that
a mammal gives birth? Instead of having to create the method for cats to
give birth, For example, you can make the cat a child of the mammal class and
then inherit the birth. That example is so weird, but I will continue at this point to invested
In this example, the cat inherits the birth
method from the mammal class. And now instead of
recreating the code, instead of duplicating
the code for the cat, we can simply inherit from
the main mammal class. And the parent class is also known as the superclass
or base class. You'll see those
two definitions for a parent class in
a lot of places. And the child class
is also known as the subclass or
the derived class. With that out of the way, let's look at a common
structure for inheritance. So for example, we
start with an animal. That animal would have a
name and a species, correct? The dog would still have a name and his
species would be dog. The cat would have a name, a species and the breed. Now obviously dogs
also have a breed. But just for the sake
of this example, let's imagine that only cats
in this case would have a breed and notice how
they inherit from animal. Then we have horses and birds. They all have names and
they all have species. But then the cat
also has a breed. So now we can create a
subclass of the cat. For example, the Siamese cat, which has a name, a
species, its own breed. And the Ames has a special method in it
that allows it to jump, which is different than
all of the other ones. Again, for the sake
of this example, I know horses can jump. Also, we have the Bengal cat, which can meow very strongly. Then you have the
Sphinx that can attack. As you can see, this is a
structure of inheritance where cats inherit from animals
and CM is Bengal, and Sphinx inherit from the cat. And the horses would also have their own subclasses
and so on and so forth. I hope you understood
how this works. If you haven't, I
recommend that you go through the slides again. Once you do you have a
challenge in front of you. You'll need to create an enemy. First of all, create
a new Python file, call it the enemy. Again, lower case inside. Create the enemy class with the following
attributes They should have name, health, and lives. These are the attributes a method take Damage
with an argument, damage taken, Remove the
damage taken from the health. And if the health
goes below zero, take a life away and print everything using a
underscore underscore SDR. Pause the video right now
and go do the challenge. Welcome back. How did
you get on with that? I'm going to go
into new and create a new Python file that I'm
going to call the enemy. Inside of the enemy, I'm going
to define a class enemy. It's not going to
inherit from anything. An enemy is not
written like that. There we go. Is that
how you read enemy? Yeah, I think so.
Then we're going to define the in the in it
is going to have name. We're just going to
set a default value for the name just in case somebody doesn't
provide us with it. The health equals zero. Let me remove this in here. The health equals zero
and lives equal to one. Then I'm going to say self
dot name equals to name. Self health equals to health. Self lives equal to
lives. There we go. Next we're going to
define underscore damage, and we're going to have the
damage underscore taken. First of all, we're
going to calculate the remaining health
underscore health is equal to self health
minus damage taken. And we're going to check if the remaining health is
greater than or equal to zero, which means we're still alive. We're going to say
that self health is equal to remaining health, and we'll simply print out
a small thing in here. Damage two dots, replacement
field, damage taken. Then we are going to say health remaining two dots,
replacement field. And we're going to
say self health. There we go. If you want, you can even add back in here. Maybe that would be nice
to back, I don't know. We'll see how the output looks and we'll adjust accordingly. But then we need to also check if the health is less than zero, then self lives minus equal one. And I'm going to define an
SDR where I will return the my name replacement
field zero. Name, Come on, lives
replacement field zero. Maybe I should have
said the health first. I don't know health two dots,
replacement field zero. Health format self. I'll just hit Tab or hit Enter. Hit Enter in here so that
we can see everything. And hit two tabs or two enters. And there we go, we have the class enemy which has the
constructor takes damage, takes away a life, and also has the STR back in our main right here at the
top from enemy import enemy. What do we have in
here? I will actually comment all of this out as well. I will comment up
until this point. Boom. Just keep Michael in there just in
case we need him. At some point, I'm
going to create a enemy underscore monster and I'm going to say that it's
equal to the enemy. The enemy will be just a
generic monster for now. Of course you can have fun
with this health, I believe. What is it on the
constructor? Can I see? The health is going to be 12 and lives will
just keep it at one. For now, I will print
out the monster. Let's take a, there we go. We know what? Let's just take
eight damage here. And a print would be nice
when I right click and I run. Let's look at the
output that I get. All right, does it look good? Health remaining. What's
this enemy monster? Okay, I think we
don't need this. Since we're printing, we can
print it out at the end. So right click and run.
Let's see what we get. Hm, take damage
health remaining. Let me check again.
What did I do in here? It seems like it's
a little bit wanky. We haven't, we didn't go
into a new line as well. Let's try this output right now. Health remaining zero, you can see right
here, health zero. Maybe because we're exactly while it's greater
than or equal to zero, okay, so maybe we should
take nine lives in here. What happens? All
right, there we go. So health zero or lives is zero. And we didn't even print out
that the damage taking and the health remaining because
we don't have it right here. I'm not sure about
this output, honestly. You know what, I'm just
going to remove these. I think it's not that good. Maybe add like a
pipeline. There we go. Looks a lot better with the
pipeline, in my opinion. As you can see, the
enemy monster lives one. And we forgot to
add the two dots. Small things that we
need to adjust in here. And I'm just showing you the
process of creating things. Sometimes you need to go back, just look at what's happened,
what we can improve. Notice that we still
have a problem in here where the
health was not taken. Because when we removed it, we did not adjust it. We still have health, but
we don't have any lives. Again, this is not
a perfect program. What you can do, you
can, for example, set the self health
to be equal to zero. If you want that, maybe
it makes more sense. But again, you have
to also take into consideration that when
you remove a life, do you want to take back
the entire original health? Do you want to
store that health? Maybe somewhere in some kind
of variable on the enemy. So a lot of questions, a lot of small
minute details that need to be handled
before this is a actual working enemy
class for an actual game. But for now, this is what we have and
we'll stick with it. Thank you so much for watching. In the next video, we are
going to be creating Orcs. We're going to be creating succo buses as
subclasses to our enemy. And they are going to
have their own methods and a change in the properties. Thanks so much for watching. I hope you enjoy it and I will
see you in the next video.
96. 11. Creating Subclasses: Welcome back, my favorite
Python programmers. In this video, we're
going to be creating subclasses and overloading
some functions. Let's go ahead and get started and understand what
all of this is about. First of all, we're going
to create a subclass of the enemy instead of just
having generic enemies. We're actually going to
be having an Orc in here. I'm going to go ahead and
create a new class Orc. And it's going to inherit
from enemy as you can see, just like we did previously I believe with player right here. So player inherits from object, the Orc inherits from the enemy. I'm simply going to
add a pass in here. So the pass will allow us to
not write any code because I don't want to define anything
in the Orc just yet. I simply wanted to inherit
from the enemy which will allow me now to go into
the main and from enemy, import the enemy class
and also import the Orc. Now I'm going to
scroll down and right here where we're creating
the enemy monster. I'm also going to create Orc. Or actually you know what,
we'll create it here. Orc one is equal to Orc. The Orcs name is
going to be Saga. There will be 16.2 You'll notice that we
have health and lives. For the health and lives and
then we'll print out or one. If I read click, I
look at what I get. Right here, I have the
enemy name which is Saga with lives two
with health 16. But what is happening or the enemy you can see right here doesn't have
anything in it. Even though there is
nothing in the Or class, we are still able
to create an object of the type Or and printed
out with the format. Why? Because Orc inherits
from enemy in here. When we say Or saga 162, basically what happens is we
create the Or object and it takes all of that information
and sends it to the in it. But what if Orc had a
constructor of its own? That's going to be a
challenge for you. You need to create
another Orc in Maine, Create another Orc
and call him Zc, and add a health of 22. And I don't know how many lives. Maybe you can just
leave the lives open. Keep the live. There we go. Sometimes I need to
review my challenges. Keep lives field empty to
take the default value. Now create an in It
or a constructor in the Orc class
and keep it empty. Meaning simply pass, add a pass. Pause the video
right now and go do the challenge. Welcome back. How did you get on with that? The first element of the
challenge was creating another Orc with a health
of 22 in the main. In here I will create Orc two. And I'll say that Orc two is Orc 0.22 And then I will print out or two when I write
click and I run there, name Azog lives one health 22. Now the not so useful thing here is that we could have made these Orcs just enemies and it would have been
the same outcome. We obviously want to have more functionalities
to the subclass that we just created. Let's go back into
the enemy's file. And under the Or, I'm going to define underscore,
underscore in it. And I will simply
have a pass in here. And let's just have one attribute or one
parameter and save that. Now notice immediately we
have something weird with the It call to it for
superclass is missed. Some things in here
are a bit weird. But if you go back into
the main and we run, so even before we run, you can obviously
see that there are problems in here because
of all of the warnings. But let's try to right click and run anyway and see what we get. There we go. We got an error. We were expecting that, kind of So you can see
everything was working well until we got to
creating the Orc right here. We can see that on line 18, we can even click in here. And. Line orc equal or in. It takes two
positional arguments, but four were given. The it in here takes
the self and the name, but we provided it with 44. First one will be the object, which would be the self, and then the name,
the health and the lives immediate error there. What's the problem? This is because Python no longer finds the init method of
the enemy class and can only use the
one given to the Orc. Which if we go back in here, does not have enough
attributes waiting, or enough arguments to be taken in order to pass it
on to attributes. There are two ways of
mitigating this problem. Or to be more precise in calling the constructor of
the enemy that's at the top. The first one is
doing the following. In here I will simply
type an enemy.in. It hit Tab, and you'll see that in here
I can pass in the Self. I can pass in the name and say that name is equal to name. And then I can say
lives is equal to one. And these are just
default values and health is equal to 20. And let me just make
this slightly bigger. We can see now that everything
will be passed to the top. But do we still
have any warnings? Nope, this should be good. So back in the main when
I write click and I run, I still have some
errors in here, but when I write
click and I run, oops, there we go. We still got an error in here. And the reason for
that is we still have not provided the
arguments right here on the, in it of the. To make this event even simpler, what I can do is I can
say super in here. This is the more common way of using this
instead of the self. We can just remove it. And now we can use it like this. If we go back into the
main right click run, we still have an error. What we basically do
in here is we need to remove these two and
remove this one. And now when I write Click
and I run, look at that. I've created Shaga and
I've created Azoc. And they have a health
of 20 and lives of one. And obviously, if
you want to have real control over the amount of health and the
amount of lives, you will need to
add them right here on the arguments that are
presented to the int. But that's basically how
inheritance would work. How we call the superclass, always use super
with parentheses. Using the enemy in here is
not the most common way. Now let's go ahead and create a method that's only
inside of the Or. In here, I will define a method. That's going to be the
charge, define charge. It's going to simply
take the self and we are going to print out in
here replacement field. We're going to have self
name charged, you charged. There we go back in Maine. Let's go ahead and print out a few stars in here
multiplied by 50. And we're going to have Orc one and duplicate this
and we'll Or two charge. When I write click and there
we go, Sag. Very nice. Now for the last example, let's try something a
little bit different. I'm going to create enemy one. Just a random enemy
which is going to be off of the class enemy. We're not going to
send in anything. Then I'm going to say
enemy one charge. Look at that when I try
to right click and run. Look at that trace
back enemy charge. The attribute enemy has no attribute charge or method charge or anything
regarding charge. Charge cannot be used
by an enemy object. That is a very important
distinction to make. We cannot go upwards. When it comes to the hierarchy, we can only go downwards. The enemy cannot use the charge, the Or can use the charge, and the Orc can take
damage as well. In here, if I try to
say Or one take damage, there we go, you can see that I can actually damage the Orc. And when I write Click, I still have this
issue right here. I will comment these out. Boom, there we go.
Damage, take health. And the health remaining is 18. Can use methods from the
class that I've inherited, meaning like Orc
inherited from enemy. Or can use methods
that are in the enemy. But the enemy in the enemy cannot use
methods from the class. Or thanks so much for
watching. I hope you enjoy it. In the next video, we
are going to look at dynamic method
implementation where we will delve deeper into how all of this method using works. I will see you in the next one.
97. 12. Dynamic Method Implementation: Welcome back to my favorite
Python developers. In this video, we
are going to be looking at dynamic
method implementation. And also meaning
that we're going to be changing behaviors
of certain methods. But before we get started, we're going to start
off this video with a challenge where you will need to create a
subclass of your own. Create a pycobus class
which is going to obviously be inheriting
from the enemy class, meaning that the sucobus is
going to be a child of enemy. Add a constructor to it and call the superclass
imported from the, meaning imported to the main. And create a saccopus
object called astarroth. That's basically it. Pause the video
right now and go do the challenge. Welcome back. How did you get on with that? It shouldn't be too
hard, basically. In here we're just creating
a class which is going to be the succabus it's going to be inheriting from
the enemy inside. We're going to define the in it. It's simply going
to have a name. And then we're going
to do inside of super, we can also do the following. We can say succobusaseelf in it. Then we will say name
is equal to name lives is equal to three and
health is equal to ten. There we go. Now that
we have the succabus, let's go back into
the main in here. I will print out
just an empty line, and I will copy this,
paste it in here. And then just have
another empty line. And I will do the same. And this because I want to start differentiating between
different sections of our code because the
output is starting to get very long in here, I'm going to have
the succobusecup. First of all, of course, we
need to import it succobus. Then in here, I'm going
to say that I have the succobus one
equal to succobus. There we go. I said
it's going to be astro. Is it asosaroth? Yes, exactly. I'm going to print
out sacobuswe. Let's see what we
get when I write. Click and I run.
Boom. There we go. Enemy name Astaroth
lives three health. Then in here I will get
Saco one damage and we'll take damage of three and we
will print out succopus one. Let me copy this and do it a
few more times. There we go. And then we'll change
three and we'll also have like I think nine and
then nine and then maybe, I don't know, another nine. I guess If I right click and
I run look at what I get, take damage three
health remaining seven and then I go lives three, health seven, lives two, health zero, health
zero, health zero. But this is because we had this protection
right here where we said the health zero
whenever the health remaining is not greater
than or equal to seven. If we try to do this again, do I still have it in
the copy in the base? There we go. I'll change this to another nine
and another nine. When I write Click and
I run, look at that, I am getting lives negative. Even lives at zero is
not something good. This is a problem in our game. We need to modify a little bit in our
class back in the enemy. I'm going to create an extra attribute in here
that's going to be the self that is underscore. That is going to first of
all be equal to false. This variable is going to change whenever we die to a true. Now in the take damage
I'm going to add an extra thing in here
inside the, elsewhere. I'm going to check if self
lives is greater than zero, then I'm going to
print out, okay. No, thank you. I'm going to
print out the following. Self dot name is dead, else. I'm going to print out name. If lives is still
greater than zero, we're going to print
out self name, life. Then in here we're going to
say that in here we'll say dead is equal to, there we go. Now in here when I write
Click and I run, there we go. Astroth, last life,
last life is dead. Is dead. But I'm still
getting lives minus one. So that issue has
not been fixed yet. So if we go back into the
enemy under the take damage, what I'll say in here is I'm going to add
an extra condition. If not underscore dead. Okay, we need the self is dead. If we're not dead, we will be taking
all of the damage. And else in here, this level mind the
indentation else, print out self dot name is already dead. There we go. So he's already dead. Don't continue like
destroying him. You should know by this point that the enemy is already dead. And I ran the wrong file. So when I right click and I
run in here, there we go. Lost a life, lost a
life, lost a life, and then he is already dead. So the lives, we are
no longer dying. And you'll notice
that this was much easier than going into
every single A class. Let's say changing
individual ones. Now we can simply change one, take damage, and it's
applied to everyone. For example, the succopus now prints out the name of the scecabus and
says that it's that, look how efficient our code is. Instead of having a take damage on each and every single class, and then having to change that, making sure that
all of it works. We can do it in the main class, in the upper class, in the parent class. Note also that we have
these weird symbols, these discs and
arrows pointing down, and this disc and an
arrow pointing up. And we're going to talk about
that in the next video when we talk about overriding
subclass methods. I will see you in a few seconds.
98. 13. Overriding Subclass Methods: Welcome back to my favorite
Python developers. In this video, we are
going to be looking at overriding subclass methods and understanding what
these weird rings with arrows are all about. First thing we want to
do is we want to give our Orcs the ability to actually block an
incoming attack. So if I scroll down
right here to the Orcs, I'm going to define
the method blocked. That's just going
to have the self, I will import random module, so you should know what the random module is at this point. And I'm going to say if random rand 1-9 is greater
than or equal to six, then I'm going to print
out the following. I'm going to say self dot
name has locked an attack. I'm also going to return true, just like we learned in the previous section
where methods or functions we used to
call them functions because they were
outside of the class. But people use it
interchangeably, so don't worry about that. You can call them classes, you can call them functions. But as a rule of thumb, when it's inside of a
class, it's a method. When it's on the outside
the window code, then it's a function. Just like functions,
methods inside of classes can also
return the value. This returns true. If we did actually block else, we will return false and
add an extra space in here. Now that we have this blocked
message, sorry, method, I'm going to go
back into Maine and I'm going to comment
everything out in here because we want to keep this clean and fresh
with nothing inside. I want one thing in here. I just want one which
is going to be, there we go, I will print out this Orc when I
write, click and I run. There we go, Enemy Name
Saga Lives One Health 20. Now what I'm going to do is I'm going to create
the following. I'm going to say Or Do is dead, while the Or is not dead, I'm going to say Or Damage
and the damage will be one. Now if I write, click
and boom, there we go. We keep on taking damage
until Saga is dead. But we don't want sage die. Well, at least we don't want
him to die this quickly. We want him to use the new ability that we've
provided, which is the block. And it's going to be
a challenge for you. You will need to
help out an Orc. Make sure that Snagaor Saga, or whatever you've
called your Orc, to be honest with you,
only takes damage when he has not
blocked an attack. A small hint, even though
I haven't written it. This should happen
inside of the whileloop past the video right now
and go do the challenge. Okay, welcome back. How did you get on with that? This is pretty simple. Inside of the Y loop, I'm going to say if
not or blocked, boom. Or do take damage. Now if I write click and I run, I should see the following,
boom, there we go. Damage taken on
damage taken one, Then Saga has blocked, taken damage,
damage take damage. And then we blocked, and then
we took a bit of damage, and then we blocked until
finally Saga is debt. As you can see, some of
the attacks were blocked. Now this is all good, but we don't want this to be
happening on the outside, meaning in the main. We want this behavior
to be changing while we are still
inside of our classes. In order to do that, we need to override the
take damage method in the Orc and make it
do something a little bit different back in our enemies right here,
inside of the Or. I will scroll down
and I'm going to create or define the
underscore damage. And you'll see immediately
I get suggestions at. I hit Tab and I will print out, or let's just make it capitals, this take damage is
in the Orc, not. Enemy. Now we know that if we
take damage that we're taking damage inside of the Orc. Notice when I define
this take damage, I got this circle with
an arrow pointing up. If I hover over it, it says that overrides method and enemy. If I go to the top
on the take damage, you'll see that I also have this disc with a
white arrow pointing down saying that is
over ridden in the Orc. So basically what this means, overwritten means
it was written or modified in a different
way in a subclass. This is when we have an arrow
pointing down right here, we can see that the in it is overridden in the Orc and the sacabuscae on the enemy. We have the in it, on the
saccobus, we have an in it. So it was overridden
in two places. And we can also see right here is a subclass by Orc
and the succopus, it shows us a subclass, It shows us when something was over ridden, et
cetera, et cetera. Now the question
is why do we have a arrow with a red
pointing upwards? Doesn't that mean that the underscore underscore
STR was overridden? Yes, it overrides
method in object. Remember, every single
class that we create inherits from object.
Hold down control. Click on underscore
underscore STR and it's not taking me, no usage found. Okay, very nice. Let's try and find
the object ourselves. Object, hold down control, go to object and scroll down until we find underscore
underscore STR. Will it find it faster
if I do this? No. In the built ins underscore
underscore SDR. There we go. So as you can see now the SDR was overridden
from the object, but we don't even have to say that enemy
inherits from object, every single class will
always inherit from object. All right, so I hope you
understood what is going on and here I hope you understood
why we have these discs. It's pretty simple.
Nothing too complicated. Now if we go back into Maine and we right click and we run. Uh huh, Interesting
look at that. So we seem to have
created an infinite loop. So if I pause this and
I go back to the top, you'll see that
Haga has blocked. So Haga is blocking
some of the attacks, but we keep taking damage
without end. Why is that? Well, because now
when we take damage, when we call the take damage, it's actually calling the
take damage that's on the Orc because we're
using it on an Orc object. So it's using the take
damage on that Orc. And you'll see that take
damage on the Orc simply prints this out and
doesn't do anything else. We need to modify this in our take damage so that it actually cause take
damage in the enemy. I'm going to say, if not what's called
blocked, there we go. I'm going to say super. Open parentheses,
Orca take damage, Excuse me, I apologize. Take damage because
we're calling the super and we need to
send in the damage taken. Damage taken equals
damage taken. Now in the main, I don't need this line anymore. I can remove it, shift, and when I write click and
I run, boom, there we go. You can see that we have
all of these attacks, or some of these
attacks being blocked. And it's happening all
inside of the class, instead of having to do
these on the outside. As you can see, some of the attacks are being
blocked, which is great. Our game is really
coming into play. But let's say at this
point we want to change all of our attributes and make them protected or private. Well, what we can do is go into the enemy and have to
change every single one. Or we can do this in
a much better way. I can, for example,
double click on name, hold down control R, and then change this to underscore name everywhere
that it appears. And I can hit Replace, all but some of them you
might not want to replace. So you can click on this
one and exclude this one. And these should be changed. You can, What else do we have? I think this one you can
exclude. And this one. And notice that I
have the exclude being pressed right here. This one as well. This
makes our life much easier. Now, hit the replace, all boom, there we go. Everything was replaced. You close it with the small x right here at the
top. And look at that. Now, name is protected except
for an unexpected argument. Oh, we should have excluded
these ones as well. I apologize. Now you can
see that it's much better. Let's try to run it and see
if it works. Yes, it does. Now I'm going to give
you a small challenge. It's not an official challenge, but make sure that
everything in here is also protected from
outside interference with a small underscore. Thanks so much for watching.
I hope you enjoyed. In the next video,
we are going to be looking at nested subclasses, meaning it's going
to be subclasses inside of other subclasses. Wow, I will see you
in a few seconds.
99. 14. Nested Subclass: Welcome back my fellow
Python programmers. In this video, we're going to be learning about
nested subclasses. Or to be more precise, we're going to learn
about creating subclasses out of
other subclasses. So let's go ahead
and get started. First of all, we're going to
create a subclass of the Or. In here we have the enemies,
we have the scopus, but both of these Orcs and succobuses
inherit from the enemy. Now we're going to
create the Orc, we're going to create a class, which is the uruk. Hi, that's how it's
written. I've Googled it. I'm going to send in the Orc inside of the, inside of the Or. I'm going to define the in it. And we're going to have a name, that name is going to be sent. I'm going to say super open
up the parentheses in boom. And just say that name is
equal to name. There we go. I'm also going to say that
self health is equal to 140. What's the problem
typo in the word k? All right. Nobody knows
how to write properly. Chi, it's a made up name. One thing to keep in mind is that when you call the super, it's not the original
it that is called, meaning the original
in, in the enemy. It's the it in the
Or class right here. This in it is being called
when I do the super. And you can even double check by hovering over this in it and you'll see that it is
overridden in Ork. There we go. This is where it's
been overwritten. Next, we would like to override the take damage as well to
make it not as bad for the Or In here I will
define the take damage. I'm also going to
make sure to call the super class and take damage. But the only difference is
that I'm going to send in the damage taken
divide divided by two. Meaning that, remember
the divide did make sure to remove any thing
after the floating point. The take damage is
basically divided by two and then sent
to the take damage. So with that out of the way, we can even trace,
even look at that. Now this is interesting. Look now on the take
damage on the Orc, we have two arrows,
1.1 pointing down. The down means that
this stake damage was overwritten in the Ork, while the pointing
up says that it overrides a method
from the enemy. And if you're ever confused on where this stake damage
is being overwritten, hold down control and
click on Take Damage. Yes. Okay, that's
not what I wanted. Let's see. Holding the control and clicking on
the actual method. A wait. You can
click on the disc. There we go. This is the
take damage that's been overwritten inside of
the Orc. Very nice. Now, where does this override the take damage on the enemy? And we can also use
this going down and look because we
have two overrides. However, over this,
it's overridden in the Or and the Or there. Go to the Or, Or go to the Or. As you can see,
we're overriding. Now, there is a challenge
that you need to do, which is to help Sauron out. If you don't know
what Lord Ring is, you're probably thinking what the hell is happening
in these lessons. But Sauron is the evil man behind all of these shenanigans, the orchis and whatever, even though that's
not Lord based. But anyway, anyways, in the
main import the Orch class, create a new chi, call him blurts and
print out the object. Apply some damage to him, but please don't kill him yet, because we need to print
out the objects again. Pass the video right now
and go do the challenge. Okay, welcome back. How did you get on with that? In the main, I will add a and add the chi
in here as well. I'm going to comment these lines out because
I want to keep it clean. We're testing the chi. I will say one is equal to the. The name is going to be lets. I will print out the one, then K take damage,
12, print out. If I write click and I run, first of all, the
enemy name alerts lives one health, 140. Remember it doesn't just take the health as it is
normally in here. We actually want to
have a health of 140. This is very important. Then in here we
print out the orch, sorry, we've already done that. Then we take damage. So you can see that we've taken the damage damage taking
six health remaining 134. And then we print
out and this is the output that we get notice, even though the damage
should have been 12, we only removed six. That is because as
we said before, we take the damage, we divide divided by two
and send it to the top. The damage taken, that's
called on the archive, is divided by two sent
to the damage taken. Boom, it's sent right here. We call whatever at the top. And notice that we also
have the chance to block. This is another
unofficial challenge for you to try and block, or try to do multiple attacks. Try to damage the alerts
further more times, and see if he can actually
block some of these attacks. That would be very
interesting to know. There we go, He
actually blocked it, and you can see that his
health stayed the same. Thank you so much for
watching. I hope you enjoyed. In the next video,
we're going to be learning about polymorphism, moving away from the current
game that we're creating. But polymorphism
is very important, a little bit more complex. But it's definitely worth it. Thank you so much for watching. I hope you enjoy it. And I will see you
in the next video.
100. 15. Polymorphism: Welcome back my fellow
Python developers. In this video, we're going to
be looking at polymorphism. What the heck is even
polymorphism in Python? It's not just in Python. Other programming
languages that have object oriented programming
in them have polymorphism. Not all of them,
but most of them. Polymorphism.
Polymorphism is a concept in object oriented
programming that allows objects of different
classes to be treated as objects of a
common parent class. It allows for a single
interface to be used to represent objects of
many different types. An example of
polymorphism and Python is the use of the plus
operator for addition, but it can only be used for
catenation between strings. It's the same operator, it's the plus sign. It could be used to
add two numbers, or it could be used to
Kcateinate two strings. Or it can be used to create a single big list out of
two lists. There you go. That's a great example
of polymorphism. It allows for more flexible
and extensive code. Let's go ahead and test out
polymorphism back in my code. In here I'm going
to open up one of our recent projects which was object oriented programming. In this window, if you remember, we were working with
the Bitcoin wallet. I'm going to create
a new Python file that I'm going to call the H or HP characters. Hp stands for Harry
Potter. There we go. Enter. And as always, Intellij just freezes
for some reason. I will use the magic of editing to see you later on
when this works. Here we are. First of all, I'm going to create
a class of wizard. I'm going to define the
it and we're going to have just a name and we'll say self underscore name
is equal to the name. Then we're going to define
speak and we'll return Hello, my name is then. Plus self taught,
underscore name, plus I am a wizard. Nice. Then we're going to
define a class that is which, and we'll define a in
it will also have name. And we'll say self underscore
name is equal to name. And we'll define speak. We are going to return and I
write hello with a W here. I will say, well met I am plus. Self underscore name plus and I am a which I made a little bit of an adjustment which
will say well met. It depends on where you are in this world,
you might not know. But this is a way
to greet people. I think it's the British
way of greeting people. I can do the accent, especially with my runny nose. That's why for the
last couple of videos I might
sound weird and I'm starting because I can't
breathe through my nose. I can only breathe and talk through my mouth. So it's hard. But anyway, well met I am with the name and then the which just a little bit
of a difference. So we know well the difference. Next we're going to
create a function. This function is going to be
outside both of our classes. And I will just remove
the space in here. I'd like it to be
more tight in here. I'm going to define
the intro introduce. I will send in the character that we'd like to
introduce and we will simply return character
speak. There we go. Add a few extra lines in here. I'm going to say Harry
is equal to a wizard, and he has the
name Harry Potter. Harry Potter. Then we will print
out introduce. Then we will send in Harry. Then I will select this and duplicate it or pasted
in here as well. Another will have her mine out her ion knee and
she will be a witch. Her name, some people thought her name was Hermione
before the movies came out, which is funny in here. We'll have also and his name
will be Ronald Weasley. We need to also
print out Hermione and run Wesley apparently
is written incorrectly. I mean Weekly Wiley. I don't know. I think this
is how you write Wesley. But anyway, in here if I
write Click and I run, look at that even though we're
calling the same function. Let me jag this
over to the side. It's not allowing me. There we go. Even though I
think all right, seems good. Look at that. Even
though we're calling the same function
on our characters, we are getting
different outputs. This is basically
polymorphism where we are using the same function but getting different behaviors. We have the same
method being called, which is the do speak, but getting different
behaviors from this do speak. I just noticed changes to
a small W. There we go. So as you can see, speak used on Harry, used on Hermine, but it
has different outputs. And that's the basics
of polymorphism. Nothing too complex, obviously, when you start using it
in real world scenarios, it can get a little
bit complicated, but as a concept, it's easy. Before we continue on,
let me provide you with a bit of a challenge
to add Muggles. Add another class
which will be Muggle. It should have the in
it with a name that you should provide it with
and a method to speak. Then create a Muggle object
and introduce the new Muggle. And add an extra method
which would be cast spell to all of our classes. Pass the video right now
and go do the challenge. Hey, welcome back my
fellow Python programmers. In here we're going
to create a new class which will be Mule. We'll define the in
define the in it. We'll have the
name and we'll say self underscore name is equal to name and we'll
define the speak. I will just copy this. Wait, wait, copy
this based in here. Too many spaces. Well met. I am and I am a muggle.
Boom, there we go. He's just a muggle right
here at the bottom. I'm going to create
a new mugele, which will be Emma, and we'll say that she's
equal to a muggle class, and she's Emma Watson. Go figure with a big upper case. I will print out introduce Ma. If I right click on it, should be obvious
that, there we go, we get a different, oh, let me just change this. I have a hello. Okay, I will say Hi, my name is just. So we have a little bit of a different output,
a different word. So we can easily
distinguish between the classes using the
speak method. There we go. That's polymorphism. Now we said there is also the part of the
challenge where we need to add an extra method, which is cast spell
for the wizard. I'm going to define
cast underscore spell. It will just take
in the self and we will return self name plus cast a spell when, I have no idea if that's
how you write it, but I'm sure that
it's, it's Laos. Anyway, we will copy this and give it to
the witch as well. Actually, let's
do something fun. And here we'll say two big S. Okay? And then we will copy this and give
it also to the muggle. What should the muggle do
with a casting of a spell? It will just say must cast spells. What's the right
there we go back. Make it into a
special character. We don't need the return. And what does it say in here?
The spell may be static. All right, that's
not an issue here. I'm going to have a print, I'm going to do the following. I will print out, and we need to
define cast in here. Send in the character. Character cast. Character. Okay. What's
the issue in here? Why is it not giving
cast underscore spell? Okay. No suggestions.
Not a problem. Maybe it's just not recognizing that character is one of these. That's okay. In here, I want to print
out the following. I will print out
cast Harry, her Ron. If I right click and I
run Harry Potter cast Leviosa when Guardian Leviosa was cast by her mini ranger. And then Ron Weasley cast another Leviosa
because he's a wizard, so he has no idea
how to cast Leviosa. Then unfortunately, Emma tried
to cast a spell as well, but she's a mule so
she cannot do it. I hope you understand
how polymorphism, or understood how
polymorphism works. It's not too complicated. It's just a way of using or naming our methods the
same in different classes. I mean, that's the surface
level comprehension in here. But it's a very
important concept to know when it comes to object
oriented programming. Thanks so much for
watching, I hope you enjoy. And in the next video,
we are going to be looking at composition. So we're going to
see the difference between a and has
a relationship. We will see you in
the next video.
101. 16. Composition: Welcome back my fellow
Python developers to a brand new video where
we are going to be talking about
composition in Python. And composition is
obviously also available in any other programming language that has object
oriented programming. That's why I told you this
is a very important section. Once you understand object
oriented programming, you can then delve into any other language if you
ever need to in the future. What is composition? First of all, composition in
Python is a way to create complex objects by
combining simpler objects. What do we mean by that? Basically, it's a class composed of other classes
at its attributes. Meaning that an
object of one class contains objects
of another class. Read that again. Listen to that. Again, understand it properly. Because inheritance
is a relationship. Meaning that the Orc is a enemy. But the composition
has a relationship. That's why the class
component of other class, a class has its attribute
as another class. We're going to see what
that is basically. Let's say or has an enemy or, or has a club. That would be a
composition relationship. It or allows us to model real world relationships
between classes and objects. And it also helps make the
code easier and more dynamic. Let's go back to our
wizarding example in here and look at what we can do to
create this has a relationship. So we're going to add a
bond class to our classes. Example, since we
have a wizard and every wizard or
which has a want, let's go down in
here and I'm going to create a class in here. I'm going to say class wand. And did I seriously
add parentheses? And I'm going to
define the in it. And we're not going
to have any names, we're not going to
make this too complex, I'm just going to say that self dot underscore w
is equal to Holly and then self underscore core is equal to Phoenix feather. In here I'm going to
define underscore one actually just use because this is a one
that can be used. And we will return
made of plus self wood with plus self core core. There we go. We'll add
an extra space in here. And then we will go back to the wizard right
here under the name, I'm going to have
underscore wand. This wand will be equal
to the wand class. We can cast a spell. We can, we can also use want with just
a self in here. And then I will return
self name first of all. Okay? Or use a want or uses, because the want
chooses the wizard, not the other way
around, self want. There we go. I'm going to
go back into our main code. We have the main
code right here. I'm going to add a print even though this output is getting a little bit
long, but that's okay. Where we have Harry, we're going to print
out Harry want. So when I write, Click and
I run, this is what I get. Harry Potter uses want or a
want made of hoy as wood, with phoenix feather core. So as you can see, we have a class want and we have an attribute in the wizard
that is of type want. So this is a, has a kind of relationship
where the inheritance was, is a kind of relationship. If you're still not sure,
think about the has a, is a relationship type. I'm going to issue you
a bit of a challenge that may help you
understand this better. So Wizards also need a house. So create a house class for the four houses in Hogwardshd. They should have
only one attribute, which is the name of the house, and make the name Griffin
Door. Just set one name. If you want to
delve deeper again, if you want to
expand this example, I would love it and
please send it to me. Show me how you
expanded the lesson. But for now, just make
it Griffin Door and create a getter that
returns the house. Mm hm. If you remember
what that is, add a house attribute to the wizard class and try to print it out
if you want as well. So posit the video right now
and go do the challenge. Okay, welcome back. How did you get on with that? Under want again, in here I will create a class that is house. Define the in it. Nothing will be in here. And we'll just say self
name equal griffin. Do. There we go. And we're
going to define get, underscore house,
underscore name. This is the getter
that I told you about. Not the getter in the sense that it's a very
complicated getter, just a very easy, normal getter. We will return self
thought, there we go, back in the wizard, we're going to have self underscore house, which will be equal to house. Now the wizard has
a house and we'll define a method that will
get us the house info. We will simply
return self dot name plus belongs to house
plus self dot house. And is that correct? Set dot
house dot get house name. Of course, because we need to return the
house name as well. There we go. Everything
in here is set. So I will scroll down to the
bottom and in here print out Harry dot get house or
Harry dot house house info. Yeah, there we go. So if I write Click and I run
look at what I get. Let me just make sure.
Okay, let's expand it. Harry Potter belongs
to House Griffin door. So as you can see, this is composition where
a wizard has a wand. Where a wizard has a house. So it's has a
relationship there. We got nothing too much in here. So, ladies and gentlemen, I think this might be the end of the video of the section. Later on, I believe I'm
going to expand on this because I really love object
oriented programming. We will delve deeper. We will learn more later on
when I update the course. But for now, I hope you
enjoyed. I hope you understood. I want to congratulate you
on getting to this video. You completed section number, I don't know. So
congratulate yourself. You are now top tier. You know how to create classes, you know how to
manipulate objects, you know how to
create inheritance. You know about subclasses, dynamic implementations,
overriding methods. You've delved deep
into attributes, into methods, into classes. You understood a lot of things. Static methods, I mean, you know so much more than when you started in
the next section. I believe we are going
to be moving on to understanding more data handling tools like
dictionaries and sets. I'm very excited to get
started with that section. Thanks so much for watching
and I will see you later on. Bye bye for now.
102. Section 8 - Dictionaries and Sets | 1. Dictionary 101 : Welcome back my fellow
Python programmers to a brand new video and
a brand new section. In this section,
we are going to be exploring dictionaries and sets. We're going to start off
with dictionaries first. What are dictionaries? A dictionary is a collection
of key value pairs. This is very important
to understand. We have keys and we have values. And they are paired
together and put inside of dictionaries in order
to create the items. Each key value pair in a dictionary is
separated by a column, and all pairs are enclosed
in curly brackets. Just like we've learned lists where we had square
brackets around the list in this situation or with topples when
we had round brackets. In this situation we
have curly brackets. And obviously we're
going to have a lot of examples showing this, but you have to know this first. And they are
separated by a colon. The key and value are
separated by a column. So for example, if
we have my dict, which is dictionary
equal to curly brackets, which I said right here, it's enclosed in curly brackets. We have the key. Look at that. The key could be a string, could be an integer,
could be anything. In this case, it's a string because we have the
double quotation marks. Then we have the column, and then we have the value one. Key one value one creates the key value pair and it's the first item in
the dictionary. Then we have a comma, and then we have key two, value two separated
by a column as well. And the key in this
situation is also a string. The value can also be
anything that you want. It could be an integer, it could be a string, it could be any object that you want. The key is like a
label that you can use to retrieve the
corresponding value. For example, let's say I can
or I have this dictionary, my **** one, value
12, value two. I can use key one in order
to retrieve value one. And you'll see that this is a very useful way of
retrieving information. It's much more
efficient and much faster than using
lists and tupples. Keys must be unique
and immutable. These are two very
important keywords here, unique and immutable. For example, keys
need to be strings, numbers, or they could
even be topples. While values can
be any data type, the value can be
anything that you want. The key should be
unique and immutable. I might have said it could
be anything you want, I apologize for that. It needs to be unique
and immutable, meaning that you can't have
the same key appear twice. You can't have key one
and then have key one. Again, it will not
cause an error, but we'll see through
some examples that it will ruin the effectiveness
of the dictionary. Finally, you can
access the value of a specific key by using the square brackets over
the brackets with the key. For example, my dictionary
open up the square brackets, send in key one and
then you should get the value one in return. I know this is a
bit complicated, especially if this
is your first time looking at dictionaries. Don't worry. Focus
on the main ideas. How we write our dictionaries. That we have key value pairs, that the keys are
unique and immutable, and that we can retrieve the
values using the key label. These are the four main points that you need to think about. But enough looking,
enough theory, let's go into our code and start actually
practicing dictionaries. I'm going to go back into my code in here and last
time we left off on classes, maybe we left off on
something different. I will keep updating
this course. I don't know what will
happen down the line, but for now we're
going to go into file and we're going to
create a new project. It's going to be Python next. This is, first of all, we need to change the
location of this. It's going to be in our Python
course inside the code. Yeah, there we go in here. I'm going to add another
one and we'll just call it the diction, Dictionaries and Sets. If I wrote that
incorrectly, excuse me. Yes. Let's go ahead and create. Let's open it in this window
and we should be good to go. There we go. From here
I'm going to go to create a new Python file that I'm
going to call underscore in. So let's close down projects and let's go
ahead and get started. First of all, we're going to
create our first dictionary. Our first dictionary
is going to hold the of some of our
bright students. We're going to have the keys as the string names
of our students. For example, Alice will
have a grade of 90. Then we have Bob, which, or who will have 85, will have Charlie, 92, David, 78. And I'll actually just
copy this. There we go. Notice that because David
appeared multiple times, we immediately got a
highlight and grace. Or before we even put grace, let me just copy this and
then take it back to David. If we hover over it, we'll see dictionary contains
duplicate keys, David. Okay, We'll handle
that later on. But for now, let's just
take it back to Grace. David will have 78, Frank will 88 for Grace. This is our dictionary. As you can see, we
have key value pairs. The keys are the names
of the students. The value is the grade
that that student has. The key should be unique, as we saw just a bit before, the key should
also be immutable, meaning a string and integer, whatever the value could
be, anything that you want. Let's go ahead and try and access some of our
grades in here. I'm going to say my
underscore grade is going to be equal to grades. Open up the parentheses
inside will have Bob and then we'll
print out my grade. And we'll print out David's grade is two
dots come up grades. David what we're doing in
here, just like we said, we're trying to retrieve Bob's grade using the
label of that key value, which is the key. We're using the key. And
keep in mind because this is a string reference and we're
using that exact label, upper case and lower
case matters in here. If we just variety
click and look at that, there is a key error, meaning that there is
no inside of grades. But if I use the upper
case, there we go. You can see that we
retrieved Bob's grade, which is 85. We printed it out. And we also retrieved
David's grade, which is 78. And I added an
extra space in here because I'm using two
arguments in this print. Keep that in mind.
We're not using the F type for the
replacement fields. As you can see, dictionaries
are something new, but not completely new. If you understood how
lists work before, this shouldn't be that
far from the same logic. The only thing that
might be a bit complicated is the
key value pairs. We'll see that there are a
lot more exciting things that happen below the surface that
we can use to manipulate. But for now, I have
a challenge for you, and your challenge is to
get our values differently. First of all, access
the grade of Charlie. We want to get Charlie's grade, use the get method. And I recommend
that you go through three schools to
get that. Get it. The ponds are infinite
here. Oh, okay. Look it up online and check what difference it makes
on W three schools. Why do we need the get if we already have the normal
square brackets? I want you to tell me why. Why use one or the other. Pause the video right now and
go do the challenge, okay? How did you get on with that? I hope you understood how
we use the get in here. I'm going to get another
underscore grade. If I can type it out, another grade is going
to be equal to grades. Get, and I'm going to
get Charlie's grade. I will print out another grade. And if I write, click
actually, let's use this. Let me just copy this.
Paste it in here. Add a comma, and we'll
see Charlie is great. Right click, Run. Boom. There we go, 92. If we look at the
grades, that is correct. But before we need to move on, we need to understand
the difference between these two methods. And I hope you tried your best to understand
why we use the get. Keep in mind the keys
here are case sensitive. We've already covered
that because these are string references
for our keys. Remember, our keys are unique, so need to be different
than each other, which means that case
sensitivity here plays a role. What I mean by that is
if I change this from a Charlie with a capital C to a Charlie with a capital C H. And what do you think the
output is going to be? Now if you've went through the get and understood
what it does, you'll know that it simply returns none. How
is this helpful? Well, because remember
when we changed from a big B to a small Bob, we did not get none. We actually got an error. Basically what
happens with the get, the get allows us to try and access these key
value pairs without creating any errors
in case it does not find the appropriate
key in our dictionary. Also, keep in mind
that indexing can be slightly faster
than using the key. When I say indexing,
I mean using the square brackets because it doesn't involve
any method calling. It's not going to matter
too much in our case because these are small
changes in the milliseconds. If you're accessing a key
many times in a loop or in a performance critical
section of code, indexing might be
a better choice. But it could also come with it. Drawback in case there is, or the key that you're
looking for is unavailable. If you know what the key is, using the indexing is
better than the dot get, but dot get is safer and
that's how life works. If you want risk free, you need to be slower. If you are a huge risk taker, then you will go faster, you choose your path. I know it's got Phil, very philosophical for
some reason anyways, thanks so much for watching.
I hope you enjoy it. And in the next video
we're going to be looping and iterating over dictionaries. I hope you're excited for
this section as much as I am. Honestly, it is kind of boring, but learning how
to manipulate data using dictionaries
is imperative. So I will see you in the
next video. Bye for now.
103. 2. Iterating over a Dictionary: Welcome back my favorite
Python developers to a brand new video. And this one, as I told you, will be looping or iterating
over dictionaries. Now, this section is going
to be a little bit hard. It's going to be
a little bit dry, but as I told you,
it's very imperative. So I decided to
lighten up the mood. I'm going to start this
lesson with a challenge. Immediately. How cool is that? Right? You're probably
hating me right now, but you still need to create a simple for loop that iterates over the
grades dictionary. So we're still in the same file. We're still going to
iterate over the grades dictionary and print out the
value of each iteration. For a second, try to
imagine that grades is just another list and
you're trying to iterate. And you're trying to print out whatever is being given to us, test it out, see how it works, and I will see you
in just a bit. Okay. How did you
get on with that? I hope it wasn't too hard. First of all, I'm going to
take back Bob Bob to a Big B. Very nice. I will
add a print in here. I'm going to say
four key in grades. Print out the key. I know what the output
is going to be, that's why I call
the variable that we're using to
iterate over the key. What we're going to get
and what you probably got as well is all of our keys. Notice when you iterate
over a dictionary, you are iterating over its keys. If you want to get the values, you need to do the following. And it's pretty simple. We need to add a common, then grades, and then we
can simply use the key. Notice that I can use
the key directly. Of course, I'm not going to add these two quotation
marks around it. Because this or this means
that we're trying to look for the grade
that has the key key, like literally the
string key as its key. If I do that, I'll get an
error because there is no grade with the key key,
it's a bit confusing. Just know that we need to do this when I read,
click on, boom. There we go. Look
at what we get. But this is not clear, so we're going to use
the Sp equals to this. This will add a
separator between the different arguments that we provide our print function. And this is the output that we, as you can see, we've
printed out our dictionary. Pretty simple, nothing too
much to think about in here. But there is a better way of working with dictionaries and getting information out of these dictionaries
without having to, first of all, get
the key and then use the key to get the
grades or whatever. We can do it in a much
more efficient way. First of all, I'm going to
comment out these two lines, select both of them, and
hit control forward slash. Then in here I'm going to say
four key value in grades, items inside, I'm
going to print out the key value p. Then, okay, there we go. The print should be
pretty simple in here. We're simply using
the key, the value, and we're adding a
separator so that we get the same output
as we had in here. The only weird thing, but it shouldn't be weird to you because we've already went
through all of these sections, is how we're creating
this for light here. As you can see, we have the
key value in grade lot items. What are we doing in here? I can hear everybody
saying we're unpacking a topple exactly. So this looks exactly like when we were
using the enumerate. And the enumerate
returns two items to us. It returned the index, and then it returned the value
associated with that index when we were working
in a list or a couple. But now it returns the key, and then it returns the value. If you remember, if you go back and learn what we did
in the enumerate, you might recall that I did
not say it returns the index. I said it returns a number. I was very specific about it, and that's why I was
specific about it, because it doesn't
always return the item. It might return a key. And that key could be a
string, it could be a number, it could be in
whatever. Oh, sorry. That key should be something
unique and immutable. Basically, the grades
item item returns an object that contains a list of the key value pairs
in the dictionary. When I write, click and I write, and I run, there we go, I get the same output being printed out. So
that's basically it. This is how you can iterate over a dictionary using the items. Or you can simply access
the keys and then use those keys to access
the dictionary values. But obviously, the
dot items is much more efficient. I
hope you enjoyed. In the next video,
we are going to be appending items to
our dictionary, so we'll see how we can add
an item to our dictionary. I hope you enjoyed and I'll
see you in the next video.
104. 3. Appending items to a Dictionary: Welcome back my favorite Python programmers to a
brand new video. And this one will be appending
items to our dictionary, meaning we'll be adding items to our dictionary
in various ways. And we'll see how having
two keys that are the same can affect the way
our dictionary behaves. First of all, we've seen that
we can create a dictionary using a literal meaning that we can literally set it
up with elements. For example, in here,
I can come in and I can add, let's say Philip. And Philip would
have a grade of 12. Philip hasn't been studying. Well, but we can
also add a grades, or people with grades, or students with grades
using a different way. For example, in
here at the bottom, or not actually at the bottom. I'll add it directly above Bob. In here, I'm going
to say grades, open up the square
brackets and I'm going to say Henry equal to 83. Now when I write
Click and I run, you'll see that at the
bottom I get Henry. So keep in mind that we
added Henry at the end. So when we add to a
dictionary, okay, outside of the
actual dictionary, the order of insertion
is preserved. Or the insertion
order is preserved, meaning that we add
only at the end. Now you'll see in here
that we have some kind of warning if we hover
over it. What does it say? This dictionary
creation could be rewritten as a
dictionary literal, So it means this one. Now, let's try to
show action and replace dictionary
creation. Uh huh. Okay, there we go. So you'll
see that it created or made the dictionary horizontal and added Henry at the
end right here. I'll just take it back because
we are trying to show you, or I'm trying to show
you how we can add items in various ways
to our dictionary. But let's continue on. Let's see what happens if we try changing a value under Henry. I'm going to try and say grades, open up the square brackets
and then Axis, David. And then I'll say that
David's grade now is 88. So remember a David's
grade was 78. We can even see it right here. But now if I write, Click
and I run look at that. David's grade is 88. So something to keep in mind
is that every key is unique. Otherwise, how would we know
which one we are changing? What if we had two
David's inside? Which one would change? Well, that's the
question you'll need to find the answer to when you
do the following challenge. I want you to add a Charlie
at the top of our dictionary, meaning inside of our
literal dictionary. You'll need to add
another Charlie. We already have one,
add another one. Give a grade different
than the second one, provide Charlie with
a different grade. And what I meant is, at the top of our dictionary, that's why I said give a grade different
than the second one, because Charlie
is like the third or fourth person anyway, give him a different grade. And what happens when we
actually run the code? First of all, I want you to
think of what would happen, and then I want you
to test it out. So pass the video
right now and go do the challenge in here. I'm going to go to the top
and I'm going to add Charlie, it should be a string,
Charlie, two dots. And I'm going to give
Charlie a grade of 50. Notice that immediately, we
have warnings in here telling us that this dictionary
creation could be rewritten as a dictionary. That's the old warning. If we hover over this warning, it says that dictionary
contains duplicate keys. Charlie, if we run this, we're not going to get an error, obviously, because it works. But we do have something
happening in here. We have Charlie at the top, which is where we've
added Charlie, but he has a grade of 92 instead of the 50
that we provided. What is happening in here? First of all, it's very
obvious what's happening. The key preserve
preserves its location, but the value changed. The key position is preserved, but the value changes. If we have two keys that are
the same in the dictionary, it behaves as if
we've changed it outside of the literal like
we did with David previously. The way you could imagine it, like a small robot going over the grades and trying
to print things out. It finds Charlie.
It's like great, Charlie is in
position number one. We print Charlie
out and it's 50. Excuse me, we don't print
actually anything out. It's 50. Then we go to Alice, grade Alice in
position number two. Bob is in position
number three with 85. Wait, Charlie. Charlie again. Oh, okay. Well, I've already seen Charlie. He had a grade of 50, but now I can see that it's 82. So we changed the value, and then we printed out. This is how the dictionary
is interpreted. And notice that in
here it gets to 92. So the dictionary kind of
has a soul of its own. Even before printing,
it already changed the grade of Charlie because it detected that there
was another Charlie. And we'll see that this Sol Sol in between brackets, of course, will be very helpful down
the line when we try to create different things and use it for different purposes. Thank you so much for
watching. I hope you enjoyed. In the next video, we're
going to be looking at removing items
from a dictionary. And we'll see how
all of that works. I will see you in just a few.
105. 4. Removing items from a Dictionary: Welcome back my favorite Python
developers in this video. As promised, we're going to be removing items
from a dictionary. Now there are many ways of removing items from
our dictionaries, so let's look at a few of them. First of all, deleting
from a dictionary is very similar to how
we did it in lists. But in dictionaries
we use the key to indicate what we want to delete. In lists and topples
we used to indicate at which index we would
want to delete it at. To do deleting at or
from dictionaries, we need to indicate the key. For example, in
here right before I print out the key and values, I'm going to delete
grades at Bob. Now when I write
Click and I run, Look, we had Bob. Now when I write
Click and I run, we don't have Bob. Bye bye Bob. As you can see, when we run, the item is deleted. If this works so well, why do we need to
have other methods? Well, to demonstrate, I'm
going to try and delete somebody that's not in
our class, for example. And when I say class, I mean the class that has
all of these grades. Not a class like in the classes that we learned
in the previous section. Just to get that out of the way, we're going to try
and delete Kalen. If I write click and I run, I get an error. It's a key error because Kalin does not exist in our grades. What shall we do about this? Well, we have other
ways of deleting. It's not actually called
deleting, it's called popping. For example, in here
I can say grades pop can provide Kalin again. Now if I write click and run, I still an error. I get Kalen or a key error where Kalin is not
available. Wait, wait, wait. Didn't we just cover this? Shouldn't this be
like the solution to all of our problems? Well, it is, but you need to provide it with
another argument. For example, in here you can
tell it in case you do not find kalen or a item
with the key kalen, you can just return none. So now when I write
click and I run, you can see that there are no errors in here
which is perfect. But we don't only
need to return none, in case we don't find anything, we can return absolutely
anything that we want. For example, I can return
a nine. There we go. Well actually it's
not printed out because we need to
actually print out. Or we can say for
example, Lens or Kalin. Underscore grade equal
to grade pop in here. We can print out kalen grade. I'll actually just
add a small print in here just so we can separate it. There we go, We get nine or we could have just
printed out none. There we go, we get none or
we can say sorry, no one. No one. Is that how
you write? No one. No one with that
name in our grades. Right Click, run, sorry. No one with that
name in our grades. All right, So using the
pop is a great way to avoid getting errors and also to be user friendly
in case the user is, let's say, looking for his
son's grade or something, or a student looking
for their grade. You can use the pop in order
to send them a message. You're not even here
or I don't know, maybe you're looking
for a different class. You can do whatever you
want using the pop. Now, time for a bit of a
challenge to pop two values. I want you to pop two values already present in
our dictionary, for example Alice or Bob. You can try to pop those
names on the second pop. Present an alternative
string to be printed in case we
don't find the key. Let's say you try to pop David. You also can provide
it with a string in case we don't
find David here. Okay, so we'll see what
happens in that situation. What happens if we try to pop
something and it's there. But we provided it with an alternative string or alternative thing
to be output it. Pass the video right now
and go do the challenge. Okay, welcome back. How did you get on with that? In here in the print, I'm going to add
another print in here. I'm going to say
Alice underscore grade is equal to the grades. And we'll have Alice
and we'll print out, oh my god, Alice grade. We'll also have David
underscore grade. And it's going to be equal
to grades Pop David. But on my second pop,
I'm going to say, we don't have a David here, backslash and one of those. Do you remember the
special characters? I hope you do,
because they could come in handy in
situations like these. And then we'll just
have David's grade. Now notice what's going
to happen in here. Very important when I write. Click and I run. There we go. You can see that we get 90, which was indeed Alice's grade, and we get 88, which was
indeed David's eight. What did we pop David? What do we have, David? Oh, that's because we
changed it in here. Very nice. Honestly, I did
not plan this, but it's good. It's good that we actually were able to find it that fast. So as you can see
Alice and David, but keep in mind that
they were popped, so you can't find Alice
and you can't find David. When we try to print out the key value using
the grades items, notice that now
the values that we just pop no longer
show up at the bottom. Because while
they've been popped. Even though I told this
before, I'm just reiterating, making sure that we
understand what is happening. I hope this wasn't too hard. Removing items is not something very complicated
when it comes to dictionaries. In the next video, we are
going to be looking at iterating over
dictionary keys using the N. And we're going
to go back to one of our previous projects where we were building a
car with wheels, lights, windows, and so on, and making it much better using our new found powers
of dictionaries. So thank you so
much for watching. I hope you enjoyed and I will
see you in the next video.
106. 6. Computer Builder: Welcome back my fellow
Python developers. In this video, we
are going to start building various
computers. How about that? First of all, we will
need a list of parts and the different
computer models that we can create with them. Below this video,
somewhere around, I don't know, in the
resources, wherever you are, wherever you're watching this or whatever different
settings it's happening in, you will find a file that you
can download where we have all of the computer parts
and the computer models. The first thing we need
to do is we need to create the computer
parts content file. We'll go to file New. We'll create the computer score, underscore content,
pull, hit Enter, and there we go. We're here. So I'm going to copy and paste
a very long list in here. And don't worry, we will
have it available to you. Once you do that, you'll
see that, first of all, we have the computer
parts storage. So we have ten CPUs, seven GPU's, 50 Rams, three motherboards, 30 SSD's, six monitors, et
cetera, et cetera. And then we have the
computer models. So for example, we have
the gaming PC in here, which requires a
GPU, CPU, Ram, SSD. We have the business laptop, which requires a CPU, no GPU, Ram, SSD, and so on and so forth. A home desktop, a media center, and a work station. Now, later on we will make this list a bit
better, where, for example, the business laptop will require two CPUs or 15 Rams and
so on and so forth. But for now, we just want
to work with what we have. We are going to
keep this file as the content place where we have all of the
contents that we have, but we're going to create a
new Python file that we're going to call the
computer Builder. Inside of this computer builder, we are going to import from the computer parts content
from computer part content. Import the computer part storage
and the computer models. All right, now if
we try printing out the computer part storage and we try printing out
the computer models, we should see something
like this. Boom. Go CPU, GPU, Ram, motherboard, et cetera, et
cetera. And then look at that. We have the gaming PC, and you'll see in here
that we have also the business laptop and
so on and so forth. Something that I just noticed
that I forgot to mention is that we have the computer
models as a dictionary, which has the keys as strings. And then the values are lists. We've never seen this before. It's a list of strings. The value is a list. It's not an integer or a string, it's an actual list. Look at how deep we can go with data handling using
dictionaries. In here, the computer part
storage is a dictionary, the item or the part as
the key being strings. And then the value is the amount of these items that we have. So back in the computer builder, I'm going to drag this
and set it to the bottom. Maybe it looks better.
So there we go. We have the CPU GPU, et cetera, et cetera. But now you have a
challenge in front of you, and your challenge is to
display all of the models. Create a for loop. Use it to enumerate over the computer models and print
out the index and the key. We should have something
like this. There we go. Keep in mind I want
you to now not use the items I want you to enumerate over the
computer models. Because we want to see what we have and we want to get
this kind of output. Make sure that you do that. Pass the video right now
and go do the challenge. Okay, welcome back. How did you get on with that? First of all, I'm going to
comment these two lines out. These were simply for debugging, making sure that we
got the correct data. Then I'm going to say four
index key in enumerate. We're enumerating again over
the computer models in here. When I said get all the models, I'm sure some of you
are very excited. But it turns out that no, we're not those types of models. I'm going to print out
the index key separator, and the separator is
going to be the two dots. This is basically it. This
is what we wanted right now. When I write, click and I
run, this is what I get. Zero for gaming, PC, one, Business Laptop, Home, Desktop, Media Center, et cetera. But in fact, we want to have a separate dictionary
that displays the different models
we can create. I'll tell you, I'll not tell you why it will become
more evident later on. For that reason, I want
to do the following. I want to create
something called a display underscore dictionary, and it's going to be equal
to this empty dictionary. Then I'm going to have, or actually know what,
Let's just move it. I wanted to delete it, but we'll just move
it up right here. Instead of printing this, I'm going to comment this out. I'm going to create or
say the display dict STR. And this was not part of
the challenge, by the way, index plus one is equal to key. What the hell is happening here? First of all, let me
right click and run. Nothing happens well because
if we want to simply print out display dict,
right click on one. Look at what happens. Now we have one being the gaming PC, two being the business laptop, three being the home
desktop for media center, five, the work station. What's happening in here? As you saw before, Maybe I should not have
commented this out. Just so you can see
that the index is zero. For the gaming PC,
we use this index. We add plus one to it, and then we turn
it into a string. And then we use this entire
thing in here that we've created as a key to add it
to the display dictionary. By saying it's equal to the key, we're calling it a key because
it was a key right here, gaming PC was a key and
now it became the value. Notice again, if it's confusing, let's think about it again. We had the computer models, we had the gaming
PC was the key, the business laptop was the key in the computer
models dictionary. Then what we did is we enumerated over the
computer models, we had gaming PC at position
zero or at index zero. Business laptop at index one, Home desktop at index two. Media center at index three, workstation at index four. But we know that
in a dictionary, we don't need to have
them starting at zero. We would prefer to have the
gaming PC start at one. For the same reason why we would use zero right
here to finish. Maybe we would like to
use zero to finish. What we did is we created a display dictionary
where the key is now the index from the previous dictionary
that we had. Look at that. Now gaming PC is at one, business laptop is at two. Now, later on, if we
want to build a PC, we can say that we
want gaming PC. By clicking one, we
would get the gaming PC. We would use that in the dictionary of the
computer models to get, for example, which
computer parts the business laptop needs. If you're still confused, I recommend that
you go over this a few more times to
properly understand it. The most important
thing that you need to know is why we used
the enumerate, which was to get the indexes, and then how we created
the display dictionary, which is right here. Which is this right here. Your time. Don't worry,
this is not very simple. I know we're getting into
the more complex parts, but it's very important to understand data handling
using dictionaries. But now we also want to print
out our choices in here, I'm going to say, first of all, I will comment this out and I do not want to print out the
displayed dictionary. I will comment it out as well. In here I will say, while true, this will be to
display the menu. Why do I get an error? And then expected. Okay, okay, we still haven't written
anything in here. When I print this
should go away. Good. So I'll say please
choose your computer model. This was part of your challenge. Even though you did not
have to do it like I did, you did not have to create
display dictionary. But you should have gotten
this output right here. Please choose your computer
model and here I'm going to print out the dashes
that I indicated, multiplied by 20 and I will say four key value in display
dictionary items. I will print out
replacement field, key, replacement field value. That should be it. Then I'm going to
get the choice, say choice equals input. I'll say your choice like this. Maybe add a space, or maybe we can add a column. I don't know. You select whatever you want and
we'll just say if the choice is equal
to zero, we'll break. Because remember we're
in a wild true loop. Now if I right click and I run, let me move this right here. Boo there we go. Maybe we could add a print in here just to
separate the truth, or maybe we could add a
backslash D. Does it look good? Not so much, honestly. I think the back would
serve us better right here. Let's see, I don't know. Honestly, I don't know.
Yeah, there we go. I think this is
good. I don't know. I'm not sure. Anyway in here, what's your choice? One gaming. Pc. Boom. 23. Okay, we're not getting anything useful yet, but at least it's working. I hope you understood, I hope it's not too confusing. Again, next video we're going to be looking at
multiple dictionaries. So it's very important that you understand
what we did in here. Because the next video, we're going to use
what we did in here. If you're worried about who
this is getting too complex, Michael, what the
hell is happening? Don't worry. Breathe,
Take a deep breath. Things are going to
only get harder from here. No, I'm kidding. Everything is going to be
easy as long as you focus, as long as you understand, and you take things step
by step and slowly build. Also, we're always available. You probably have my
numbers somewhere. You probably have an
instructor's number somewhere. Don't hesitate to contact
them and we will help you. I will see you in
the next video.
107. 5. Iterating over dictionary keys using `in`: Welcome back my fellow Python programmers to a
brand new video. And in this one
we're going to be iterating over
dictionary keys using. The main goal in here is to understand how we
can iterate over dictionaries using the
n. But the other goal is to also understand which data
structure should we use, a dictionary or a list when we come up into a
situation like this. When I say this, I mean
a few sections ago, a few videos ago, we created a car
dealership where we had a list of
available parts and we had numbers attached
to these parts. Well, it was the indexes, and we would add wheels, lights, front wing seats, and
so on and so forth. I hope you remember what I mean. Unfortunately, in
this current project, I go back and find it. I'm sorry for that,
but you can definitely go find it in the
lists and pupples. Or maybe I called
it car builder, I called it car dealership. Maybe I called it by car. If I'm not mistaken,
it was by car. But in any case, try
to go back and find it in that project. First of all, we used four
loops in order to create it. Then we upgraded it using lists. We made it better using a list. Now we're going to
do the same thing where we are going to
make it even better, but this time using
dictionaries. First of all, I'm
going to go into file new and create a
new Python file. That's going to be the
by underscore car, underscore dict, indicating that we are using
dictionaries in here. I'm going to create the
available underscore parts and it's going to be
equal to the following. First of all, we'll
have 12 dots. Then wheels duplicate this, we'll have lights
duplicate this, we'll have the front
wing duplicate this. We'll have, oh my God. We will have the
seats. Duplicate this. And we will have
the window, window. And duplicate this again. And we'll have the stereo. Obviously, we cannot
have duplicate keys. They all should be unique
and should be immutable. 56. There we go. In here I'm going to create
the current choice. We'll have the current
underscore choice equal to none, while the current
choice is different than or equal to zero, because remember zero
is where we finish. We're going to say that if the current choice is
in the available part, then the chosen part is going to be equal to the available parts at
the current choice. And we'll also print out adding replacement
field chosen part. There we go. Also, of course we need to get
the current choice of, the current choice will be equal to an input
which is going to be your chosen part, two dots. And then we will just
select a number. Now if I right click
and I run right here, you can see that
your chosen part, if I hit one, for example, and hit Enter, you can see
that I'm adding wheels. If I hit six and hit Enter, you can see that I
am adding stereo. Do you remember how hard it was to get to this point when
we were using lists? Look at how easy it is. Now we simply created
the available parts. Each part has its own
key attached to it. And for example, if I press
nine in here and hit Enter, there you go, Nothing
happens at all. So how cool is that? But very important thing to realize is when we are
using the on a dictionary, we are going through its keys. For example, if I try to
add windows or window, look at that, it does not work. If I try to add wheels, it does not work when we are
using the with a dictionary. Unlike lists, we are looking
only through the keys. That is a very
important distinction, not through the values. I hope you understood. I
recommend that you go through the code a few times to make sure that you properly
get everything. And when you do, you have a
challenge in front of you. You will need to print
out all the parts. Create an L for when
the current choice is not in the available choices, iterate over the available
parts using the items. And get the key and part, meaning the value of the key, and print them out. Display them in a way that
the user understands. Basically, right
now, you'll see that we are not displaying
to the users what options they have
when they want to add a car or car item or
whatever car part. So you need to do that using the items on our new dictionary, which is the available part. Pause the video right now
and go do the challenge. Okay, welcome back. How did you get on with that? It shouldn't be too hard. Right here, we're
going to say L, meaning if the current choice is not in the available parts, we're going to say
L, four key part. In available parts, items, I'm going to print out the key part and then
separate using the column. And also we need to print
out in here zero to finish. Basically what
we're doing again, remember the items gives
us a list of topples, which are the key part. And then we unpack them
into the key and the part. And we print things out
with the zero to finish. Now when I write click
and I run, look at that, I get one wheels, two lights, three front
wings, et cetera, et cetera. Do you I recommend that you
go back to that code and you check out how hard it was
to do all of these things. Look how easy it is right now. Also something to keep
in mind before we move on is these two
lines right here. We are not worried about using the wrong current choice
inside of our available parts. Because remember, if we use a key that's not
in our dictionary, we can cause an error. But because we're using the if current choice
in the available parts. So first of all, we're
checking if our choice is one of the keys that
are in our dictionary. So if it's 12345 or
six only then do we try to access one of the
values inside of there. This is something very
important to keep in mind. In summary, when should you use a list and when should
you use a dictionary? Well, obviously, it depends on the situation that you're in. You should use lists when you need to maintain the
order of elements and access them by position and use dictionaries
when you need to access the elements by keys or need to store key value pairs. If you have something where it's very important that you
maintain the order, go ahead use lists when you have something
that is a bit more complicated and
you'd like to have key value pairs than the
dictionaries are the way to go. Finally, before we move on, we need to actually add
the items that we try to. Well, get in here, the chosen part we print
out that we are adding. This is not true
because before we print out that we're adding, I'm
not going to leave this. We have to check if the current choice is in
the car parts already. We need to first of all,
create these car parts. We're going to create
underscore parts, and we'll say that it's equal to an empty dictionary in here. I mean chosen part,
not the current part. If the chosen part
is in the car parts, then I'm going to go
ahead and print out removing the chosen part. How do we remove an item? How do we remove an item? By using the pop, even though in this
case it's going to always be inside
of the car parts, but being extra careful
never hurt anyone. Also in here we're
going to add an L and we'll say that we want to, we're adding then car parts. Current choice
equals chosen part. What else do we need
to do? We would also like to maybe print
out our list. We'll print out your
dictionary now contains, we'll just print out everything. So we'll print out
our car parts. Right click and run.
Let's add wheels. Boom. Now we have
one wheels to boom, lights to boom, and lights
were added on top of it. That's because, oh, I apologize. This should be indeed the
current choice because again, this was a mistake that I made. I could have edited this out, but I would like
to keep it because at first I did it correctly, then my mind was still in
the lists part right here. Current choice should be used
instead of the chosen part. Because remember when we use in, we are iterating over the key. We're checking if the
key was already there. Now when I write
click and I run, for example, I add
wheels, I add lights. I want to remove the lights. I hit too, and there we go. Now it gets removed. When we were trying to
use the chosen part, it was a value, the
chosen part was lights. So we went through our dictionary and we
didn't find lights in here, so we did not remove it. So I hope you understood, for example, three
front wings four. If I tried to add another four, you can see that
it gets removed. We add seats. We
then remove seats. So I hope you enjoyed it.
I hope you understood. I hope you appreciated
that I kept the mistaken side because
maybe some of you did it, maybe some of you did
not understand why we turned from a current choice to the chosen part
and then back. I think this is worth keeping. I hope you understand. I hope you appreciate the transparency that
I'm trying to show here. And I will see you
in the next video where we will apply
this knowledge to create a computer
builder project. I will see you then.
108. 7. Multiple dictionaries use: Welcome back to my favorite
Python programmers. In this video, we're
going to be using multiple dictionaries
together to get the data that we need. First of all, we want to display the item that the user selected. Right here, you can see
that your choice is we press two and then we just
get our computer models. What if we wanted to actually show the user what
they selected? Let's go ahead and do just that. Under where our
choice is checked. If it's equal to zero, I will add an L. If in here, sorry, I will add an L. If in here LF, the choice is in the
display dictionary. We are going to go
ahead and say that the selected underscore
item is going to be the display dictionary
or the choice in side. And then we will simply
print out you have selected and then
replacement field and the selected
item, there we go. When I write click and I run, and I want to also maybe
add something in here, maybe like an extra space. Maybe a space in here. Print out just an empty print, right click, and I
run your choice. Let's go with the three. There we go. You have
selected Home desktop. Maybe two dots in
here would be good. Then if I hit one gaming. If I hit six, there we go. I get nothing. I just get everything
displayed to me again. If I hit zero, I exit out perfect. Our program is working
perfectly well. Now, before we move on, we want to do one more thing, and that is when we
actually select a computer, let's say the gaming PC, We want to print out
all of the components needed to create or to
build this computer. So I'm feeling tired,
I'm feeling lazy. I've recorded for such
a long time today. That is why I'm giving it to
you as a challenge where, yes, you will need to display
the needed components. First of all, print out
the components needed. Well, that's just
a broad challenge. You'll need to use
the computer models dictionary we've imported, and get the component using the selected computer
model as the key. If you remember, we
created the selected item. This can be used as a key on the computer models
dictionary in order to get all of the components. Good luck. This is not easy. But trust me, if you can
solve this challenge, you are on the road of complete data handling
mastery using dictionaries. So please take your time, do your best, and I will
see you in a few seconds. Welcome back. How did
you get on with that? Our goal is to get the
components needed. In here, I'm going to
print out the following. I'm going to say that we
are checking components. Components needed, three dots. It's like we all were checking. We're going through
so many things. Now, components is equal
to the computer models. We're going to use
the selected item, then we'll print
out the components. If I write, click and
I run your Choice one, look at that, look at that, your gaming PC, checking
for components needed. Cpu GPU D, HDD
motherboard cooling, and a case, if I wanted
to get a workstation, then I would need CPPD, HDD, power supply, motherboard, everything the same
as the gaming PC, but I also need a monitor, a keyboard and mouse. I hope you did the challenge. I hope you tried your best. Before we leave, let me just re, explain what we actually did in here because some of you
might be still confused. First of all, this
should be obvious by now The way we created a
display dictionary, where we get the following, then the user selects one of these computers
that we have, one of the computer models, for example, they select four. When they select four, so right here, the
choice is four. We check if the choice is or is equal to zero,
then we break out. If it's not, we check if the choice is in the
display dictionary. If it's not, then
we go back through the wire loop and we
print it out again. If it is, then we create something called
the selected item, which is going to be
the display dictionary at the current choice. For example, if I press two, then the selected item is
going to be business laptop. If I press four, then the selected item is
going to be the media center. This is how we created
the display dictionary. If you're not sure
how this works, go back to the previous video. Then we say, we want to print out you have selected
et cetera, et cetera. This is where the output
we get then checking for the components needed and
this is where we get them. Now the more important
part is when we use the selected item as a key on the computer models to get
access to all the components. For example, if we
selected the media center, then we use the media center. The selected, let's
say we selected four. The selected item is
now media center. We use this media center, we feed it into the
computer models dictionary right here
on the computer models. We scroll down media
center and we get CPU, Ram, SSD, power supply, Blue Ray Drive, TV turner. What? Tv Turner tuner. Tv tuner and remote controller. Okay, so I think I explained
it as detailed as possible. If you're still unsure, rewatch the video, make sure that you
understand everything. Because in the next video, we are going to be looking or checking for computer parts. We're going to be
expanding on our storage. Expanding on what
each model needs. Please go back, make sure
you understand everything, even if it takes you more time than you think it's
worth, trust me. Once you understand it, data handling skills will
go through the roof. It's imperative to
understand dictionaries. No career that you
will go through will require you to
not use dictionaries. You will always have to use dictionaries in
some form of way. Thanks so much for watching. I hope you enjoyed, and I will
see you in the next video. Where we will be
checking and going deeper into computer parts even.
109. 8. Checking the computer parts: Welcome back my fellow
Python developers. In this video, we're going to be checking the actual
component parts. Meaning do we have the parts required for this
specific build, for this specific
computer model, I mean, or do we not
have these parts? And then we will upgrade
our dictionary so that we also can see how
many parts we need, Meaning that we might
not need just a Ram, we might need ten Rams
or 60 SSDs or whatever. So basically, the goal of
this video is going to be to expand our project. And while doing so, expand our ability for data handling using the dictionaries that
we just learned. So let's go ahead
and get started. First of all, we'll need to type in the following code that will tell us whether the item that we're looking for is
available or not. Someone here, I'm going
to say four components or component underscore
part in components, we're going through
every single component. If the component part is in the computer parts
storage, there we go. We're going to print out back
replacement field computer is available and then else we'll print out backs, you don't have the
necessary part, we'll tell them which
part they don't have. Boom, there we go.
Maybe I should move this more to the right side so that we can clearly see
what's happening in here. We've got our components
from the last video. Now we use these components, we iterate over them, and we check if those component parts are
in the computer storage. Remember the computer
storage is this, right Here we have the key. Remember, when we do we
go through the keys? We've learned that in
video number maybe five. And if the component
part is there, then we say it's available. If it's not, we
say that we don't have that necessary part. If I write click and let
me make this bigger. So one boom, let's see, the CPU is available, GPU is available,
everything is available, nice for a gaming PC. Let's try the Business
Laptop. There we go. You can see that we
don't have a battery, we don't have a display, and we don't have the touch pad. A few things are
missing in here, but now it's working. But obviously, I said
but too many times, but obviously that
is not enough. We need to check the
quantities as well. First thing we have to realize is that the models
don't specify how many of each
component we need in order to build the computer
model that we want. Meaning that we don't know how many Rams does a
business laptop require? Does it require more
Ram than the gaming PC? Probably not. So we need to check for those
things as well. So adding them will be easy. Very easy, of course,
because right here we can simply just add an extra
item or do something. I don't know, adding
them will be easy. The hard part is knowing how and what data
handling tool to use. For example, would we want to put this or make this
into a list of couples, you know, with the CPU
having a number next to it. Maybe we would like to make
it into a instead of a list. We can change it
into a dictionary. Maybe we would want to use sets. So what would we want
to use in this case? I'm going to update this list and I'm going
to use dictionaries. You will have a file with all
the necessary information. I'm just going to copy this
and paste it right here. There we go. You can see the computer model. The computer models dictionary. You can see that it's made out of the keys which are
the computer models. Each model key has a value
that is a dictionary. And that dictionary contains
the keys as the components, with the value being the required quantity
of set components. For example, we need two CPUs. For our gaming PC, we need four GPUs. For our gaming PC, we need 16 Ram, we need two SSD's, two HDDs, et cetera, et cetera. Now please, some
of you might be. White Point? No, we
don't need CPUs. There are different kinds
of models, whatever. Listen, let's just stick to
this because we will need to create a way to handle
the data that we have. We don't care right now
about the accuracy. We care more about our
ability to be able to access this data
and work on it. Now that we have that, you
will have it somewhere under the video or
anywhere around. If you have a
problem finding it, please contact me Or if
you're not able to download the file or any problem
for that matter, contact me or your
local instructor. Now that we have
that, the next thing we want to do is we
want to change this. Because we don't
want to just print out the components
that are needed, we also want to print
out the quantities. We have the four component part. Now I'm going to say the required underscore
quantity in components, items. So remember now when we use the selected item to
access the computer model, for example, let's say
it's the business laptop. The value that we get
is another dictionary. The other dictionary
is now the components. And now we can use the
item to access the keys and value pair that are
in that dictionary. We can parse them or unpack
them into component part and the required quantity if the component part in
computer parts storage. That's good. But that's not enough
because we will also want to see if we
have enough quantity. Meaning right here, if we have
the necessary quantities. For that reason, I'm going to issue you a challenge to get
the quantity in storage. So, use the dot get method to get the quantity we
have in storage. No, to get the quantity that
we already have in storage, put the value we get
into a variable. And if we do not
have the component, we want to check
for return zero. So pass the video right now
and go do the challenge. It's just one line of code. Okay, welcome back. Hope it wasn't too hard in here. After we get the component part and the require the quantity, what I'll do is I'm going to say the quantity in storage
quantity underscore Underscore storage
is going to be equal to the computer
parts storage get. And I'm going to use the
component part zero, we're basically simply axing the computer parts using
the computer part, because remember the
computer part here is a CPU or GPU or a Ram
or SSD or whatever. We're going into the storage, we're checking this right here, We are returning the
value on that key. If there is no key
with that said name, we are returning
zero. Why is that? Because now it's not enough that the component part is in
the component storage. We have another more
important thing in here. We need to check
for the following. We need to check if the required quantity is less than or equal to
the quantity in storage. If it is, it means
that it is available. But if it's not, then what
we'll do is we're going to do something a little bit different and set things
up for the next video. We're going to say that the
quantity underscore two, underscore y is equal to the required quantity minus
the quantity in storage. Instead of saying you don't
have the necessary part, we're going to say
you need to buy replacement field quantity
to buy of de component part. Now let's see what we
can check in here. And first of all, I want
you to look at the code. I want you to breathe in, breathe out, fully comprehend
what is happening in here. The main points are
the component items, how this became available to us, because now we have a dictionary of
dictionaries in its values, how we access the quantity in storage using
the component part. And also how we're comparing the required quantity to
the quantity and storage. All of these things
are very complicated. Maybe if you're
still a beginner, it's probably like mumbo jumbo. Take the time, pause
the video, rewatch it, redo it, try your own test
things out on your own. Make sure that you
understand what's happening. Because it's very imperative for the next video where we will
be creating shopping lists. Let's test it out. Before we move on in here, let's go back to the computer. Let's see, we have ten CP used. We have anything
that we can't get. Let's see, motherboards,
all of them will require only
one motherboard. What? Let's just try something. Let's say the Ram for
the gaming PC is 16. Let's say we only
have like ten Rams. Okay, so when I write
click and I run, oops, I ran the incorrect
one, right click and run. So your choice. Gaming PC. Hit Enter. The CPU available,
GPU available, But then it says you need to
buy six of Ram or six Rams. Yeah, it's going to be
tricky nailing this down. Maybe just 66, whatever with
an S. Let's try this again. 16 Rams, there we go, six Rams. The SSD is available.
Everything is available. Let's try the media station. Everything is available. The case is available.
There we go. We need to buy one TV tuner, one sound card, and
one remote control. Nice. Let's see. Maybe if we use the
business laptop. Uh huh. We need to buy a
batteries so it's not perfect. Of course, you can create
if statements, change this, change that, make sure that
all of that fits correctly. You can check if one
or greater than one. But the goal here is not
to make this perfect. The goal here is for you to understand how this is
working, and I hope you did. Please go back through the code, make sure you understand
what's happening and I will see you
in the next video. But one thing I wanted to add, we could have changed
this from a dictionary. The value could have been
changed from a dictionary to be a list of topples. For example, imagine that all of these are the
same as this one. Now we could have done that, it would have worked. The only problem is maybe gaming PC would want
to be modified. Maybe we want to modify it. Maybe we want to
give the option to some users to increase the, increase the SSD or whatever. And we want to change it
on the actual model here. In that case this would not
becauses are immutable, but dictionaries can be changed. It's better to have a
dictionary in this case, But a couple would work fine. Thanks so much for watching.
I hope you enjoyed. In the next video,
we will be creating a shopping list out of the quantity that
is required to buy. Some of you are mega
confused at this point. Again, as I said,
take a deep breath. Please try to understand this. If you can get through
this, it's very, very simple moving forward
and you will have a very, very strong grasp on
everything that is related to data handling
using dictionaries. See you in the next video.
110. 9. Create a shopping list: Welcome back my fellow Python programmers to a
brand new video. And in this one we
are going to continue in our computer builder project. Now what we'll do is we're
going to take all of the required quantities of
the required components that we lack and we're going to be adding them to
a shopping list so that they could be sent to Amazon and then the
components could be bought. I don't know if it's
going to be Amazon. I'm just saying there will be a shopping list that's
automatically created. So let's go ahead and do that. First of all, we need to create that dictionary
or initialize it, at least right here at the top. I'm going to create
something called a shopping underscore list, and it's going to be equal
to an empty dictionary. Next, we're going to create
the function that will add these items to
the shopping list. I will define underscore, underscore items or the item because we will be working
one item at a time. We're going to have the data, I will make sure that
it's type is dictionary. You should know how
these annotations work from section number, I don't even know, a few
sections back function. Then we'll have the item,
it should be a string. And we will have the
amount offset item that we need to buy which
is going to be an integer. And we'll make sure
that this function returns none or nothing in here. I'm going to say if
the item in data, then I'm going to
access the data, add that item, and I'm going
to increase by the amount. What this does is it basically looks through the entire data that we have and checks if
the item is already there. Because remember, the item, in this case is going to be the key and the value is going to be the amount
that we need to get. First of all, we
want to check if that key is already in the data. If it is, then we will
add the amount to it. Meaning that, let's say we
needed to buy one battery, now we need to, I don't
know, three batteries. But the second condition
is going to be L or not. The second condition,
just the L statement, is going to be that
we simply say, data at that key item is
going to be the amount. Obviously, this is a function, so it needs a bit of space
from the bottom and a bit of space from the top as
well. There we go. Now we've created the
ad shopping item. Finally, we need to actually
start using this function. Again, I'm feeling lazy. This is a new day for me. It's still early morning. So it's going to be a challenge for you
to call our function. First of all, where should we be calling this function
in our code? Very important,
call the function and provide the following, the empty shopping list, obviously the component part, and add the quantity
that we need to buy. Finally, print out the
shopping list when we exit out of the wild loop. So pass the video right now
and go do the challenge. Okay, welcome back. So the first part of
the challenge was, where should we be
calling this function? Well, if you skim
through the code, if you've understood the code
from the previous videos, that's why it's very important
that you understand what happened in the previous
video and then move on. We're not here to win a race. This is not a 100 meter dash. This is a long marathon that we need to pace ourselves in. Where should we be
calling this function? Well, first of all,
in here we are checking or what
the components are. So the component part and the
required quantity for it. And then we're checking if that required quantity is
available in the storage. If it is, then we
say it's available. If it's not, we say that
we need to buy this item, meaning that this is
where we should be also adding it to
the shopping cart. So, I'm going to
add shopping item, and now I need to provide the dictionary that we
want to add said item to. What dictionary is
that? Yes, exactly. It's the shopping list. Next, we need to
provide the item that needs to be added.
What's that item? It's the component part,
which is right here. That's the component that
we're looking to add. And then finally, what's the
amount that we need to buy? It's pretty obvious
it's the quantity to buy. There we go. Now that we've
called our function, the last thing to do is to actually print out
the list at the end. Once we finish with all of this, I'm going to print out, I mean, I'm going to say four items
in the shopping list, items, I will print out. Items. All right, we
are set, I believe. Let's go ahead and
test this program out. I'm going to run in here. Let's go ahead and
add a gaming PC. All right, so we have everything we only
needed to buy the Ram. Let's go ahead and
add a workstation. All right, what did we buy? We should have bought 22 Rams. Buy one additional IC. I don't know what
that is. Let's go add a media center, right? You need to buy one V
tuner, one sound control. All right? I think that's
enough computer models. Let's hit zero, exit out, and let's see, look
at what we got here. We have Ram, additional IC 111, and the Rams are 28. Let's go and just have a small check of what
if that's correct. So first of all, we needed
to buy six Rams, good. Then we needed to buy 22, which makes this 28. There we go, 28 is what we have. We also needed to buy the NIC. If you remember, we checked that out, it was
the weird thing. I don't even know what that is. Tv tuner, there we go. Look at that, the sound card and the remote
control, look at that. These are couples
funnally enough, what's happening in here is that the data that
we're receiving, even though it's a dictionary, it's being given
couples if you're not sure why and what kind of logic that is,
let me show you. Let's try and just print out the shopping
list on its own. Without anything, I will right
click and run this again. 15.4 and then zero. All right, there we go. Look
at what we have in here. What we're doing is we are
printing out the topples. Remember we have items, and when we're doing the items, it returns a topple
that we should unpack. But in this case, we
are not unpacking it, we're just printing it out. That's the basics of it. As you can see, the shopping
list is a dictionary. We are printing out
the dot items of it. I hope you enjoy it, I
hope you understood. I believe that's not the
conclusion of our project. We still have one
small thing to change, which is going to
be adding items using something called
the set default. And we'll see where that. I hope you understood
everything. I hope you've enjoyed. I hope you are understanding the complexity behind data
handling using dictionaries. Again, I highly recommend
that you go back, you check it out, you
understand what's happening. These are crucial moments in our journey in data handling
using dictionaries. And I will see you
in the next one.
111. 10. Adding Items using setdefault: Welcome back, my favorite
Python developers. In this video, we'll continue
working on our project. This will be the last video
related to this project, so we're going to be adding
items using the set default. And we'll see what the
difference is between the set default and the get
that we were using before. Let's go ahead and get started. First of all, I'm
going to create a new file in here, a new file, just so we can test
out the set default, or first of all, to see what it actually does
and how it looks like. I'm going to create
the underscore set. Underscore Default.
Boom, there we go. Then I will say from
computer parts, content. Import computer parts storage. I'm just getting the
storage in here. Let me close this down.
We don't need it for now. And then I'm going
to want to check out the GPU quantity that we have
in our computer storage. I'll say GPU underscore
quantity quantity, all right, is equal to the computer
storage set default and then I will get the P and
then I will say also zero and I will
want to print out P, two replacement field
and GPU quantity. So what did we do in here? We're not going to run or maybe let's just run and
see what the output is, first of all, okay, GPU seven. If we look back at the computer,
computer parts content, we'll see that GPU right here is indeed seven.
All right, perfect. So if we just look at it
on the surface level, it just returns whatever the value is for that
specified key perfect. There's nothing more to it, at least on the surface level. But if we offer over
the set default, let's see what
description it gives us. It inserts key with the value of default if key is not
in the dictionary. And then it says,
returns the value of the key if the key is
in the dictionary. Basically what this
does is it has an optional effect, if
you want to call it that. If the key is in our dictionary, or the dictionary from
which we're trying to access the value offset key. If it's already there, we just returned the values. For example in here GPU, we wanted to get the
value at the GPU key, we just got the value seven. If let's say the GPU was not in our computer
parts content, then the GPU would be
added to that dictionary. There we go. One more thing in here is the zero
that I provided. So this is the actual
value that would be given. For example, let's say
GPU did not exist. Then when we use the
set default GPU zero, a new item with the key GPU would be added
with a value of zero. We specify what
value we want added. Let's try this out by adding a battery because we know
that we don't have a battery. If you remember, if
you look back in here, we don't have the battery. I'm going to say
battery underscore one, T is equal to the computer parts
storage default and we will add the battery and zero then I'm
going to print out the battery two replacement field
battery quantity. If I write click and I run, look at that, I get a
value for my battery. This looks good. This
is something that we are expecting because of the default value
that we've said, because of what we explored. But this looks awfully similar to something
that we used before, which was the second, let me find where it is. The where did we use the dot? Get somewhere around here. Where is it? Why? There we go. We use get where We would try to get the value from
our dictionary, but in case the dictionary
did not have that key, we would return a default value. This looks awfully similar,
but as I told you, the difference
between these two is, wait, I'm not going to tell you. We're going to test it out. We'll add a sound card
underscore quantity because we also
lack a sound card. And I will say that it's
computer parts storage. Do get. Sound card, comma one. And actually let's add
two batteries in here. Here I will print
out the sound card. Two dots, replacement
field sound card quantity. Right click, run. There we go. Now we have two batteries
and we have one sound card. But there is a difference between using the get
and the set default. Let's see how that is in here. I'm going to print
just an empty space. I will print out that storage
now contains three dots. We're reprocessing things, we're looking
through the storage. I'm going to say four
key value in sorted. I want to sort out my
computer part storage items. The sorted is just a
little bit of extra, it's not super required. In here, I will print
out the key value and add a separator which will be just a column
right click and run. Let's see what we
have. Look at that. We have a battery, but if I scroll down, I cannot find a
sound card anywhere. So that's the basics of it. The battery was added, the sound card was not. So the set default actually
adds to our dictionary, while the get simply prints out a value in case there's
nothing in there. This is a very
standard procedure of adding to our dictionary in case we are working with
something like a shopping list. Challenge is going to be
to update our method. First of all, back in our
computer builder script, I don't know why that's
a point on its own. You'll need to improve our
code by using set default. Simply access the data
using the item key and use set default with item
and add the amount to it. Pass the video right now
and go do the challenge. Okay, how did you
get on with that? It's not an easy challenge, but if you take your time, you should be able to do it. Let's go back into our
computer builder file. And in the method
where we were applying the data or applying to the data the amounts
that we were getting, we're going to change it to
have it work in a better way. I'm going to comment these out just to keep
them for later on. Maybe you want to go back. You want to see what
changes we've made, how we improved our code. And I'm going to say that data, that item is going
to be equal to data. But said default item that we're getting
zero plus amount. What is happening in here? Why is this single line of code, first of all, so complicated? Second of all, why does it
alone replace these two lines? The first thing that we should notice is that we are
accessing the data, which would be a dictionary
at specified item. First of all, we're
either adding or are creating a new
item in there. Then we are using the set default on the
data using the item. What this will do is it
will first of all check if that item is already
inside our data. If it's inside of our data, if the item key, or we have a key that is
also equal to the item, we will get the value from it right here and it will
be added to the amount, and then it will be
set to the data item. And always good in the world, but in case there's not
an item in this data, then we will set it to default, and then we will add
the amount to it. And this should fix
all of our problems. Let's go ahead and
write, Click and run, but before we do wait, I think in here it's a
good idea that we print out the computer parts storage. So in here I will
get a gaming PC. I, you know what, Let's get the whole package. We will buy all five of these. And now I will hit zero and
we should see that Ram 28 battery one touch pad
11111, everything is one. And we've added everything
to our dictionary, so the output is the
same as we had before. But now, instead of
using two conditions, keep in mind this is not something to necessarily
look down upon. Avoiding Using a condition in here could help us out a lot. We simply call one function, now it's debatable, which
is what's more efficient? What's more elegant? Definitely using this
line is more elegant, It looks more professional,
more in depth. And it helps avoid
certain problems that can arise from using
something like this. This is similar to
the choice between dot get and the Dos defaults. Default is simply more advanced. It's better could
avoid future errors. So thank you so
much for watching. We are at the end
of our project. I hope you enjoyed if you're still not sure how
all of this works, especially this
part of the code. I know some of you may be know in general
how this code works, but if you want to go
through every single line, you might get confused. I highly recommend that you go through this
one more time. Make sure that you
understand everything properly and leave me a
question if you have any, anywhere that you can. Thank you so much for watching. I will see you in the next video where we will be
looking at creating, updating and something called values dictionary
from sequences. Thanks so much for watching and I will see you in
the next video.
112. 11. Creating, Updating and Values Dictionaries from sequences: Welcome back my favorite Python developers to
a brand new video. And in this one we're going to be learning about creating, updating, and something
called values. Let's go ahead and get started. The first thing I
will do is create a new Python file that I'm
going to call methods. There we go. Now in here
I'm going to create a surprise surprise
list computer list which is going to
have the CPU GPU. By the way, of course
it doesn't matter if you use double quotations
or single quotations. I just try to use both of
them from time to time. Then we're going to create a new underscore dict which is going to be
a new dictionary. And I will say dict
dot from keys and then computer items and I will print out
the new dictionary. The first, there are
two new things in here, the dict and then the from keys. Let's talk first of all
about the dict dot. You'll see this is
the class dictionary. We can hold control
and click on it to go to where this
class was defined. You can read all
about it if you want. You can even go through the
documentations right here. If I hover over this, you can even go to
the documentations all about the dictionaries, how they work, what they do, what functions they have, everything that
you can think of. You can come in here,
look at the copy, look at the items, for example, look at the keys, the pop, there we go. Some of these, we've already seen the set
default, the update, we'll see in just a bit
the values that we'll see also later on and
so on and so forth. A lot of useful information
and one of the methods available to our dictionary
is the from keys. If we hover over it,
what does it say? It creates a new
dictionary with keys from itteruble and values
set to value. Mm hm. So basically what it's
saying is that it will create a dictionary with
keys from an itterble. So the itterble could be a
list, could be a string, could be a topple, Whatever
that itterbal is from, the items in that itterbal
will create a dictionary, or the items that were
in this itterbal will become the keys in the
dictionary that we create. Let's see what
happens when we write Click and we run
and look at that. So we've created a dictionary out of the keys in our uterble, which is the list in this case. And you'll see that the
values are all none. The list items became the keys for different items in the new dictionary
that we created. But we could have also specified a value
instead of having none, we could say zero. Now when we write Click
and look at that, they all have zero. And from here we can
start changing things, updating things, and
so on and so forth. Let's continue and
let's look at updating. I'm just going to have a small print in here and
I'm going to say that I have one and it's equal to a, then one, then 2.3 I'll have also two, which is going to be A. Wait four, D five. There we go. Now we have these
two dictionaries. You'll notice that only one item has a key in common between
them, which is the B. I'm going to say that
dice update two, let me tell you
what the update is. We'll have or over it
and see what it is. But first, we'll have value in dice items and we'll print
out key value column. If we hover over the update, it does not provide
us with a lot. On the contrary, it provides us with too much
for some reason. Let me try to do this again. Yep, still isn't
showing properly. Anyways, let's try to right click and run and
see what happens. You'll see that we're printing everything from dict
one on the items, the key and the value. You'll see A is one, B is. Four, C is three, and D is five. So at this point, with your knowledge
of dictionaries, you should be pretty sure
what's happening in here. Just like we've seen before. When we try to add another
key into our dictionary. The key doesn't get added
as a separate item, just updates the previous
location of the key, not the location the
previous value of the key. For example in here
the only thing that's in common is the B. The B goes 2-4 when we update dictionary one
with dictionary two, and then this item with a key D gets added
to dictionary one. I don't think that's
too complicated. I think it makes a lot of sense. Now let's continue on, and let's look at
using the enumerate on one of our dictionaries and
what happens in that case. I'm going to add another print. Let's continue from here. I'm going to create three, which is going to be
equal to the following. We have zero as the key. Notice that it's an integer, and the keys can be integers. It will be a display. Oh my god, come on. One. The keyboard two, touch pad three, SSD for the HDD. All right. There we go. This is dictionary number three. And we're going to have did. We will update it with the enumerate over
the computer items. That's a big, big,
fancy line there. But in any case, I'm
going to copy this and I'm going to print
out **** number three. Before we run, I want you to think of what's
going to happen here. Please take a moment, think of what the
enumerator is going to do. And I know there's
a highlight here, but this is not going
to cause any problems. Do as Maybe intelligent
is just warning us, you know, maybe something bad is going to happen,
but I don't think so. I want you to think of what the enumerate usually returns, what it gives us. And then when it's used on the computer items and used
to update dictionary three, what the output is
going to look like. Take a moment and think
about it obviously past the video when I write
click and I run, look at what I get. So my dictionary three had
at zero road display at one, keyboard at two, touchpad at
three SSD and at four HDD. Now after my update here
at zero I have CPU, at one I have GPU, and at two I have ran. So what happened in here? Well, what happened is, and by the way, the
3.4 stayed the same. And this should be a
huge indication to you, the computer items
is the list that we created right
here at the top, we have CPU, GPU, and Ram, and they conveniently went
into their positions. Why is that? Well, because
remember the enumerate returns the index and the value associated
with that index. We have zero CPU, one GPU, and two Ram. When we do the enumerate, we get the zero CPU, 12 Ram. And then when we update
dictionary three, it just looks at it and it says, okay, so zero was display, but now it's CPU,
one was keyboard, but now it's GPU and three
or two was Touchpad, and now it's Ram. And then on the SSD and the HDD, nothing changed because we don't have extra
elements in here. If we had an extra
element right here, it would change the SSD as well. Okay, I hope that was clear. I will try to do something to maybe make it
even more clear. What do you think would
happen if I changed this 2-6 Think about it.
Take your time. Think about what the
output would look like if I write click and I run, look at what I get bit weird. Let's diagnose it. First of all, the CPU and the GPU go through
the same process. Where we have the computer items 01.201 but there's no two, the 0.1 get replaced. Then we have the touchpad. Correct? Touchpad
stays the same. Three SSD stays the same. Four HDD stays the same. Now the question is, how did the Ram get here? Well, remember we
still have the Ram. We still enumerated over this
entire computer items list, we have 01.2 The
only difference is that the 0.1 were replaced
using the CPU and GPU, but the Ram was
added at the end, at the bottom after
everything else. Just in case you're still unsure of what's
happening in here, I will just say four
value in enumerate over the computer
items and then I will print out the index value. And the p will be, as always, these two dots. And let me just add a print in here just so we
can separate things. Look at that, CPU GPU, Ram 01.2 they were used to, they were to replace the
display and the keyboard. They were not able to
update the touchpad, the SSD, nor the HDD, but the Ram was still
added at the end. This is how we can
update our dictionaries. Before we move on,
let's go ahead and look at values in here. I will do another print, I will three underscore values is equal to dict three values. I will print out
dict three values. So if I write Click and
I run, what do I get? I get dict values, CPU, GPU, Touchpad,
SSD, HDD, and Ram. So what is this? Basically it returns
a view object that contains the values
of the dictionary. You can use this method to
iterate over the values of a dictionary or convert
the values to a list or maybe
another data type. It's very useful to
check what the values that are inside of
this dictionary are. So look, we have the values
that are represented. So we have as the keys, the 016342, and inside
we have the values. So now we have this list of values and we're going to
see how this could help us. And actually when I say we, I mean you because you have
a challenge to check for an. So I want you to use the dot values to iterate
over dictionary three, even though I've done
this for you already. But I want you to print
out all of the values, and I want you to use an F
statement to check if we have Ram in our dictionary
using the values. Pause the video right now
and go to the challenge. Okay, welcome back. How did you get on with that? We've already used the values. I'm not going to
delve again into it. What I'll do is,
I'll say if Ram, actually Ram in dict values
three. I should have. Sorry for this. Okay,
what am I doing? Hold down shift shift
Alt to move this down. Make our code look good. And it's going to
be three values. If Ram is in the
**** three values, I will print out,
you have Ram, Ram. Congrats. If I write Click and you'll see
that you have Ram. There we go, so you have Ram. Congratulations. As you can see, this is a faster way of us
going through the values. Because remember, if we do, if Ram in dict three without the values that we're
checking right here, it will simply iterate
over the keys. Then if we wanted to
go through the values, we had to use those
keys and put them in a dictionary and then
extract the information. A long process, this allows us to access the values directly. If you're still looking at this, this is called a view object. It's something a
bit more advanced. I don't want to delve too
deep into it right now, but if you're like a way way, what the heck is even object
are these real values. You can simply do a four loop, four value in dict values
and print out the value. This should become
very clear right now that we are iterating
over the values. I hope you enjoyed, sorry
for the very long video. Honestly, I was not expecting
it to be that long. But we learned a lot. We learned about creating
using the From keys. We learned about the updating. We learned about enumerating. We learned about updating and
enumerating and we values, so a lot of valuable
information. In the next video,
we're going to be looking at shallow copy and then deep copy and we will be done with dictionaries
and move to sets. Thanks so much for watching. I hope you enjoy it and I will
see you in the next video.
113. 12. Shallow copy with Dictionary: Welcome back my fellow
Python developers. In this video, we're
going to be looking at shallow copy
and dictionaries. Or with dictionaries, let's
go ahead and get started. First of all, we need to
understand that there are two types of copying. There's the shallow copy and
then there's the deep copy. We'll be looking at
deep copy later on. First of all, we'll
go to file and create a new Python
file which will be the show underscore copy K.
Let's close this one down. We don't need it for now. And we'll create dict one
which is equal to a one. Oh my God. And close
this down again. Let me copy this because
honestly, I'm feeling lazy. Base, base this Bc23 space. Does it look nice? Yes, it does. All right, so in here I'm going
to say that I have **** two equal to **** one. **** one at position or
at key B is equal to 15. Then I will print out
**** two At look at that. What I did is I changed the
value of the key on **** one. What do you think the output
is going to look like? I will write click
and I will run, and now I will get 15. Hm. Interesting. Even though I changed it only on
dictionary one. Dictionaries are mutable,
which means that you can change the content of a dictionary after
it has been created. This is very important
to keep in mind, but what can we do
is actually create a copy of our dictionary without having that
second dictionary change, just to keep an old
version of our dictionary. Let's go ahead and do just that. I'm going to comment
this out, this line out. Instead, I'm going
to say that dict two is equal to dict one copy. Then in here we change dict one at B. I'm going to
print out **** two. Let's go ahead and also
duplicate this and print out dict one at kb. What do you think the
output is going to be now? Well, if you don't
know what copy is, it just creates a
shallow copy of D. If I write click and run, it should be pretty obvious that first of all
it didn't work. Now it works. Look at that. On the dictionary number two, we still have B as two. On dictionary number one, we have at 15 because we
only updated dict one. When we create a shallow copy, it means it's a completely
different copy, a completely separate copy. And we're going to see more
examples that explain this. But this should be
pretty straightforward. There's nothing too much
in here to think about. I'm going to add a
print and I'm going to continue on in here. I'm going to create the
original underscore dict. I'm going to say that
the original dictionary is going to be a two dots. Pop 111 space, copy all of this, and then paste and paste. We're going to have B
and C and have 2202333. And we'll just remove
this even though it won't cause any errors because
Python is that amazing, but better to keep it clean. And then here I'm going to
have shallow underscore, underscore dict and
it's going to be equal to the original
dictionary copy. Then I'm going to say
the original dictionary at position at kb. Old habits die hard. Append and I will append by 22. What is happening in here? I want you to really think what the output is going
to be like when we print out the original and
we print out the shallow. First of all, what
does the append do? Please remember the append. Append, okay? Or appending means
it adds to it. So remember in here we have
dictionaries with keys, strings, and the
values are lists. So right here, this is a list. So when we say append, we are adding two to
222 to two, okay? So we're adding 222
to the list on B. This is what we mean
when we do this, because when we extract
the value at key B, we have a list which
means we can append it. So what do you think the
output is going to be when we print out the original list and the shallow? Think about it. Boom. There we go. Yeah, wait, wait,
wait, wait, what? Wait, Isn't this a shallow copy? It is, isn't it? Then why did the original
also change in weird, but very interesting indeed. Let's take a challenge in order to understand
what happened. What I want you to
do is to create separate lists out
of each key value. What I mean by that
list should be 111, list B, 222 should be 333. Then in the original dictionary, I want you to set the keys a, B, and C to their
corresponding list. Meaning we don't want
to literally say that a is 111, is 222, whatever. We want to say that a is list a, B is list B, C is list. And then I want you to append
list and I want you to tell me what happens to both dictionaries and
how do they behave. Pause the video right now
and go do the challenge. Okay, welcome back. How did you get on with that? I'm going to have
a equal to this. Duplicate this twice. We'll list list 2202333. Now instead of this, we'll have list a list list. Then we need to, instead of doing this, I'm going to comment this out. I'm going to get
list B append 222. Now if I write click and I run, the output stays the same. But it should be much
more obvious how this changes the
shallow copy as well. I might have made a mistake. I was saying how did the
original copy change? Because we actually changed
the original dictionary. What I meant to say, how did
the shallow copy change? And as you can see, it's because lists are mutable. In here we got the list, we appended the list. And the list appended not only on the
original dictionary, but also on the
shallow copy of it. So the list actually updated. The list is an object
that we updated, and because it's mutable, it also updated on the shallow
copy and everywhere else. So we're updating a list. Okay? That's why
the shallow copy had its values also updated. Let's bring this home and
make sure that we fully understand it in the
original dictionary. I'm going to do the
following original at key B, append and I will
append added original. The shallow copy added
via shallow copy dict. Even though it's a
list of integers. We are appending
it with strings. When I write click and I run, look at that, I get both. Okay? This is
because when we are appending one dictionary
at a certain key, it means we are
appending that list. And lists are mutable, which means they change
across all of our program. So regardless of if we use the shallow or if we
use the original dictionary, we are appending a list
which is changing. And it will change across
all of our dictionaries. If we're using the same list, I hope that makes sense. It might be a little
bit confusing, but if you go through the
steps and you understand that these were just simply lists, it becomes much more obvious. Thank you so much for watching. In the next video, we are
going to be looking at Deep Copy with dictionaries
and I will see you soon.
114. 13. Deep copy with Dictionaries: Welcome back my fellow
Python developers to a brand new video, and in this one we're going
to be looking at deep copy. Let's go ahead and get started. First of all, we're
going to create a new Python file that where we are going to be
doing our deep copy stuff. Deep copy. Hit enter here. First of all, I'm
going to create the original underscore dict. It's going to be equal
to the following. We're going to have
a two dots, 12. And then we'll have to do, I keep calling them two
dots. These are columns. They are called columns, but the name is not as
important as the functionality. And as long as you
understand what's happening, this is a dictionary, with the keys being
strings, being letters. And then we have
inside the value, which is a list. Next we're going to
create a shallow copy. Shallow copy and shallow
copy dict, let's call it. And it will be equal to the
original dictionary copy. We've seen this in the previous
video and how it works, I'm going to print out the ID of the original
dictionary A. Duplicate this and print out
the shallow, shallow copy. Dict, shallow copy.
Yeah, there we go. So we are printing
out the two IDs of a first of all of the original and then of
the shallow copy. What I want you to do, what I want you to
do is I want you to think of what the
IDs are going to be. Now, obviously I don't want
you to guess the exact ID. I want you to guess
if they're going to be the same or they're
going to be different. And it should be obvious if you clearly understood what
happened in the previous video. Think about it before you run. And when we run, you'll notice
that they are the same. Now why are they the same? Well, this is because it's a shallow copy, if you remember. Because the shallow underscore or shallow underscore copy, underscore dictionary, it's because the shallow
underscore copy, underscore dict is a
shallow copy dictionary of the original one. What happens is the
items or the value inside of the items of
the original dictionary, which are lists, stay the same. In here, notice we're
copying at a at the key a, which means we are
referring to the same list. We've seen the result of
having this shallow copy. When we change one list, the other one changes
on the second copy. Now we're going to be
looking at deep copy and it's going to be a challenge for you to create a deep copy. First of all, look up how to create a deep copy
of a dictionary. You can go to a website called Geeks For Geeks, I
think it's called. You can check out how
deep copy works there. Create a deep copy of
the original dictionary, print out the ID at the key a, and try appending the
original dictionary so that we can see what
would happen in that case. Does the deep copy change when you change the
original dictionary? Pause the video right now
and go do the challen. Okay, welcome back. I hope you tried your best to go and search on how this is done. It's very important
for you to also understand how research works. So first of all, I'm
going to import copy. So this is the first
thing we need to do. There is a module
that we need to import which is the copy. Next, I'm going to create a print in here just
to separate things. And maybe even, let's just do a few stars in here multiplied by 50 so that we know that we are now entering into
the world of deep copy. We had shallow copy, now we're working on deep copy in here. I'm going to say
underscore copy. Underscore dict is equal to copy deep copy of the
original dictionary. I will print out, let me
just copy these because I'm lazy. There we go. So what do you think the
output is going to be now? Now, I, obviously you've done this probably at
this point, you know. But let's say you haven't
done it, you were lazy. Now is the time to
stop being lazy. So tell me what these
are going to be. Are they going to be the same or are they going to change? When I write, click and I run, you'll see that they
are indeed different. Why is that? Well, first of all because at the first
time they were the same. So obviously some
of the changes that we made should change
how these behave. But that's beside the point. This is psychology, but
we're talking about real science or
programming science. I don't know what
you want to call it. You can see that they
indeed do change. Because when you
create this deep copy, let me hover over to see
deep copy operation. Okay? Doesn't necessarily
describe this, but if you go and search for it, it actually creates a
completely separate items from the original list, from the original dictionary. Meaning that the lists are new, they are completely different, they have been deeply copied, if you want to call it
that, to double check this, let's go ahead and try to
change the original dictionary. Just like the challenge told us, the original dictionary
at a append with 12. Let's append it with 12 and we'll print out the
original dictionary. And we will print out the
deep copy dictionary. And we will print out
the shallow copy. I want you to tell me what the values are going to be
before we run the program. It should be fairly
obvious that now you'll see that the
original one modified, the deep copy was
not modified and the shallow copy
indeed modified. So there are no changes
to the deep copy because these are two
completely different lists. They are no longer linked in any shape or
form by anything. They have different IDs, they have different
complexities. They work on completely
different playing field. So I hope this was obvious, I hope you understood what
is happening in here. When you're doing
a shallow copy, it's a simple
transform of the list. But when you're working
with a deep copy, you have a completely
different dictionary, with completely different lists, with completely
different values, and items, and keys. They are not the same at all. So thanks so much for watching. I believe this is the last
video on dictionaries. Maybe I'll add more later on, but for now, this is the end. In the next video,
we're going to be taking an introduction
into sets, which is very exciting. I'm always excited to
start something new. Thanks so much for watching. I will see you in the next
video. Bye bye for now.
115. 14. Introduction to sets: Welcome back my favorite
Python developers to a brand new video. And in this one we are going
to be looking into sets. I'm going to keep
dictionaries and sets in the same section because they
are, well, very similar. I think maybe I'll
separate them. Who knows? Let's go
ahead and get started. First of all, what the
heck are even sets? A set is a collection of
unique elements in Python, emphasis on the word unique, denoted by curly brackets
or the set function. So this might come
as a surprise, but dictionaries and sets are denoted both using
curly brackets. But you'll see that
it's pretty obvious, or there's a very easy way of distinguishing
between these two. First of all, let's
look at sets are mutable and can be modified
using various methods. They are mutable,
they can be modified. Sets can contain elements
of any data types. You can have strings, integers, lists, maybe dictionaries,
maybe a set of sets. Even you can do that. Sets do not allow
duplicate elements. This is very important. Unlike dictionaries
where you might have the same key and then you'd
have changes to the value. When we're working
with, with sets, there is no way that you can
have duplicate elements. You cannot have two elements
being the same in a set. Sets are ordered. This is very new to us. This is a new concept, meaning that their
elements do not have specific positions or indexes. If you remember when we
were working with lists, we start at 0123. We can access these
elements using their index. When we're working with
topples, the same holds true. We can use the index to access certain elements
in the topple. And when we're working
with dictionaries, we can also access
elements using their ID, using their keys. But now, when
working with a set, you cannot access any element by its index because they
don't even have an index. They are not ordered,
they are unordered. They do not have a
specific position. And you'll see every single
time we run the program, the set is going
to look different. Sets can be used for
operations such as union, intersection difference, and symmetric difference
using operators or methods. We will see all of these
in the upcoming videos. So strap on your thinking caps because we're going for a
ride looking into sets. They are not very complicated. Sets are actually very simple. Everything that we do is
going to be very easy. It's much easier
than dictionaries. But keep in mind that
it needs concentration. It needs understanding. So this is a set of animals, cats, dogs, horses, birds,
chicken, and reptiles. So I want you to tell me if
this set or in this set, what's index number zero? You can't because
they are unordered. You can start from the
top and you can say, oh, dog is slightly higher than cat, Dog is at zero, Cat is at one. But somebody might argue, we want to start from the left, Dragon is at zero,
cat is at one, bird is at three.
You see what I mean? Every single time it
will be different, they are under
this, for example, will be a representation in code of what this
set would look like. We have a set of animals, cat, dragon, chicken, snake, reptile, et cetera, et cetera, whatever you want to
fit inside of this. All right, so enough theory. Let's go and explore using code. I'm going to create
a new Python file in here that I'm going to call the introduction to
sets or set int int. I will write click and I
will close other tabs, we can write Click
in here and close other tabs so that
we have a fresh tab. Just for the sets in here, I'm going to create fruits
and it's going to be equal to apple banana, come on orange, kiwi and pineapple. And then I'm going to print out the fruits when I
write click and I run, this is the output banana. Orange apple Kiwi.
Pineapple. Mm hmm. Interesting. Did you
notice that banana is in the first position and
apple is in the third, and then orange
is in the second, whilst in our original fruits, apple banana, then orange. You can see that
there is no longer an order to these if I
right click and run again. Now apple is in the beginning, but there's not a
banana after it, there's an orange and
the kiwi is at the end. As you can see,
they are unordered. Every single time you run the display changes and it might be different on your
side, it doesn't matter. You can also iterate over a set. For example, in here I can say four fruit in fruits.
Print out the fruit. When you write click and
you run, boom, there we go. Orange, pineapple,
apple kiwi, and banana. You can iterate over it. If I run it again, you'll
see that the order changes. And notice how it's the same
as the set that we created, or output it right here. Apple, kiwi, orange,
banana, pineapple. This should be obvious.
Nothing too much near. There are a few things
to keep in mind when having an unordered list. It means that there is no
point of trying to access an element from a
set, for example. What I mean is if I
try to print in here, and I try to print out
fruits at position one. I mean fruit, fruit
at position one. Notice that we immediately
have a highlight. If we hover over the
highlight, what does it say? Class set not defined, Get item operator cannot
be used on this instance. If I try to write click and run, you'll see that I
get an error and actually a type error because the set object is not subscript, you cannot subscribe to it. Unlike my future Youtube channel or the one that is already up, you cannot use the brackets to access certain elements
because there's no point. What is at element
one, We don't know. There's no order to this. It's not like this order
right here. Don't get full. Don't think that one
should be banana. Because if I write
Click and I run, it's different, now it's orange. There's no point of
trying to access. What can we do with sets? Well, we can get two unordered
sets and compare them, for example, I'm going
to comment this one out. I'm going to create more
underscore fruits in here. I'm going to have orange. I'm going to have banana. I'm going to have apple. I'm going to have
pineapple and kiwi. There we go, You'll notice
that it's the same, but these have two
different orders. Interesting, at least
when we rolled them. I'm going to say fruits
is equal to more fruits. I will point out they
are the same else. I'm going to say they
are not the same. What? They are not the same. What do you think the
output is going to be? Are they going to be the same or are they going
to be different? Think about it. Tell
me what you think. When I write, click
and run, boom, they are indeed the same even though their order is different. Because there's no point
to having an order. They have the same
elements inside of them, which means that they
are indeed the same. If I change this and for
example, add cherry here. Now if we write
Click and we run, you'll see that they
are not the same. They can be used for comparing. Let's continue on and let's
look at something that I might have not talked
about as much as I should. You'll see that in here we
have something where we said denoted by
the curly brackets or by the set function. Let's look at the
set function and how it operates in here. I'm going to add another print. I'm going to say numbers, numbers underscore
list is equal to 12,318.9 Then I'm going to print out the set
of numbers list. Before we run, let's look at
the set I have right here, new empty set object built an unordered collection
of unique items. If I write click and
I run, there we go. You can see that we've
created a set of these numbers that we have noticed that they are unordered. Even though 12.3
they are ordered in, if you want to call
it like their order of the integer meaning 123918. Maybe if we add
like five in here, it should also go in
the correct position. There we go. But this
is just by default. It's not because the
set gets ordered, you cannot access
elements inside of it. So I hope you understood
this is not too complicated. Sets are fairly easy. Now I have a challenge for you. Your challenge is going
to be to set a string, create a string variable, any string variable you want, convert it into a set
using the set method, and print out the output and
tell me how it looks like. Okay, so pause the
video right now and go do the challenge. Welcome back. So how did you get on with that? Shouldn't be too complicated. Simply in here, I'm going to print out just an empty line. And I will say string
underscore var is equal to Hello World. And I'm going to print out the set of string before we run. If you haven't done
the challenge, even though I'd be very
disappointed if you haven't, We need to right click
and run and you'll see that this is the
output that we get. We have the space, obviously, because
it's also a character, the W exclamation mark,
et cetera, et cetera. Because remember also something very important in here that
you might have overlooked. How many L's do we have? We have three L's
in our string var. How many L's do we
have in our set? Only one. Why is that? Because inside of a set, you cannot have
duplicate elements. I hope you understood. Thank you so much for watching. Keep in mind that because this is an interbal meaning that each character is an
item in the string, just like we have
a list in here, that's why we have
each character being an item in our set. Thanks so much for watching.
I hope you enjoy it. In the next video, we're
going to be looking at adding into sets and duplicates. So I will see you then.
116. 15. Adding in Sets and duplicates: Welcome back my fellow
Python developers. In this video, we're going
to be looking at adding items to a set and
checking duplicates, meaning removing
duplicates from a set. Let's go ahead and get started. First of all, I'm
going to create a new Python file in here
that I'm going to call adding underscore
two underscore sets here I'm going to
create numbers, so I will initialize numbers, but the problem is, is this a set or is
this a dictionary? Mm hmm. Let's not try to imagine this. Let's just try to
actually test it out. Let's check what type number is. If I write click Run, you'll see that the class
is that of a dictionary. Well that's because in
order to initialize a set, we need to set it
as this function. Now when I write click run, you'll see that I
indeed get a set. So how do we add to the set? Well, I'm going to go ahead
and do the following, saying that number ad, and I'll just add 42, the answer to the universe. And I will also print out
numbers, right click, Run. And there you go.
You can see that I have 42 inside of numbers. Add simply adds nothing
too much in here. Let's create a loop that
keeps adding to our set. In here, I'm going
to add a print, and then I'm going to say, while the length of
numbers is less than six, I'm going to create the
value underscore two. Underscore ad is going to be integer input and inside
I'm going to say, please enter the value
to add the value add. Let me make this bigger. In here, I'm going to
say numbers, value. Then I will print out
numbers at the end. Right click and run. We're going to be
getting inputs. I don't think this code needs to be explained too
much at this point. You know exactly
how we loops work, you know exactly what length is, you know exactly how to
get into your inputs. Now we just learn how to add. I don't think there's
too much in here. Let's go 1216, 4089,
0230, 2605 pumps. I was looking at my keyboard, as you can see we have
these different numbers. All of them have been
added and they are set. And notice that they don't have the same order as we've added them when
we were doing input. That is very good and
it's an indication of how class or how
our sets operate. Let's now try this again, but this time I'm going
to add 122 times. There we go. You can see that now
we have a 12 in here. And by the way, if
you're counting the numbers and
there are still six, keep in mind that we added
42 right here at the top. Keep that in mind. You can see right here that we have 42. I 12 only added once
even though we've added it multiple times or tried to add it
multiple times. Let's add 12 times. There we go, Look at that. If I keep adding 12
even before we do this, it will keep trying
to get inputs because the length of numbers
will never go above six. Because we keep trying to add 12 and the duplicate
is being removed. So this is one good
functionality of having sets in case you ever do or
don't want to have duplicates in your code
or in your lists or sets, or any data set that you have. You can shove it into a set, it will just remove
the duplicates. So it's a great, great tool. Let's continue on,
and let's now look at removing duplicates
in various ways. I'm going to create
a new Python file that I'm going to call
removing underscore. I'm going to have
a list of orders. Will one come up? And a few times I
will order 234567. I think that's enough, but
I want to scramble them. What I mean by that is I want to 132. Let's just keep 45 to 83123456. And let's just have a seven
here and a five here. Okay, so as you can see, there's an issue in here. The issue is that we have
order two appearing twice, correct? Yeah, only twice. So this is an issue and maybe the user or the
programmer did not notice this or there was a bug in the program to get
it order unintended. In order to make sure
that we don't have duplicates inside of our orders, we can convert this into a set. And when I say we, you know
the drill, I mean you, because you need
to create a set, you'll need to
create a set out of the lists of orders
that we can have. Use the set function and
print out the result. Pause the video right now
and go to the challenge. Okay, welcome back. How did you get on with that? I'm going to have
the unique orders, and it's going to be equal to a set of orders, and that's it. And now when I tried to
print out the unique orders, you'll see that they are
all different and we do not have duplicates.
How cool is that? Now, of course, you
could have went through this list and tried to check if you have order two
multiple times. But what if you had order
seven appearing three times, order 25 times, order 310 times? It would take a lot
of time to make sure that there
are no duplicates, a lot of statements, a few four loops, a few y loops. Using this, you can simply shove your list that has duplicates
into the set function, and it just returns a new
set with no duplicates. It saves us a lot of time. We could also do the following. Instead of just
having these orders, we could have them sorted instead of these being random
and all over the place. If I write click on There we go, you can see that they
actually get sorted. And notice something
very important as well. When you use the sorted, it converts it into a new list. Now you have a sorted list of your orders as well,
without any duplicates. But what if you wanted
to keep the same order? We can do the following. Instead of using the sorted, we can say that we want to have, actually let me duplicate this. Let me take this back to its original form and
then comment it out. And duplicate this as well. And comment it out now, so that you can see
all the phases of our project or
program or example. We can do the following.
We can say dict that from keys, orders. Now when I write
click and I run, look at what I get, I
get order 13247865. Okay. That's too long. Okay. Let me put it down here. Or actually, I could
have used the bar. Why didn't I use the bar? You'll see that order
two only appears once and order three is
in the correct position. Using dictionary, what you could do is let me duplicate this, turn it into a list. There we go. Now you have a list which still has the same
order of orders. The set, unfortunately, will not preserve the order for you. This is an overview of how you can add, how
you can convert, how you can create sets, and we are beginning to see
how useful this can be. In the next video, we're
going to be looking at erasing items from sets. So I'm very excited
to see you there. Thank you so much
for watching And I will see you in the next
video in a few seconds maybe.
117. 16. Erasing items from a Set: Welcome back my favorite Python programmers to a
brand new video. And in this one we'll be looking
at raising and deleting, and discarding and
clearing everything that involves taking elements
or items out of a set. Let's go ahead and get started. First of all, we're
going to create a new Python file
that I'm going to call decrees set here. I'm going to create the
computer underscore components and it's going to be equal
to the following set. We're going to have a CPU, GPU, Ram control, SSD control D, and HDD. A few computer components. Let me put this back on the right hand side
to have more space. Let's first look
at what happens if we want to clear out
the entire list. I'm going to simply get
computer components clear and then we'll print
out computer components. And if we write,
click and we run, this is what we get a set. Notice that we don't have two curly brackets
with nothing inside of them because that can be confused with an
empty dictionary. It's a set with
nothing inside of it. Let's continue on
and let's look at two different ways of
removing items from a set. I'm going to comment
these lines out in here. I'm going to say,
computer components. Remove the SSD. Duplicate this, and now we
discard them because we've, the SSD should be removed. Also, we want to print this out. Let's move this
one up right here. If I write click and I run, I should see that the B and
the SSD were both discarded. If I write click and
run again, there we go. You can see that they are
no longer there. Very nice. Why do we have two ways to
remove elements from a set? Why not just have one? Since both of them work well, this is going to be a
challenge for you to raise something that is not in
our set or not there. Try discarding an item that
is not in our set now. Or try the mouse, for example, print out the components. Now, try removing the mouse, what is the difference? Pause the video right now
and go do each challenge. Okay, welcome back. I hope you tried your best to. Let's comment this out as well. In here, I'm going
to do a print. We don't need a print in here. I'm going to simply print out, oh my god, this, the mouse, three dots, computer, mouse, and print out
computer components. Then, let me just
copy these two lines, because I am lazy in here. We're going to
remove and remove, mouse and print out
the components. And let's see what
happens if I write click and I run.
Boom, There we go. You'll notice that if you try to discard something
that's not there, there is no error raised. But the remove does
raise an error. It depends on the
situation that you're in. You would use either
the discard or remove. Maybe you're saying to yourself, well, why not use the
discard all the time? Since who has time for errors or another question
you might be asking, shouldn't we always
be getting an error? Because we need to be careful
about what we're removing? So again, it depends
on the situation. If the information that you're trying to remove
is not sensitive, you don't care if
it's there or not. You just want to
try and remove it. You can use the discard. If you're very worried
about what you're removing, you want to make
sure that you're removing something
precise, correct. You can use the remove
method instead. It depends on the situation. And if we hover
over, these methods removes an element set number. If the element is not there
is not a member, do nothing. If you hover over the remove, you'll see if the element is
not a member, raise a key. Or finally, we have
the last method for removing items from a set, which is going to be the pup. We've already seen the pop, but let's see what
it actually does. I will comment
everything out in here. I'm going to go ahead
and pop something out. Computer components pop and just print out computer
components. How about that? If we don't put
anything into the pop, what happens is a random element or a random item gets removed. This is useful in situations
like random removal. Maybe you're looking to increase memory
efficiency because using the discord and you
remove can create new sets. Sometimes sets are mutables, sometimes sets are mutable. When you're discarding
and you're removing, you're creating new sets, it's less efficient
using the pop. If you're not worried about which element you're removing, you just want to
remove an element. Random removal a game
maybe or something. Then set is your best friend. Thanks so much for watching. This was a very simple exercise. In the next video, we're
going to be looking at union, which will help us understand
better why sets are useful. Thanks so much for watching and I will see you in
the next video.
118. 17. Set union: Welcome back my fellow Python programmers to a
brand new video. And this one will be
looking at set union. So let's first of all
understand what it actually is. Let's say we have
set one which has 123.6 and we want to create a union between
set 1.2 which has 754.8 the resulting union, and this is how we
would write it, this is the operator in Python that we use
to create a union. The result would be a
third set which has 123 both set one and set two
together, all meshed up. So let's see a practical
application of this. This was a small sneak
peak in two challenges, but not the full peak. You'll have that in just a bit. Let's go ahead and create
a new Python file in here. And let's call it the
underscore e mail. Yes, because what we
are trying to do in here is we're going
to have two sets. The first set set is going to be all the customers that purchased some kind of electronic
from a store. The second set is going
to be all the people that purchased from the store. What we'll do is
we want to check all the people that made a purchase and send them
a promotional E mail. We're going to first of all, create the electronics
underscore purchased and it's going
to be equal to John. This is not how you write John. This is how you write John, Sarah, Peter, and Anna. Duplicate this. We will have the clothing purchased
purchased. Yes. We're going to have John, Emily, William, and Anna. These are the people
that bought electronics. These are the people
that bought clothing. Now we're going to say all
underscore customers equal to electronics purchased,
union clothing purchased. And now we can print
all customers. If I write Click and I run, let me put this down here. You can see that we've
created a union. But even better than that, we don't have to send John
and Anna two e mails. Because when we create a union, we're creating a third set. Meaning that all the duplicates are removed automatically. How cool is that? It saves you a lot of time,
a lot of headache. You already know, because
in this situation, you don't care the order. You don't care if you
send Sarah or Peter, or John or William,
whoever it is. You don't care who
receives the e mail first. All you care about is
that everyone that bought from your store
receives an e mail. So that is perfect. In our case, we've created this, and now we can send them an
e mail to all the customers. But there is a different
way of creating a union. We can use the operator
that we just saw. So I'm going to duplicate
this line actually. And I will have
all the customers. But this time I'm going to
add this pipeline character. Yes, this is called the
pipeline character. Each keyboard has it in
a different position. On my side, it's
above the entarkuy, there's the backslash, and
then there's the pipeline. If you hold down shift
and click it on a Mac, I have no idea where it is. You have to do your
best to find it. But this is the
pipeline character. And if you right
click and you run, you'll see that
we also unionize. Unionize that, that's that's for something
completely different. We create a union between the electronics purchased
and the clothing purchased. I hope you understood
the assignment. I hope it wasn't
too hard for you. There's nothing
too much in here. Very simple union
between two things. Now I'm going to issue
you a bit of a challenge, and your challenge is going
to be to print out sorted. So all you need to
do is print out all the customers
in a sorted list. Hm, interesting sorted
list. Keep that in mind. Pass the video right now
and go do the challenge. Welcome back. How did
you get on with that? Shouldn't be too hard. We've already seen this before. This is not what I want in here. We are going to, instead of printing out all the
customers directly, all that we need to do is we
need to say all customers. That's actually, not only will this sort out the
people that are there, it will also create
a list out of it. There we go. Now we have a sorted list by name just
in case you needed it. There is also a way to add the two sets together
using the update. If you remember, if
I do the following, I do, electronics purchase, update closed, I print out
the electronics purchased. You'll see that I
also have this and there are no duplicates is the same as the one that
we've done before. What is the difference in here? By the way, the update also
has an operator of its own. I will duplicate this and I
will comment this one out. You can do the
following. You can say electronic purchased
and then you can Pipeline equals
clothing purchased. This does the same thing. All right. Click Run. Look at that, The pipeline, you don't have to
remember the operators. And we'll talk about
the difference between using an operator or a function, But the main difference between the union and the update is that the union returns a new set containing all the
elements from both sets, while the update modifies
the original one, the one that we're using
on the left, for example, the electronics purchased by adding all the elements
from the other set. That's the only difference. Before we move on, there is one more thing worth
talking about, and that is when to
use a function name and when to use the operator. There are three
main things that we need to think about in here. First of all, it's clarity, flexibility, and error handling. If we look at clarity, using the set operation methods like union and intersection, which you'll see
in the next video, can make the code clearer
and easier to read, especially for
people who are not familiar with such operators. First of all, if you're
looking for clarity, using methods is better. Now, when it comes
to flexibility, the set operation methods
are more flexible than the operators as they can be used with a variable
number of sets. If you want to pass multiple
sets to the argument union, maybe you want to create
multiple intersections. Maybe you have ten sets
instead of just one or two, whereas the operators
can only work sets at a time. And finally, when it
comes to error handling, methods are also better. The question becomes,
why use an operator? There's no real reason,
like it depends. Sometimes if you have some
quick stuff you want to do, you want to accomplish these
two sets like quickly. You know you're
doing mathematics, You don't want to have
too many functions, maybe it depends also
on the situation. If there's nothing
too complicated, using an operator
is perfectly fine. I think the operator might use slightly less
computational power. I'm not 100% sure about that, but I do think that is one
advantage of using operators. It's slightly faster in
the millisecond realm. For example, if you're
using it in a loop and you only have minimal error, error handling requirements,
using an operator would probably be a
better choice here. But in any case, if
you're ever in doubt, use a method like the dot
union and not the operator. Thanks so much for watching.
I hope you enjoyed. In the next video, we'll be
looking at set intersections, and I will see you
there. Bye bye for now.
119. 18. Set intersection: Welcome back my fellow Python developers to
a brand new video. And in this one
we're going to be looking at set intersection. So first of all, let's look at what set intersection
is in the first place. This is the operator
for the intersection. We have set three equal
to set one and set two. Unlike like the union, we create a third set. So if we have set
one and set two, set one has 625,738.4
Set two has 5 731-323-1917 The intersection would be this set right here. The set three in
this case would be 57.3 Let's go into our code and let's
actually try to apply this intersection
and see how it works. Back in here, I'm
going to create a new Python file that I'm going to call intersection
underscore set, hit Enter, and I'm going
to create set one. Which will be equal
to set range. And the range is going to
be 050.2 Duplicate this. We're going to have set two. And this time the step
is going to be three. Remember ranges where you
have the starting point, the endpoint, and the step. Let me print out set
one and set two. When I write click and
I run, look at that, I have 0, 246-810-1214, et cetera, Two steps at a time. Now the second one is scrambled. I don't know why the
first one is not. I'm not entirely sure. Let's try to run it again again. Okay. Apparently we're
getting the same. I think sometimes it just selects random numbers,
sometimes it doesn't. I'm not entirely sure. Oh, wait. We do have a few scramble
numbers here, like 40, 42. No scramble number
in the first one. The second one has a lot
of scrambled numbers, but it's not a problem for us. We have two sets. We want to see where are the intersections in
here very easily, we create the in section
underscore set which is going to be equal set
one, intersection set two. And I can print out intersection set when
I right click maybe. Let's add a print in
here just for clarity. Right click, run and
look at that number. 0306 6402, 1248, 1820. 4.30 are intersections between
these two sets in here. So pretty simple, pretty
self explanatory. There's nothing too
much to do in here. It just finds where there are intersections and it
creates a set out of that intersection or out of the items that intersect
between two sets. Now let's look at a
more useful example in the real world. Let's say we have two lists of customers who have made
a purchase at a store. One list would be from January, the other one would
be from February. And we want to see where
that intersection, where are the people that
bought in January and February, because we want to give them a promotional discount
or something like that. So I'll add print
and I will have Jan underscore customers
equal to Let's set. John, can I get the
ones that were here? I'm going to use
different names. John, Sarah, Sarah. That's all. You're right, Sarah,
Emily, David, Katie. Duplicate January,
February customers. So, I will have Sarah here, David, Katie, Stephen, and Jenny. Now we want to find
the intersection. And when I say we,
of course I mean you because it's a challenge
to find the intersection. Get the common customers
between January and February. Use the function intersection. Use the operator as well that I showed you. This
is the operator. And then print out the result of both posit video right now
and go do the challenge. Welcome back. How did
you get on with that? I'm going to call this the customers and I'm going
to say that it's equal to January customers
intersection February customers and print out the common customers or the incommon
customers or whatever. Right click run, Katie, David, and Sara or all three of these. But in January and February, we send them a promotional. The other way of doing this, I'm going to duplicate this. Come in the line at the
top and say the following. Boom. This is the
operator that we can use. If I right click and I run, we have the same output, Sarah, David, and Katie. That's basically it.
This is intersection. Before we move on, I want to take this opportunity to look at how or how you can create intersections between more
than just two sets In here, I'm going to create
the march customers. So the march customers
are equal to John A, Alex A, Emma, Sarah A. Let's continue using single
quotation mark and Katie. Now if we want to create the
intersection between three, we would use the following
March customers. When I write Click and
I run, there we go. We only have a bought
in January, February. And as you can see, John did not buy in February in Katie,
our loyal customer. So we will give her
a special bonus, the other way of using this, instead of having the operator, we can use the intersection. And we do that by simply adding a comma in here and adding this, and we should have
the same answer. So ladies and gentlemen, I hope you enjoyed this
was set intersection. In the next video,
we're going to be looking at the set difference. And finally, we'll
look at subsets and supersets and be done
with the section. Congratulations on
making it this far. If you have leave me a review or a comment
or just tell me like, hey, nice, I love this. Of course, thank you so much and thank you for
watching so far. I really appreciate it. And I will see you
in the next video. Bye bye for now.
120. 19. Set difference: Welcome back my fellow Python programmers to a
brand new video. And in this one,
we're going to be looking at set difference. Set difference is very simple. We have set number one, we have set number two, set number three,
and set number four. Set number four, for example, would be set number two. This entire yellow thing
minus the green part. What we get is this part right here without this intersection. In the middle, we will have set four without the intersection. And set three,
which would be set one minus set two would
be the green part. So these are the set
three and set four, this is the difference and the operator is just
the minus sign. Very simple. Let's go and look at some practical examples
of this back in our code. I'm going to go ahead and
create a new Python file, which is going to be the
difference underscore sets, and in here I'm going to
just copy set 1.2 from here. Paste them in here and we should get a very normal answer
just like we had before. It's same range that we're
converting into a set. Now we're going to create the
difference underscore set, which will be equal to set
one difference set two, and then print out
the different set. When I write click maybe, let's just add a print in here. Write click Run, and
this is what we get. This is the difference
between these two. For example, 28 is
in the first set, but it's not anywhere
in the second set. This is the difference
between it. But keep in mind we're doing
set one difference, set two. If we change these around, let me copy this and
paste it in here. And if we do set two
different set one, now we have a different answer. Because we look at set
two and remove from it everything that was
in common in set one. For example, 27 is only
right here in set two. What else? For example, nine is only here if we
take a number like 42. It's in set two. And in set one we
remove the difference. Doing it the other way
around is different. Mm hmm. So let's look at
a practical application. As always, let's say we have customers shopping list that includes apples,
bananas, and oranges. And we're going to
check if we have some kind of promotional items, maybe there's a promotion on these apples or these
oranges or whatever. So we're going to create
two lists in here. Two shopping lists, I mean, not like actual lists, these are going to be sets. So first of all, we'll
have a print and then I will do the shopping
underscore list, which is going to be equal to apple, bananas, oranges. And the promotion underscore
items is going to be apples and bananas. Now there is a
challenge for you, and your challenge will be
to find the difference, create the difference between the shopping and the promotion, and use the methods
and the operator. Posit the video right now
and go do the challenge. The goal here is to get the items that are
not being promoted. Underscore on
promotion is equal to the shopping list minus
the promotion items. So a little bit of challenge here was that you
needed to figure out whether to do
shopping list minus promotion or promotion
minus shopping list. But I think it's pretty obvious. So I'm going to have items
not on promotion, Come on. Not on promotion,
right click, run. And there we go for
a second there. I was stunned. I was like, whoa, wait, wait, what happened? And it turns out
that we have apples, apple, right click, and run, And now it should work. Oranges are in the promotion. I was like, wait,
wait, what happened? I was stunned because this
is so easy and simple, and I made a mistake. I'm like, What happened? Anyways, there you go. As you can see, this is
how the difference works. Thanks so much for watching. I hope you enjoyed. I believe this is the
end of the section, but we might add more
videos down the line. Maybe we'll work on subsets and symmetrical differences,
But for now, I hope you enjoyed and I will see you in
the next section, which should be reading
and writing again. Maybe we're updating. I don't know what we have next. I'm so excited to
get started for the next section and I will see you that. Bye bye for now.
121. Section 9 - Reading and Writing Files | 1. Opening Text files : Welcome back my fellow Python programmers to a
brand new video. In this video, we're
going to be starting a new section which is reading and writing
files in Python. This is a very
important section. It's very crucial
that you know how to write and how to
read from a file. Let's go ahead and get started. First of all, what is a text
file in a Python context? Obviously, we know
already a text file is, but we want to know what is
it in the Python context. So first of all, a text
file is a file that contains ASC II or
Unicode characters. This is a standard in, in which the computer writes certain characters
like ABCD, et cetera, et cetera, which can be read and written using Pythons
built in functions. We can read and write these files using Pythons
built in functions, and we are going to
see what these are. They are used to store textual data such as
strings, numbers, or any other kind
of data that can be represented as a text. Python provides several built in functions to read
and write text files, such as open read,
write, and close. And we're going to see
all of those and more. When working with text files, text files can be opened
in different modes, such as read mode for
R and write mode. We're going to see these
when you want to read, you use, when you want to write. The mode is specified as the second argument
to the open function. And we'll see how that
looks like when we have the file object is equal to open the text file
that we want to open. Keep in mind it's dot, this video will be about opening text files and then we
will move on to reading. Stripping, parsing
extra, et cetera, using the R right here to
indicate that we are reading. If you don't provide
it with anything, by default it will
think you are actually reading from the file
without any further ado. Let's go ahead and
actually start applying this
knowledge from here. I'm going to go ahead and
create a new Python file. New Python file,
and I'm going to call it underscore text. Underscore file. First of all, I'm going to
create Python underscore poem, and it's going to
be equal to open. And we are going to
open a Python poem. Immediately you see that we have all of these suggestions. When you have them, just
click. Don't worry about it. Now I'm going to
provide you with these files somewhere in
a button or something. So make sure to download
them, unpack them, and then simply drag
the Python poem into the reading and
writing files right here, it will ask you where
you want to do this. Move to D one. For some reason it's like, but if you want to do
it in a better way, right click open with
Go to Explore in here. Open up the reading
and writing files and just send in this file. This is a much better way. Close this down again. Right click open, Explore. Go into the file and
send in the Python poem. Down from here, I'm going
to say Python poem, and it should recognize it. Obviously, we're trying
to read from this file. So we will add an R here and
we'll add an extra space. Now that we have this,
let's write Click and run just to make sure that
we don't get any errors. The open function is used to open a text file and it returns a file object that
can be used to read and write
data to that file. Now that we have access to
all the lines in the text, we need to print
out these lines. Conventionally, we call
them lines in a text. In here, I'm going to
create a four loop because we can iterate over
the file object. I'm going to say four
line in Python poem. In here, I will
print out the line. If I write, Click and I
run, this is what I get. Look at this in lines
of code and syntax. Clear Python beacons with
promised deer with power to transform and create a language
to master, to elevate. Now, super cheesy I know. But it's a good poem
if you go through it. If you read it, it's
not a bad poem. I do recommend that
you read through it, but as you can see, we were able to read through this file. Let's open the file and look and see how it
actually looks like. If I double click, it
opens up an Intellij. Intellij allows us to read, and as you can see,
this is our poem. Now immediately you'll
notice a few things in here. First of all, we have these extra spaces
in between lines. And we also have three spaces
in between each paragraph. Obviously, something
is going on in here. We're having to get
extra lines of code. Now this space is being printed
out in the output only. This is because in the
actual text document, we have something which
we refer to as the Enter. So every single time you finish
the line, you hit Enter, you go to a new line, and that key is being
printed out in the output. Because remember when we are
working with characters, the spaces are also characters, and in this case, the new
lines are also characters. So that's why we have
these extra spaces. We are reading every
single character, and one of those characters
is the enter that the user pressed when he
wanted to go to a new line. So that's why we get
this in the output. Now to mitigate this
problem, it's very simple. We simply go in here to the
line equals and just do this, meaning that the ending of
the line should be nothing. Now when I write, click
and run, there we go. You can see that the output
is much better and there are no space or no blank
lines in there. Keep in mind the white lines which are the space and the tab, and the new lines are all
counted as characters. We've already seen this before when we were indexing strings. So none of this should
be very new to you. It's just a new way of
seeing those things. So now that you have all
of this information, time for a bit of a challenge. And your challenge
is going to be to strip the unnecessary objects. I want you to look up the method strip on three
schools or Google or whatever, your favorite choice
of information, Python resources, whatever, use it on the lines extracted
from the Python poem. So try to use it on
the lines that we are using or we are getting
from the Python poem. Print out the strip lines
and tell me how it looks. Post the video
right now and go do the challenge. Welcome back. How did you get on with that? In here I will comment
this line out. I'm going to say that the strip underscore
line is equal to line strip and then I will
print out strip line. Now if I write Click and I
run, this is what I get. You'll see I can now do
this without the end. Because what strip
does if we hover over, it will give us anything. Returns a copy of
the string with leading and trailing
white spaces removed. If character is given
and is not none, we remove the character
that we want instead. For example, if I want to
remove the right click and run, you'll see that the white
spaces are not removed, neither is the comma. But we will delve deeper
into how this works exactly. But for now, don't
worry about it. Just know that when we
don't provide anything, it actually just strips
out the white spaces. Before we move on, there is one more thing that
we need to look at when using Python poems or
opening up text files, or any files for that matter, it's very important that
we always close our files. What I mean by that is
once we're finished with reading with
writing from a file, we need to always type in the following
Python file, close. This is very important
because it avoids data loss sometimes if you
don't close the file properly. So you know, when
you're shutting down your computer and the
windows tells you like wait, there are still
some files that are open and haven't been
saved and whatever. Like, it's a huge deal. Well, it is a huge
deal because it can corrupt the data that is
inside of a text file. Now obviously in here,
it's not a problem, it's just a silly Python poem. But still, we need
to close the file, but sometimes it's
a bit cumbersome, having to open the file and then close the
file and whatever. Thankfully, there is a
small trick in here in Python that you
can do in order to avoid forgetting
doing those things. I'm going to comment these out, please don't delete them,
keep them with you. And I'm going to show you with
open and then we will open the Python poem or for reading as Python
underscore poem. Then in here we'll say four
line in Python poem stripped. Actually, why am I going through all of
this trouble when I can copy paste this? Here, there we go. So this
is a better way of opening the file because it avoids forgetting the close
with the width. You actually automatically
close the files. Now f right click and I run, you'll see that we
get the same output. Thanks so much for watching. I hope you enjoyed this video. This is a new start. This is a new section, so I need your full
concentration. It might seem a bit scary
at first, but trust me, reading and writing
files is not as complicated as one might think
once you get used to it. I will see you in
the next video, where we will be
looking at reading files in. So see you then.
122. 2. Reading Text Files: Welcome back my fellow Python programmers to a
brand new video. And in this one we're
going to be looking at more ways of reading text files. Let's go ahead and get started. First of all, I'm
going to create a new Python file in here, which is going to be
the reading text files. Reading underscore. Underscore files. Boom. I'm going to close
the projects down. I just wanted for you to see the Python poem text in
our file collection. For now, I will just
close down from here. I'm going to do the following, I say with open Python poem R as Python underscore poem. If it wasn't clear
from the beginning. Right here, when we
say S Python poem, it means we're creating the file object just
like we did in here. But this time it's a
little bit different using the width from
here. Python poem. I'm going to say that lines
are equal to Python poem, red lines. There we go. This is a different
way of reading. Then outside the width, I'm going to print out lines. I also want to print
out the type of lines. And maybe we can do
this just above it. Now when I write
click and I run, this is what I get
a class of list. And you'll see right here. Unfortunately, I
have to move from left to from left to right. But as you can see, each line now has become a part or an item inside
of a list, the read lines. If I hover over it,
what does it say? Let's open this right here
and let's look at read lines, three schools to get an explanation because
the documentation just doesn't provide
us with anything. It simply returns all the lines in the file as a list where each line is an item
in the list object. And it's pretty obvious
from the way that we have seen it in
our code right here, that we have each line
as a separate object. But you'll also notice that some weird
characters are included, like the new line
that you see in here. Now we're justified in
what was happening in the previous video where we had separate lines between
each line and the poem. It's because of this
character right here, it manifested in a new
line in the output. So this is a more beneficial way of accessing these
lines, because now, for example, what I can do is instead of printing
out everything, I can do the following. Let's say, what does this do? Think about it for a second. This, for example,
could provide us with only the first five
lines in our code from 0,123.4 What is this? I want you to tell me. I
want you to think about it. What is this element
right here in our poem? Well, obviously it's
this line right here. We have the first line, second line, third
line, fourth line. And this one is
just a new line and it's actually an
item in our list. There is something to consider about this way of
reading from a file. That is, if we have
a huge file file with millions of lines and all of those have to
be added to the list, it can break our
code at some point. Let's look at the read function, which is maybe slightly more efficient but still
not the best in here. I'm going to say actually
it doesn't like that, so I'll do it from here. I'm going to say that the
text is equal to poem, read, read, lines do read. I will comment
these out as well. In here I'm going to print
out the type of text. I will print out the text as well when I write,
click and I run. This is what I get. If I hover over the read, will it give us any useful
information this time? Apparently not again. No worries. I'm going to
type in read in Python. Three schools again,
schools. Let's see. All right, let's read
a little bit about it. The read method returns the specified number of
bytes from the file. Default is minus one, which means the whole
file with the read, we can actually specify how much we want to
read from the file. For example, 33. I'm not going to delve
too deep into it. Is slightly more efficient than the read line since it creates a single string of the
output and you can determine how many bytes you
want to read from that file. But it's still inefficient
for large files because it reads the entire file
into memory all at once. The last reading method
that we're going to look at is going to be a
challenge for you. Your challenge is going to
be to read striped lines. You'll need to use
read line instead of read lines to read a single
line from the text file. Again, I recommend that you look it up in W three schools, then find a way to print out these lines without
a special character. And I'll give you a hint. If you don't want
the hint, pause the video right now and
go do the challenge. If you do want the hint, use the strip on our
read lines and then, or on our red lines and
then print them out. Pause the video right now
and go do the challenge. Welcome back. How did
you get on with that? It shouldn't be too complicated. I will comment this line out. I'm going to say that line
equals Python poem read line. Let's just keep it at
the read line for now. I will comment these
out at a space. Then in here I will
print out the line and print out the type of line. Before we do, I didn't talk
about this line right here, the class is string When we did the text,
when we did the read. So something to keep in mind. But now when I write
click and I run, look at that, the
class is a string. And we have in lines of
code and sense text clear. So we read a single line
from our text file. There we go. But
you'll notice that we also have this extra
space in here. And what is that? It
should be clear by now, it's because of the
backslash N or the new line. So how do we get rid of it? The strip, and now if
I right click and run, you'll see that there
are no spaces anymore. There we go by. Now this should all be clear. We can use also the while
loop with the lines. For example, let's say we
want to continue reading lines until we get to a line
where we have the word tool. For example, I would
do the following. I would do while true, I will keep reading a
line, reading a line, reading a line until
I print out the line. And I mean not until I will
keep printing out the line. And then if I find if
tool in line case fold, I will break now. Right click and run. And there
we go in lines of context, clear, Python, beacons, deer, whatever a language elevate tool to solve complex problems.
And then we stop. But obviously we still
have, these are separate. Let me show you. There we go. They are separated from
the original one, okay? That is basically it. Notice that if we don't
add this parameter, this is one small little detail. If we don't add this parameter, if we don't specify the mode
in which we're opening, it simply defaults to a read. And I just wanted to
tell you about that. Thanks so much for watching. I hope you enjoyed. I don't think it's
too complicated. I don't think we need to
delve too deep into this. In the next video, we're
going to be looking at stripping and understanding
better how it works. Thank you for watching.
See you in the next video.
123. 3. Stripping Text Files: Welcome back my fellow Python programmers to a
brand new video. And in this one
we're going to be looking at stripping text files. Let's go ahead and get started. First of all, I'm
going to create a new Python file and
I'm going to call it the Stripping underscore
Text Underscore files. In here, I'm going to say string equal to and
I'm going to add 123. Hello world, 123.
As you can see, I have three spaces on each
side of the Hello world. In here, I'm going to
print out original string, two space, even string
if I right click, and this is the
output that I get. Three spaces on the
left hand side, three spaces on the
right hand side. Actually, in here we
have four spaces. Why? Because we have two
arguments presented to the print which adds a
space automatically. Next we're going to have
the version we're going to have equals do strip. Then in here we're
going to print out that the string two dots, close down, stripped right, click and run, and look at the output that we get only a single
space because of the two arguments and no
spaces on the left, the right. We've already seen this before. If we don't provide
anything to the strip, it will simply strip out the white spaces or remove
the trailing white spaces. Trailing and
leading, by the way. Important keyword that
we didn't talk about, the leading and trailing, and what does that mean? Well, because we
don't just have the, we have something else. I'm going to say left
underscore stripped is equal to the string L strip. Now when I print out the
left stripped string, left strip, you'll see that now when I right
click and I run, it looks as if the
output is the same but on the right hand, on the right hand side we
still have our spaces. This separate things
from the left hand side. If I hover over the left, it returns a copy of the string with leading white spaces, removed the ones that
are on the left. We have the same thing happening
if we do the following. I do this and I say in here, right are right, right. It should be obvious by
now that it only removes the trailing or the spaces
on the right hand side. Now we can use the strip method to remove
certain characters as well. I'm going to be
changing the code in the appropriate places. I recommend that you copy this space in here and then make the changes and comment out the old ones just so you always
know the flow of things. But it's up to you. You can do it however you want. I'm going to add three pluses
on each side this time. Now if I do the following, add a plus in here. Let me copy this. Paste, Paste, right click, run, and there we go. You can see on the
original string we have these pluses
on each side. In the stripped version, we don't have any pluses, neither on the left nor on
the right on the string. We have them, we have
them on the left. I don't think there's
any confusion in here. I think this is pretty
much self explanatory. I'm not going to delve
too deep into this, I'm going to move on because
there are a few intricacies that we need to understand
about the strip in here. If I add two minus
signs and then I add a minus sign on
the left hand side. Now we have a bit of a mix. Let's try to strip these things. First of all, I
will try to strip the plus and minus on each side. If I write, click and I run, you'll see that the minus and the pluses have been
stripped on each side. But on the left and the right, nothing has happened because I'm simply stripping the plus. Now you might be
saying, well wait, why isn't this plus
being stripped? Hmm. Interesting.
And it's definitely a very interesting
question to ask. And that's because
of the nature of how the left strip and
the right strip work. So I'm going to be
testing a few things out. Let's say I add a plus
equals on the left strip, right click, and I
run look at that, it all disappears. Why is that? Because even though
in here I have two minuses and then a
plus, it doesn't matter. As long as there's
a minus in here. It means that a minus
will be removed. And it will keep
going until it finds a character that it cannot remove. What
do I mean by that? If I add an H in here and
I right click and I run, you'll see that Hello world, or the H and hello disappears. If I now try to add an L, do you think the L's
are going to disappear? No, they don't. Why is that? Because as it was going, as the strip was
looking, It's plus. Okay. We don't have
that. It's minus. It's like. All right, perfect. Let's remove the first minus. Another minus. Let's
remove it. A plus. We do remove A plus H. We do
remove an H. Now we're at. Okay, Do we remove an No, we don't remove an All right, that's enough stripping for now. What we can do is if
we add an right here, boom, you'll see that now does
disappear. Can you see it? Now, the disappears
and the L's disappear. If I add an X in here, for example, it's
still the same output. So it doesn't matter in
which order we break, as long as the letters
in here are continuous. Meaning that if we
don't have an E, then the L's are not
going to be removed. Why? Because as the strip is
going through the string, it arrives to H. Okay. H is there, We'll strip. It is not, therefore
stripping, so we stop. I hope that's clear. The same
is true on the right strip. Now, I don't have a
challenge for this video, but as a mini challenge. As a challenge, or let's call
it an unofficial challenge. I recommend that
you try and test out a few things
here on the plus. So for example, if
I do a minus plus, what do you think the
output is going to be? This is a challenge.
Please try to think about it. There we go. Of course, it
disappears because we start with a minus
and it sees a minus, a plus, et cetera, et cetera. What do you think will happen
if I do the following? Right click and run, and you'll see that
nothing happens indeed. Because remember we're
going from the right. What if I do A also? Nothing happens. Click run, nothing happens as well. But now for the last one, what would happen if I
add an exclamation mark? And boom, there we go. Because we've removed
the minus and plus. We found an exclamation
mark, removed it, found the D, removed it, and then we encountered
an L. Do we remove it? The L. No, we don't. It means that we move
on with our life. Thanks so much for watching. I hope you enjoyed the strip is not something
that's super, super crucial, but if you ever encounter it when reading from a text file, it's very important that you
know how the strip operates. If you ever want to go
back to this video, rewatch it, re, understand it, try to test out different
things in here. See the left strip, See, see the right strip,
and so on and so forth. Thanks so much for watching, and I will see you
in the next video, where we will be looking at
parsing data in a text file. Bye bye for now.
124. 4. Parsing data in a text file: Welcome back my fellow Python programmers to a
brand new video. And in this one we're
going to be looking at parsing data in a text file. Whenever we want to
get data from a file, we first need to understand what that data is or what that
data looks like in that file. The most important
is to understand the structure of said data. Making sense of the data
is parsing, for example, the code that we're typing in
right now in the computer, like the strip and the
equals and the whatever, all of that is parsed by
the computer or by the IDE into one and zeros to really understand
what is happening, sent to the processors, then given back to us and so on and so forth to
create the output. In this video, we're going to
be looking at parsing data. Let's go ahead and get started. First of all, we need to
provide the peoples list dot. Now I already have
this file right here. Peoples list dot, There
we go, People's list. I keep doing this. Please let me show you what I
did wrong in here. Right. Click open and explore, and we should see this right
about here. There we go. Then in here, I
actually moved it. I shouldn't have moved it, I should have copied it. Let me copy back the Python poem into my resources location. And then copy the people's list. And paste it in here into the
reading and writing files. There we go. We have
the people's list. Let's open up the people's list. And let's see what
we have in here. As you can see, we
have a list of people, but not just people. We have the ID name, department salary,
and the job title. You can see the ID's
on the left hand side, one for John Doe. His name is John Doe. He works in the
Department of Sales. His salary is 5,000
I don't know what. And his job title
is Sales Manager. Then we have Jane
Smith at ID two with a department
that is missing. And this is going to
be an issue for us, this is what we mean
when we say part data. Because sometimes the structure of the data can be corrupt. Some things could be missing, like the department
of Jane Smith. And then we have the salary. And the title marketing manager, Mary Brown for example, doesn't have a salary. And so on and so forth. So let's first of all understand how this
data structure works. Because, look, we have
pipelines instead of spaces. This is more akin to a CSV file, and we'll look at
CSV files later on. But for now, this
is a text file, we need to extract
information from it. Let's go ahead and create
a new Python file that is going to be parsing
underscore people. Parsing underscore people here. I'm going to say that
the file name is equal to people's list of Xt. This is a handy way of using the file name and not having
to type people's list. Every time I will say
with open file name, as people file, I
will say four row. Now we're working in rows. You can call it lines,
you can call it rows, You can call it x
whatever you want. Just know that it's the row or the line four row in
the people's file. I'm going to say that
the data is equal to split over the pipeline. I'm removing the pipeline, or actually I'm splitting
on the pipeline. And I will print out the data just in case you're not sure
what the split does. I recommend you go through W, three schools or you can look at the documentation right here returns a list of the
words in the string, using the separator as a delimterliit between the
split between the pipeline. In this case because
we've provided it with a pipeline and we're
printing out the data. If we run the code, there we go. You can see that each individual has been added to a
list and for example, the ID is one or
the ID is an item. The name is an item. The sales are items, et cetera, et cetera. And then finally, we have
this symbol right here, which is not good at all. So it's time for a
bit of a challenge. And your challenge
is going to be to remove the unwanted symbols. First of all, use
the strip function. Then make sure that
to only remove the new line
character because we don't want to remove
anything else. Also you can use both the
right strip and the strip. Choose whichever one you want. Positive video right now
and go do the challenge. Welcome back. How did
you get on with that in here on the data road split? Now, the challenge here
was to know should we split and then strip
or strip the split. Well, it's going to be strip, strip the split I'm
going to strip oh, no, this actually is bad and
then split on the R strip. I'm going to strip the backslash N. I'm going to do a right
strip. It's the same. It doesn't matter if you do the entire strip or
the right strip, as long as this
symbol disappears. Let's look at representing
this data in a better way. Meaning that I
don't want to have all congestion congested here. I want it to be represented
in a more sophisticated way. Which means that we want
to actually split up this data and more
accurately unpack this data. So instead of just printing, I'm going to say that
name or actually ID, let's call it per sono,
underscore ID, name, department, salary, and title are going
to be equal to data. We've already seen
what this does. This is called unpacking data. We're unpacking the data in data into each of these
variables right here, the ID name, department, salary, and the title. Then I will print
out personal ID, Let's say I want to change their order, salary, job title. We'll create a separator
which is going to be, first of all, a new line, and then a back back. Do you remember what
the backslash S are? Do you remember the backslash N? Because we've done it recently. But the back, what is it?
I'm not going to tell you. You'll have to do the research. Right click and run and
look at what we get. Of course, this is
not the best way to represent our data. I know, don't hang me for that, but at least it's
slightly better. You can see that we
have the name ID, department salary,
and job title. Then we have John Doe ID one, sales salary, job title, Jane Smith, ID two. Hmm, Nothing in here. The problem, this is
a problem because we have these empty
fields fields. We will deal with that later on. But for now as you can see, we've created a better
representation. And you'll see that
there are a lot of missing things in here. Some people really don't have all of their
stuff together, So now we want to add that
information into a dictionary. And for that we
need to get rid of the first line which
indicates what the data is, meaning that in our dictionary, I don't really want to see name, ID, department,
salary, and job title. That's not something
that I want. Think of what we can do in here. How can we do this?
Well, it's very simple. Some of you might have
overcomplicated this in your head, but it's very simple. All we need to do
is we need to say people's file read line. Now if I write Click and I run, I go to the top, you'll
see that I no longer have the name ID department.
And why is that? It's because the file is
able when we do a red line, it's like we've already
handled that first line and now we're onto the
other lines of text. What I mean by that is okay, wait, we can work with this one. Let's imagine that when
we're reading from a file, it's like a robot. The robot is a
small, tiny robot. Stands right here at
the start of the line. And it starts like this. It reads character by character. But the robot, if it
wants to go back, it cannot just jump to
this part right here. The robot needs to go
back step by step. Actually, the robot cannot
go back that easily. The same thing holds
true with the read line. When we've opened the file
and we're reading from it, what happens is the robot, when we do the read line, just reads the first line. Now when we do the
four row in people, when we get to
this line of code, we actually start from here because we've already
read the first line, for example, as a test, what if we don't want
to include John Doe? We duplicate this line. And now we start
from Jane Smith. Because we've read John Doe. This is very crucial to understand about reading
and writing to files. It will come up a
lot down the line. So make sure that
you've understood it right here, right now. Now, now that we've read
through the first line of code, we made sure that we don't
have the name department and whatever we want to add
these into a dictionary. Instead of just
printing them out. I will comment this out here. I'm going to say the
people underscore dict is going to be
equal to the following. We'll have to do, well, the ID to do personal ID. You're pretty familiar with
dictionaries at this point. The department two dots,
department salary. Two dots salary.
Actually you know what, I don't like having these
capitalized except for the ID. Let's take these down
to the lower case. You'll see why later on. It might cause problems
when we're trying to access these keys. Job title is going
to be the job title. I will add a because I can. Then I will print out
the People's Dictionary. There we go. Now, let
me move this down. I have a feeling we
will need a longer tab. Right click and
run. There we go. You can see that we've
simply added Justin Lee ID, which is the last person
which is not good. Obviously, this is
not what we wanted. The reason why this is happening is because
if we look closely, we have a people's dictionary. It's only a single dictionary
that we keep adding. The personal ID name, department, salary,
job title, two. And remember,
dictionaries are mutable. We cannot have duplicate keys, so the values keep updating. And the last one to get updated is the actual last person
that we have in the list. So when we get to Justin Lee, we parse the data, we put it in the
People's Dictionary and we get the name being the
name which is Justin Lee, ID, et cetera, et cetera. In the next video,
we're going to be using the sparse data and actually putting each one of
these into a big dictionary. Thanks so much for watching. I hope you enjoyed and I will
see you in the next video.
125. 5. Using parsed data: Welcome back my favorite Python programmers to a
brand new video. And this one we'll
be using parsed data that we've extracted
in the last video. So now that we have our data properly
parsed and extracted, after we are going to put the data into one
big dictionary, currently we have
these dictionaries. Oh, and by the way, if
you look at this output, and where the hell
did this come from? I was just testing
something out. You can actually
move this print into the fore loop in order
to see all of the names. As you can see right here, they did not show up
because what we did was we printed the People's
Dictionary outside. That's why it was the last
name, which is Justin Lee. But if you want, you can print
it on every single line. And it just occurred
to me before starting this video,
I tested it out. Maybe this is a
better way for you to see things better
for you to understand. I'm not sure. I
hope it does help. Let's now put all of these
into one dictionary, with the names being the keys. So we'll have a huge dictionary, which will be the
people's dictionary. We'll create like a
people right here, which is going to be equal
to an empty dictionary, and we're going to be putting these names into the
people's dictionary. So these dictionaries
will become the values, and the keys are going to
be the names of the people. Then we can access these
names in a meaningful way. Let's go ahead and get started. First thing we're going
to do is we're going to actually start putting these into the people's dictionary. After we print out each person, I'm going to say people, open up this and
say name case fold. It's not allowing
me, but that's okay. Named case fold
equals to the people. Dict or dict. Then at the end I
will print out, sorry, print out the people. So when I write click and I run, look at what we get here. First of all, we're printing
out the names as usual. And I don't want to
do this actually, let me comment this out so that we know exactly
what we're getting. Okay, so look at
this dictionary. Let's start from the beginning. First of all, we have
the dictionary starting. Then we have the key, which is the name
case fold right here. And I make sure
that it's case fold because I don't want to
have any mistakes with the upper case and
lower case and so on. Let me make this smaller. We have John Doe being the key. And then inside we have all the information
about John Doe. We have his name, ID, department, department,
salary, job title. And then we close down. So this is the
value, this is where the value ends for John Doe. And then we have another
item in this big dictionary, we'll call it the
People's Dictionary. And then we have Jane Smith. And Jane Smith is the key. And Jane Smith has a value of the dictionary that
contains the name ID, department, salary,
et cetera, et cetera. Now we have a big, big dictionary that has the key as the names
of our individuals. And then the values
are dictionaries with the information
about these individuals. Now what we'll want is to
have a way when a user, let's say me or you. When a user inputs the name of a person and gets their salary. And this is going to be
a challenge for you. You need to get
input from the user, which will be the name
of one of the employees. Make sure the name is case, Fold check if the person's
name is in the dictionary. This is the first things first, and if he exists or she exists, extract the salary field
and print it out in a user friendly,
a positive video. Right now, this is
a hard challenge, especially if you're not 100% sure of your
skills in dictionaries. But it's a very
important challenge. If you can do it, that means you have dictionaries on point, positive video right now
and go do the challenge. Okay, welcome back. So first thing we'll
do is I don't want to print the people
anymore in here. I'm going to say
person underscore name is going to be
equal to the input saying provide the
name of the persons, person's person's salary
or person's salary, sorry, provide the name of
the person's salary, you'd like to look. Up and then we'll
simply do this, this is going to be the
input then I'm going to say underscore key is going to be the person's name
fold in case someone, because you know,
usually when you write somebody's name it's
going to be capitalized. But in here, remember these
are strings, they are unique. They are key sensitive. So we make sure
that we take them down by the case fold and then we will check if we actually have this person
in the dictionary, how did we use to do that? We simply say if key in
people and then we'll say person is equal to people at the person key and
then person's salary. Salary. No suggestions,
Yes I know is equal to person at the salary. And print out the salary of replacement field person
name is person salary. I keep forgetting
the And salary. Now if we don't find the person, we'll just print
out person salary. Sorry, person name is not in our or is not
an employee here. Okay, I don't know why we need the explanation mark,
but there we go. So let's go over what's
happening in here. First of all, we're getting
an input, very simple. Then we're doing a case fold. It's important here
that we do the case fold on a separate variable, otherwise the name
of the person will be printed out in
a lower case here. And that's not very
user friendly. We want the names to be
in their upper case. That's why we created the
person key a separate variable. To check this, then we
use the person key. We check if the
person key in people. We're checking if the key
is available in our person. If it is, we'll
do the following. If it's not, we'll simply print
out it's not an employee. Remember when we do if a key or if person key in a dictionary. We're going through the keys. We're checking the
keys, not the values. We're checking if
we have John Doe, or if we have Jane Smith, whatever the name was,
then we grab the person. We say person equals
people at that key. So for example, if the
person key was Jane Doe, then we grab the
value and we put it in the person variable. Then we say that
the person's salary is going to be that person. Because remember, this is also a dictionary and we
grab the salary. It shouldn't be too hard, especially if you understood what was happening
in dictionaries. It shouldn't be hard
at all for you. First of all, we check if that key is in our
people's dictionary. If it is, then we grab
the person by their key. Once we grab that
person by their key, we grab the salary
by the salary key. Now if I write Click and I run, If I try, let's say Michael. Nope, Michael is not an employee here.
Let's run this again. Let's say I try John. Let's say we type in
John Doe like this. It enter the salary of John Doe is 5,000 If I go
back to the list, let's see. John Doe does indeed
have a salary. Let's try Steve Kim. He makes a lot of money. Steve Kim. Let's see
how much he makes. So if I write the click
and I run put Steve, there we go, Steve Kim. The salary of Kim is 7,500
All right, very nice. This seems to work. Before we move on, let's
suppose that we'd like to look a person up
not by their name, but by their ID. We have two solutions for this. Either we can create a second dictionary with
the keys being the ID. And then we can check
for a few things, but there is a better way. And that is actually adding another key to our
people's dictionary, which is going to be
the ID's For that, we can simply come in
here, duplicate this, and instead of name
dot case fold, we can do personal ID do case fold even though
we have numbers, so it's not going to matter. We put them in here. If I try to print
out the People's dictionary, look at what we get. John Doe. Okay, The
information is still the same. But then we also have one and we also have
the information. Now we could, for example, say provide the name or ID of the person's
salary you'd like to get. When I write Click and I run. For example, let's
say I want the salary of the person with the ID 11. Boom, enter the salary of
11 is 4,000 Obviously, this is not very good. What we can do for
example in here is get the underscore name. We already have the name, Let's call it the
person info in here. Change this to info and then, okay, seems to be good. Then we have the person name
is going to be equal to the person and we're
getting the name. And then in here, person name. Because we're doing
this outside, it's not going to
get recognized. Maybe we could create a
like a function for this. For now, let's just
keep it as it is. Let's just keep this as the key. All right, because we don't
want to have duplicate codes. We could create a
function that would get the person name and salary. But for now, our focus
is to actually get this, for example, 11, Chris Lee. Let's look if Chris Lee is indeed at 11. Yes, there we go. Chris Lee is at 11 with
4,000 Ladies and gentlemen, I want you to really feel
how much we've progressed. We've parsed a file, we've got all of
the information, we've put it into the
first dictionary, and then we put it into
the big dictionary, which is the
people's dictionary. We've used two keys in here. We've used their name, and we've used their ID, and now we're axing all
of that information. I mean, this is great stuff, this is high level stuff. If you're not really sure
about what's happening, please please, please
take your time. Go back through the code, understand every single line. If you have any questions, make sure to ask me or your dedicated instructor
that you've been assigned to, they will help you
through this process. Thank you so much for
watching. I hope you enjoy it. And I will see you
in the next video, where we will start writing data to a file,
not just reading. I will see you then.
126. 6. Writing Data To a File: Welcome back my fellow Python programmers to a
brand new video. And in this one, we're
finally going to be looking at writing
data to a file. So the first thing
we want to do is we want to save some
animals. Yes, indeed. We're going to create a new
Python file that we will call Save underscore animals. So in here I'm going to provide you with a
list of animals. Don't worry, I hope I
don't forget to provide. If for some reason I do forget
to provide it somewhere or the way that I've
provided it is not adequate, Please send me a message, send your dedicated instructor a message and we
will get to you. But in any case, this is the
animal data that we have. Now what we want to do is not
save all of these animals in Peta does or whatever
animal organization there is, We're going to actually
save it to a Txt file. We're going to first
of all name this file, which is going to be the
animals underscore file name, is going to be equal to
animals underscore printxt. Now you might be wondering, we don't have the file
right here in the projects. Don't worry. The file will be created when it's
needed in here. I'm going to say with
open animal file name now, instead of the R, we need to provide it with the W indicating that we want
to open the file in write mode and
we're going to say as animals underscore file, this is the where
we will be writing. Keep in mind this
is only the name, the animals file name. This is the actual file
object that we'll use to write two in here. I'm going to say four animal, Yes, in animals data. I'm looping over this list from top to bottom
and what I'm doing is I'm printing out animal file, equal animals file. There we go. As you can see, this
is something that we haven't seen before, but I'm going to
take you through it. First of all, if
the file exists, meaning that animals underscore print or the animals
file exists, it will be overwritten. If it doesn't exist, a
new file will be created. That's 12. What is the
file equals right here? This is an extra parameter
given in the print. The file parameter in the print function
specifies that the output should be
written to the file object, which is animal file right here, instead of the standard
output that we see in the dropdown menu or
what do you call it, the console or whatever. So when we say file equal, it means the output
will go to that file. Now let me open up the project
so you can clearly see. We didn't have any
animals print. When I write, click and I
run, Boom, there we go. Now we have the animals
print right here. And if I open this,
notice I don't have anything printed
out to my console. It's all in the animals print. If I double click
and open it up, I have it right here. But let's imagine
we've written to a file and we can't really open. This can happen in many cases, especially when you're
using special encoding. Let's say we want to actually open this file and
see what's inside. To check if we were able to
properly write to it in here, I would just say new underscore, animal underscore list is
equal to this empty list. And I'll say with
animal file name as the animal file, you
can use the same name. And here, don't worry,
it's not a huge deal. We've already closed this file, remember, because
we're using the width. So we've closed
this file so we can use the same file
name. It's okay. And in here I'm going
to say four animal. In the animal's
file, Animals file, I'm going to say new animals
list append with the animal. Now, there is one thing missing in here and I want
you to tell me, it will be obvious, but I want you to think what's
missing in here. What have I left
deliberately out. If I write, click and I run, look at what I get my list. But what do I have in here? I have my new line symbol. How do I solve this?
Take a few seconds, think about it. Yes, exactly. I can hear you on the
back saying the strip, when we do this now it
works completely correctly. Okay. It's pretty similar to what we've been doing before, but there is a different
way of storing data in a text file and that is
using the right method. So let's do that. I'm going to go back in here where we've
written the data. And I will comment this
line out right here. I'm going to say animals file, right then I will write
the animal into it. Now keep in mind we already
have an animal's file. What happens when we
already have one? It will be overwritten. When I write Click and
I run look at that, my output is a bit different
and this should give you an indication of what is going
to be in our actual file. Look lion, mammal, and then we immediately
start with Eagle. Notice we have a list of one single item with all of the names of the animals
mushed together. If I open the animal's print, you'll see that this
is how it looks. The only difference, or the main difference
between the print and the right is
that the print adds a new line character by default, while the right does not. Let's look at another thing
that the right cannot do. My words are getting confused. And when I say we or let's, I'm saying let's
see, You see what? Okay. I'm not good
with words today. Just write ten numbers. Write the first ten numbers, one through ten, to a file
called the numbers file. This is something
completely different. If you want, you can even create a separate Python file for this. Actually, it's a good
idea if you create a completely separate
Python file for this. First, you must open the
file with the W, of course, with the W mode inside the width create a loop
in the range of ten. This with means when
we say with open, et cetera, inside the width. Create a loop in
the range of ten. And use the print and then the right
functions to write the numbers to our file. This is a challenge
for you to try out writing to a file using
the print and the right, you know the difference,
You know how this goes. Positive video right now
and go do the challenge. Okay, welcome back. How did you get on with that? I'm going to create a new Python file in
here which is going to be right numbers in here. All that I'm going to, I'm going to say numbers underscore file name is equal
to nunscorefilet. I'm going to say with
open numbers mode as numbers underscore file, we have the same
name number file. I think we can use
that no problem. And I'm going to
say four in range. And this is the loop
that I told you about that's inside over ten. I will print and then
file equal numbers. File, there we go. And add an extra space at
the bottom for the eight. Now if I right click and I run, I get the numbers file which is zero through ten with
an extra space at the end. Neat. But now I want
to use the right. And I don't think
there's anything that I need to really
explain in here. The for loop. We've
already seen that. We've seen how to
open a file to right. We've seen how the
print operates. There's nothing else to explain. All that there is to
is to use the right. So I will say
numbers file, right. And then I'm writing
V, I right click, Run, and we get an error because I argument must be
STR not an integer. Not that the right method will write only what
you tell it to write. No conversion is performed, and obviously when you're
writing to a text file, it shouldn't be an integer. It doesn't understand integer. There are ways of converting. If it's not dot, for example, you could
do a conversion. Why use right at all? Why use right in the first
place if it's so bad? Well, it depends on the
situation you're in and how you want the data being written into your
file to behave. So for example, if you
need more control over the data that is written
or if you need to write, for example, binary data to save as much
space as possible, then right might be
the choice for you. Meaning that maybe
you don't want to add an extra line but but
the print forces you, maybe, I don't know
convert things. Maybe you want them to stay
the way they are filed. Again, print does not allow you. If you want more control
you would use the right. If you're just writing
something simple to Txt file, then using the print
would be your choice. In this case, I would use STR to convert the right click and run, and I still get a bad output. And the numbers file, they
are all mushed together. How do we solve this? Take a
few seconds, think about it. What should we do? There we
go. And we have this output. Ladies and gentlemen,
thank you so much for watching.
I hope you enjoyed. In the next video, we're taking
things to the next level where we are going to be
learning all about Jason files. So thank you for watching. I will see you and the
next one. Bye bye.
127. 7. JSON files 101: Welcome back my fellow
Python programmers to a brand new video and
probably a long one, where we are going to be, first of all, explaining
serialization and what it is we're going to be
explaining what Json file are, Jason files are. We're going to delve
deep into them, test them out, so
on and so forth. Then I'm going to also
show you how to write and read from these
files and we'll see a little bit about
encoders and decoders. Let's not waste any more time and let's go ahead
and get started. First of all, let's
look at serialization. What is serialization? Serialization is the
process of convert and objects state to a format that can be stored
or transmitted. For example, if we're sending information through Bluetooth, the information doesn't get sent as in strings or
couples or whatever. They are sent through
waves and zeros and ones. That's how they understand the stuff, that's serialization. When writing to a
file in Python, serialization is often used
to convert an object into a text representation that
can be written to a file. To write representations
of the object to the file, we use the function dump. We dump the
information in there. There are many ways of
serializing data and one of the most widely used
is the Chason file. If you're thinking, whoa, this is too complicated
and whatever, don't worry. For example, when we
were trying to write a number to a file in
the previous video, we had to convert it to a
string and then add a new line. And that is what we
call serialization. Seralization can
come in many forms. It could be very complicated, and it can be very, very simple. Just like we saw in
the previous video. Now let's look at what Json is. Json is Javascript
Object Notation. It's a format commonly used for website application
or web application. Not just a website, but anything that you do
when you're interacting with the World Wide Web uses
Json serialization. In the context of the Json files refers to the process
of converting a Python object into a Json encoded string that
can be written to a file. We have an object and Python
we encoded using the Json. And then it's a string that
can be stored in a file. When we want to use Json, we need to import a module, just like we import the random. When writing a Python
object to Json file, we use the Json dot dump, we've already seen in
the previous slide. When reading a Python
object from Json file, we use Json load. Not all Python objects can be
serialized to Json format. We'll see a lot of examples. But for example, the set cannot be serialized to Json format. And Jason serialization and deserialization is faster than other serialization
formats like XML. We were not going to go into
XML in this course unless I, for some reason decide to
update it and use XML. But Json serialization and deserialization is the
more commonly used one. You've probably heard it before and it's what we are going to be focusing on,
enough theory. Let's go and look at an
introduction to Json files. First of all, I'm
going to create a new Python file in here which I'm going to call
Jon Underscore Intro and I'm going to right click on Json intro and I'm going to close all close other tabs so that we only
have a single tab. Close this down as well and maybe keep this one right here. The projects, just so if we have any extra files
added so we can see them. I'm going to import the
Json, as I told you, it needs a module and
then I'm going to have computer underscore parts. I'm going to have this list. Now, again, I'm going to provide you with
this information, don't worry, it's just a
list of these elements. 198, it's the year where the
hard disk drive was created, the random access memory, the Ram 1968, et
cetera, et cetera. Now what I'm going to do is I'm going to write this
to a Json file. I'm going to say with open and I'm going to
do the following. I will say, Jason
underscore score, just test file dot Json to
make it an actual Json file and then as Jon
underscore test file. Then in here I'll say
Jason dump and I think, yeah, no, it's okay. It's
okay for some reason. I thought maybe it
interpreted it as the folder here,
the entire module. I mean, then I'm
going to send in the computer parts into
the Json test file. And you can read all about
the dump and how it works. You can see it send a
very extensive function or method that you
can look into for me. All that you need to know is what you are
actually sending in, what you want written
to and the file you want things to be written to or the data to be written to. Now if I write, Click
and I run, look at that. A new Json test file
has been created. If I open it up,
look at what I have. I actually have a list. But there are a few limitations to Json and we're
going to see them. But before, let's look at what happens when we want to
read data from file. If I go back in here, let me comment this out because I don't want to write again. I'm going to do
with open and then, oh my God, I hate
this by the way. I hate this and I don't
know how to get rid of it. Json test file, it will
default to writing and it's just going to be the Json
underscore test file. And then the Jon underscore data will be equal to Json load. And we've already seen and
notes we have loads and load and we will see the
difference Json test file. Now if we try to print
out the Json data, right click, Run, boom. Look at that. We get all of the data still in
the form of a list. Let me try to print out
the type of the Json data. Right click, there we
go. It's still a list. So keep in mind, we wrote
into the file as a list, it was serialized by Json
and now it was deserialized. And it kept its integrity, it stayed in its four. This is something very
important to keep in mind when we did it previously,
when we serialized, for example the integers, the numbers 0-10 or 0-9
in the previous video, they were converted
into a string. If we tried to read it again from the file, it
would be a string. But in this case it
kept its integrity. We can even, for example, axis the data at
position number two. If I write Click and
I run look at that, I get the central
processing unit CPU, which was made in 1971. This all looks fine, but there are
limitations to what Json file can
serialize and serize. Let's take a look
at this limitation. First of all, what we
want to do is we want to convert all of
these into pupples. Now, we could come in here
and start adding this, and then, oh, wait, it
changes automatically. I think, yeah, we can do this. I wanted to show you a nifty
way of doing these things, but unfortunately,
it just showed what? Let's just do it. If you hit, for example, control R, R. You'll see maybe
just one control R, one control R. For example, you can say that find all
of the square brackets. It will find them and convert
them into round brackets. You'll see it will give you
where do you want to convert? You can, for example, select
this one and say exclude, exclude this one,
and replace all. Boom, there we go. You can see this one. We don't want
include replace all. Okay, there we go. Now
we can select this side. We can click in here and ex, then convert it into the. Boom, this one. Replace all. There we go. So we've converted
this into a topple. And by the way,
this wasn't present a few months ago when I
was working on the scores. For some reason, maybe in
the update they included it. But anyways, what we
want to do is we want to convert these into topples. Hitting the control R, you
can select what you want to change and then exclude the things
that you want to keep. Very, very powerful
tool, by the way. So now that we have these
in the form of a couple, I'm going to, Let's keep it, let's keep the read, and
let's comment this one out, meaning that we are
going to write again. Now if I write click and
I run, what do I get? I still get a list. If I open this file, I still have a list. But guys, this is Apple. Let me write, click, and
run again. It's Apple. What is happening? Well, it's the
limitations that Jason faces where it cannot
serialize topples. Let's look at a
few things that it can and a few things
that it cannot. If I open this and don't worry, I will send you
the link for this. This is the Jason. Jason
encoder and decoder. If you scroll down, you can read all about this,
how to use this, go super, super in depth, but I don't want to waste
time on that for now. I want to look at
encoders and decoders, the Json file in here, you'll see that performs the following translation in decoding when you
want to decode. If, for example you
have an object, it becomes a dictionary. If you have an array in
Jason, it becomes a list. If you have a string,
it goes out as a string in Python, and
so on and so forth. If we scroll down to decoding, I mean encoding following
objects and types. By default, for example, a list and a couple are
converted into an array. An array in this case
is just like a list. It has square brackets. A string stays a string, but an integer float integer, and flow derived enums, whatever are stored as numbers, true stored as true,
false as falls, and none as null in a Json file. That is why when we converted in Python from a
list to a couple, we still got an array and we
still had the same output. So I hope this was understood, I hope this is not
too confusing. You can always look back at this and understand
how it works, But using Jason files is
super, super important. For example, if you want to
save dates into Jason files, it's impossible, They are
not registered properly. Jason has its limitations. Anyways, I know this
video has been long. I try to be as brief and
as in depth as possible. In my explanations, I think I covered everything
that I needed to cover. To give you a broad idea and a little bit
more in depth idea. I do recommend if when
the time comes when you become the data analyst or the Python developer
or whatever, you will have to delve a lot
deeper into these things. I'm not going to do that
in discourse for now, Maybe later who knows. But let's now look at a practical application
of using Json. Back in here, I'm going to
create a new Python file. Sorry, not a new Python file. A new just file. And I'm going to
call it students. Jon, I want to have
a Json file created. Then I'm going to put this
data in again, please. You should see it somewhere. If you don't nudgeI don't
know if you remember nd MSN, I don't know, how old are you. Maybe what I just said
makes no sense at all. But anyways, look at
what we have in here. We've created a Json file and intelligent recognizes that
we've created a JSon file. Maybe on your side it
does not recognize this. Maybe you have to
install something that pops up on the
bottom right corner. Do whatever is needed. You should see
this color change. So notice what we have in here. It's kind of a dictionary, if we look back at
this right here. So we have object, right? So this is an object because Jason doesn't have a dictionary. Now in theory, what
should happen when we convert this or when we
read from the Json file, We should get dictionaries. So keep that in mind because we're going to
create a new Python file that is going to be
practical underscore Json. And we're going to issue you a challenge where you need
to load the students. First of all, import
the Json module, open the students folder
in the correct mode, load the data into students variable to a students variable. You can call the variable
whatever you want. Keep in mind you have to load, print out the data that you get and does it
look user friendly? Can we do it in a better way? Pass the video right now
and go do the challenge. Okay, welcome back. How did you get on with that? First things first is
importing the Jon. Right? And I know some
of you at this point are complaining like
these challenges are getting really, really hard. But what I'm imagining you as is you've already done like
maybe ten, maybe 20 hours. I don't know how long
this entire course is, but you've done so many hours, you should be very,
very familiar, especially if you were working with one of our instructors. You should be top notch. So you should be attacking
these challenges without any mercy mercilessly. So I'm going to say with Open. Oh my God. Students Jason, I want to be faster
than the other one because I emphasized
using the right mode. I will do the R as students underscore
file and then in here I will have students
and I will say Json load and we will
load the students file. That's it. We've
already seen the load. We've already seen
the Json module. We've already seen most of the things that
we talked about. All that's left to
do is to print out the students and
to print out Wait. Before we do that, first of all, we wanted to look at the students and what we
get and look at that. These are what, let's
say we don't even know. Let's not assume anything. These are dictionaries. Indeed, if we wanted to print things out in a
more user friendly way, how would we do that?
What do we have in here? Look at the data and
understand what it is, parse it, really
understand how it's looking in this file.
What do we have in here? We have the key students
and then we have name, a major, et cetera, et cetera. These are our students. The key is student. The value is a list and it's
a list of dictionaries. So for example, how do I access, how do I go deeper in here, I print out students, students, what do I get? Boom, I get a list. How do I delve deeper? I open up the first element
inside of this list. I get this dictionary. I get the name John. How do I access
this even deeper? I want to get the
name, for example. I get John. Again,
practice this. Make sure that you've
understood how this works. There is nothing to this. I'm just going
deeper and deeper. Actually, let me duplicate this so that you can see
what I want to do. This one and then this one. Okay. Yeah, this should be good. Okay, so now let's maybe deerize this information
and printed out properly. I'm going to let me first try to click and
run. Okay, there we go. So we've created the steps. Now let me print in here. And I'm going to say students underscore data is
going to be equal to students at the students
in student data. I'm going to print out student. No, wait, this one
should be a student because we're accessing
each individual student. Student name is my God, what am I doing, years old and studies. And by the way, this was
part of the challenge to print it out in a
user friendly way. Studies student
major, right click, run and look at that. John is 20 years old and
studies computer science. Alice's 22 and Bob 21 and they each study
mathematics and physics. Ladies and gentlemen, this
was a very long video. I think we're at
the 20 minute mark at this point, maybe even more. If you made it to the
end, you are incredible. If you understood 50%
of what just happened, you are doing extremely well. This is not easy. These are new concepts. Serialization, deserialization,
Jason, reading, writing, load, write, dump, what the hell is happening? Don't worry, it's natural to feel like you're
getting started. It's natural to feel that
these things are hard. You're seeing this for
the first time again. Breathe out. Go over the video, how many times you
need extra resources. Go to W three schools. Make sure you
understand everything. Contact your local
instructor at Tm Python Dev. Make sure that they
explain to you everything. Make sure that
they help you out. Don't worry, it's very important
what you did right here. If you can understand what
happened, you are amazing. We serialized JS file, we deserialized AJson file, We extracted information
from whatever this was. And look at what
we got in the end. Look at what we printed out, this beautiful
looking information. I don't know what that even is. We just got this. I
hope you enjoyed. I hope it wasn't too confusing. The next video, we
are going to be streaming Json file
from the Internet, which is going to be very cool. Which is going to be like
something like we do, for example in Netflix
when you stream files. Thanks so much for watching. See you in the next video.
128. 8. Streaming JSON files using urllib: Welcome back my fellow Python programmers to a
brand new video. In this one, we're
going to be streaming Jason files using URL Lip. What does that mean? We're
going to see in just a bit. But first we need
to understand what is file streaming
in the first place. You might have seen streaming in many places like
Youtube, like Netflix. I don't know anywhere else
where you've seen streaming. What is file streaming? Jason is a data format
that is commonly used for exchanging data
between client and server. So as we said, Jason is used very widely in
web application. And when you are using the web, you are communicating
with a server. So you have, let's
say you've opened Facebook or Instagram
or Twitter or whatever. When you're on your
phone and on Facebook, let's say you're scrolling down or you're
uploading a photo, or you're liking a photo, what's happening is
you as a client, you are having an interaction
with a Facebook server. So you're interacting
with a Facebook server. So how does that
data come to you? Some of it comes through Jason. So you're streaming that data
through Jason, for example, or you're streaming
that data from the Facebook server using whatever encoding that they use. Streaming files like
streaming movies on Netflix, is accessing Json files online that are
always up to date, and printing them out to an application for
a user to see. So for example, you have
the Netflix application, or you might open Netflix
on Google Chrome. So then you are streaming the Netflix files
to your computer. You don't download them. Remember this is
not downloading. You are streaming, so
you're getting bits and pieces of the file as
you're getting them, you're displaying them
on your application. R Lip is a Python library that is used for accessing URLs. It can be used to make HTTP requests and retrieve
data from web servers. So HTTP is a way to
create security, let's say HTTP request,
how can I tell you? Like, for example,
if we open again the link that we had in
the previous video. Okay. All right, here, that continue. Right here, you'll see we
have HTTPS right here. Let me check what it
actually stands for. Control HTPS copy that, meaning hyper transfer
protocol security. Basically, it allows you
to create a connection between you and the
server that you're trying to work
with, that's HTPS. When working with Json
data using URL Lip, you can use a stream
to retrieve the data rather than loading
all of it into memory. This is done using the URL open, which returns a file
like object that can be read in chunks
using the read method. Let's go ahead and stop with the theory and
actually start working with streaming Json files
back in our code in here. We're going to create
a new Python file that I'm going to call Jon. Underscore file. Underscore streaming. Boom, here we need to
import Json and we need to import UR lib request.
This is very important. This is what will allow us
to access websites in here. I'm going to say Jason
underscore data. Underscore link is equal to the following link
I will of course, provide to you somewhere. There we go. Now with
that link, if you want, you can even open this
link if I open this link. So this is the link. If you follow it, you'll
find that we have a list. A huge list for that matter. Boom. Inside of this
list, what do we have? We have this dictionary
which has ID, name, user, et cetera. Then the address, the
address has inside of it, another list,
another dictionary. And I'm saying
dictionary, but in fact, what is it when we're talking about this
in a Json context, it's an object,
not a dictionary. But when it's deserialized, it will be a dictionary. In Python, right
here, there we go. You can see that the geo, which is a key inside
of the address key, has its own dictionary in it. It's very important
for you to go through this and parse it correctly. You need to understand
what is happening here. But anyways, let's
take this back here and let's go
ahead and continue on. We are going to
do the following, we're going to say with, and this is going to be
new but not worry. Url, Lip request, URL, Open Json data link as
Json underscore stream. Then in here I'm going to say
that the data is equal to Json stream, read, decode. And it's not giving
me suggestions. I'm not sure why user equals Json loads data. Keep in mind this
is not load like we've done before,
this is loads. If we hover over loads, okay, that's a lot
of information. But basically what the loads, the difference
between the load and the loads is that it
allows for streaming. Can I find in this documentation
somewhere that it says that this
is for streaming? No, I cannot. I do recommend that you go and you look up this in more detail. There are more differences than just the streaming
part print out and maybe we should do the
users right click and run. What do we get? There we go. We get
list for that matter. To look at this, the
list which inside has the ID and the name, and the username, and the e
mail, and then the address. And then the address is a
complete based on its own. So a lot of data in
here that's happening. And somebody has to decode it. And you know the drill by now. When I say somebody,
it means you because you need to print things
out in a user friendly way. You need to use the
data that we got to print out a user
friendly output. We want the name of the
person, their city, and their phone number to
be printed out correctly. We want this for
all the people we have in the file
that we streamed. Pass the video right now
and go to the challenge. Welcome back. How did
you get on with that? I admit this is not an
easy task to do here. I'm going to say four
or four user users. I'm going to print out the following if we just
follow the example in here. First of all, what do we want? We want the name very simply. We're going to do the following. Open the parentheses and say, open up the brackets and open up the the
brackets as well. What's the matter here? What is the problem name? What is it expecting from me? User parentheses. Okay. I think it's not recognizing. Let me try to run and see. Okay. Name parentheses,
unmatched. I don't think it
recognizes that. I apologize, this
is embarrassing. I spent a few seconds
trying to figure this out. Again, I like to keep these mistakes because
you should always know that everyone does these
mistakes, even an instructor. The problem was that when I used these two quotations and I
was like, What's happening? Maybe Python isn't realizing that dictionary or I don't know, something is very, very wrong. The problem was that I was
using single quotation marks around these and I was using single quotation marks inside. That was it. I spent, the editor probably
edited that out, but it took me 2 minutes
to realize this name. If I write Click and
I run, there we go. You can see that we
get all of the names. Very nice. Now they live in. We open this up again, You
should know the drill by now. What do we next want? We want the city, correct? We said the city and
their phone number. We want the city. Our stream right here.
Now we found the name. It's pretty easy were accessing every single individual
item in here. And then we access the
name, we get the name, but then the city is
inside of the address. First we need to access the address and make sure that it's written correctly.
Let's double check. Where is it? Right here. Let me copy this actually and paste it
in here. It's the same. Then we, the city, we click and not debug. If I write, click and let me stop this and run. There we go. Lee Graham lives in
Gwen Burl Irvin. How lives in Wiscommb. These names are very weird. I don't know where
they are from, but as you can see right here, address, address, city,
and so on and so forth. Now, we want to also get the phone number you
can call them at. Open up the parentheses, where is it phone?
It's on its own. It's not inside of the address, so very easy to access. What was it? Phone.
Phone, right click, Run. There we go. Now I'm getting
the sweet symbol here. What is it? Oh, it's part
of the phone number. All right, there we go. So maybe this was
completely nuts to you. I think everything was easy. Maybe this line
of code is weird. It's part of decoding,
it's reading, decoding, and then
loading into users. This should be pretty simple. This is new, but this is
how we access, not files. We're not opening a file,
we're accessing a stream here. These should be pretty simple. The hardest part, I
think, in my opinion, the one you might
be struggling with, is understanding
how this operates. Take your time.
Understand exactly what is happening in
here step by step. Focus on one at a time. Just focus on Lea Graham. Focus on the ID, on the name, on the username, and email. Just for training, just as an extra challenge
on the side, try to access the latitude. Okay, try to access the latitude that each
person is working on. It will be a great
exercise for you. Once you can do
that, you are solid. In the next video,
we're going to be looking at CSV files which are a completely different
beast on their own. But don't worry if you
can understand this. You can understand
anything in life. Thank you so much for
watching. I hope you enjoy it. And I will see you
in the next video.
129. 9. CSV files 101: Welcome back my fellow
Python developers to a brand new video. And in this one, we're
going to be looking at CSV files without any further or let's go
ahead and get started. First of all, what the
heck is even a CSV file? Csv stands for comma
separated values. It's a is a simple or CSV is a simple file format used
to store tabular data. Tabular data means data
that's in a table, meaning Excel. Google Sheets. Very important in data
analytics and data analysis. It's often used for exchanging data between
different applications, such as spreadsheets
and databases. The CSV module provides
functionality, provides functionality for
working with CSV files. Just like we imported
the JS file. In order to work
with Json encoding, we also need to import the CSV. To read CSV files, we use reader function, which returns an object
that can be iterated over to access each
row of a file. We've seen how we access
rows in a text file. The same holds true when we're using a reader on a CSV file. We access individual rows and each row is represented
as a list of strings, with each string representing
a value in the row. We're going to see
more of that when we actually start working
with CSV files. And finally, to write CSV files, we use the writer function, which allows you to write
rows of data into a file. We're going to see
all of that strap on your thinking caps and let's
go ahead and get started. First of all, I'm going
to go back into my code. In here I will create
reading CSV file, Python file to a
new Python file, reading underscore CSV,
underscore files head book. Next I'm going to write, click and open and explore. I will go right
here on the side, just like we've done before. You'll see that we have,
we have this as well. We should have the resources. Again, if you do, if there's any problem,
please let me know. We should have two ones. One is quoted, one
is not quoted. And I'll tell you what
the difference is. Control C control. And now we can start
using this file. We should see Av file, Where is it? Where is it? Somewhere in here. Wait, am I just blind and I can't find
it? Oh yeah. There we go. So the SV file. Let's open it actually, and
let's look at what we have. So this is the comma
that I promised you some versions of. Intelligent have seen
it with students, maybe because of the
update even though I keep this updated
as much as I can. There we go. It's in
the table format. Some of you might
not have these in color or you might not have
the option for table editor. I think somewhere when you
try to open the CSV file, you'll have a pop up right here, or you can see CSV plug in. You need some kind of
CSV plug in or whatever. Download it, Set it up so that you can see
it in this format, just as I do right here. If I move this up a little bit, you can see that this is a
table format or tabular data. So we can see we have
names, the ID, department, salary, and a job similar to what we
had with the XD file. But this time it's a little
bit different with the ID's being these huge
different numbers. Usually ID's don't come in 1-10 in order back in the
reading CSV file. First of all, we need to
import the module CSV. Next, we have to say that
the CSV underscore file name is equal to the
people list CSV Sv. Now, just like we do with
every single other file we say with open CSV file name, new line, I'll tell you what this new line
is in just a bit. As people or people underscore
CSV, underscore file. Then we're going
to use the reader because remember we
want to read from this. We'll create a reader variable which is going to be equal to CSV reader and we're reading
the people CSV file. Then we'll say four
in reader print. There we go. So first of all, what is this new line? The new line parameter
is used when opening a CSV file to specify how line endings should be handled when
reading from the file. This is only special
for the CSV. What do you want to have
at the end of the line? And I told it that I
don't want anything. So let's right click and let's run and look
at what we get. So as I told you, it's going
to be a list of strings with each separation between the com being an item of that list. So you'll see name, ID, department, salary,
job title, John Doe, ID sales, their salary, and the job title, et
cetera, et cetera. You'll see even some
of these are empty. Now let's expand on our example and make it
more suitable to read. We'll start by setting
the headers properly. First of all, obviously I don't want the headers
to look like this. I'm going to go inside of this file file and
I'm going to say headers equal to people
CSV file read line. I'm reading a single line
and we always have to strip. I'm not sure what
I want to strip. I'll just keep it as it
is. I'll just say strip. I don't know what it will be. And I'm going to
also split over via. Then in here I'm
going to go ahead and print out the headers. I'll have headers,
two dots, placement, field headers, right
click, run and boom. Look at that. I have my headers. The only problem is that I'm
not getting rid of these. It's still in the form
of a list in here. First of all, I'm going
to do a few strips. I'm going to do a backs R, which is called the
carriage return and the backslash N. Let me just show you what happens
with the backslash R. If I right click and
I run look at that, I'm stripping away
the R's in here. First of all, we want
to catch the headers. I'm going to say
that the headers are equal to the
PeoplesVfilereadline. I'm reading the first line from my CSV file and then I am
printing out the headers. There we go. Now if I write, Click and I run, look at that. I have my headers right here. Just for an extra thing, you'll notice that we
have a space in here, we just do a strip and
this should look good. Now we have the headers in a
slightly better looking way. Now, the issue with this is if you notice
on these tables, we can extract this information because we have them as roles, we have them as lists, we can extract the information. The only problem is that all
of these values are strings, even the ones that are
supposed to be integers, like the index, or that are supposed to be floats,
like the salary. So that is obviously a problem. So now we're going to
look at something called the quoting CSV files. You'll notice that I also have, you also have another file, It's the People's
List CSV quoted. So I will copy this, I will
paste it back in this file. Now in here we should
see the quoted. If I double click
and open it up, look at what we have in here. The quotation marks indicate that this should be a string, that this is a special something
that should be a string, while the ones that
are not quoted mean that they should
not be strings. Anyways, let's see this in
action and in real life. Now I'm going to create
a new Python file. A new Python file that
I'm going to call q CSV files did underscore
CSV underscore files. In here I'm going to import CSV. I will say that the CSV
underscore file name is equal to people quoted. People list CSV quoted
with open CSV file name, new line, just an empty
space or just nothing. I mean, people underscore
CSV, underscore file. I will say that I have
the reader which is equal to the V reader. People CSV file, and this is the most important one in
here, I'm going to say. Equals to Sv non numeric and four row in reader print doesn't like the spaces here. Okay, let's right click, Let's run and we have a problem. Before I tell you
what this problem is and how to handle it, first of all, we need to look at this
argument right here. The quoting has
been non numeric. This argument tells
the reader to automatically convert all
the fields that are not enclosed in to a float or
an integer if possible. Now the error that we got
is from this argument, because it's telling
us that we tried to convert the ID, but we couldn't. Meaning the word ID right here, you'll see that ID is
not in quotation mark. And the same will
happen to the salary. For that reason, we have to do the same thing
that we did before and that is take out
the headers first. In here I'm going to say that
we have headers equal to the people CSV file
dot read line hoops, dot read, line, dot strip. And then I will print
out headers, headers. And now we should
not have any issues. As you can see, we don't, you'll see that we
have the name ID, department, salary,
job title, et cetera. In here we have the ID, but it's a float. Now the salary is a float. And that's great,
that's perfect. But this should not be a float. We have to find a way to fix this by issuing you a challenge. Your challenge is
making integers. So first of all, how would we go about fixing this problem, to think about it before
moving on to the next steps? If you can think about
it, you can do it. Go ahead and do it. I highly
recommend that you do, but if you don't, this is your last chance
to think about it. Here's a hint,
convert every ID into an int using the int
function before printing. But make sure you access the
ID correctly from our roles, pass the video right now
and go do the challenge. There's an extra
challenge hidden deep inside of this challenge.
Try to find it. Try to fix it. Welcome back. How did you get on with that? I hope it wasn't too hard. It shouldn't be too hard. All that we need to do is
inside of this fore loop, I will take the row at position one because remember
this is where we have it. And I'm going to say that it's
equal to integer row one. And that's it. And now we can print
it out in here. What's the issue?
Unexpected type. And I think it's just not sure what's happening.
Right click and run. Uh, what is the problem? A invalid literal. Everything worked except for what's the hidden issue here? Some of our ID's are not full. For example, after Mike
Chen, if I opened this, let's look up two until
we get to Mike Chen. Where's Mike Chen? Mike
Chan is after David Lee. Sarah Kim. Okay, so my Chan, there we go, look at that. The ID in here is missing. So what we need to do before we convert all
of these is we need to check if the row one is actually different
than an empty string. If one is, excuse me, different than an empty string, only then will we convert it. And then we will
print out the row. So and I right click and
I run, look at that. We have everything
printed out properly. Thank you so much for watching. I hope you understood
what was happening. There's nothing
too much in here. Nothing too complicated. In the next video, we're
going to be looking at dialects and sniffers. Dialects and sniffers are
going to be very important to be able to parse data because right now we know
that we have commas, okay, in the case of
the text documents, we knew that we have
the certain limiters. But what if we can't see the
file? What if it's hidden? What if we want to extract data from it and it's
encoded in some way? How would we know
we would need to use the dialect and the sniffer? And I will see you
in the next video where we tackle these issues. I will see you then.
130. 10. Understanding Dialect and Sniffer: Welcome back my fellow
Python developers. In this video, we're going to be understanding dialects
and sniffers. Now, you might have
noticed that every time we get information
from a file, we need to know what that
file or what the file that we're reading
from looks like. Especially when we're
working with TXT files. Does this file, let me
show you what I mean. For example, right here,
the TD for the Python poem. I mean, does it, how does it end?
What does it have? What are the spaces
in between it? Or when we try to
parse, for example, to do the animals print
on the people's list, x T, for example, we needed to know that we had
this delimter right here. What if we don't have access to that file?
What would we do? Well, we're going
to use CSV in order to see how we can sniff through and understand what
this file is made of in case we don't have access to it or maybe it's
hidden or encoded, or top secret or whatever and you need to extract
information from it. Let's go ahead and get started. We'll go to file new, create a new Python
file that will call CSV underscore dialect. In here I'm going to import
CSV and I'm going to create the people's file name equal to the people's list T. Let's say we have no idea
what is happening in there. I will say with open
the people's file name. New line because we're
working with CSV even though it's a XD file, but we're working
with a CSV file. And we'll say people
underscore list here. I'm going to say that
we have the reader. We always create a
reader when working with CSV reader and the
people's list. Then we'll say four lines in People reader, print the line. If I write click and I run, we should get all of the
lines from that file. Notice that they are
in the form of a list, but that is not a
problem for us. The next thing we want
to do is we want to see what are the separators
inside of this file now. Okay, I know it's a pipeline, but imagine that we have
no idea what these are. Also, keep in mind that each of these lines are a list
that contains one item, which is not very helpful. So let's go ahead and
start dissecting this. Let's say we know
that it's a pipeline. If we add a delimitter in here, delimit, yes, this should
be correct. There we go. And if we add the
pipeline, if I write, Click and I run, look at that. We have dissected our lines. As you can see the
problem is solved. But what if you wanted to
create a code that can receive different types of Txt files that might have
different delimeters? If the Demeter was for
example. I don't know. Maybe you want this code
to work on multiple files. Whatever type of file
that you send it, it will limit it using
its own delimter. The way we do this
is going to be using the dialect
and the sniffer. Sometimes CSV files or TXT
files for that matter. Any type of files have different formatting options such as different delimeters, de characters or line
endings, that is possible. Csv module provides
two very useful tools which are the dialect and the sniffer dialect
allows you to define the formatting option for a
particular type of CSV file. The dialect is going
to be the formatting, you know, when you
have a language it always has its own dialect. How it's written, what are
the rules for its writing, what is its grammar? The same holds true
in cases where we have these different
types of file formatting. And the sniffer works by analyzing a small sample
emphasis on the word, small sample of the CSV file to determine the
formatting option used. So the sniffer goes through
a sample of the file, and I know I keep saying
CSV file in here, but it's because the dialect and the sniffer work from CSV. But as you saw, we can apply
TXT file to this as well. The sniffer goes
through the file, sniffs around, sees
what the dialect is, and gives it back to
us so that we can then use it in the
formatting and you can then pass
the sample data to the sniffer sniff method, which will return
the dialect object representing the detected
formatting option. The dialect object representing the detected formatting option. You take a sample from the file, you send it to the
sniffer sniff, it returns the dialect
and then you can use that dialect in
your programming or in your parsing or formatting or whatever
enough theory. This is a bit complicated
on the surface, but don't worry,
it's very simple. Back in our code in here. Let's say we want to change
a few things in here. First of all, we need to create
a sample from that file. I will say sample equal
to peoples list Read. Now you'll see that
this is not something that we want but for
now it will work. Then I will create the people dialect which will be equal to CSV sniffer sniff and I
will send in the sample. Now if I write Click and I run, you'll see that I
don't get anything at all even before using the
dialect or testing things out. We don't get an output.
And why is that? You should be familiar by now. Because we already read
through the entire thing. Now the cursors again, imagine that you have this
small robot cover going over every single character
and line in that file. It's already read through it. What should we do in here? We should change this. Or at least we
shouldn't change this, we should take it
back to the top. And the way we do
this is by using the people's list zero. Now this takes it back
to the beginning. Before we continue
on, we need to change this dilimeter in here to the dialect and say that it's equal to the people's dialect. If I write Click and
I run, look at that, I get the separation without even knowing
what we have inside. This is amazing, but there is a problem here that might not appear on the
surface immediately. It's the fact that we are
reading the entire file. And remember I told
you that we need a small sample from this. Imagine if we have a file that's 10,000 or 1 million lines
long and that could happen. Don't think it can't happen. You can encounter a
lot of huge text files from databases or collecting data throughout years and years. So imagine you have to
read through all of it. It will take a lot of processing power
from your computer. So the better thing
to do in here is to simply read
through three lines. And that should be enough to get all of the
information out. This is going to
be a challenge for you to only read a few lines. First of all, instead of
reading the entire file, read only a few
lines from the file and use them as sample
for the dialect. I'll give you a few hints if you don't want
any of the hints. Positive video right now
and go to the challenge. If not 321, create an empty
sample string variable, create a loop over
a certain range. At every iteration, a pen that sample variable with read line, pass the video right now
and go do each challenge. Okay, welcome back. How did you get on with
that in here in the sample? Instead of doing this like this or reading the entire file, I'm going to comment it out. I have an error,
but that's okay. I'll say that sample is equal
to just this empty string. I'll say four line in range. I don't know why I call it
the line doesn't matter. It's because we're
going line by line. I think it does make sense. Do sample plus equal
peoples list. Read line. There we go. That
should be enough. We are reading only
three lines now. This should stay the same. Obviously nothing should change because in the first case, we were reading through
the entire document. Now we're just reading through
the first three lines. There we go. That is
all we have for this. Before we move on, there
are a few things that I would like to show you
right here at the bottom. Let me add a print
and let's print out a few elements
that are available to us or a few properties
from the dialect. The people's dialect that
delimiter duplicate this, the people's dialect,
The duplicate this. The quoting. If I write Click and I run,
this is what we get. This is the delimiter. Look at how it was sniffed out. This is the, the character
that we use for, if it was, for example,
something different, maybe a single, we would have had that present
to us as well. Then finally, zero means that we don't have
any quoting in here. Let's test something else out. Let's test, instead
of the people's list, let's test the people's List SV and see what we get.
Keep those in mind. Right click, Run. All right, there we go. Now the delimiter is the comma, the quoting double quotation
or the code chart is still double quotation marks
and the quoting is zero. Let's test out the quoted. The people's list. People's list quoted.
Let's see what we get. There we go. It stays the same.
Nothing too much in here. Let's finally test
out the Json file. What was the Json file called? J was this We could test
out the Json test file, but I wanted to. What else? The students. All right, so the students let's
test out the students. Jason, Run. All right. There we go. So you can see a few things are
different in here. Don't worry about
what we're reading. Obviously, this is not set
up to read from Json file, but as you can see, there is no delimitter
which is good. At least it's got that and there are a few code
charts I'm quoting. Ladies and gentlemen,
the dialect is very helpful when working
with CSV files, JS files and TXT files in order to understand what is
happening on the inside. If you don't have access to
the file for some reason or you don't want to go
sniffing through it yourself. Thanks so much for watching,
I hope you enjoy it. At the next video, we
will be writing CSV file, so I will see you then.
131. 11. Writing a CSV file: Welcome back my fellow Python programmers to a
brand new video. And in this one we're
going to be looking at writing CSV files. Let's go ahead and get started. First of all, we're going to create a new Python
file that will call writing underscore two, Underscore CSV and
Enter obviously. First of all, we
need to import CSV. That's obvious by now. The next thing is we
need to get this data. Now I'm going to provide
you this data somewhere, and as always if I do
for some reason forget, please let me know in here. We're going to create
an output file, we're going to have the output file name and it's going to be called people underscore
written underscore v CSV. And then we'll say with open output file name comma because remember we're writing new line equals nothing in here
as the output file, or let's call it out
file just so we can have a clear distinction between
the name and the out file. First of all, we need to
create the writer object in CSV just like we have
the reader object. We have the object, we'll say that the w is equal, is equal to sv. There we go. And
then the file next, we want to actually write
that data into the writer, we'll say writer right prose. The data, the data is
what we have right here. Now if I right click and I run, you can see there's
no output obviously. Let me right click
and close other tabs. And then in here we should find that we have people written CSV. There we go, look at that. We have name, age,
gender, country, city. And there we go, you
can see we have John, Bob, Alice and so on. All three people, not too much, This is what we wanted. John Jane, we have everyone. John, Jane, Bob. Yes, we do have
everyone in here. But sometimes the problem in here is that we don't
have all of the data, meaning we don't have the
headers for our data. For example, we would have this kind of data
and we would have the headings underscore data like this or not even like this, maybe it's written like this. We have the headings on
one side and we have the data for the people on the other side or in other list. How would we write the headers? Because now if I write click on, you'll see that in
the people written CSV we don't have the headers. We don't know what's the name, what's the age,
what's the gender. Obviously we do know. But
imagine if we might not know. How would we solve
this with a challenge? Write the headers
into our CSV file. This should happen before we start writing all
the other rows. And I will give you
a hint in here, look for a function
called right row. Pass the video right now
and go do the challenge. Okay, welcome back. Just like we have read lines and we have read
line which reads either a lot of
lines when you use the red lines or one single line when
you use the read line. The same principle
holds true in here. You can write a row and you
can write rows in here, right under the writer. I'm going to say right, right, oh my God. Right row and then
the headings data, and then we write the data. So write the click and run, and if you look right
here, look at that. We have the name,
age, gender, country, city, and then we have
the rest of the data. So ladies and gentlemen, this was very, very simple. We are almost at an end, but before we leave, there are two other methods that I want to show
you that allow us to read and write from
files much more easily. Or not much more easily, but maybe in a more
sophisticated way. So thanks so much for watching. I hope you enjoy it
and I will see you in the next video. Bye bye for now.
132. 12. Reading in a different way (DictReader): Welcome back my fellow Python programmers to a
brand new video. And in this one
we're going to be looking at dict readers, so it will be a different
way of reading from files. Let's go ahead and get started. First of all, the dictreader, it is used to read CSV files and parse the data
into Python dictionaries. Immediately, we parse
data into dictionaries. We've done this before, but in a much longer way. Now with the dict reader we
have a much simpler way. A dictionary is created for
each row in the CSV file, with the keys being the head er, row and the file, and the values being the corresponding
values in that row. Dictreader objects
can be used in a fore loop to iterate over
each row in the CSV file. And dict reader can
be used to read CSV files with
different delimeters. Finally, dictreader is
a convenient way to read CSV files into
Python dictionaries, making it easy to
manipulate and analyze the data using Python's
built in dictionary methods. You have a CSV file, you have a lot of information. You use the dict reader to
set it into dictionaries. And then you analyze
and manipulate that data using the
built in methods. Without any further ado, let's go back into our code
and let's start coding. First of all, in
here, I will create a new Python file that I
will call the dict read, or let's just make the
R capitalized CSV file. Hit Enter, and let's close
all other tabs in here. First of all, import CSV. As always, we always say
that it works on CSV, but this could work on
other files as well. File name equal people's list, CSV with open file
name, new line. And then as people file and we'll create
the reader equals Csv, Reader, reader and
people's file. Now when we try to,
first we'll do four line in reader print line, right click run.
And there we go. Notice how the output
is in the form of a dictionary that
we learned before. Now we're going to
apply all of this to our people's text file and
make a dictionary out of it. The keys are going to
be the people's name, and the values are going to be the dictionaries from the read. Now before we do that, I want to also take you to parsing people, if you remember this file or
project that we worked on. So in here we did
basically the same. What we did is we
parsed the file and created a
dictionary ourselves. To help us look through it, we use two keys, the name of the person and
the ID of that person, which we can then use down
here to access their salary. So now we're going to do the same thing
that we did in here, but in a few or a
much less few lines. How do you say it?
In a lines file? Let's create a new Python file. I'm going to call it dict, Read underscore people. Underscore xt. In here I will import CSV. I will create the
people file name equal to people list of the XT equal to not parsing people equal to
just an empty dictionary. Now I'm going to
issue you a bit of a, your challenge is to use the, did open the file, use the dictreader in the file. What is missing in here, Add a second argument
to the dicta function, which should be the liter
is obviously the pipeline. No need to create or use
the sniffer in here. We can just use the
lime to do this fast. The main focus of this
video is going to be the dict for now. Do the following challenge,
okay, welcome back. Very simple, with
open file name, come on new line. Obviously as people
underscore file and then the dic underscore
reader is equal to Sv dictreader, then
people's file. Let's just try this. With nothing, I'll say
four line in dictreader. Print line. Let's see what we get when
I write, click and I run. This is the output
as you can see. We have all of the headers being the keys and then the values are all of
these things mushed up, so we need to use the limiter
is equal to the pipeline. When we do this, we should see something a
little bit different. So we have the ID
one named John Doe. Department sales salary, 5,000
job title sales manager. Look how nice this is. Now we have separated
these into dictionaries. Dictionaries have
been created with the keys being the headers
and the numbers or the values being each
individual person with their corresponding
ID, salary. You know what I mean?
Before we move on, there's something we need to do. We want to start writing to
our files using dict, right? To do this, we need to have a dictionary to
write to that file. Let's go ahead and
create our current code. I'm going to create
a new Python file which is going to
be called creating, underscore, underscore
four, Underscore writing. You're going to see that
this is going to be special. Honestly, I'm tired.
I'm just going to copy this and put it in here. This one is going to
be the People's CSV. For the CSV, also, we're going to have
People's Dictionary. Actually, I'm going to have this exact same
thing except four. I will have four line in
the underscore reader, I will print out the line, but I will also
do the following. Say that we have people line name case fold is equal to line, duplicate this and then the ID. What are we doing in here? Right click. And then I run. What do we have in here
that case fold name. Wait, the limit. The read, okay. The limit in here is no
longer the pipeline. Let's try to remove the
limit. What do we get? All right, looks good to create the print and
then print out the people. Let's see what we get. Right click and okay, something is not wrong. Built in method case full
to STR, something is wrong. I mean, now we do
have this dictionary, but it's not associating
with the name. Excuse me, I apologize. Yes, there we go. So as
you can see now we've parsed this data and look
how many lines it took us. Look at the difference between this 16 lines with extra spaces. We could even reduce that. Look at parsing people, look how many lines it
took us to do this. And look at how many
lines it took us to do this using the dict read. So you can see
that we have a lot of advantages when
using dict read, but we haven't finished here. The next thing is to actually
start writing to set file. First of all, we need to
understand that we can actually open multiple
files at the same time. In here, I'm going to open another file that we're
going to be writing to. This is going to be the
people underscore list. Underscore dict. Now this is a dot py file, and why are we doing that? At the end, it's going
to make so much sense. This is going to be the
output underscore file. First of all, we
need to import CSV into our new dot py file, right? I'm going to print
out import CSV file, file equals output file
we're writing at the top. Let me show you.
Right click and run. Let's look at the output, sorry, is that the
people's list? Dictionary. People list, dictionary, list. There we go. Import CSV. Look, we are writing code
without writing actual code. Next, we're going to
print out file equals. Output file. Now what do you think this does? Very interesting. This actually creates an empty line of space. The next thing we'll do is
we'll print out the following, people underscore
table is equal to. We open up the
parentheses output file, right click run, and look at what we get in here in the
people's list dictionary. Next we're going to actually
start writing things. And side, first of all, we
need to determine the order of the headers that we have
at the top right here, maybe just below the file name. I will say that the order
underscore headers is equal to name ID, job title, come, and salary. Now I'm going to
create a pattern. Now you might be very
surprised at this pattern, but once I use it, it will also make
sense zero through nine star back
zero through nine. Basically, I'm going to
add a comment in here, this will help us identify when we
have a float number. Look at this, it
says zero through 90 through nine with
a.in the middle, or it might not have a dot. This is the pattern that
will help us identify if we have a float
number, for example. And we will be able to
convert it then into an actual float instead
of having strings. Now that we have that, next
we need to do the following. After we do reader equals V dot read four line in
the dict reader, we will not be
printing the lines. Let's just remove these for now. The first thing we'll
do is we'll create a new underscored dictin here. This is going to be just
a temporary variable. Then we'll say four
key in order headers, value equal to line at that key, we're getting the value, we're checking if the
value is numeric. It's not allowing me to use the method on it
because it's not sure if the value can
even use the Is numeric, but the numeric should be there. If the value is numeric, we'll say value is equal to value LF bull. And I'll tell you this
is going to look crazy. But R E match pattern come a value value
equals float value. Let me just finish off
and we will come back. Newt at the key case
fold is equal to value. Then at the end we will print. Now we're printing
to the output file. We are open this up, the back, the new dict, come on file, output file. And then at the end,
once we're done, let me remove these,
we don't need them. We will print out the
closing brackets. File, output file, and then
just an empty line of space. Let's write the click
if we have any issues. The file, output file, IO operation closed
up. I apologize. These two lines
should be at the end. This is a very bad
mistake on my part. Right click. There we go. If we look at the People's
List dictionary, look at that. Look at what we've created. Now obviously there's
still an issue in here. We need to add them. Because remember, this is where the new dictionaries are being written into the output file. Now if I write click
and run again, we should have all of
these look at that. The ID is an integer and
the salary is a flawed. Let's go through
this from the top to understand everything
that is happening. First of all, we're opening the first file which
is import file name, sorry, it's the
People's list, CSV. We're importing the
CSV file and we want to go into the people's
table dictionary here. And you'll see in the
next video we're going to be using this a lot
with the dict writer. The next thing we're doing is we have this order
of headers, correct? So we have the name ID,
job title, and salary. We are going to be using these later on to create these lists. Right here we have
the pattern as well. This pattern, as I said, will help us identify
float numbers. And we've actually used it
right here in this lip. We'll get this lip. We
opened the first file. We open the second file, which we're going
to be writing to, which is the people's
list dictionary dot py. This is a py file. We print out, import CSV into the people's list
dictionary right here. We write a small line of code
or an empty line of space, which is right here. And then we print out people
table with an open bracket, which is right here. Now we are going to
get the dict reader. Create a dictionary reader. And we're going to go through every single line
that we've read from the people's list CSV to see what we have
on every line. We create a new dictionary, a new empty dictionary. We go through the keys
in our order headers. Right here we use the key, we access the line. Correct. We've seen how line is accessed from
running it previously. If you're still not sure, maybe what we can do
is we can maybe print out the line again,
just so you can see. Okay, so that we have
everything in front of us. Let's say we're
working with John Doe. Okay, we are at this
line, we access the line. This is our line at the key. The key remember is going
through the order headers. First of all, let's
say it's name. We access the name.
What do we have? We have John Doe. We check if John Doe, which is the value is numeric. If it's not, we check a Lyp. Is it a bull in here? The bull just like we
have the integer which converts anything that you
sent to it into an integer. The bull converts
anything that you send into it into a bullion. It returns true or false. To check if the rematch, don't worry about this too much, just know that it allows you to match two things together. Try to apply the pattern at the start of the string to
return a match of the object. We're, if this is not
numeric then what is it? A float, for example. The way we're checking this
is we're seeing if we have a number that goes
0-9 right here, zero to nine, right here, we have this match. If we have somewhere
a floating point, it means that this is a float, which means we want to
convert it to a float. I will add in here,
this is used to check if we have a float
using the pattern. Using the pattern, a
good comment to that. After we do that, we create a new dictionary or we add to the new
dictionary key case, fold value, and then we go
back through this for loop. Again, we get the ID. Now on the ID we have
a numeric string, which means we convert
it into an integer. That's why in here we
have this as an integer. Then we go through, again,
the department sales. It's neither numeric nor
does it match this pattern. It just gets added normally. Then we go to the salary. I mean, the department and the previous words I was saying, now we go to salary, we get the value we go
through. Is it numeric? No, because remember
we have a.in here. So we have some
kind of character. Then we check if it
matches this pattern. It does match this pattern. We convert it into a float, we put it back in the value, and this is what we
get, the salary. And we also have the job title. We forgot to do that right here. Salary, job title. I apologize, and we're not getting
it because job title. Oh, I'm so sorry for this. We already had job title, but for some reason
I saw it at the end. It's being gathered right
here. Sorry for that. As you can see, this
is how it works. I tried to explain it
as best as I could. If you're still unsure, please contact one of the instructors or me so that we can give
you further help. This video has been too long. I think it's like
around 22 minutes. I think it's a very long video. I do recommend that
you watch it again. It's very, very helpful if
you can understand this. I mean, I think the worst thing is this right here, the match. Don't let this throw
you off guard. Make sure that you understand
how we're creating a new dictionary and how we're writing it to
the output file. And after we write all of these, look, we have the backslash D, which creates a tab. Then we close it off and we
add an extra line so that, oh, you know what, maybe
we don't even need the extra line in here because
it's added automatically. Let's see. Yeah, there we go. So that we adhere to the
Papa ladies and gentlemen, thank you so much for watching. We are almost at the end. In the next video, we're going
to be looking at dictrter, which is going to complement this people's list dictionary. Thank you for watching, and I will see you in the next video, which will hopefully be
not as long as this one.
133. 13. Writing in a different way (DictWriter): Welcome back my fellow Python programmers to a
brand new video. And in this one we are
going to be writing in different ways using
the dictwriter. We started with this project
in the previous video. In the previous long video. And in this one
we're going to be continuing what we started. First of all, back in our file that we've just wrote
our dictionary into, dict class is similar to the writer class that we've
seen in the CSV module, but it also allows you to
write data to CSV file directly from a list of dictionaries as we
have right here. Which can be more convenient
when you have data that is already organized
in a dictionary. Let's go ahead and get started. First of all, at the top and here I'm going to
add the fields. The fields that are going to be in that CSV file are going to be the name on the ID, on the job title,
and the salary. They have to be
exactly the same as the key names that we have
in our people's table, In our dictionaries inside
of the people's table. Next we're going to open
up the file that we want to write the data to open. We've already seen
this so many times. People, people data dot CSV to write and new line
empty space as output. Underscore file two dots. We're going to
create the writer, which will be the Svc
writer, requires two things. First of all, it
requires the object file or the output file that we
are going to be writing to. And a list of the field
names or the column headers, if you want to call
them that, that correspond to the keys
in the dictionary. In the list here, we'll have the field names
equal to the fields. Basically what I mean in here. Let me open some ACSV file. It's these fields
right here at the top. We need to provide it
with those as well. That's why we created
a list of fields. Next, we need to access
the writer and write row, write headers or the header. We write the headers first. This method can be used to write the field names to the
first row of the CSV file. And then we are going
to do four row in people's table, two dots, right? Right. If I write
click and I run, I don't get any errors. That's good. Let's look
at the people's data, CSV, People data, CSV. There we go, Look at that. Ladies and gentlemen, we've
created everything in here. Salary, job title, a name, ID, job title, and the salary. There we go, Name ID, job title and the salary
for each and every person. This is one way of doing things. The other way is to use
right rows right here. I'm going to comment
this out and I will do, and I'm going to send
in the people's table. If we click and I run, let's look at what I get. The same output.
I set the names, and then I set every, There
are two ways of writing this. Maybe you want more
focus on each row. Maybe you want to
change some things. You would use the for loop. If you don't, you just want
to send in all of that data, you can just use the right role. Before we move on,
let's say that we wanted to have our names sorted. You might think that
it's as easy as saying sorted in here and then sending in
the people's table, right clicking and running. But you'll see
very fast that you cannot do this because you cannot compare
two dictionaries. You cannot check if one
dictionary is bigger or smaller than
another dictionary. What we need to do is we
need to actually compare the names of the people
that are inside. To do that, we need to create
a function that will do. For us, this is going to be part of your challenge and
we are back to functions. First of all, create
a function that takes a dictionary
as a parameter. Very simple, it should
return a string. These are indications
that you should show the string it returns
is the value in the name. Key access the dictionary, access the key
name and return it as the return object
from that function. Pause the video right now
and go do the challenge. Okay, welcome back. So this should be pretty simple. I don't think it
was hard back then. Where should we do this? I will do it under the import. I will say define
underscore keys. Open this up and I
am expecting act, which should be of
type dictionary and it should return the SDR. These are the
annotations that you should have added in here. You will return the dict
to sort name. There we go. We add an extra space here and an extra space
here. There we go. For example, in here,
if I, for example, want to print out what was named sort keys, Keys. And it's not allowing
me to do this. Let me write, click and do this. Okay. What do we have? The peoples table, for example. People table at the, at one, let's say. Right click, Run up. We're still comparing this. Let's remove the
sorted from here. Try this again. All right. Jane Smith. Because at Jane Smith we simply
return the name. You might think that it
doesn't do anything. But what we can do in
here is the following. We can say that key equal to the sort keys. Very interesting,
but make sure to remove the parentheses from here around the sort keys because we're not
actually calling this. If I write click and then
if I go back to the people, you'll see that I have Bob
because he starts with A B, Chris, with David,
with the Emily, E, H, J, L, K, L, M and P. So they are all sorted just like magic. What
did we do in here? If we hover over the sorted, we can see that we can provide it with something called a key. A custom key function can be supplied to customize
the sort order, and the reverse flag
can be used anyways, the reverse flag is
just to reverse. But what we want to focus on, on this is this line right
here in the documentation. A custom key function
can be supplied. Basically, what we did
in here is we did not call the sorting function
or the sort keys function. We were providing the
name of the function and the sorted will call
it when it is needed. When you pass a function as a parameter to another function, you don't need to
use parentheses after the function name
because you're passing a reference to the function itself and not calling
it. Makes sense. I hope that was understood. Basically, what's
happening is the sorted is trying to sort the people's stable and it only uses the sort keys when needed. It goes, checks the name, comes back, then goes again, checks the name for
the next people, and the next people,
and the next people. Just as an extra thing in here, let's just create
a new Python file, and we'll call this the
function underscore argument, just so we can test it out. So I will define in here the underscore by
underscore length. Let's say we're
providing a word, not going to delve too deep. I simply will return
the length of the word. Then in here I will say, we have a few words. Let's say the words. Let's say apple. Let's just pick fruits, banana, cherry, and the orange, orange. Let's say in here
we want to have the words with an underscore equal to sort the words key, sort by length, okay? And then print sorted words, or actually will call the
sorted words by length. This right here will be
the sorted words by. Letters. And I
will say that it's equal to words. Okay. This will help us understand
what's happening in here. Let's add an extra space. When we do the normal sorting, we sort with the letters. Now, unfortunately,
I made a, let's add. We'd, let's make the apples apples or like the apples
to make it even longer. But now now apples,
banana, apples. How many does it have?
Three and then three. Okay, that's not good. Banana. Okay, cherries, orange. Actually, let's do banana
apple, apple pies. Okay, So apple pies. So now if I write,
click on, look at that. Apple pies is the longest word. Unfortunately, I made a
very bad choice of words. In here, they are
all the same length. Let's maybe remove
the from oranges. And now you'll see that
cherries is at the end. One, right here, we created this function that sorts or
that returns the length. And we use that as a
key to sort the words, not by their letters, notice, and here as a start, B, C, and maybe I should change
the location of these, and this example is off
the top of my head. So that's why I am not 100% sure of the
word that we're using. Okay, What is the problem
in here? There we go. Okay. On the first word, when we use the sorted
without any keys, we are sorting by the letters. When we use the key,
sort by length, we are sorting by the
length of the word. Banana has six. Orange also has six,
but for example, if I make this bananas, you can see that now
orange is at the start. And then we have cherries
and then bananas. Okay? And for example, if I add an extra R in
here, there you go. You can see it's orange
bananas, cherries. The key use in here by
the sort, by length, Remember it's a function, but we're not using
it as a function, we're using it as a parameter. But that's besides the point, the main focus here was
using the right header. But we got, of course, but I still think
it's very important that you these concepts. Thank you so much for
watching. I hope you joined. In the next video, we'll
be looking at how to use the dictwriter
without a dictionary. And maybe we will be adding
more lessons to the section. But I think for now
that is enough. I think your head
is probably about to explode because of
all the information. But trust me, read through
it, understand it. It's very simple, very easy once you use
it once or twice. Thanks so much for watching and I will see you
in the next video.
134. 14. How to use DictWriter without a Dictionary: Welcome back my favorite Python programmers to a
brand new video. And in this one we're
going to be using the dict writer
without a dictionary. So first of all, we're going
to create a new Python file. And the Python file
is going to be the zipping underscore lists bo. The first thing we'll
do is we're going to add this information
into our file. Now, obviously I'm going to
be providing you with this, but just in case
you can't find it, let me know in any form of communication that you can
get to me or the instructor. We could have easily added these CSV files and
just be done with it. But we'll use this opportunity
to transform them into dictionaries first and then
use them in the dict rider. Now how are we going to create the connection
between these two? We have movies,
director and year. It's obvious that
we have a list of couples in here and each
couple contains three items, which are the movie director
and the year it was made in. But how are we going to
create this connection? How are we going to merge
these two together? Well, we have a very
useful object in Python that's called
the zip object. The zip object is a
special collection that is created by the zip
function. Pretty obvious. The zip function takes one or more itterubles and constructs an
iterator of tupples. It creates multiple tupples
out of multiple itterubles. When we say itterbles, it means a list, a topple, or a dictionary, or a range, anything that you
can iterate over. And then it constructs
an iterator of tupples, meaning that you can iterate
over multiple tuples. And we'll see what
that means when we take a few examples where each tuple contains element
elements from each itteruble. We said that we had
two itterubles. These two itterubles are joined together to create
iterator of tupples. And then this topple, or each tupple in that
iterator contains elements from each of
these two iterators. You're probably
like, whoa, whoa. What the hell is even
happening now? Don't worry. Once you see a few examples, it should become more obvious. The length of the zip object is the length of the
shortest itterble. Because remember, we are constructing a third topple
out of two itterbles. The shortest one will be
the length of set topple. And finally, the
zip object can be useful for tasks like iterating over multiple lists simultaneously
pairing related data, like an hour example, or transposing data also
like an hour example. So without any further ado, let's go back into our
code and let's try zipping our two lists in here. I'm going to say
four row in movies. I'm going through
every single movie. I'm going to create the
zip underscore object and I'll say that
it's equal to zip keys row and if I truck keys
to print out the zip object. When I write click and I
run look at what I get, I just get a zip object, It's a reference to
said zip object. It's not like actually
printing out something useful. In order to see
something useful, I'm actually going to just remove this because
we don't need it. I just wanted to show you that it's the type of zip object. I'm going to instead do a
four items in the zip object, print out the items. And let's just add a print in here just so we can separate
these from each other. When I write, click and I run, this is what I get. I have movie the Godfather, Director Francis
Ford Copolayear, 1972 movie, Pulp Fiction
director Quentin Taro year 1994. Does this format remind
you of anything? Doesn't it look like
a key value pair? Basically, what's happening
in here is we're taking the keys which are movie,
director and year. So this is our first it, remember we said we
had two itterbles. Then we are pairing it with another itterble,
which is the row. And the row is changing
for each movie, we pair movie with the
Godfather Director, with Francis Ford Pla. And here with 1972. We go through this, we print out the items,
boom, boom, boom. And this is why I told you
that the zip object is an iterator of tupples because
you can iterate over it, and at each iteration, you get a topple. That's why it's an
iterator of topples. That's also why the length Where is it? The length of the zip object is the length
of the shortest itterbal. Because if we had in here, for example, something else like for example, I don't know, actor right click and run, You'll see that the
output is the same because there's no
fourth element in here. There's nothing
to join the actor with one of the elements
inside of the stopple, we just take the shortest one, that's why it's the shortest. Now that you've understood how the zip object
combines these two, how are we going to use
this to our advantage? They do look like
key value pairs, but how do we actually make
them into key value pairs? Well, we've seen this before. What we can basically do, let's comment this out for now. Basically, what we
can do in here is we can say movies underscore dict equal to dict zip object. We convert the zip objects
into dictionaries and if I print out the movies
dict at every iteration, we should get the following. Look at that. Now we
have a conversion. We have literal key value pairs with the director and
the year and the movie name. Now that we have
our dictionaries, it's time to use the dictwriter. When I say it's time to
use the dict writer, I mean it's time for you to do a challenge to
write dict writer. First of all, we need to
obviously import the CSV module, open the file, we want to write two with the correct mode. You can name the file
whatever you want. Create the writer object
using the dict writer, write the headers, don't
forget the headers. And then add the
code we did earlier inside the with block of code. When I say when we say
with open et cetera, the code that I'm talking about is the code
that we just created here. This code, this should
be inside of the width. It should be pretty obvious. But just in case, right, the dictionaries created to the CSV file with the right row. Pass the video right now
and go to the challenge. Welcome back. How did
you get on with that? First of all, as we said, we need to import CSV. Great. The next thing we need to do is we need to
create the file name. In here we'll have the file
name equal to movies zip sv. Next, we need to open the
file with open file name, that is the correct
mode and the new line, nothing as the movies underscore CSV or movies
zipped underscore CSV, that's a very long name,
that's very unnecessary. I'm going to make
this a bit smaller, push this to the front and we'll say that the
writer is equal to Sv dict writer and we
are going to be writing to the movies zipped
underscore CSV with the field names
being equal to the keys. We've already seen this before. Then with the writer
right headers, we will go four row in
movies, et cetera, et cetera. And then what do
we do at the end after we print out the
movies dictionary? We don't even need to do that. We'll say that the writer right row the movie
dictionary. There we go. When we run this,
we should see that a new file was created
right here in the project, which was the movie zipped. If we open it up,
look at what we get. Nice. The headers are in place. Movie director, year,
the movies are in place. Everything looks good. Ladies and gentlemen,
thank you so much for making it this
far in the videos. Thank you so much for
making it this far. And of course you are part of the two M Python master class. I mean, if you've
gotten to this point, you basically have more
knowledge in Python than 99.7% of the human
population on Earth. And I congratulate you already
with your amazing skills. You can start applying to jobs, you can start looking
for deeper information. But I think that you still need the extra information that is going to be coming
up in the next section, which is Database SQL. It's very important. This is probably the last video. I might update this later on
to make it more extensive, but for now, this is the end. Thank you so much for watching. I appreciate you being here. If you can leave me a
review anywhere, please do. Let me know what you
think and I will see you in the next
section or video.
135. Section 10: Using Database in Python | : Welcome back my fellow Python programmers to a
brand new video. And in this one, oh, and a brand new section. Of course, in this one or in this section we're
going to be looking at using databases and
Python and SQL language. So this video is going
to be database 11, where we will just be
understanding some terminology, what database is, how it
works, what can we do. And then we will
install SQL Lite three. We'll also explain what SQL
Lite Three is going to be. We will set things up and
just make sure that we can confirm or continue
on from there. First of all, what is database? A database is a structured
collection of data. We've already seen a lot of
structured collection of datas like couples lists,
dictionaries, and sets. All of these are also
structured collections of data. But database comes
in handy when we start having huge
amounts of data. It is organized and stored for easy retrieval, manipulation,
and management. So just like we have with
list stupples, et cetera, et cetera, we also have the
same idea behind databases. If we have a lot of data like e mails, names,
locations, whatever, we want to set them in
a structured manner so that we can then later
retrieve them when needed, change them up, manipulate
them and manage them, make sure that they
are well organized. It's designed to efficiently, efficiently store and manage
large volumes of data. Store and manage is
the key word here. Large volumes of data
is also very important. You get to a certain
point where saving the data to a list is
not feasible anymore. Setting it up in, I don't know, maybe Json file is
not feasible enough. You need a database, you have millions and
millions of people. You have thousands of gigabytes
that you need to save. Files are no longer good, You require database
allows users to store, retrieve, update, and
delete information. Databases are widely used in various applications
such as website, enterprise systems, mobile
apps, and many more. For example, when
you're using Facebook, when you're using Instagram, when you're using Google, when you're using any website, any website that
you can think of, any application that
you open that you can think of uses a database. Database is super,
super important. This is one of the
advanced sections. But if you want to
go into any career, almost any, if you're looking
to become a data analyst, data scientist, if you're looking to do machine
learning in Python, database SQL is important,
super important. Let's take an example of a database so we
can see what it is. To be fair with you, a database is just a very glorified table. Of course, there are many
more intricacies to it. It's a collection of very advanced and well
organized tables. But if you look at it,
it's just a table. First of all, it's the table. It's the collection
or a collection of related data organized
in rows and columns. Then we have the fields. A field is a single piece
of data within that table. Sometimes it's referred
to as an attribute, sometimes it's referred
to as a data value. You'll find a lot of different nomoclatureor terminologies
for these things. Just try to follow the ones
that I provide you with. Maybe if you go looking
around on the Internet, you'll find different
terminologies. For now, I would follow these. Next we have the columns. So as you can see, it's a vertical arrangement of
fields within a table. So for example, the customer IDs are all arranged in a column. The last name, last names are
all arranged in a column. The phone numbers,
the countries, and then finally
we have the row. So it's a horizontal arrangement
of data within a table, also known as a
record or a couple. You'll see both of
these words used. We're going to be
referring to them as rows as often as possible. This is an example
of a database, It's just a glorified table. You'll see there will be more intricacies to this later on. What is SQL and what is SQL? Light SQL stands for
Structured Query Language. It provides a set of
commands and syntaxes to interact with databases
and perform operations. Just like you have
Python language, which allows you to interact with the processor
of your computer, which you send it some commands. In English, it
returns some output. The same is true with the SQL. It's a language that allows
you to talk to databases. These operations are selecting, inserting, updating,
and deleting data. We will be looking at all
of the operations in SQL. Query is the request for data or information
from a database. Maybe the only weird
word here was query. The query is the request for data or for information
from the database. Now what is SQL light? It's a lightweight
version of SQL which is server less and self contained. When you're working
with databases, you're usually
working with servers. Servers are just, you can
imagine them as a big, had a huge hard hard drive with millions of gigabytes that are available to you where
you save information. When you're working
with Facebook or any website or application
that you're working on, it's usually you as the client
or as the user contacting the server through SQL language and retrieving data from there. Now what we want to do is
we want to use SQ alight, which is server list, because we don't want to
go through the hassle of getting servers and trying
to test things out on there. We'll do it server
list using SQ alight, meaning on our computer, so the databases
will not be saved to some server on the
outside of our computer. It will be on your desktop
or your PC or whatever, and we'll do it using SQ alight. Don't worry. The same
commands hold true. It supports the
full SQL language, so when we work on SQ alight, it's the same as working
with SQL language. It's used in applications that require local database like us. Or for example, if you have
a small application that saves some file on the
user's cell phone, then SQ Alt is the way to go. Without any further ado, let's go ahead and get started. The first thing we
need to do is we need to go to this
website right here, which is Sqlite.org in here. Just go to the
downloads, of course. I will be providing you with the link once you go
to the downloads. And here you need to
pick either the Linux, if you're using a Linux, the Macos, or Windows, you need to select this. A bundle of command
line tools for managing SQL database,
et cetera, et cetera. Either this one or this one, or this one right here. Select one of these.
Download the file. As you can see, it's
a very small file. Now, it's very important
that you do the following. You take the directory, you take the file
and you need to put it in one of the directories, meaning either the D
or or somewhere else. And it needs to look
exactly like this. Look at this SQL tools, Do whatever the name
of your file is. It doesn't have to
have the same name. As long as when you open it, you have these three
folders inside. This is very crucial to follow. You have these three folders. It's in the local
disc D directory. You can see the
folder right here. When we double click
on the folder, we have to see these
three folders inside. Okay? Clear on that. Good. Once you have this, the next
step is also very crucial. First of all, I want you
to go to control panel. When you open it, I want you to go to
system and security. Now maybe yours is
a bit different. I will set the steps
somewhere below the video. If you forgot the steps
or you can't follow them, please contact me or your instructor and
they will help you. Once we have the system
and security in here, we need to go to
system from system, you need to go to
Advanced System Settings. It should be around,
maybe your version of Windows is older or newer. Go to Advanced System Settings. Once this is opened right here, I want you to go to
environment variables. Now we have two things to do. We can either or one
of the two options. You'll see right here, we
have user variables for ish. Now ish is the name
of my Windows. Unfortunately, when I bought this laptop and I
changed the names, I didn't set it correctly. Now, I'm stuck with this
curse, but that's okay. No problem. You should
find the path here. If you don't have the
path, you need to create a new use variable. When you click on the path, you need to go to Edit. Inside of the edit, you'll
see many options in here, but one of them should
be this right here. This is the path
of the folder that we just set up in the directory. If you don't know
what the path is, go back into your
directory, open this file, select any of these
three folders, right click property
and copy the location. Copy it, control C, You don't want to type it out. Just copy it out, right? Control C, Go back in here, add a new right here, and just paste it. Okay. And that should be good. I will cancel because
I don't need to do this just in case
because I've had some students that don't
have the step work for them. You can also go into
the system variables, go into path, go into edit, and add it right here. Please do not delete
anything from this. Don't delete anything
from this part either. Keep it exactly as it is
and just add the SQL tools. And you should be
good to go if you follow the steps correctly. The most important part is
making sure that this folder right here is the exact
same scale light tools, not as mine as yours. When you extract the
folder and everything, when you open the folder, you should see these
three folders or files, or applications wherever you
should see them in here. Then when you go
to control panel, system and security system
advanced system settings, environmental
variables right here. Copy the path. Where is it? Right here. Use variables, path, edit, or new. If you don't have one edit, send in the path of the
folder of the applications. If that doesn't work, you can also add it to
the path right here. But I don't think
it's necessary. For example, on my side, it was not necessary. On one of my students, it was necessary, test it out, see what works.
Hopefully it does. And if you don't find it, contact one of your
local instructors, of course, from two empt on De. Now, with that out of the way, we want to test out
our SQL connection. So it's going to be
a challenge for you. Open the command prompt. If you don't know what the
command prompt is right here, type in command
prompt book and you should see the following with your PC name instead of mine. Type in Q three, it's right here, just
as it is right here. It should have a version
displayed, type Inq. Now we are ready to work. Posit the video right now
and go do the challenge. Okay, welcome back. How did you get on
with that in here? Ask lid three, hit enter, and you should see
something similar to this. You don't, if it's
telling you there's something missing or
this is not available, go back, do the steps again. And if you still can't
figure it out, contact me. Contact the instructor
that's assigned to you and that is it. Thanks so much for watching. I hope you enjoyed it. I hope you're ready for this journey. Sql database is very easy
when you go through it step by step and understand everything that is
happening. Don't be afraid. Even though this might
seem as a new language, it's fairly, fairly easy. If you've done all the
sections in Python so far, this should be a cake
walk or a piece of cake? Or a cake walk. Do
they say cake walk? I'm not sure. But anyways, thanks so much for watching. By the way, we'll be working
in the command prompt for the next couple of videos until we learn and comprehend
SQL correctly, then we will move on to using
the Intelligent and Python. Okay, thanks so
much for watching. I will see you in
the next video.
136. 2. SQLite 101 : Welcome back my favorite python programmers to a
brand new video. And this one will
be delving into Skylite 11 or Esculte three or whatever
you want to call it. First of all, as
we've seen before, we need to open skylite three. But this time we actually
want to create a database. I'm going to type in
light three space test B and a Sem column. Hit enter and you'll see that testdb was indeed
created or opened. Sometimes it's opened. Now if we go right here, let me show you where
this is actually created. So if you go to see users and
then the name of whatever, you'll see that the Testdb or Testdb was
created right here. As you can see, I have this one. What I'll do actually, is I'm going to
delete it because this was from previous students. I will delete this.
Okay? It's not allowing me because
the file is in use. Very nice. What I'll
do in here is I'll do quit and this is going
to be very important. That's why I will
keep it in the video. I will delete this one as well as you can see now I can do esculte three space
test B semicolon, hit enter, and we
shall see that. Let's go back. Where is it? Why hasn't it been created? Where is my database? It should appear. Okay. It's not
appearing, It's okay. We will look at it later on. For now, let's start
with escult three. First of all, let's do the help. Help shows us a lot
of useful information that we can or we will
actually be using later on. Some of the useful
information we've already used like the Quit for example, which stops interpreting
input streams and exits. If whatever the recovery
is going to be important, the restore the
schema or schema. In French, we pronounce
it schema, schema. You will find also
something very important, the header. Where is it? The headers will be in use? Those are a few things. First of all, in here, I will do the headers space on which will turn on any headers
that we have in the table. Now it's actually time
to create the table. I'm going to create
table contacts. And the table name is
going to be contacts. And inside I will have the
name which is of type text, the phone which is
of type integer, then the e mail which is
going to be of type text. Whenever we do a line
or command language, we have to finish
with a semicolon. When we hit Enter, the table is indeed created. Now maybe we'll see the
test DB. There we go. I think it was, oh, by the way, I apologize. We didn't have to
use a semicolon. Right here, right here when
we're doing the SQL three. When we're doing SQL commands
like table contacts, we need to add a semicolon
when we're doing just prompt commands like
the Sqlite three test B, we don't need to
use a semicolon. It's just a force of habit. Like for example in here
on the dot headers on, we didn't need to do a
semicolon, I apologize, it was a force of habit, but it's good seeing like you, seeing the mistakes
that I make from time to time is very important. But anyways, and here we've created a table in our database. Now you'll be like, okay, where is this table? Well, if we look right
here in our Helps, maybe we could find
something useful like for example dot ABC, RST do tables nine. So list names of tables
matching like pattern. Don't worry, let's just do
tables and there we go. It gives us all of
the tables that we have and one of
them is contacts. Very nice. Now let's try to insert some information
into the table. I'm going to type in
Insert into contacts, into the name, into the phone, and into the e mail. And I'm going to say that
the values are going to be, and we don't need
to add a space, but we'll add it anyway. And by the way, make sure you understand how dis cursor works. The name will be Michael. It should be in between
single quotation marks. The number is going to be 1,589.365 And I just
made it up, by the way. Please don't call this number, then the E mail is going
to be contact at two M. Python dev.com Very nice. When we don't hit Enter. Oh, actually let me show
you what happens if we hit Enter on a command
that is not complete. Look at that. It
opens a second line. It doesn't execute
when it executes. You'll see it right
here. You'll see it just prints out as a light. But it did not finish executing. So we can add this extra
semiclumnow executes, all of these follow. So what did we do in here? We insert it into. So these are the
commands insert Into. Into, into contacts. What do we want to insert? The name, the phone,
and the e mail. What are the values,
Michael, this number, and contact at 02:00 A.M.
Pythondev.com As you can see, the only issue in here is
that if we did get an error, it does not show
us how to fix it. But this is why we're using. The command prompt is
going to help us increase our SQL skills substantially from just using the
normal IDE for this. Because either way, there are very few ID's and
languages that really give you any hints of how SQL works or where
the exact error is. Getting to know SQL through the command prompt
with almost no help, is going to be very
helpful for us. Now, by the way, I
might have lied. You can actually use
the double quotations. Let's say I want to insert another value instead of selecting all of
this and copying it, which I'm not even sure works. And if you hit control C, you have to right click
in order to paste it. The control V works as well. But that's besides the
point, let me remove it. There is an easier
way of doing this. So let's say you want to go into a previous command that you had. You can use the arrow keys. So if I hit up, look at that. I get into the
command key that I had used and now I
can add a semicolon. Let's try the double quotation
marks around contact. And Michael, let me change this actually
changes to Steve. Sure, Steve, let's change the number and we'll change
their E mail to Steve. At Steve.com There we go. No such column as.
Okay, there we go. That's I think only using
a single quotation marks. Let's test it out. There we go. Exactly. So it is very nice
we're exploring together. We're testing out
things together. It's very important we've inserted another
piece of information. Now how can we display
this information? Well, we can type
in the following. Select star from contacts. Star means that we are
selecting everything. If I hit Enter, look at that. We have the headers if we
haven't typed in the head, if you didn't do it, you'll notice that you don't
have the headers. But because we typed
in headers on, we have the headers and
these are our information. You'll see that
they're separated by this delimeter which is
the pipeline character. Now as you can see, we've inserted this information, but this is not really how
we write SQL language. Some people write SQL this way. But this is not the
conventional way. The more conventional
way is setting the actual SQL
commands as capital. For example, select
star from contacts. The QL commands here are the select and from the insert into. These are the things that
don't change and the values, these are the words, the commands that don't change. These are the actual L
commands, they don't change. But for example, the
name of the table could change the name of the values
that we want to insert. Could change these stay
in the lower case. Like for example, contacts. Because we are from
the contact table, we might want to change
this to another table. Now, what is the star in here? The star means we are
selecting everything. The name, the phone, the e mail, and everything
that's available to us. But what if, for example, we just wanted to
select the names, Then we would select name. Name. Because keep in mind it's the same word
that it's right here. So if we type in names, for example, it will not work. Select name from contacts. Hit Enter, and look at that, we just get the name. Very nice. Now, let's
go back into inserting. I will use the arrow
up key in here. Actually, we should
start changing. If you know what, let's just delete all of
this. We don't want it. We will start from
scratch because we will use insert into, what are we inserting
into the contacts table. And now usually in here
we should do name, phone, e mail, and then
provide the values. But if you have all
the values in place, for example values, I can
now provide it with kalen. The number is 123-45-6789
and we'll see that it's Kalen at
kalen.com semiclumn. Insert into values are the actual SQL
language key commands. I mean, then you have the contacts table and
so on and so forth. So that's why we have them in upper cases and lower cases. Notice in here because
we've provided the name, the phone, and the e mail, or all correctly, we
don't need to tell it to which fields we want to be added or to which roles we
want these to be added. It will be added automatically
to the appropriate roles. Now if we hit Enter, you can see that it worked because we don't
have an extra line. We just have scar line command without any errors or warnings. Now if I hit the arrow, keys select and we'll do star from contacts.
Look at that. We've inserted kalen
into our database. Okay. Now the issue in here is what would happen if we tried
to insert into contacts? Let's now try to do, Bob, let's say for some reason
we just forget the e mail. Forget the number. Just forget the number by
mistake. Hit Enter. Oh, there is an error
parse error table. Contacts has three columns, but two values were supplied. So how do we fix this issue? Well, we provide you
with a challenge. Add the contact anyway, find a way to add the
person into the database. Anyway, I will give you
a hint if you want, you can go search
for this yourself. This is a great journey
to start on your own. But the hints are specify which
attributes you're adding, similar to what we did before. And when I say what
we did before, I mean right here. So for example, you are providing
the name and the e mail specified that you are providing
the name and the e mail. So pass the video right now
and go do the challenge. Welcome back in here we're
trying to provide, Bob. So if we go up right here, you can see that
we're only providing the name and the e mail. So I will say name, come on e mail book and now
select star from contacts. There we go, you can see that
Bob does not have a number, and he's also in the lower case, which doesn't look good. But we will see in the next
video how we can update, delete, and also
use the War in SQL. Ladies and gentlemen, thank
you so much for watching. I hope you enjoyed. Some
of you might be scared, some of you might be excited. But please don't worry. That is the most
important thing. We will go through
these step by step. If you're not sure what we did
right now, please go back. Understand every single
small detail that we did. These are going to
become very trivial, very easy as we progress
through the section. And I will see you in the
next video. Bye bye for now.
137. 3. UPDATE, DELETE and WHERE: Welcome back my fellow Python programmers to a
brand new video. In this one, we're going to
be looking at update, delete, and where, meaning more
SQL using SQL light. First of all, we're
going to quit. When we quit, we simply
close down the database. Let's go ahead and clear all of these lines so we
can type in CLS. If you're using a Mac, I think you can type in Clear. Hit Enter and it should
be cleared again. Let's open up Sqlite
three, test B semicolumn. Unfortunately, I've
called it like that. I have to type it in
again to open it again. If you've called
it something else, then please do type
in something else. Next we're going to hit Select Star from
contact semicolon. Hit Enter. There we go. These
are all of our contacts. Next we're going to
insert into contact. Then values. And the values are going to be, James must have an upper case, the number should
be, there we go. And then we will have
James at.com And I'm using James.com and
everyone by their name or the website with their name on it because I don't
want to sponsor anyone. And we have a problem.
Because look at that, this is a very good issue
that we just encountered. No such table as contact, because the table is
contact with an S. So there we go. It's very crucial
that you always have everything set up correctly. The next thing we want
to do is we want to create a backup
for our database, because now we're going to start deleting and adding things. So we want to make sure that
we always have a backup for our database just in case
we mess things up in here. It's very simple, just hit
back up and then call this the test underscore
backup. Boom. Hit enter. Now, if we go back in here, as you can see we have
test underscore backup, which is our backup. Also something very
important that we just glanced over right here. When we selected
star from contacts, we did not get the headers. Why is that? Because we started where we opened the
database from scratch. We need to say headers on, and then select
star from contacts. There we go. Next I want to
update one of our e mails. Let's say Kalen
got a new e mail, I want to update it. I'm going to do
update contact set. These are the important
keywords, update and set. Email equals underscore kal calen.com and then semicolon. Hit Enter, select
star from contact. Oh my God. Oh no. Oh, no. Look at
what just happened. We just changed all the e mails of all of the
contacts that we had. That is a huge problem. We've destroyed our database. Somebody trusted us with this database and
we destroyed it. But thankfully, we did something very important that
Michael told us about, which is to back up and how
do we restore our backup. We restore test. Underscore back up. Boom. Select star from contacts. That's good. We
were almost fired from our job, but thankfully, we were able to watch Michael's course and now we are no longer fired. Very good. Next thing we need
to actually update only where we have Kalen.
How do we do that? Well, we do the update again, but now we don't stop here. We actually where
name is equal to Ken. And keep in mind
it's case sensitive. Now if we enter and we
select Star, there we go. You can see that only Kalen
had their E mail updated to new Kalen at Kalen.com There we go.
This is the update. Now it's time for a
bit of a challenge. And your challenge is going
to select only Steve. I want you to select
from contexts where name is equal to
Steve Google It, and try to find the solution. Otherwise, here's a
hint, if you want, you can positive
video right now, go do the search on yourself. Or maybe you already
know the solution without any Google search. But the hint is to use
where name equals Steve. Select from contexts where
name is equal to Steve. Positive video right now
and go to the challenge. Okay, welcome back. How did you get on with that? In here I'm going to select Star because I want to
get everything from texts where the name is equal
to Steve and Sem Nicolo. Now if I hit Enter,
boom, there we go. That I only get Steve and
not everyone else in here. We could do something
else, for example, we can not star. But let's say I want to
select only the phone and the E mail from contacts where
name is equal to Michael. All right, this is
Michael's number and that's his contact e mail. We can also use delete
and we should also be super careful when doing this
because like the update, we can potentially delete
everything in here. When we want to delete, I can say delete from contacts where name
is equal to Bob. Because if you remember, Bob
doesn't look really good. They're missing an E mail, the written in the lower case. We want to get rid of that data. Hit Enter and now select
Star from Contacts. There we go. We don't
have Bob anymore. Keep in mind if you do
delete from contacts, you'll keep that in mind. And by the way, something
that we did not mention or maybe something you might
not be clear to you. When we do delete from contacts where name or when we do select
from contacts were name, we don't just have
to provide the name. We can say for example where number or when where
foam is equal to. Let's say let's delete James. I will just copy James number. James number and then click. Did that work? Nope, it did not. Let me try this again. Control C, will it work?
Right, There we go. Boom. Select Star from contacts. And there we go, you
can see that James was deleted isn't just
with the name, it could be used with
any of our headers. Right here. Right here. Okay. So before we leave, one more thing I want to do
is I want to try and insert. Let me just find it.
Insert into contacts. James, I want to try to insert. Instead of a number, I want to try to add a number
in the form of a string. Because I want to
do this plus 15. Obviously this is not an
integer because we have pluses. But remember, we said that we wanted the phone
to be an integer. So let's see what would happen
if we do the following. If I had Enter, it works. We added it even though
it's not an integer, it's say string, and it worked. If we try to select
star from contacts, look at that, we actually
have the number. Now on the surface, you might look and be like, okay, this is no problem. But if you start working and interacting with
this database more and more, this can cause huge problems. We need to always make sure
that we add things properly. We don't want to have
issues like these. If we said that the
phone is an integer, it should stay an integer. And you need to
make sure through your user interface
that this is the case. So I'm going to delete
from contacts where phone, where name is James, because this is not good. Bye bye James. Select
star from contacts. All right. This is
the basics of it. The last thing I want to do
is I want to go over a few, a few commands that
we can do in the SQL. For example, tables. This command displays all of the tables that we have
in our current database, we have the schema. This is a very important one because this command is used to display the schema or
of a specified table, or all the tables
in the database. The schema represents the
structure of the table, including the columns names, da, data types,
constraints and indexes. For example, if you're trying to select only a few columns, but you don't know what D's are, you can use the schema to find out how the table
was created and what values or what headers you can insert into or what
roles you can insert into. The other thing
is the dump them. This command is used to
generate a text file containing the SQL statements that can recreate a database
scheme from scratch. It outputs all the SQL commands necessary to recreate the
database and its contents. For example, first of all, we ignore these for now. Later on we will explain
them in more depth. But for now, look
at the Create table and the insert values so that we can recreate
this exact database. Notice that we didn't
provide or the dot did not provide us
with the deletes and the updates and
so on and so forth. It's just if you
want to recreate your current SQL
database as it is, you can use this text file. And notice at the
end we have commit, something to keep in
mind for later on when we start working in Python. And finally, we have the exit which is similar to the Quit. This command is simply
used to quit out of the SQL light command
line interface. Ladies and gentlemen, thank you so much for watching.
I hope you enjoyed. I hope you're not too confused. In the next video,
we're going to be looking at database
administration, where we will be querying
data with our SQL light. And we'll be using a much more extensive database
that I will of course, provide you with
in the resources. So thank you so
much for watching. I hope you enjoyed
leave me a review anywhere that you can contact me if you ever have
any questions. And I will see you in the
next video. By by far now.
138. 4. Database Administration: Welcome back my favorite Python programmers to a
brand new video. And this one will
be actually going through an actual database
that I've provided you with. Below this video, there
will be a link or a button or something where you
can download movies B, which is a database of movies. The first thing we want to do is we want to right click on our desktop and
create a new folder, and we'll call it the
movie Database, okay? And we're going
to put the movies into the movies database. So we have something
like this from here. I want you to right click and I want you
to go to properties, and I want you to copy this exact location as it
is control C. And hit okay. And now back in the
command prompt, I'm going to do CLS to clear everything and I'm
going to do CD. And then right
click to pass this. And when I hit Enter,
look at what we open now. We're no longer in C, users ish or whatever the
name of your computer is. We are now in the
users is desktop and the movie database that we just created because now we
want to open the movies B. If we don't specify where
this movie dob file is, it will not be able to
find it on its own. In here I will type in
Sqlite three and then movies B and hit
Enter and we are on. Let's go ahead and
first of all set the headers on headers on Enter. Now how do we know
what tables we have? Tables, boom. Hit Enter, we have three tables, we have
actors, genres, and movies. Let's go ahead and let's
go ahead and actually select star from the movies. Let's select everything in
the movies. And there we go. As you can see,
we have the Shaw, Shank Redemption, Godfather,
Dark Night, Pulp Fiction. And in total, we have ten very nice movies
that I've selected. So you'll notice
that first of all, we have the movie ID, and then the title, and
so on and so forth. Now I have a bit of
a challenge for you, and your challenge is
to show me the headers. Now, sometimes I forget
what the challenges are. So one of the challenges
was to turn the headers on. This was an easy one, but now I want you to select
from the movie table, the movie title that has
a movie ID of three. Now keep in mind what
did I ask in here? I want you to select
from the movies, the movie title that has the movie de of three
on the movie title. I don't want everything on the movie title where
the movie idea is three. Pause the video right now
and go do the challenge. Okay, welcome back. How did you get on with that? So we said we only wanted the
title and look right here, we have this title. So I'm going to select title from movies where movie
ID is equal to three. Hit Enter and it's
the dark night, very nice as you can see. We have a database that now
we can administer and we're obviously going to
be looking a lot deeper into this database. But for now the first
thing we need to do is to create a backup. And the backup is going
to be movies underscore, back up one, Let's call it back up one because
I have a feeling that we will need to create
multiple backups back up one. Now if we open the
movie's database folder, you'll see that this is where the movie backup was
created. Very nice. Now let's go ahead and
look at other tables. Let's go ahead and Genres. We'll select everything
from genres. Yep, that's how it's written. Boom Head enter. No such table as
genres because this is case sensitive and I've already told you,
and sometimes. Okay. It's still not a select
star from Jeans. Okay. Okay, Let's test
out if it's actually no. Okay. And in here we
have an E, hopefully. Yes. There we go.
So the table name and the column name are not
actually case sensitive. It's obvious because
right here we did movie ID with
a lower case M, and here we had a upper
case M. But for example, if you want to
select 12 angry men, this would be case sensitive. So just keep that in mind. Now if we look at our genre, you can see that we
have the genre ID and the genre name
and we have drama, crime, action, and
adventure. Very nice. Let's try to insert
into this database. I'm going to insert into values. Values are going to be, well, first of all, we need to provide the ID. The ID will be four. I will do comedy. Now, obviously you're
telling me right now, whoa, wait, why four? We already have a four.
What's the issue here? I just want to show
you something. If you'll see that I
get an error and it's very important that we
read what this error is. So you'll see parse error
near inserts and tax error. But what really is it? The error is that we typed
in instead of insert. And I don't know
what the matter is in the matter with me today
not typing correctly. The words are not coming
out as you can see, but we'll try to get through it. Runtime error, unique
constraint failed, and the genres, genre, ID. There is a problem in here. Basically what it's
telling us is that you cannot have keys
that are not unique. But why is that? Let's do the schema and look at how
this table was created. So you'll see that
we create the table, movies, table genres
and table actors. And you'll see right here
that we have the movie ID, which is an integer and it's
a primary key and it auto increments and that holds
true for our three tables. Right here we have the actor ID, it's an integer and
it's a primary key. And when we say a primary key, it means that you cannot have
the same key appear twice, meaning like four adventure. You cannot have four comedy. Also, something very important about the primary
key in here is that it auto increments and we'll
see how that works later on. Another thing that
we also should keep in mind is the null, meaning that we cannot
have empty fields. If we try to add a movie, we have to provide
it with the movie ID and the title and
the release here. And the genre and the
director and rating obviously because
they cannot be null. Okay, I hope that's clear. There's nothing
too much in here. The main important thing is
that we have a primary key. Primary key means it
cannot be duplicated. Just like we have a set, for example, a auto increments. It increments on its own, and I'll show you
how that works. And we also have something
called a foreign key, but we'll look at
that more later on. For now, if we want to insert
something into genres, we have to do the following. Insert into genre's value. And now instead of
comedy or four comedy, I can just do comedy like this. And instead I'll just
have in here documentary. Okay, hit enter. Look at that parse error table. Genre has two columns, but one value was supplied. How do we solve this issue? You should know this by now. Exactly. I can
hear you say that. So the genre Name and make
sure that it's correct. Name, Genre name, hit
Enter, and there we go. Now if we select start
from Res, there we go. You can see that the ID auto incremented and we have the
documentary at the bottom. Thanks so much for watching. I hope you enjoyed
now getting into the administration of
an actual database. I will see you in the
next video where we will be working on order by and joining tables using
the foreign keys that we looked up right here. Before I go, just to show you, we have the movie ID, title, release, genre, ID,
director, and rating. You'll see for example,
the Shashank Redemption release year 1994, and the genre ID is one. And if we go back
into our genres, you can see that one is drama, because the Godfather, or the Shawshank
Redemption, is a drama. If we look, for
example, Pulp Fiction, the genre idea is four. If we scroll down, we'll
see that four is adventure. We're going to see how we
can connect these two keys. How we can create a connection between the genre table
and the movie table. Thank you so much for
watching and I will see you in the next video.
Bye bye for now.
139. 5. ORDER BY and JOIN our Tables: Welcome back my favorite
python developers to a brand new video. And in this one we're going
to be looking at two things. First of all, we're
going to be creating the connection between
the genre ID on the movies and the genre ID
in the actual genre stable. So this is going to
be the joint part. But before we do that, we need to look at order by. So for example, right now
if I select from genres, you'll see that we get them
in the order of the genre ID. But that's just because
this is the default and we don't have to adhere to
any default settings. So we can specify
that we want to order them by the genre name. Now if I hit Enter, you'll see that they are
ordered by their genre name. Well, it should be pretty obvious there's
nothing much to it. We start with action
than adventure, because we start with the first letter and then
we go to the second letter, A, B, C, D. Then see drama. But not something. Documentary is at the end. And you might be thinking, well, that's maybe obvious since drama and documentary
and that's the end. Let's try to insert into genres, genre name, values, and
then we will do comedy. Just to properly show you when we do this and we
select the genre, you'll see that comedy, even though it starts
with a C, is under drama. And we've already seen
this before when we were trying to sort out lists and letters and so on and so
forth and Python that the upper case are considered to be before the lower cases. So how do we make sure
that the comedy and documentary appear in
the correct positions? We can do the following. We can select star from
genres ordered by genre name. And then we can specify that
collect no case hit enter. And as you can see now, documentary appears before drama and comedy appears before crime. Because a appears before R
and also appears before. That's obvious. As you can see, we don't use any case. We can also add an
extra option in here and that we
can present it in a descending way or descending
manner As you can see. Now drama is at the beginning. And then we have
documentary crime, comedy, and action and adventure
are listed at the end. Pretty simple, nothing
too much in here in case you want to
display things in a different order or using
a different parameter as an order if you want to
display them without any case. And also you can display
them in descending order. Now I have a bit of a challenge for you to sort out the movies. Select all the movies
from the movie table. Sort them out based on the
genre and the movie title. This is something
that you can look up. The case should not
matter and they should be in descending order. I will give you a hint about the second point
where you should display them or order them based on their ID
and their title. If you want to go
search for this yourself, go ahead and do that. If you don't, I'll
give you the hint in 321 at a common between the
genre ID and the title. Pass the video right now
and go do the challenge. Welcome back. How did
you get on with that? In here we want to
select star from movies and then we want to
order order by the ID. We start with the Genre
ID and then the title. Collect, case Descending,
Hit Enter, and there we go. As you can see, the
Genre ID in here are 111-122-3344 And then
we display them, first of all based
on the genre ID, but how would we
order them next? Well, we ordered
them by the title, so you'll see, because we have and then we have
numbers at the end. Why? Because we are
using the sending order. If we were using
the normal order, we would start with
the numbers first. Same thing holds true right
here in these two movies. Unfortunately, they both
start with the same. Letter. And they have
almost the same name, except for the godfather
at some point. Or the godfather part two
has the column right here. Another example
would be the threes. Right here we have two threes. They are also, we compare the D and the ABC
D. D appears first, but because this is
descending order, we present the good, the bad, and the ugly first. This is the order. Nothing too
much in here, very simple. Let's try this in a
slightly different way. Let's try to print
out the actors. I'm going to select
star from actors. Or by, by the way, if you don't know what
we have in actors, again, you can use the schema. If I scroll up, look at actors, what do we have? Oh nice. We have the movie ID, We have the first
name and last name. I'm going to the first name
and then come up movie ID. Yes, that is enough. There we go, these are
all of our actors. You can see it starts from here. Sometimes this
might be confusing, but through trial and error it will be very easy
for you to spot. So you'll see, first of all, we have Al Pacino and
we have two Al Pacinos. Why? Because they act in
two different movies. They act in the
Godfather part two. And in the Godfather you'll
see even the connection. Because notice, and this is
very important for you to understand right
now on the actors. Right here on the actors
we have the foreign ID, which is the movie ID. References movies. Movie ID. So there is a connection
between Al Pacino to the ID right here and the
godfather, very important. So there is a connection between the movies and the actors. And then we also have
Al Pacino Nine because he stars in the Godfather
part two as well. Ladies and gentlemen,
thank you so much. I apologize, thanks so much for watching
so far because now we're going to talk about the
join and what is the join? The join is basically going
to allow us to create the connection between
these two movies ID, the movie ID on the act, and the movie ID on the movies. The join is used to
combine roads from two or more tables based on a related column
between them. So in our case, the related
column is the movie ID. Here are the most
common types of join. So we have the left
joint, full outer join, and left join if
null, right join, if null, right join,
and inner join. All of these are different
joints, don't worry for now. What we are going to be
focusing on is the inner join. All of the other ones are
for very special cases. 90% of the time you'll be doing inner joints because you want the connection between these. What's in common between the two tables or combine the roles
between the two tables where they have related columns. Let's take an example to
make this more clear. Let's go back into
our command prompt. In here, I'm going to
select at first name. The reason I'm
doing this is going to get very clear and a few. First of all, I want
the first name on the actors from
the actors table. This is indicating the table. Next I want to get
the actors last name. So keep in mind, and in here, this should be last name. Come on, and then I
want the movies title. I'm getting the first
name from actors, the last name from actors. And the title from movies. Now, where am I
getting these from? Well, of course I'm
getting it from actors, but that is not enough. Because I'm not just
getting it from actors, I'm getting it from actors. Join movies, it's
joined together. And then I'm going to say on what are we joining these on? What is the connection that
we're trying to create? It's on the actors do movie ID, where it's equal to
the movies movie ID. And there we go.
So as you can see, we've never before had the actor and the movie
displayed in the same table. But we've created this
display ourselves. So we've printed
out the first name, last name, and the title. For example, Tim Robbins,
The Shawshank Redemption. Let's take an
example. Here we go. This is Tim Robbins, right here. You can see Tim Robbins
has his own personal ID. The actor's idea
of one first name is Tim, last name Robins. He was born in this date. He is American and
his movie ID is one. If we go to the movie stable, where is the movie stable? This is the movie stable
right here being displayed. If we go to the movie stable, what movie has
their movie ideas? We I want you to find it. It's the Shawshank Redemption? That's correct. This
is the movie ID. Our command in here
said the following. I want to select the first name, last name from the actors
and the movie title. This is why we have the display. The second part is where do
we want to display this from? Where do we want to get
this information from? We want to get it from
actors join movies. We're getting it not
just from actors, we're getting it from
actors joined to movies. And how are we joining these on the actors movie ID
and movies? Movie ID. I understand you're
probably very confused. Like Michael, what the
hell is happening? Like I just learned
the order by now. You're throwing all of
this information on me. I understand the join is not
something easy to master. But again, like always, you've come this
far in the course. You should trust me
that at some point it will become very intuitive. The most important thing is to understand the connection
being created. For example, George Mckay is British with ten their movie ID, which means he
acted in the movie. Where's the movie? So these are the movies he acted in 1917. What should be the
output at the bottom? Let's find, who are we even
looking? George Mckay. George Mckay. If we look
to where is George? Actually, I can't
find George anywhere. There we go, 1917. So very important that you understand the join
before we move on. Something very important
is that when we say join, we automatically
mean inner join. Okay? Because we're
only getting the things that are in common
from both sides. Very important to know
that we're getting the inner join Finally, in here, let's say we want to get these, but we want to create
a certain order. I will remove the semicolon
from the end and I'm going to say order by and then movies, title actors or
actually know what, let's do act, first name, title. There we go. So we
start from the top. Al Pacino, the godfather. Al Pacino the
godfather part two. You should have seen this
coming because in here, look at that right here, when we had these
two, we had 2.9 which means the Godfather and
the Godfather part two. You can see from the movie ID, when we scroll down,
this is what we get. The Godfather and the
Godfather part two. Ladies and gentlemen, some
of you might be going crazy. Some of you might be
excited for the challenge. Some of you are like, I
did not sign up for this. What the heck is happening? Trust me, everything with
time will fit into a place. All the puzzles will
fit into their place. Just take your time, fresh breath of air, and then look back at this. Understand how to join works. Try to test a few things out. Try to see how you
can mess things up. Don't worry, you
have the backup, you can always restore it. So thanks so much for watching. In the next video,
we're going to be delving deeper into
joint queries. So make sure that you understand it right now before you move on, and I will see you in the
next video. Bye bye for now.
140. 6. Chaining JOINs Queries : Welcome back my fellow Python programmers to a
brand new video. In this one, we're going to be chaining multiple joint
queries together. Now we're going to start
writing more complex SQL, and that means we're going to be maybe making more mistakes, which means that we will have to reorganize our code
in a better way. And when we are working with command prompts that's not
really flexible and possible. What we're going to do
is we're going to create a new text document inside of
our movie database folder, which is going to be
the query test file. This is where we're
going to be writing our SQL queries and then we're going to be sending
them to the command prom. That way if we make a mistake, we can then copy it
from the text folder. And I'm going to show you
what I mean by that later on. First of all, and here we
are going to select from the genres and the
movies and we're going to join the movies and genres. I'm going to select
the genres, genre, name movies, movie,
it was just title. And it's going to be from what movies interjoinenres on movies, genre ID equal to end, sorry, genres, genre
D also in here. I'll just enter and
I will order them by genre, do genre name. I just made a huge mistake in here and I know that
I made the mistake, but I made it for
a specific reason. I've written them. I was thinking of them, but I just written them. Let's say you made a mistake,
how would you fix it? You cannot go back in here and change it.
That's impossible. And if we go back
with the arrows, you'll see that we can
only get certain terms. So we will have to
rewrite a lot of things. So what we can do in here, and this is where
the SQL text file that we created comes into play. We will select this, we will open up the text document and we will
paste everything in here. And of course, we will
remove this arrow. Now, I can simply fix
this by removing it. Copy this, and then paste
it in here. And hit Enter. There we go. Very nice. Again, No such column as genre, genre name. Where is that? I'll write very nice. We changed this once, copy base, hit Enter,
and there we go. So as you can see, this
is a very helpful tool to save everything that we do
inside of a text document. And maybe sometimes you want
to redo a few of these. Having this is a
very helpful tool. Great, let's now see what would happen if we wanted to access three tables
at the same time. Instead of just two, we are going to try and
print out the genre, the movie, and the
actors at the same time. So let's go ahead and do that. First of all, what do
we want to display? We want to select genres,
genre name, Okay. Then we're going to
get the movies title. Then we're going to get
the actors first name. Actors dot last name again. Remember when we're working with the names of our
fields, It's okay. It doesn't matter if we have upper or lower case letters and then from actors, right? But of course, this is not
the end, because on actors, let's go to the top and
see what we have in the scheme when
working with actors. We have first name, birth date, and then we have the four and key which references
the movie ID. What should we be
joining on in here? Well, of course we should be
joining on the movie ID in the actors to the movie
ID of the movies. I'll scroll down, since we are already getting
things from the actors. I'm going to create
an inner join with the movies on the
movies. Movie ID. Equal to equal to
actor movie ID. Round of applause For
the shark anti virus for keeping us safe. And this is not
sponsored by Shark. Unless they want to contact
me and give me some money, then yes we are
sponsored by Shark, VPN. Anyways, inner join on the
movies and the movie ID. Movies movie ID with
the actor's movie ID. Now the next thing
is we want to get what the genres and
where are the genres. Again, if we scroll up, I know this is a bit cumbersome, but this is necessary in here. What we have is the movies
we have the genre ID, and then in the genres we
have genre ID. Perfect. So we're going to
join on these please. I do recommend that you
take a few seconds in here to fix this as
well, or do it yourself. So in our join, genres on movies do moved equal to genres, genre ID, and I really hope
that we make a mistake here. And finally, why do I hope
that we make a mistake? Because I want to show you
the power. Okay, thank you. I mean, this two scans
in a couple of minutes. I mean, that has to be a record. They're making sure
that we're safe. Anyways, I want you
to take the time to really appreciate
what is happening here and how we are
connecting these. And I hope you make a mistake
to show you the power of using the text document that
we just created in here. We want to order by genres, genre name, and then by the movie title and then by
the actors dot first name. And I think that's enough. So let's hit Enter.
And there we go. We have everything correct. But just in case I'm
going to copy this, Just put it in here if you want. You can also add
like a description of what this does
maybe above it. That would be very helpful, but I will just keep
this right here and then control S to save
it. There we go. As you can see we've joined on the movie ID in the movies to
the movie ID in the actors. We were able to associate every single actor
with their movie. Then we joined the movie
ID with the rest genre ID. There we go. We did
make a mistake in here. Something is definitely
not correct. Let's try and figure it out. What we did was we
joined the genres on movie ID and then G genre ID. That's why we don't
have all the, and we have some weird
things in here happening. Let's change this again. We have comedy. Schindler's List is definitely not a comedy. And documentary doesn't work. We made the incorrect thing. What we had to do in here to fix this is we would
have to get select, then go to the inner join, then the second inner join,
et cetera, et cetera. Obviously, we don't
have time for that. Instead what we
can do is in here, just change this to the genre, now we can simply copy this, boom, pasted in here
and head enter. All right, there we go. So now we have everything
set up correctly. The action, the adventure, the crime, and the drama. So as you can see, saving very, very crucial. So what did we do in here? We associated the movie ID on the movies with the
movie ID on the actors. So we created the
first connection, then we created the
second connection from the genre ID on the genres, with the genre ID
and the movies. And we got everything
written correctly to us. I hope you enjoy
it before we go, there is a bit of a
challenge in here for you. So we want to get only
from a single movie, so we want the same
result that we just got. Meaning that we want
the genre name, the title, the first name, and the last name of the actors. But we only want the actors from Pulp Fiction
to display here. The challenge here is to know
where to insert the query. Get it where The important
part is where to insert this. Pause the video right now, and get all the information. But only from the
movie Pulp Fiction. Welcome back. How did
you get on with that? Basically in here we will
not copy everything. We will copy these
first three lines because they are
exactly the same. We will hit Enter, and now
we're going to say where movie title equal to Fiction. I hope I've written
Pulp Fiction correctly. And then in here I will
copy the last line because I'm lazy and
hit Enter Error. No such movie C. This
is exactly what I mean. Mistakes can always be made, especially when we're
working with SQL, where the slightest
mispronunciation can lend you in big trouble. Let me remove these, save a copy, paste it, Enter, and there we go. So now we have all the actors from the movie Pulp Fiction. Ladies and Gentlemen, I hope
you enjoyed this video. I hope you understood
the importance of using the text files. In the next video, we're
going to be looking at like wild cards and
creating views. Very exciting stuff. I can't wait to show you how
all of that happens. Thanks so much for watching and I'll see you in a few seconds.
141. 7. LIKE Wildcards: Welcome back my favorite python programmers to a
brand new video. And in this one we're going
to be looking at like wild cards and how
to create views. First of all, what the heck
are we even talking about? Let's say you're not sure what the name of the
movie that you're trying to look up or print
out the information of, but you know approximately
what its name is going to be. This is where we would use
something called the like. So first of all, let's
do the following. I'm going to go, first of all, let's try L S in here. Okay? That does not work. We need to quit. And
then open it up again. You know what? Let's
just keep it as it is. It's okay. And here I want to go back and I want to
get the following. I think select border by genres. Yes, I think this
is good enough, So I will print all of this out. Okay, so at this point, it's a good idea
to start putting our codinsXDfile because it's going to be much more extensive. So if you haven't
started doing that yet, I recommend that
this is the point where you do so in here, let's say we want to
get all the movies with the word or whatever
you want to call it, for example, the Godfather
or the Lord of the Rings. Or for example, we don't want
Pulp Fiction in this case. The way we do this is
the following way. I'm going to copy this in here. I'm going to change the swear the movie title two or the
movie title equals to, to where the movie title is, like where is it, this and then the percentage
sign again, don't worry. I will explain to
you what this means. So I will copy and
paste it in here. And when I hit Enter, you'll
see that all the movies with the in them are
going to appear. Everything that doesn't
have the will not appear. This is wildcard. If you want to first
we use the keyword. Instead of the equal second, we use the percentage character, which is called the wildcard. Hence the name of this
video, wildcards. And a third thing, you can also use like
without any wild cards. So for example, if the word just like
in here for example. If we just remove these
wild cards and we will be then looking for a
movie that is of title. But let's look a little
bit deeper into wild cards because there's something
other than the percentage. Wild cards are a
special character used in pattern matching
within the queries. So you're trying to match a pattern in your search
for specific data. They allow you to perform flexible and
powerful searches by representing unknown or
variable parts of your string. There are two wild cards. The first one is the
percentage sign, which represents any sequence
of 02 more characters, Like you might have
one character, two, or maybe none of them, just nothing inside and
the underscore which represents any single
character for that matter. Okay. So with that out of the way, of course in this case we wouldn't need,
where's the query? We wouldn't need the
percentage sign behind that. But we were thinking of the idea that maybe
we want this to appear somewhere inside of our word or the movie title
doesn't have to be at first. Obviously, all of
the movies that we have have the start
in the beginning, but maybe it could
be in the middle. So that's why we use
the percentage sign on the left hand side as well. So with all of that information, now it's time for a
bit of a challenge. Your challenge is going to be to find something like this. Find all the actors
who have a first name with only three letters.
Interesting challenge. Print out the title and the
year they were released in, of the movies whose directors have a ran somewhere
in their name. These are two completely
different tasks that you need to do, okay. So first of all,
do the first one, then print out the title
and the year they were released in the movies whose
director have somewhere? Get the directors
that ran somewhere in their name and print
out the movie title and the year the movie
was released of the directors that have an
somewhere in their name. Pause the video right now
and go do the challenge. Welcome back. How did
you get on with that? First of all, we need to
select star from actors where the actors do first
name like underscore. Underscore. Underscore.
There we go. So when we hit Enter, as you can see we have Tim, Tim, Ben, Eli Lee, and
Lee. Very nice. These are all the actors with only three letters
in their first name. Now we need to get
all the movies and the year they
were released in, when the director has
a name that has in it, we need to select the title. Release here, is that
how this is called? First name title. Okay.
No, it's not here. We'll have to go
more to the top. Let's just go to where.
Okay. There we go. Movies. We have
the release here. Yep. There we go.
And the director. Okay. Perfect. Release here. And then from movies where percentage ran, percentage closed
the parentheses. Sam Colin, hit enter the
Shawshank Redemption. Actually know what a good idea here would be also to print out the director's
name, the as well. All right, so we
have Frank Arrabon. You can see we have Ran, we have Francis Ford Copola. We have Quentin Tarantino and another movie by
Francis Ford Copola. And these are the movies. So ladies and gentlemen, this is a quick one, this is a very
important one as well. In the next video,
we're going to be looking at creating views. So thank you so
much for watching. I thought it would be in this
video, but apparently not. I apparently found
that it is too long, so I had to create
two videos instead. Thank you so much for watching. I will see you.
And the next one. Bye bye for now.
142. 8. Creating Views: Welcome back my fellow Python programmers to a
brand new video. And in this one we'll be
looking at creating views. Let's talk about views
and what they are. Views are virtual
tables that are based on existing tables. If we want to
combine one or more, if we want to combine
two or more tables, we can combine them into a
virtual table, that is a view. They allow us to group
together data from multiple tables and
presenting it in a way that is easier
to understand. Views can be used to
simplify complex queries, height sensitive data, and grant users limited
access to certain data. To create view, you use
the create view statement. After that, I'm going to give
you a challenge directly. I mean, who doesn't love a video that starts
with a challenge? Your challenge is
to create a view, you'll need to create
a view, name it, movies underscore title or
movie underscore titles. It should have all
the movie titles ordered by their title. Check how you can
create view search, Google four creating views, and SQLW three schools. Even though I showed
you a bit of help with inter pass the video right
now and go do the challenge. Okay, welcome back. How did you get on with that? From here I'm going to create view and then movie
underscore titles as then I'm going to
select title from movies. And then order by the
keep liners I now giving by the title head. There we go. Now if I
select star from movie, underscore titles, look at that. We have just the title from all the movies and look,
we selected everything. So this is how we start
looking at views. They simplify complex squaries. Okay? Even though this
is not a complex squary, but it does simplify the query. It also hides sensitive data. So for example, the Genre ID. Maybe we don't want people to have access to the genre ID. Now we've hidden
that sensitive data. And it also granted users
limited access to data. So for example, let's
say we didn't want the users to see the year
the movie was released. I know bear with me,
these examples are a bit absurd but still gets
the point out there. Maybe just replace
the genre ID with a password and the
release year with, I don't know, location or
something live location. It gives users limited access
to certain information. And it's simplified
like look now these three lines
are a single line. We can select
everything very easily. Actually, let me copy
this and put it in our text file in here just so we know how
we created this view, even though it's
not very complex, but still could come
in handy later on. With that, out of the way, let's look how we can maybe
destroy or delete a view. I'm going to drop view
underscore titles. There we go. Now if
I try to select star from movies titles there
you see no such table. Let us create it again, but this time with a
few modifications. I'm going to set
this right here. I'm going to make sure to title and make sure that there
is no case as well. Boom. There we go.
Select star from movies, or why is it like this? Where's the actual select
star from movie titles? There we go. Even though there's no case in here.
No problem with the case. I just thought it would
be a good idea to add this. This is very simple. This is not something that
we would really like. We want to look at a
better use of our view. Let's go ahead and create
a more substantial, more complex view
and see its use. First of all, I'm
going to create view and call it the Genre
Underscore List. And we're going
to say that we've created the view list as, then we're going
to select Genres, Genre name as genre right here. Notice that we had
the title as title, but if we had something
else, what would we call it? Now we have specified
that we want the genres, genre name to be
represented as the genre, then we want also to
have the movies do. Title as movie name. Maybe then we would like to have a first name and I think first name will be enough or should we add last name? Yeah, let's just stick with a last name from actors. Let's just, yeah, let's just keep it first
name and last name. No need to change
anything in here. I think from actors hit Enter. Now we're going to have an
inner join of the movies, and you should know this
by now, of the actors. Movie ID equal to
movies, movie ID, hit enter inner
join of the genres on the greenD equal to movies, genre ID and we are going to order by Johns name, movies, title and
actors do first name. Great. I will copy this. I will paste it in here
and we'll remove this one. This one. This one. This one. Okay. What is
the problem in here? It's telling me that are movie
title as Oaks movie name. Okay. It doesn't
like having spaces. So we'll have to maybe
make an underscore, or let's just call it movie. Why go through all this hassle
right here? There we go. Now if we try to select Star from the genre underscore
list, look at that. We have this complex query printed out using just
the simple line of code. Now we have a view, which is a virtual table, which gives us the
following information. And this is going to be very
helpful in the next video where we will have a
few challenges for you. It will be a very special
video with lots of challenges that you will
need to find on your own. Thanks so much for watching.
I hope you enjoyed. I hope you understood
the use and the usefulness of having
views and virtual tables. That's basically, that's
everything that I have to say. In the next video, we're
going to be looking at restoring backups
and a few functions and also a pack of challenges
to finish off with database so that we
can move on to using Database and SQL in Python. Thanks so much for watching. See you in the next video.
143. 9. Restoring Backups and Function: Welcome back my fellow Python programmers to a
brand new video. And in this one
will be restoring backups and looking
at functions. And as I told you, do the big, big challenges first of all, in here, as we've said, we have already created
a backup for our movies, but we want to create
another backup. So we'll have backup then
movies underscore, back up. Wait, let me just check. What did we call the first one? Movies back up one. Movies back up, one. Okay, so this one will be
movies back up to. Now we have a second back up which is movies back
up to Excellent. Now we're going to
delete from actors all the nationalities or all the actors that have
an American nationality. I'm going to delete from
actors where nationality, is that what the name actually, let me copy this. Let me delete it and
do the schema again. Okay, thank you for that schema. Okay, what do we
have for the actors? Yes, it is indeed,
nationality control. Nationality is equal
to American enter. Now if we select a boom, we'll see that we don't have any Americans in here because
we've deleted everyone. Now let's try and delete
everyone who is not British. We'll see that we
have an Australian, and an Irishman, and a
New Zealander as well, which is Peter Jackson. Let's try and delete everyone
except for the British. The way we do this is actors where nationality is
different than the British. British. Now, if we
select star from actors, you'll see that we only
have British still left. Let's go ahead and
do the following. I'm going to also
show you the count. We select count
star from a boom, you'll see that we
have nine actors left. 12,345,678.9 Let's do the same for the movies to see
how many movies we have. I believe we have
ten. Boom, exactly. There we go. And then
finally let's do the genres. And I think we had six or six. There we go, very nice. Let's do the restore
movies underscore, back up to boom, and now if we count
the actors again, there we go, we're back to 39. So as you can see,
restoring is very helpful. That basically, of course this
doesn't cover all of SQL. Sql like would need maybe
hundreds of hours to make sure that we understand every single small
nook and cranny, but this is basically SQL. In the next video,
we'll be using database inside of Python, meaning inside of Intelligy. But before we go, I have a
series of challenges for you. First of all, you need
to select the names of all the actors on the
movie Pulp Fiction. Second, you'll need to
repeat the previous query, but this time display the
actors in name order. Display all the
actors in the genre. Action set Al Pacino's
nationality to Italian. Select the titles of
all the movies in the drama genre in
alphabetical order, include only the
title and the output. Count the number
of those movies. Search the Internet to
find out how to get a list of the movies from step six
without any duplicates. This is a very cool one. And then search the Internet
again to find out how to get a count of the movies
without duplicates. Also, I recommend that you always keep the view
that we created. So we've created two views, the genre list and
the movie titles. So think of how you
could use these views to your advantage in some of the later steps past
the video right now. And try to do your best
to do these challenges. Because if you can
do these challenges, it means that you've become
intermediate at SQL. Not super advanced, but
intermediate and above. And you know a lot about
SQL at this point. Of course, with more practice, with more examples, with
real world examples, and when we go
through it in Python, it will become much, much
more evident for you. But for now, try your best
to do these challenges. And I'll see you
in a few minutes. Okay, welcome back. So how did you get on with that? Let's first of all look
at select the names of all the actors on the
movie, Pulp Fiction. This should be fairly simple, we just need to get
all the actors. We'll select act, first name, actor, last name, then
where from actors. And then we'll create inner
join of the movies on actors. Movie ID equal to
movies, movie ID, then where the movies title is equal to Pulp Fiction. All right, there we
go. So these are all the actors from the
movie Pulp Fiction. And obviously, we
needed to create an inner join just to make sure that we have
the same movie ID, where we have Pulp
Fiction as the title. I will save it. Right here. There we go. Save that. What do we need to do next? We need to repeat
the previous query, but this time display the
actors in name order. This should be pretty
simple in here. I will just copy these lines. Actually, let's just
write it in here. We need to order by name. Actually copy this and
put it right here. Copy this and put it right here, and boom, as you can see. Bruce Willis, Harvey Keitel, John Travolta, Samuel.
And there we go. Yes. Abc, D, E F G H I, J K Mano Pi R S, T U, V, et cetera. Let's continue on and
let's look at three. Display all the actors in
the genre action. Very nice. Again, we go back in here, let me actually use the arrows to select the actors first name and
last name from actors. Then we're going to create
an inner join to the movies because we don't have access to the genres from the actors. In order for us to get
all of the action actors, we need to first get
all the action movies. First of all, we create an
inner join of the movies on the actors movie ID equal
to the movies movie ID. Then we create a
second inter joint on the genres or with the
genres on the genres. Genre ID equal to
movies genre ID, where we have genres, genre name equal to action. Uh huh. Very nice.
We have an error. No worries. We copy this,
we paste it in here. You know what? Actually,
just for extra safety, so we know that we
have the movies, we're going to get movies. Movie, it's just title
then genre, genre name. This is for extra protection. And what was the error? Not extra protection,
just to make sure that we got it correctly. And what do we have in here? The error was no such column as movies do genre D,
where did I write that? Genres ID. Okay, movie, genre D. Yep, there we go. So if I copy this,
paste it in here, Hit Enter, and let's see, the first name, last
name, title and genre. The Dark Knight, The Dark Night, the Good. Deb and Ugly. The Good and the Ugly. Yep, there we go. Do
we have anything else? Let's try select star
from books, from movies. Let's see, we have
what's even the genre. Let's select the genres as well. The genres we have,
action is at three, so we have two. Okay. Yep. So there we go. We made sure, I'm
just making sure that this one right
here is correct indeed. So we only have
two action movies, which are the good and
the bad and the ugly. And we actually got all of the
actors for that very nice. But in this situation, we could have done
something even better. So remember the genre
list that we created? Let's select, oh my
God, select star. From the genre list of
view that we created, but as you can see, we already have the actors
associated with a genre. What we can do in here is
we can say the following. Select first wait, let
me check the headers. Okay, first name,
last name, Genre. Underscore list, where I believe
it was called the Genre. The Genre is equal to
action. And look at that. We got the same output
as we had in here, Christian Bail, the
dark night action. Let's see, there we
go, Christian bail. Now, obviously we don't have
it, but it's Christian bail, Heath Ledger, Clint
Eastwood, whatever it was. Three or four from the dark night crisis and three from the movie at the bed. And the ugly, how cool is
that we were able to do. Look at how big this one was. Oh my god, where is it? Yeah, it can get a bit
confusing. So there we go, look. We had 1234 lines of SQL because of the view
that we've created. It was done in one. Yeah. There we go. Next we need to set Al
Pacinos nationality to it. Let's go ahead and do just that. How do we do this? We
need to do the update. If you remember, we need
to update actors and set nationality equal to it, where first name is equal to all and then select star from actors. Al should be at the top. Oh, no, he's not in here. Al Pacino now, is it? He's no longer
American Al Pacino. Where is the second
time is only one time. No, he's not. We've seen him appear
multiple times. We just need to find Al Pacino who is Italian
as well. There we go. Number four, done.
Challenge number five, select the titles of
all the movies in the drama genre in
alphabetical order, Include only the
title in the output. Again, this is
where you can start thinking of the view
that we've created because we already
have a table or a virtual table where we have the movie and the genre
in the same place. If we go back and here
we can do the following. And I believe it was movie. Yep. Movie, not the
title. Very nice. Also something very important to keep in mind that the view, you might have a change in
the name of the headers. Select movie from
genre underscore list where the genre is equal
to drama. Was it drama? Yes, the drama genre drama hit. Enter Boo. There we go. Movie 12 Angry Men. And notice what we have in here. We have duplicates. And why do you think we
have duplicates in here? Why do we have four
Schindler lists, two Shashank Redemptions
to 12 angry men? That's too many angry
men. What is happening? Well, if I do select star
from underscore list, you'll see that for
example, okay, action. As you can see, the dark
night appears three times. 12 Angry Men appears twice. Schindler's List
appears four times. Why? Because for every
actor we have to display the genre
and the movie title. So how do we avoid this? Avoid this with
challenge number six. Challenge number
seven. First of all, we need to count the
number of these movies. If I go back in here, I go back to this one, and in here we
select the movies, but this time we count them. Instead of displaying
them, count, boom, boom, boom,
and we have ten. But obviously that is not true. We have ten because
we've counted these multiple times in
challenge number seven. We need to make sure that we
get them without duplicates. I hope you tried your best to look this
up on the Internet. So the way we do
this is right here. We need to add the following. Select distinct movie from
genres list. There we go. Now if we try to count it, but notice this is also
a very important part. How do we count
these distinct ones? We need to count
the distinct ones. There we go. Now we have four. And that is the end of
our series of challenges. It is the end of the use of a command prompt to
work with databases. I hope you enjoyed. I hope you learned as much as possible. If you're still not sure, please go back and review this. Using SQL is mega
mega important? I cannot emphasize it enough. Thank you so much for watching. In the next video,
we'll be looking at databases SQL and Python. I can't wait to start or to
go back to our Intelligent, to go back to Python
and to use SQL with Python and blend
our two tools together. Thank you so much for watching. I hope you enjoyed and I will
see you in the next video. Bye bye for now. Oh, also leave me a review. I mean, if you don't
have anything, if you're satisfied
with the course, come on, leave me a review. Contact me. Tell me how
great it is. Let's go.
144. 10. Commit Changes: Welcome back my fellow Python programmers to a
brand new video. And this one will be actually committing our changes
through connections, cursors, and making
transactions. Let's go ahead and get started. First of all, we're
going to create a new Python file which is going to be
contacts number two. Contact two, enter in here. I'm going to import
escult three. I'm going to create the database connection and
say that it's equal to escult three connect and it's going
to connect to contact, sorry, cult the one, the database that we've created. I'm going to say four row in B execute or execute because I don't want to
create a cursor yet. I'll tell you the difference between the cursor
and the connection. Select star from contacts. I will print out the role
and I will say Db close. If we run this we should, we don't get anything
that's weird. If you were expecting
to get all of the information printed
out, nothing happens. The problem is not
with the code. The problem is that
we did not commit our changes and it's different
than writing to a file. Let me explain to
you what that means. Back in our contacts, we've created a table, we've inserted information, but we haven't really
committed our changes. Do you remember when
we were working with prompts and
we did the schema? You can even test it out on
your own command prompt. We did the schema, actually, let me try to see
if I can replicate this. Let me try to ask
you light three, test B and I will do schema. I hope it shows up. That doesn't show up.
I will have to open the movies folder for now. I just don't have the time. I recommend that
you try the schema and you'll see
that the last line has the semicolon,
the function commit. Because whenever
we make changes, we have to commit those changes. If I do, b commit right here, now we've committed the changes. Now when I write
click and I run, if I go back to contacts
two, write click and run. There we go, we have
all of the information, how cool is that? But let's go ahead and
dissect this slightly. So instead of just
having the row in here, I'm going to have the name, the phone, and the E mail. I will do and print these out, just like we've done before. Actually, let's
make it the dash, It looks more appropriate,
more user friendly. Right click and run.
And boom, there we go. We have all of the
necessary information. And keep in mind
we don't need to commit the things in here. And I call them
things on purpose. Why do we commit the things? Because we haven't
made any changes. We don't need to
commit those changes. Okay, so let's go
ahead and now try to update a few things inside
of our contacts too. In here we've created the
connection with the contacts. Let's go ahead and
do a few things. I'm going to update
underscore SQL, and this is going to be
our SQL querian here. I'm going to update contacts. Set E mail equal to update at update.com Where,
let me get rid of this. I'll put it down here where the contacts do
phone is equal to. Let's change Michael. There we go. Now
I'm going to create the update underscore cursor and say that it's
equal to b cursor. Then I'm going to do the update cursor,
execute update SQL. I will print out that, let's do it like this
replacement field, I will say the updates, I will tell you what this does. Updated. And we need
to make sure that we close the cursor right here. After we finish update. Cursor close, Actually it's better that we put all
of these at the end. We close the cursor,
close the database. If we look at what
the row count does, let's hover over this, okay? It doesn't provide
you with anything. I mean, you can look at the
documentation if you want, but basically it tells you
how many rows were updated. Right click and run. And we should see right
here that was updated. And you can see it was of Michael With that
out of the way, if we issue you a challenge
to make some changes, you should be able to do it, change the phone so it doesn't match the one that
we want to change. And by the way, you
should know by now, because we haven't
committed anything. If we do the following, for example, we'll see that the e mail goes
back to what it was. Of course, we have an error
because we're trying to close a cursor that
we haven't created. But there we go. Now your challenge is
going to be to change the phone so it doesn't match
the one we want to change. Remove the entire Were
query and of course, test it at every point. First of all, change the
number so it doesn't match. Then run it. Then try to remove
the entire query. Run it. Create a new Python
file called checkdbtpy, and print out the list
of all the contacts. And remember I said the list. And then what did we
get as the output? Pass the video
right now and go do the challenge. Welcome back. How did you get on with that? I'm going to change these. 6958-69 2047. Now the numbers don't match. If we write click and we run, you'll see that we
get zero rows updated and we have still contact
at two python dev contact. Obviously nothing
gets updated because we don't commit our
changes from before. The next thing to do is to
remove the entire Were clause. What do you think the
output is going to be? You should know this from all
the work that we've done. In the prompt, the
command prompt, try, click and run.
Boom. There we go. Because we haven't specified where we want to
make these updates. It made the updates everywhere. Now, before we move on, the excuse me, we need to create a new Python file and
call it check DB in here. We're going to
import escult three, we're going to create
the connection. And this time we'll call it connection, not just database. And then contacts lite, excuse me, Contactes Lite. And then we're going to do, I said list, right? Let's print them out. Normally, if you did print them out using the fetch
all that's okay. I said list but I
just changed my mind. Four in connection execute
and we are going to select star from contacts
and print the row, and I forgot the two dots. And of course we need to
close the connection. If I write click and
I run, look at that. I still have the old e
mails and you know what? I just want to copy this. I like having a good
structure in here. Even though we've made the update in contacts
to it didn't work. Why? Because we haven't
committed our changes. How do we commit the changes? We've already
committed the changes. Look back at it in here. Before we close
the update cursor, we need to do update commit. Oops. But we don't have
it because we first need to do connection commit. It should work if we do
the commit directly on the cursor, there we go. We can see that we cannot. On the cursor, we need to
do it on the connection. Now if I write click
and I run, there we go. We've made the update
to everything. If we do check B, we should get, there we go, because we've updated or we
committed the changes. The changes also
happened in the check. We've officially destroyed
our beautiful database and here and made everyone
have the same E mail update. And just before we move on, I want to show you
one more thing in here in the contacts right here. I want to show you that
the connection from the update cursor is the
same as the connection that we have in here at the B. I'm going to do
a print in here. Just print and then
I will print out are the connections the
same replacement field, Answer this is a replacement
field and I'll say update cursor connection
is equal to B. And this basically should return true if it is and
false if it's not. And yes, these are
the same connection. Thanks so much for watching. I hope you enjoyed
something we didn't talk about is that two roles were updated because we
removed the word clause. This is something I
forgot to tell you, but it should be obvious by now. Thanks so much for watching. In the next video, we're going
to be looking at hacking. Sort of kind of, it's
not officially hacking, but I'll show you how vulnerable our database actually is. It can be easily exploited. So I will see you in the next video. Thank
you for watching you.
145. 11. How To Hack (Kind of): Welcome back my favorite
Python developers to a brand new video. In this one, we're going to
be looking at how to hack. Not quite how to hack, but just an introduction
of what happens behind the scenes when somebody tries
to infiltrate a database. Let's go ahead and get started. First of all, back
in contexts two, we want to create a
new update in here. I'm going to create
another update. Where should I do it? I think I will do it right here, just above the
update that we had. And I'm going to create
the new underscore e mail and it's going to be another update
at.com Then in here, I'm going to have the
phone number which will be equal to 65. What was the actually, let me just comment this out. Right click and run. What number did I have? Let's copy this one. Paste in here and then co, And then I'm going to say that the update contact set e mail to be equal to the
replacement field inside. I will have the new e
mail. That should be it. Oh, and also we need
to make sure that we only update where the A phone is equal to replacement
field and then the phone, this should be good enough
If I write Click and I run, I should see that I
have another update right here on Michael where the phone
number is different. All right, so now that we
know that this is working, the next thing we want to
do is we want to change this phone from just the
typical phone to an input, let's say the user
wants to input which person or data entry
they want to change. In here I'm going
to change this, Please provide me with
the phone number, two dots and in here
I'm going to call this another update input. And I'm going to
call this one input, just so we always
know to distinguish between each and
every single update. Now if I write Click and I run, you'll see, please provide
me with the number. I will hit control V.
Okay, that did not work. What was the number again? I have no idea. Let's redo this real
quick. And now it does. Okay? Let's duplicate this. If we comment this out,
it will also work. You know what? Let's check
B. Right click and run. Okay, copy the number. This is no longer needed. This can be uncommented. Right click and run
past the number. Hit Enter, and there
we go another. Update Input at update Input.com So we were able
to change this e mail. All right, this looks great, but one last thing I want to do, and that is I want
to update or execute the update SQL
using not execute, using the execute script. And basically what
the execute script does is it allows us to execute multiple
lines of SQL commands. So for example, in
here we just have a single line which
is the update SQL, meaning that this
is the only command that we're providing it with. What I mean by here
is for example, somebody can have a
Sem column and then continue with another update.
You know what I mean? That is the purpose of
using the execute script. It allows you to have
multiple executions. But for now we don't
want just this. I want to, okay, I want to print out the
update SQL actually in here, I might want to create a print just so we can have
an empty line of code. This is going to come very handy later on when we
actually start hacking. But for now, I'm
going to tell you a little bit about SQL
injection and what it is. Sql injection is a
type of attack where an attacker can inject malicious
code into the SQL query. So they inject malicious code. And you might now have started forming the idea of what's going to happen in a few minutes. So this malicious code
can then be used to gain unauthorized
access to a database, modify the data, or
even delete data, which is the scariest part. Sql injection attacks can
be carried out by adding special characters or queries to a user's input
field every single You know, like
when you're trying to work with the database, usually the user has the option to search
through this database, send in SQL queries. Not directly obviously, but when you do click on a
button to search, I don't know,
through usernames or to find your friend on Facebook. Usually this is an SQL query or it gets converted
into an SQL query. What the attacker does is they inject a malicious code
into that search engine, which then produces some
result and gives them access. So for example, you can use
a single quotation marks, get all the roles
in the database. This is something
that's very scary, and I'm going to show you a
few of these ways of access. But before I show you, you have to try and hack the database yourself.
How about that? Instead of just
providing the number, I want you to provide it
with some malicious code. And what I want you to do is to delete the contacts table. Interesting, isn't
it? I'm going to give you a hint of
how this would work. For example, if we
have the number, I then want you to
add a semicolon and type in drop table contacts. Then I want you to
go into check B, and I want you to run it. And I want you to tell me what the results
that you get are. Pause the video right now
and go do the challenge. Welcome back my fellow hackers. How did you get on
with that in here? What I'm going to do when
I write Click and I run, is I'm going to provide
it with the number. And then I'm going
to do semicolon drop table contacts
and hit Enter. Oh, what just happened? First of all, we have
minus one update. You can see what the actual SQL command
or update was like. It had a semicolon and
then dropped the table. And then when we tried to access contacts,
what did it tell us? No such table as contacts. Something weird happened if
I tried to run the B. Oh, I also get an error. So what happened?
Well, what happened is that the contacts
table was dropped, was deleted by our hacker. And this is not good at all. So now let's say the
hacker doesn't know what the table names
are from the beginning, they don't have an idea of
what it is. Let me show you. First of all, I want to go
into contacts and I want to run this again so that
we recreate the table. Now if we go into check
the B right click and run, you can see that we have our
information and tables back. This is from running
the contacts. I want you to see something. I want you to look
at the following. I'm going to add a print in here and then
I'm going to say four row in the
connection. Execute. And then select star from
cult underscore master. This is a scary, scary proposition
because in here I'm going to print out the row. And if I right click and
I run look at what I get. The Esculte master gives you a lot of information
of what's happening. The hacker can use that
information and they can use it to access all
of the available tables. And even they can see
how they were made. So they can see
the actual fields. They can see the names, the phone, the e mail, and what type all of these are, and they can use that
information to their advantage. That's a very scary prospect. Obviously, throughout the years, people have found
ways of defending against such
malicious injections. But one of the most
simple ones is going back to contacts two and instead of having
execute script, we can just execute. Now the reason why we were using execute script
because as I told you, it allows you to use or to provide multiple SQL
commands at the same time. Which led to us
being able to drop table or to our hacker being
able to drop the table. But what the execute does
or the cursor execute, because remember this
is the update cursor. What it allows you to do is
it allows you to escape out and disregard any
further SQL statements. Once you get to the first or once you get
through the third one. Let's try running this again. If I write Click and I run and I provide the number and I try to drop table contacts, Hit Enter, you can only execute
one statement at a time. Okay, this raised an error. This is not a very
good thing to do. But at least the hacker was not able to destroy
our contacts. Of course, there are much, much deeper layers to this. Hackers use tons and hundreds and thousands of ways to gain access to
the information. But I just wanted to show
you on the surface level what the SQL injection
would look like. Thanks so much for watching. I hope you enjoyed
Leave me ribbon. Leave me review somewhere. I would love to hear
your opinion of what you think of
the current lessons. And I will see you
in the next video where we will be looking at placeholders and
parameters substitution. So thank you for watching. See you in a few seconds.
146. 12. Placeholders and Parameter Substitution: Welcome back my fellow
hacker developer, Python programmers. In this video, we're
going to be looking at placeholders and
parameter substitution. Which is going to
provide us with a better way of allocating
and providing inputs to certain database L commands and also help us in
preventing SQL injections. First of all, I'm
going to go back in here and I'm going to
update this code a little bit. I'm going to duplicate the
update SQL and comment out the first one instead of
using this E mail directly, or what I mean by
that is instead of using the replacement fields
like we've always done, I will remove the F from here. And then I will replace
this with a question mark, E mail equals question mark, and phone equals question mark. Then I will do the
goal fashion format and in here we'll provide
the new email and phone. Then here when I scroll down
into the Execute update SQL, I'm also going to do
comment and provided with the new E mail
and the phone, The question marks are called placeholders and the extra
parameters we've added to the execute is called sanitizing the input
which checks if any extra queries are added
and detects SQL injections. Now obviously, this is a very low level sanitation
and this will not, again, prevent very experienced
and high level hackers. But as I said, this
is a start of you understanding how
these levels work. From here, I'm going
to first of all, explain to you, actually
let's test it out. If I write Click and I run, please provide me
with a phone number. Do we still have it? No, we don't. What
was the number? Actually, let me go back
and try to do this. Let's try to get this number. If I write click and I run, and I provide it
with this and I try the drop table contacts, boom. As you can see,
nothing was dropped. Nothing was updated. And we are good to go. Nothing happened in
here and we've printed out the update, which is great. We did not drop the table. At least that was good. Let's go and talk about
placeholders and what they are. Placeholders are special
characters that are used to represent parameters
in SQL statements. Just like we saw right now, placeholders are useful in preventing SQL
injection attacks. They are similar to using replacement fields
and print statements, or any strings for that matter. By the way, something
that I did wrong. You don't even need the
format in here because while obviously we're not using the
replacement fields anymore, so I apologize for that. Parameter substitution
is done using the cursor execute method. They are indicated
by the question. Obviously, in the SQL light, these are very helpful. You can use them in the execute. For example, right now
if I write click and I run and I just provide it with the number
and I hit Enter, we should see that we
have another update. If we write click and we run, and we try to provide
the number with the drop table contacts, boom. Nothing. Oh, it does get
updated. There we go. As you can see the oh, because we've already
committed the changes. That's why we have
this. Let's try to add a few Xs in here.
Right click and run. And let's strike this again
with the drop table contacts. Boom, there we go. It did not update even though we've provided the
number correctly. But that is because we
tried to drop the table. Let's try this again with just the number and we
should have access. There we go. Very nice. So let me just take it
back and that is enough. All right, so now that we've understood what
placeholders are, let's go and try and use them when we're working in
the check B in here. What if we wanted to
get the information for only a specified name? Instead of getting all of the information
from the contacts, let's just get the name
of a certain individual. So I'm going to get the input in here and I'm going to say, please provide the name. To search for. I want you to pause
the video and I want you to try and
get this yourself. Time's up in here where name is equal to question
mark and then name. I will actually,
let's not do it here. Let's instead do it down here. Let me take this
part and let me put it here where the
ask from contacts. Let's first work on the rose and then we will take
it back to the from contacts where name
equals question mark n comment be here. This should be this. Yes. Let's right click and let's run the name that we're
looking for is Michael. Hit Enter. All right,
what do we have in here? Michael? Michael, everything is up but there's still a problem. The first loop worked. And actually maybe we should get rid of the
first loop just so we know what is happening
exactly in here. If I try Michael, boom, what is happening in here? Cult three, programming error, incorrect number of
binding supplied. The current statement uses one and there are seven supplied. Is it telling us that we've
supplied seven items in here? What do you think is the
problem if you're not sure? Let's try another name. Let's hit Enter. It's telling us that we've provided five.
What is happening? What's happening is that the parameters we're
sending should be couples. When we did it right here, you can see that we
provided the new e mail and the phone under the
form of a couple. We've sent in a couple. What's happening here is when
we're sending in the name, what it's doing is it's
dissecting the name. We're getting K, L, E and we're getting
five elements supplied. That's where the number
five comes into play. And if we run and we
provide it with Michael, Michael is 123,456.7 That's why it's telling us that
we are providing seven. What's the solution in here? We add parentheses around
the name with a comma, which makes it into a topple. Now if I write click and I run, and I type in hopes Michael
hit Enter. There we go. I only get the
information of Michael. And if I try to right
click and run and try to get the
information of Kalen. Boom, there we go. I also only get the
information of Kalen. Of course, this could be applied right here in this format. If I remove this and I say in here space where
the name is equal to this and then provided with on the name right
click run in here, just Michael and I get the
information for only Michael. Thanks so much for watching.
I hope you enjoyed. But before we leave, there is a small hiccup here. That's why you always
have to test your code. If I write, Click and I
run and I type in Michael, I don't get anything. Hmm, that's not good at all. So what should we do in here? We should give you a challenge. Did you think that
I would forget about giving you a challenge? No. What should we do? Look for how you can
send in parameters to your SQL queries without
worrying about the case. This is some research
homework for you to do, test it out in our program. And I will give you a hint, but I do recommend that you go and try to do this yourself. Use the like instead
of the equal. Pass the video right now
and go do the challenge. Okay, welcome back in here, instead of using where name
is equal to the peace holder, we'll use the like and
we'll use the like. Now if I write click
and I run and I type in Kalen without any upper case
on the K and I hit Enter, I still get the
correct information. Thank you so much for
watching. I hope you enjoyed. In the next video, we're
going to be looking at introduction to exceptions because we need to handle exceptions in case
some errors come up. This is not just useful
for SQL language, it's especially useful
for SQL language, but it's useful for any field of Python that you're
looking to learn through. I will see you in a few seconds.
147. 13. Introduction to Exceptions: Welcome back my favorite python programmers to a
brand new video. And in this one we're
going to be looking at an introduction into exceptions. I think that this
video is going to be exceptionally
long because we have a lot of information
to cover and this could have been a
separate section on its own, but I decided to keep it in this section using
databases in Python. It's very important
that we learn this not just for
database and SQL, but also for anywhere
else that you might encounter this throughout
your professional career. For this, we need to create
a new project in here. And this project is of
course going to be Python. And make sure to save it
in the appropriate place. And I'm going to call this
the exception handling. And finish up. Yes, this window. First of all, I'm
going to create a new Python file and I'm
going to call it the examples. Just a few examples where
we're going to look at very surface level errors that can occur.
And what happens? First of all, we're
going to say x equals eight equals five. Now obviously this is something that by
fund doesn't like. As you can see,
even before we run, we already have this
error right here. Test that you cannot
assign this literal. If I try to write, click
and Run, there we go. Syntax error cannot
assign to a literal, meaning you cannot assign five to the number eight.
You cannot do this. This can be saved by a simple correction where
the student, or the user, or whatever just
made a mistake and they were intending on
writing eight minus five. Now, there we go. No more error. Of course, this is a very simple or surface level error
that can happen. Let's look at something
more serious. For example, if I
do the following. If I say that I want y to be
equal to x divided by zero. Now this is a different
type of error where we don't have any indication
with a red line. Before we saw that even before running the program,
there was something wrong. Now, there's nothing wrong. But you should be aware that dividing by zero
is a big no, no, we have an error
specifically for that zero division
error, division by zero. It's not possible.
As you can see, the issue here is that sometimes we might
get an indication, sometimes we might not
get an indication. And we have many different
types of errors. So I'm going to show you
the following website, and of course I will
provide it somewhere. If I don't, please contact
me and let me know. So this is the built in exception in the
Python documentations. You can go through
this entire website, understand properly
all the exceptions. So for example, except
except buffering errors, these are how should I
say it more in depth? Things like the buffering
error and the lock up error. But still you can find any
error that you want in here. If I do control andintype in
zero division, there we go. So raised when the
second argument of a division or modulo
operation is zero, if I try to search for value. For example, value error. There are many
iterations of this. There we go, raised when operation or function
receives an argument that has the right type but an inappropriate
value. There we go. As you can see, there are many
different types of errors. You can go through all of them. Also, I recommend that you
check out this website, so this is a more compact way because sometimes
as you can see, the documentation can
be very overwhelming. Like what do I need to
look at right here? And by the way,
the table is also very crucial to understand. You don't have to go through and remember every single one. But now at least you can
go back to this website and see a few examples. Now right here, the
Python built in exceptions are also
very important. This is W three schools. It's one of my all
time favorite. I've been using it since I
think I was like 11 now. I'm much older than that. I've been using this for
years, more than 15 years. Amazing website,
highly recommended. They're not sponsoring me, although I would take
their sponsorship and actually I would do it for free because they were incredible. Again, go through the exceptions,
Look at what we have. For example, index error raised when the index of a
sequence does not exist. They've created, compiled
a very nice list in here and I recommend
that you go through it. I will have the link
somewhere around. But let's go ahead and try to create something called
a recursion error. Meaning that when a function
calls itself too much here, I'm going to do the following. I'm going to define
a new function, which is going to be,
actually I think. Let's comment these out. Let's define the
function at the top. And we'll just have this, we'll have the count underscore down and we'll count until
n. Then in here I will check if n is equal to zero, then I will print of last. Then I'm going to print out
n. Then I will count down. I'm calling the same function, but this time n minus one. This is a recursive function, meaning that it calls itself, what does this happen,
what does this do? I mean, if I print out
countdown I provided with. Actually, we don't
need to print. I apologize because
we already have a print inside in here. I will do ten. If I write click and
I run look at that, we have 109-876-8321, Blastoff. We have a blast off. This function can have its problems because if
we do 100 and write, click and run, we
do get a blast off. If we do 1,000 boom, you can see that we were
able to get to five, and then suddenly we
had a issue in here. And that issue was that we
repeated 993 more times. The Python went into its
maximum recursion depth. It was exceeded while calling
or calling a Python object. This is another error
that can come up. So how do we catch these
errors and how do we make sure that they do
not break our code? As you saw right here, we can do that using exceptions and try
and get exception. Exceptions are objects
that are created when an error or exceptional
condition occurs. Just like we saw right now, what you're seeing are
objects being created. Just like I told you, everything
in Python is an object. Almost some built in exceptions in Python
are value error, type error, file not found, error, and the zero
division error. These are just a few examples. Accept is a statement
that allows you to handle these errors and I'm going to show
you how it works. The tri block contains
the code that you want to try to execute. The accept block contains
the code that you execute if an error
occurs in the tri block. So the final block contains
the code that you execute. The final block contains the
code that you will execute regardless of whether or not an error occurs
in your tri block. And we're going to look at
the final block later on, but for now we're going to
work on the tri except blocks. In the next video, we will
look at the final block. Let's see how we
can use this tri except block to make
sure that we don't get the recursion error back in here where we
call our function. So this is the code that
we are trying to run. What I'll do, and you've
probably seen this before, we are going to try the code, then we're going to do
an exception in case we have a recurs or
recursion error. We're going to print out
the counts are too many. What should we call the
counts are too many. Then in here we will print out program program terminated. If I write click and
I run, look at that. Instead of getting
an error and having our code stop or break. Instead we have
the counts are too many and that the
program is terminated. And I added the sprint just to show you that we
actually were able to continue down the
lines of our code. And this is great,
especially on the user side, it's usually better
to be explicit when presenting the potential
exemption that would occur. But sometimes you might not
know what the error could be. So right now, sure, we know that this is a recursion error because
we've tested it out. And we know that we
called the count down too many times, but what if? We had a small
potential error inside. And obviously, again, I want you to take this
with a grain of salt. And here, of course,
this would not happen. But what if it did? What if we were trying
to divide this by zero? Now if I write Click and I run, you'll see that our code
breaks again. And why is that? It's because we were
simply trying to catch the recursion error and not
the zero division error. To fix this, we can
do the following. I can say except zero division
error, then print out. You cannot divide by zero. And I write divide
incorrectly, divide yes. Now if I right click
run. There we go. You cannot divide by zero. That's great. We've
got the second error. But there is a more
efficient way of doing this. Instead of having two
different exceptions, we can create something like
this, zero division error. Close this down, and we can
simply comment this one out. So in here, the counts
are too many or you divided by zero, okay? So this allows you
to, of course, this is not as specific
as we had before, but this can help you
raise an exception in case you have just a
general error catcher. And you don't want to use multiple lines to catch very specific errors
unless you have, for example, different types of codes that you
want to execute. Not just a print
in case you have a zero division or in case
you have a recursion error. But in situations like these
where you just have a print, you're just printing
something to the screen, it's not as important. For example, when
you're entering your E mail and you type in your username and
then you type in your password and
it's not right, one of them is incorrect. When you hit enter, they
don't specify, for example, that your password is wrong or that your username is wrong. They tell you either your username or your password
are written incorrectly. In that case, you have
something like this situation. Okay, I hope that is understood. Now let's go ahead
and try creating a program that
would have a lot of potential errors for us and create the necessary
exceptions for that. I'm going to go into file new and create a new Python
file that we're going to call operations bull and
close the examples down. And I should have had added an underscore between
the catching operations, but that's okay for now. We'll have number
one equals flowed input the first number. Duplicate this number two flow, enter the second number, then I'm going to have result equals number one
divided by number two. I will print out the result is two dots result. Okay, there we go. Before we even launch, you probably know
that there could be a lot of potential
issues in here. Like for example, having
number two being zero. This is just off
the top of my head. Now what I want to do
is I want to issue you a challenge to catch them all like Pokemon. Get
a catch them all. First of all, catch all the possible errors
that might occur. I want you to take the
time to think about them, because there should
be at least two. The important part
is knowing where the Troy block starts and where the exception
block should be added. I don't want you to go too in depth and think of all
the possibilities. Just think of two, at least. The main important thing I
want you to do in here is to know where to add the block. And I'll give you
a bit of a hint, you should have value error
and zero error division. These are the two
or the first two. I want you to think
of a third one. Buzz the video right now. Sorry, I forgot to give you a few seconds before
showing you the hint. I just thought that these
are very new things. Maybe you're still overwhelmed. Buzz the video right now
and go do the challenge. Okay, how did you get
on with that first? Or we need to create the tri
block for the value error. I'm going to tab this. I'm going to add the tri
block right here at the top because this is where the
errors would start here. Or after we try to
print out the results, I'm going to create the accept. We are going to
have a value error. I'm going to put in here. You need to be inputting some, you need to add an
actual number in here. If you went through and you
read about value error, you should know that
if we, for example, try to just hit Enter
on the first number, we get an error that you need to add an actual number in here. You can't just have
a. If we didn't have, I should have tried this before. Actually, let's just copy the
code and add it right here. I will right click
and I will run. And I will just hit Enter. And there we go. You
can see that we get a value error and
our code breaks. This is the first thing that
we need to watch out for. The second thing, or
the second exception should be the zero division, because we've already
seen it before. I'm going to print out who the heck still divides by zero, Go back to school. Right click, run
first number 12, second number zero, the heck still divides by
zero, go back to school. Now, in all fairness, we should at least indicate that
we are going to be dividing number
one by two so that the person knows that
they cannot enter a two. But that's beside the point. We've got the zero division. The last exception
we can think of is an overflow where the
number is just two big. I'm going to add an extra
one in here, an extra line. I'm going to say
that the result is equal to result multiplied by not multiplied to the power of 1,000 I don't
know if that's enough. Let's try 10,000 Right click, run 12 to boom. There we go. An overflow 34 result is just too large. How
do we handle this? Well, here we say, except overflow
error and we'll just say number is too
big to represent. All right, click run 125, sorry, number is too big to represent 2.4 Where
did we get that? Oh, it's the normal result
that we have in here. And then the result of the
multiplication was 2.4 Now, you might be thinking, wait, Michael, you cheated.
You cheated. I saw you, you cheated because you added an
extra line of code. How could I have known that
this is an overflow error? Well, even if I removed this, and I know this is
going to be hard. But for example, if I type in, let's say just one, I type in 0.0 0000
0000 0000 0000. A few 0.1 okay?
That still works. I mean, if you type in
enough zeros at some point, the number is going
to be too big. Let me try and actually
do this. Let me run. I don't know, even if I will
get okay, that still works. I think we need a lot more. And at this point, I want to thank you so
much for watching. I hope you enjoy it, and I will see you in the next video. But if you're interested in this experiment,
let's test it out. Uh huh. Who? Oh, oh, oh, okay. So it considered it as zero
before we had an overflow. Okay. You can say,
Michael, I cheated. I did cheat. So what
can you do about it? Thanks so much for watching. I hope you enjoyed sorry for
the very, very long video, but I believe this wasn't a too hard of a video
to think about. That's why I kept it as big. There were no very tiresome
things to think about. So in the next video, we're
going to be looking at the finally block and how it works and how it
can be very useful. Thanks so much for watching. I will see you in a few seconds. Bye bye for now.
148. 14. Finally block in Exceptions: Welcome back my fellow
Python exceptists. Let's continue on working
with exceptions and we're going to be looking
at finally blocks and a few extra things in here. First of all, let's say we want to have a
general exception, we're not sure what it is, we just want to catch
some kind of exception. We can do the following. We can then, as then in here, I can print out
unexpected error, expected error, two dots. Yeah, there we go.
The warning is gone. If I right click and I run
and I don't provide a number, you need to add an
actual number in here. As you can see, we
went down through this list and we actually
caught it at this point. Let me, for example,
show you if I remove this overflow error and I turn
this back on right click, and let's say 125 result,
Unexpected error. And I get the result
is too large. As you can see, just in case we want to catch general things, we're not sure
what they will be, We just say unexpected
error and do the following. Now let's look also
at the finally block. Finally, if I type it in and
print out this finally block will execute less
of just regardless. If in here I let me remove
this right click and run. And if I type and 125, hit Enter, there we go. This finally block
executes regardless, we don't get any errors. If I take this back on right click 125 again,
we get an error. We handled it, but the finally
block executes regardless, the final block will execute whether there is an
exception raised or not. It is used to maybe used for clean up options such as closing a file or
closing a database. And we'll be using the
finally block a lot. And you'll see a lot of
use cases for it later on. Now we also have the L in here. If we test it out,
you can see that for some reason we can't
have the finally, it needs to be below
the exceptions. And before the finally
in here I will add an L L. We could say, for example, division
was successful two. Let's comment this one out because it always
causes an error. If I write the click
and I run 125, boom, 2.4 division was
successful, typically used, or the else clause is called when there are no
errors getting caught. This can be useful in
situations where you want to ensure that if the code
correctly you provide something. Meaning that some code in case
everything goes smoothly. One last thing before
we move on to raising our own exceptions
is that the order of the exceptions is
also very important. Catching more specific
exceptions before catching the more
general one is better. The reason for this is that if a specific exception is caught
before a more general one, the program can take
appropriate action to resolve the exceptions and prevent more severe
consequences. For example, if let's say move this hold
down control shift. Or hold down shift down, shift alt, shift alt. And I move it right
here to the top. You'll see that I first of all have exception supercluster, exception has already
been cut, see that? So right click and run, and if I just hit Enter, Unexpected error could not
convert string to float even though the issue here
wasn't that we weren't able to convert a
string to a float. The problem in here was that we just did not
provide a number. So we have to be more specific. The more specific we
are at the beginning, the better the results
are going to be. So thank you so much for
watching. I hope you enjoyed. And in the next video, we'll be raising our own exceptions. We'll see how we
can create or use these exceptions in a more
real world situational way, where we will be
creating a bank account, which is going to be very fun. Thank you for watching. I will
see you in the next video. And no, there are no
challenges in this one.
149. 15. Raising Exceptions: Welcome back my fellow Python programmers to a
brand new video. And in this one we're going
to be raising exceptions. First thing we're going
to do is we are going to create a new Python
file that we are going to call bank account. You think I would come up with a shorter, more eloquent name. But as I'm just a humble
Python instructor, not a name come upper
that came out back as you can see, class bank account. We're creating a new class. We're going to define the Init, which is going to take in the
underscore balance inside. We're going to set the
self balance equal, equal to the initial balance. Then we're going to define
the deposit inside. We're going to, of
course, have the self, it's already written, and the amount that we
would like to deposit. Then we're going to say that the self balance plus
equals the amount. Then we're going to define
the withdrawal with draw. Then we're going to also
have an amount in here. Of course, that amount
is going to be taken out of the balance
minus equal amount. We're also going to have the
show Underscore balance. And here we're going to
return return self balance. Okay, there we go.
This is our class. And actually I'll just remove
this extra space in here. And now we can work on
the body of our code. So I'm going to create the
bank underscore account one. And it's going to be
equal to the bank account and I'm just going to
deposit 200 inside. Then I'm going to take the
bank account one, deposit 120, then I'm going to withdraw, uh, 20 and then I'm going to take my bank account and then show the balance
just so we can see. So we should have 200 plus 120. 320 -20 We should have just 300. So when we run nice,
we don't get anything. Oh, I apologize. We need to actually
put it in a print. There we go. And now this
should come out as 300. Excellent. So we have
everything working in there. But there are a lot of
problems with this code. For example, we can create a bank account with a
negative initial balance. So for example, if
I do bank account two equal to bank account, and I can start with
a negative balance. So I actually open a bank account and I
owe them money already. So if I print out
bank account two, Dutch balance, yeah, it's
not going to look very nice. Because I have -300 and
let's make it minus 22. There we go. So let me know
what we're working with. This is a negative initial
balance, Not very good. The other issue is
that I can actually deposit and withdraw
negative amounts, which is even worse in here. For example, I will create bank account, bank
account three. And I will say
that it's equal to the bank account and
I will deposit 200. And then I will say bank
account deposit deposit -30 And I will print
out bank account three, show balance and then write click and run and
look at that I've actually deposited
negative amounts which means that
I withdrew money, but I did not call
the withdrawal, which is very bad. And I can also withdraw
negative money. So I can do the following, bank account three
withdraw and I can actually withdraw -20
which means I will add 20. So I'm using the
withdrawal to add money and I'm using the
deposit to take money out. All of this is extremely, extremely bad and we can also withdraw more
than we actually have. So all of these
are problems that we have to somehow look after. Bank account four equals to bank account and I will just
deposit in here like 100. And then I will do bank
account four, withdraw. And I will withdraw 300. And then print out bank
account four, show balance. So now I have -200 All of these are very
huge issues that we need to find a
way to get rid of, or at least terminate the program before
they actually work. And of course, I know
what you're saying, like obviously we've
created more eloquent, better bank accounts before that would handle all
of these situations. But for now, I just want
to show you how we can raise exceptions in order
to counteract this. So what is raising exceptions? So we've seen how
sometimes if we use unorthodox methods,
like unorthodox, unorthodox methods, that's
putting it lightly, meaning that when you
try to divide by zero, for example, a
error gets raised. The same thing should
happen in here. For example, before
we set the balance, I want to check if the initial
balance is less than zero, we're going to
raise value error. And I'm going to
say in here that the initial balance
cannot be negative. Now if I tried to run
this before we do this, before we actually try to do
this, we need to of course, add and accept blocks. That is going to be
a challenge for you to get it our new bank account, add accept block to our code. But that's not the
only thing that you need to do because
you need to add the other exceptions
that need to be raised in cases like the deposit
amount is negative, the withdrawal
amount is positive, and the amount of withdrawal was more than the
available amount. And finally, these all should be done inside of the
methods of our class. And of course, along with
these raised exceptions, you should add the try except
block for every single one. So pass the video right now
and go do the challenge A. Okay, welcome back. How do you get on with that? First of all, we need to add except block four when
adding the initial balance. And of course, we should add
this to every single one, But because I've created four
different bank accounts, each one with their own issue, that is why I'm only going
to add this to this one. And what we're trying is to add a negative amount in here. I will have an
accept value error because we know
it's a value error. And I'm going to print value
error as sorry as print out. There we go. What's
the issue in here? Bank account can be undefined. Undefined, we are, we're trying, this line might not execute, this might not be defined. What I'll do is I'll
move this right here. Inside of the block. We will try to create
the bank account and to show the
balance when I write, click and boom, there we go. Initial balance
cannot be negative, the bank account two did not
execute and did not work, but we did not
break our program. That's good. Next we need
to work on the deposit. Let me move this to the
side because we have a lot of horizontal space in here. And the deposit, first of
all, we will want to check, if the amount is less than zero, then I'm going to raise another value error which
is going to tell us that deposit deposit amount
cannot be negative. Oh my God, why can't I write deposit amount
cannot be negative? Where do we add the
tri block? Right here. We need to try this deposit and raise an exception or just I mean catch the exception
in here and print out. When I write the
click and I run, the initial balance
cannot be negative and the deposit amount
cannot be negative. We've got two errors so
far, that's very good. Unfortunately, there are
a few things that we also need to do which is the
withdrawal in here. On the withdrawal, there are actually two things
that we need to do. There is making sure that the amount is less
than zero and also making sure that the amount is greater than
the self balance. And what I mean by
that is, first of all, I want to check if the
amount is less than zero, then I'm going to
raise a value error. I want to say that
withdrawal amount cannot be negative and I'm
going to check if the amount is greater than
the self dot balance. I'm going to also raise
a value error telling me that in sufficient
funds, insufficient. Is that how you write
insufficient? I have no idea. Insuficienthh. Okay. I forgot the. All right, so there we go. Now, where should I add this? Well, I should try this one. It inside of the accept, let me add a space, add a tab, remove this, accept the
value error as print out. Now when I write,
click and I run, boom, Withdrawal amount
cannot be negative. I also got an error for
the insufficient funds. Let's go ahead and try
and catch these as well. Where did we do it? Right here. Right here. We're going to try except value error as
print right click, run, and there we go. We have insufficient funds. Ladies and gentlemen,
this is all. Thank you so much for
watching. I hope you enjoy it. I hope you understood
how raising exceptions can be very helpful. In the next video, we're
actually going to be creating our own exceptions. Is that I will see you in the next video. Bye bye for now.
150. 16. Creating your own Exceptions: Welcome back my favorite python programmers to a
brand new video. And in this one, first of all, we're going to do a
bit of cleaning up, where I will show you how to make this code more
efficient and look better. And then we are going to be
creating our own exceptions, so our own errors. How cool is that? So let's
go ahead and get started. First of all, as you can see, this is not very feasible. Trying to create a try and
accept at every single point. Not really good, not
really efficient. We want a better way. And that way is to do
the tri accept block inside of our actual
definitions of methods. For example, instead of creating the tri
accept block right here on the bank account
object instance, we are going to
create it inside of the It or inside of
the constructor. Inside of the constructor, I'm going to create the
try and then I'm going to tab this forward and then
I will create an accept, and then we'll have a value
error as I will just copy. We're, we're printing the print. I will say error. Boom. Replacement
field E. There we go. Now we can shift this, Remove the accept, the try, and if I right click on I
should see, there we go, that we have an arrow
bank account object has no attribute balance. What is the issue in here? At the time, no. So the problem in here is
that we got a second error. And where did that
error come from? Well, it came from, so
here we have an E. Okay, Don't worry, this is a shadow name because we've
used the E here and here. And don't worry, this
will go away later. The issue in here is
that we tried this code, but because it's a
negative balance, we haven't created self balance. And that's correct, that's
exactly what we want. But the problem is when we
tried to show the balance or I mean return the balance which was
in the show balance. If you follow the error, you'll find that we don't have a balance or self
thought balance anyway. So how do we handle that? Well, we have to handle it inside of the show
balance in here. We are going to create
a try and we're going to try if has attribute. This allows us to check if we have an attribute on the self because we're
referencing ourselves and we are checking for balance. So this is a string object, You can even hover
over the attribute, and you can see
that, first of all, we provide the object where
we want to check if they have that attribute and the string which is going to be the
name of that attribute, so it's the self, which is our own object. And then the balance name, or the attribute name,
which is balance. And if we do have
that attribute, then we will return balance. And then else what
shall we return? We're going to raise a error in here which is going
to be the attribute error. And we actually have something called the attribute error. And we're going to say
that this bank account has no balance, boom. And then we are going to do the accept attribute error as E and print out error E. Okay? So there we go. Now if we right
click and we run, we shouldn't get
this error again. We should get initial
balance cannot be negative. This is from right here. And you can see this error. And then this bank
account has no balance. And also it I
recommend that you, if you remember from the
function section that we did, one of the last sessions was
when we used color in here. I recommend that
you also use color. Make it bold, make it very obvious that there
are errors here. But that's for a static
reasons for style, I'm not going to delve into it. The main important
thing in here is that we were able
to fix this issue. You'll notice that we are
printing none because we don't have a bank account, I believe because
we've put it in a variable and tried
to print it out. Is this the line? Let
me check bank balance. Let's just make sure where
this none is coming from. Yes, it was indeed
coming from this print. Because we're trying
to print something and it's just coming out as non. I hope that was understood
and wasn't too complicated. The main important thing and
the very new thing that we learned is the has attribute
that we have right here. So let's continue on and now let's look at fixing
the withdrawal. Instead of doing
the try and accept right here or first we'll
work on the deposit. I think instead of doing the try and catching
the error right here, we're going to do it instead inside of the deposit in here. We're going to try
this first we'll, if amount is less than zero, then we're going to
raise the value error. And then we're going
to accept value error. Value error as boom. And then I'll just
copy this line. Put it here. There we go. Now if we write,
Click and we run the error deposit amount
cannot be negative. Perfect. It's working
exactly as intended. Let's do the withdrawal. So the same thing
holds true in here. We're going to do a column tab except value error as I can just copy this
and paste it in here. It's just the same. I
will remove the tri except in the body of our code. And we should have all of
the errors now done, right? Yeah, there we go. Error.
Insufficient funds. Excellent. Everything seems to be working completely fine. We were not able to withdraw
more money that we have, and we were not able to
withdraw negative amounts. Perfect. So we fixed everything. And the body of our code is much more reliable,
much more dynamic. We don't have to write every
single try and accept block for every single
transaction that we make. It's much better
to do these inside of our classes and inside of
the methods of our classes. Okay, so I hope that
was understood. Now it's time to start
creating our own exceptions. I'm going to create a
new Python file in here, a new Python file, and I'm going to call
it creating exceptions. Exceptions. And let's actually add an underscore just in case we want to use
it somewhere else. In here, I'm going to create
a class which is going to be invalid transactions or transaction this class is going to inherit from
exception exception. If we hold control and
we go to exception, you'll see that it's a, it's a common base class for
all non exit exceptions. We can see that we can
initialize it right here, we have some static methods, we can do a few things
with this exception. Mainly you can obviously
go and read all about this exception class
in much more detail if you go to the
Python documentation. But for now we're just going to use it on the surface level, I'm going to define
the It in here inside of the it we are going to be sending in the message. Then I'll have the self dot a message equal
to the message. And I will do a super
because I want to call the top level super in it
and then Seselft message. Obviously you can create much more intricate classes of these invalid
transaction errors. But for now we're just going
to keep it very simple. I'm going to create a class bank account the same
that we had before, but a little bit simpler. So I'm going to
define the It with an initial balance balance, okay? I forgot the here. And
then I'm going to say solve balance equals
initial balance. And then I'm going to
define the deposit. And we'll have an
amount in here. I'm going to do two things. I'm going first of all,
to try and check if the amount is less than zero, which is something that
we've done before. I'm going to when am I going to raise the invalid
transaction error. And what's wrong with deposit? Deposit may be static. Okay. No worries
about that in here. And I'm going to send in
the message deposit. The Posit amount amount
cannot be negative. We are going to also
in here say that self lot balance plus equals amount and I'm going to catch the exception, invalid transaction
error as E and print out error to dots
replacement field. There we go. Then I'm going to define the withdrawal
withdrawal. Of course, we'll have
the self and the amount. And we're going to check
for two things in here. Actually, let me just copy
this code and modify it. Boom. In here, K value error
instead of value error, we're going to have the invalid tactvalidvalid
transaction. We should be done with this. Let's, I think all of
these are well created. Now, before we continue on, I do have a challenge for
you to create an exception. So I want you to create
an exception for the negative initial balance. And I want you to use it, because keep in mind we
haven't created it yet. To create your own exception, it's basically like creating a class that inherits
from exception. We've already covered that. But I just wanted to give you some extra hints because
this is something new. So your definition should be class negative, initial
balance, error, exception, and right here, exception, meaning
that it inherits from the exception based class. It needs to have a constructor that takes in a message and sends it to the constructor of the exception class
using the super. Pass the video right now and
go create your own errors. Welcome back. How did
you get on with that? Right here, two lines below, I'm going to create a class
and I'm going to call it a negative initial balance error which inherits from exception. I will just have the
same in it that I had in the invalid
transaction error in here. I hope you tried to
do this yourself even though it wasn't
part of the challenge. But try and catch it right here. We're going to try to check. If the initial balance
is less than zero, then I'm going to raise the
negative initial balance, telling the user that
balance cannot be negative. Oh my god. Let me check. Okay, so we will hit that
because this should be part of the tri block we're trying to
create the initial balance. And then we will do accept negative initial
balance error as E and we will print out
error. There we go. So this is our bank account. Let's try to create a
bank account in here. Bank underscore
account one equals to bank account -300 Right click. We should get the error. Initial balance
cannot be negative. All right, let's make it normal. Do we get any errors? No, we don't. We don't
have any printing. It's okay. No need
for the show balance. You want the extra exercise? I do recommend that you
create the show balance with its own error or exception that you can raise in case
somebody doesn't have the attribute bank account
one, bank account 300. Let's now try to deposit
some negative money. -30 Right click run. We should get deposit amount cannot be negative. Very nice. Let's try to withdraw
negative amounts of money. Amounts of money
cannot be negative. Withdrawal amount cannot
be negative. Perfect. What else can we do? And by the way, like we can
do something like this. Okay. It will not allow us. Let's try to just
raise this so we can see our own error in play. Right click and run.
Boom. There we go. Invalid transaction
error. How cool is that? Withdrawal amount cannot
be negative? There we go. You can see that we were
able to raise our own. So thanks so much for
watching. I hope you enjoyed. In the next video, we're
going to be making our bank account much
more sophisticated. So I will see you then
where we will also be like we will start building a new project which is a
bank account database. So it's going to become
much more sophisticated. We're going to be using all of the things that
we've done so far, including the
exceptions, including the databases,
including the classes. So this is going to be one
of our biggest projects. So I will see you then. Bye bye for now.
151. 17. A More Sophisticated Bank Account: Welcome back my favorite python programmers to a
brand new video. I think this one is
going to be a short one. We're just going
to be setting up our bank account database because this is going
to be the start of, I don't know how big this
project is going to be, but it's going to be
a fairly big project. First of all, we're going to
go into file new and we are going to create a new
Python project next. And it's going to be called the bank account database book. Open project in
this window. Yes. Then in here I'm going to create a new Python file which is going to be the bank accounts. There we go. Now we have a bank
account class in here. I'm going to create
class bank account. It's just going to
inherit from object. Obviously we don't
have to do this, but sometimes you get in
the habit of doing things. I think it's a good
habit to have. Then we are going to initialize it and this one is going to be much more complex
than the other one. We're going to have
deep annotation. The name is going to be an STR. The initial underscore balance is going to be of type float, and we're going to set it to be 0.0 We're going to give
it a default value. Then we'll have self
name equals name. And in here we need
to add a space. Then we are going to
have the Self Balance. And it's going to be equal
to the initial balance. And I will print out the account created for replacement field
self name. There we go. And we will also
show the balance, but we still don't have that. So let's add a comment in here to show balance. Then we are going to define
the deposit deposit. We're going to have the self and the amount which will
be of type float. It will also return a float. We're going to add the arrow in here saying that it
returns a float. And we'll check if the
amount is greater than 0.0 we'll have balance plus
equals the amount. We are going to print out replacement field
amount deposited. We will return self balance. By the way, I want to
make balance hidden, I will add an underscore
behind balance from now on. It's better to have it hidden. Let's continue on and let's
now work on the withdrawals. In here, I'm going to define the withdrawal again
with the self, again with the
amount which will be a F and it will return as well. And then in here
I'm going to check if we have the amount between or greater than zero and
less than or equal to self dot balance, then I will have the
self dot balance minus equal the amount. I will print out
replacement field amount. With draw, I will return the amount else
I'm going to print out. Now in here, I was
always thinking, should I create exceptions
for this particular project? To be honest with
you, I just felt like maybe right now it's not a good idea because
we want to focus on the actual database
handling of things. Later on, we will add exceptions to the
withdrawal deposit. We will keep these simple. We will add try and
accept blocks when we are working with executing
database commands. It will be much more
important there, but for now we'll just
keep things simple. We'll just have
conditions and we will work within the
needed parameters. In here, we will say
the amount must be greater than zero and
shouldn't exceed, shouldn't we need to make it
into a special character. Shouldn't exceed account balance And we will return 0.0 Finally, we are going to define
show underscore balance. Let me close this one down so that you can have
a better shouldn't. I think it's just so
okay. No worries. So balance self. And we will simply
print out in here, balance for account replacement. Field name is replacement field self
Balance. There we go. This is our bank
account we've covered, I think almost everything.
Oh yeah, Yeah. There we go. In here, we just show balance self. So balance, This is when we create our bank
account right here. Let's go ahead and test
it out with a few lines, I'm going to create Michael. And it's going to be
the bank account. The name is going to be Michael. No initial deposit. We're going to get Michael and deposit 10.5 Click and run. Let's see what we get as an
answer account created for Michael Bank balance of account. It maybe should be Michael's
account, I don't know. It is 0.0 10.5 deposited. So let's try to withdraw Michael Withdraw 2.5
Let's see what we get. Boom. Okay. 2.5 Withdrawn. Withdrawn. I think it should
be withdrawn at that time. You write withdrawn. Yes.
Okay. Withdrawn. Nice. Do we show the balance? I
don't know if we should show the balance every single
time we make a transaction. We'll see, we'll see how this progresses and we will
work accordingly. Let's just do the show
balance right now, manually. Right click and run. So is that correct, 10.5
-2.0 that is correct. Let's make another withdrawal of 2.8 Let's just see
how accurate this is. Show balance, right click, run. There we go. 5.2 Thank you so much for watching.
I hope you enjoyed. We're just setting
things up because in the next video we're
going to be adding database to our backcount class and start really putting all of these things
into databases. And we're going to be working
with a Database Explorer or a browser that will allow us to look
through our database. It's going to be
so, so much fun. So I will see you then.
Bye bye from now.
152. 18. Adding a Database: Welcome back my favorite Python programmers to a
brand new video. And in this one we're
going to be adding a database to our bank account. First of all, we need to establish what we're going
to be actually doing. We want to create a
database for two things. We want to create a database for our accounts and a database
for our transactions. So we're going to
have two tables, and let me show you how these tables are
going to look like. First of all, we're going
to have the account table, which is going to be
a very simple table. We'll just have the names, which is going to be PK. Now, what's a PK? Pk
means primary key. And we've already seen
what a primary key is before when we were working
with the movie's database. Meaning that the
primary key, well, is a key that is primary and
it cannot be duplicated. The name is going
to be a text and we want to make sure
that it is not null. Then we have the balance
which is going to be an integer and it also
should be not null. Then we have the transaction
table which is also going to have its own primary
key which is going to be, which is going to be
of type time stamp and it's also going
to be not null. Now, time stamp is a value
or has values that store data of time and of a certain event and they
are automatically updated. And I will show you
how all of that works. Actually, I'm not the one
that's going to show you, you're going to be doing
it in a challenge, but that's for a
few minutes later. First of all, we need to also know that the account is also going to be a primary key. Yes. Every table can have
multiple primary keys. It's going to be a text and
it's going to be not null. And finally, we will
have the amount which is going to be an integer
and it also should be not. Let's now look at a challenge
that you will have to do. You'll need to
create two tables, just like we've done before
where we imported Esqulite, created the connection,
etcetera, et cetera. You will have to do
the same inside of the bank account class file or what was it called?
Let me just check. Yes, bank account class. First you need to
establish a connection. Use the connection
to execute queries. Make sure that the tables don't exist already and we've
seen what that is. And set the primary
key and make sure that the fields are not not now. If you're uncertain
of how to do this, this is the perfect
opportunity for you to go and research how
to do this stuff. Please take your
time, do your best. There's no rush, but it's very important that you start
doing things on your own, especially at this point. We, of course, this class or master class
will always be updated, but we are almost at the end
of the usual or normal one. So please take your time. Go try to do your best. And I will see you a few
seconds. Welcome back. How did you get on with that? First of all, right,
here at the top, I'm going to import
my Sqlite Three. Then in here I'm going to
create the connection. I will say B, we can call it
connection, we can call DB. It depends on what
you want to do. Sqlite three connect and
we're going to connect to Accounts Light, there we go. We will create a
new file in here. I'm going to have the B execute. And we will want
to create table, if not exists accounts
inside of accounts. We're going to have
the name which is going to be text and it's going to be primary key null. This is what we needed to write in order to create the name. And we're also going to have the balance which
is an integer null. Now of course, there are flaws with this stable
and this database, having a name as a primary
key is not really good. Because imagine if two people called Michael wanted
to open the account, it's better to have an ID that would automatically
increment. But for now, we just want
to keep things simple. So we'll just have the
name, text, primary key. No, I'm going to duplicate this because I
want to create a table. If not exists, but this time
it's going to be that of transactions and we're going to have a few different things. Transactions. What did
I write Incorrect. Okay? I add an extra in there. First of all we're going
to have the time and it's going to be of type time stamp. I'm actually going to add or hit Enter in here to
go to a second line. Then we're going to have
the account which is going to be of type text,
it will be not null. And finally we have the
amount which is integer. Why can't I write
today integer and it's going to be not null. Finally, we want to make sure that we have these
two primary keys. Now in here, we don't need to specify that this
is a primary key, because we will have
two primary keys. What we can do is we can
write it this way key. The, oops, come on account. We could have set primary key
here and primary key here. But we can also do it this
way if table not exists. Transactions time,
time time null, account text null amount, integer, okay, looks good. And we have the
class right here. Now we're going to make a few changes to our
constructor so that it retrieve information from the database and
fills data as well. If the data is not in the table, we're going to create one
and add it to our table. Right here in the T, I'm going to create
a cursor object. In here I will have the cover. And it's going to be
equal to b execute. And I'm going to have select name balance from counts where name
equals placeholder. And let's add spaces in here. Remember, because we've
already talked about this, these should be topples in here. We'll have row equals
cursor, fetch one. Then we're going to check row. Meaning if we have anything inside of row and it's
not just an empty, then we're going
to say self name. Self underscore
balance is equal to row and we will print
out account record. Retrieved. Is that how
you write Retrieved guys? I'm a Python instructor. I have no retrieved.
Yeah, there we go. I'm very bad at English, so four self. There we go. This should be good else, meaning that we don't
have any roles. We are going to
create that role. But before we actually say
that we've created it, we want to actually
execute it or insert it into our table cursor. We are going to insert into
accounts values in here it. And the values will
be placeholders. And then we're going to
have name, initial balance. And of course, we need
to commit these changes. Cursor commit or
connection commit. Boom, there we go. And
something to keep in mind. You might think that I
just printed out account created by convenient ways. I put it right here
under the insert. But it's actually very
important that we as print out that the account was created for name after we make sure that
we've committed our changes. Because sometimes you might run the program or do something
and the connection with the database did not
commit and then you print out account was created
when in fact it hasn't. So it's very important
that we do this. And actually in here, the
last thing I want to do, maybe we can just
show balance anyways. I don't think so. I think we
should only do it in case. But you know what? The
only issue is that sometimes I think we should
show balance anyways. Because if we retrieve a value, we would like to show
the balance if we haven't retrieved a
value and created one. Instead, we also want
to show balance. So the show balance
should be on the outside. So as you can see, let's try to run this program, write a click and run. We should get the
following bank account balance balance balance, 5.0 Okay, there we go. So account created for Michael. This was the first run. Let's now try to write
the click and run and we should get account
record retrieved for. And let's hope this works. Yes. Nice. As you can see, the account record now was
retrieved for Michael. It wasn't created for
Michael, it was retrieved. If we go in the
accounts esculite right here into our project files, we can see that account
Este was created. Before we move on, let's create a few more bank
accounts in here. I'm going to duplicate this
twice and I'm going to Kalos bank account are obviously going to be Al Thomas
capital K capital. Let's also create one for Mark. I want to have many accounts mark 500. Let's give Galen
35400 at the end. We always need to
make sure to b close, let's write, Click and run. And we should see that we
get three accounts created, account retrieved for Michael, then account created for Kalen, then account created
for Thomas as well. If you write, click
and we run again. Boom, there we go. You can see that balance for
Michael is zero. This is because we haven't
provided anything. And then the accounts
for Thomas and Kalen in fact, retrieved. Before we move on,
there is something very important that
I want you to do that is go to this website and download
the database browser for Su. This will allow us to look through the database
that we've created. Let me show you how this works. Once you've downloaded
it, it's very simple. Just scroll down or
just click on download. Find which version
you need to download. It's very simple. You should have something
looking like this. This is the database browser. Then I want you to
go into Skylight. Let's try dragging it directly. Let's putting it right here. If I drag it directly, I don't think it works. Yes, no database file
opened. Okay, no problem. Right click and
open with Explorer. We should have opened it right
here. Okay, there we go. Now, from here, I think we can drag it. Yeah, there we go. So as you can see,
we have two tables. We can even see how
these were created. Let me just set things up. So right here we can see
that we have accounts, the name and the balance text. Null integer not null. We can even see that
it's a primary key by the small gold key next to the name under
the transactions. We also have time
account and integer. And we can even browse the data. So you can see right here on the accounts we have
Michael with zero, Kalen with 350, Thomas with 400, and Mark with 500. And if we go to
the transactions, we don't have anything yet. But we will soon enough please download
the database browser. You can even look through the database that
I've provided you, the movies one, it's going
to be very, very nice. You can go through, see all
the actors, see everything. And you might be thinking like, why didn't you show
me this before? Like I've been wasting my time
doing select and whatever. Because I want you
to get in the habit of finding things without
the database browser. This is a crutch. This is not something should be taught or should be shown at the
beginning, in my opinion. This should be later on when
you already know how to retrieve data using
just QL command lines. When you can do
that confidently, you get to enjoy the ease of the database browser.
I hope you enjoy it. I hope you understood, and I will see you in the next video, where we will actually
be updating and inserting inside of our
withdrawals and deposits. So I will see you
then. Bye bye for now.
153. 19. INSERT Withdrawals and Deposits: Welcome back my favorite python programmers to a
brand new video. And in this one we're
going to be updating and inserting withdrawals and
deposits into our database. I hope you downloaded the database browser
because it's going to be, or it's going to come in very handy as we progress
through this. So first of all, we
need to make sure that we do everything properly, Meaning that whenever we make a deposit or whenever
we make a withdrawal, that it's added to the
balance of our accounts. So let's go ahead and
get started with that. First of all, inside
of the deposit, after we check that the
amount is greater than zero and we are going to create a new balance which
is going to be new underscore balance is
going to be equal to self, but balance plus the amount. This one right here, I'm just going to
remove it because we're going to be creating
completely different code. This one we're going to keep, but we're going to be writing
new code and you'll see the justification for
creating a new variable. And just a bit, first of all, we need to set the deposit time. We're going to create
deposit underscore time and it will be equal
to pytZutclocalize. Then we'll have
datetime time utc now. Date time time utc now. And we've seen this
before in our oop, or object oriented
programming section. I hope that you're familiar with what's
happening in here. Even if we didn't go too
much in depth into this, you should be familiar that this just returns our current time. Then we're going
to do DB Execute, and inside I'm going
to update Accounts, set balance placeholder, where the name equals
a placeholder. And we're going to
be replacing these with the new balance. The balance will be
the new balance. That's why we created a variable forward and self name for the name of the account. Then we're going to also do
insert into transactions. Insert into transactions values. And the values will be
three placeholders. And then we will have
the deposit time, self dot name and the
amount that we had. And finally we will commit bit. After we've committed
and we make sure that the
database was updated, we're going to then update
the balance in our object. Finally, we will print out that we've actually made the deposit. And I actually can separate
these so that we have a clear distinction
between where we are working on the
database, on this part. Actually it's just
these three lines. But you know what, actually we can separate these. This is where we work
on the database, this is where we just
set some variables up, and this is where we work
on the actual object. So there we go. So in here, we create a new variable, which is going to
be the new balance, because we want to use
it right here to update the balance of the
database of that account. We deposit the time, and we do the execution, we update the balance
because remember we already have these
accounts present. You cannot deposit to an
account that's not there, that's why we are
updating the account. But when it comes to inserting or when it comes to
the transactions, we need to insert
and not update. In fact, we cannot
update transactions. That wouldn't be right.
We don't want to be able to change transactions up. As you can see, everything
in here makes sense. But there is something
that we can do in order to alleviate the pain of looking at this
line the whole time. And we've done it before
because we're going to be updating the time
the same way always. It's a good idea to
create a static method. Right here at the top,
I'm going to create a static static method. And it's going to
be the underscore, get underscore current,
underscore time. You've already seen this before, so I'm going to be returning, where is it, Bo. This line, we're going
to be returning this, but we're also going to
add with the IS time zone, which if you have or over it doesn't provide
you with anything. It will just take me back to
my current time zone which is not a good idea
because you will know my approximate location.
But that's okay. I have guns I'm in are
we're going to have the bank account get current time and it will provide us with the current time. Now that we've done
this, if for example, right click and I run, let's see, no such
table as account. What are we doing in here? Wrong? New balance account. So let's see, in here should be account. Right click and run. Boom, There we go, through
the balance in account eight. Let's look at our transactions. If I refresh look at that, how cool is that? Actually, we actually
have a date. We have the account Michael and we have the amount 10.5 Why? Because we've deposited
10.5 Let's try and maybe duplicate this
and maybe make this, I don't know, 6.5 or
6.3 right click run. And now if we look
back at our database, we'll see when we
refresh that we also have 10.5 Now this
should be obvious to you, it's because we are constantly
updating our account. And you'll also notice that Michael's account
has actually grown. Why? Because we're committing these changes and because they
are on top of each other, they are building up. So now our data is
actually being saved. But as you can see,
if we run this again, we are going to get another
10.5 and another 6.3. There we go. So these
are our transactions. Well, we are finally
working with databases, so our actions actually
have consequences. But before we continue on
and look at this deeper, we need to set up the
withdrawal as well. And it's going to be
a challenge for you. So your challenge is to, just as we updated the deposits, you need to update
the same or need to do the same for the withdrawals
in the withdrawal method. Make sure that you make
the appropriate changes. There is only one small
change that you need to make, so we'll need to find it, post the video right now, and go do the challenge. Welcome back. How did
you get on with that? First of all, we make sure that the amount is less than the self balance and
greater than zero then, just like we did before, we're going to say that
the new balance, actually, I'm going to cheat and I'm going to
copy all of this. How about that boom? Because it's almost identical, but there are a few changes. First of all, obviously the new balance is going
to be minus the amount. The deposit time is
going to stay the same. Bank account do
get current time, this is not going to change. We are going to be updating the accounts and we're setting the balance
where the name, it's all the same to the new
balance and the set name, this line does not change. Next we have the Db dot execute. We're going to insert
into transactions values the deposit
time set name, but this time the
amount is going to be negative because
we are withdrawing. And then finally we're going to of course be committing
the changes and we're going to be setting the albot balance
to the new balance. And this line is
no longer needed. As you can see, it is
basically the same. And we're going to take
advantage of that in just a bit. But for now, let's just list out what we've done,
right? Click and run. So we've made a few withdrawals. If we write, Click in
here and we look, boom, there we go, 2.5
and 2.8 withdrawn. And you can see
that our values are starting to get a bit murky. The reason for this
is because we're having small floating
numbers changing, and that can sometimes cause Python to start
making mistakes. We're going to figure
this problem out. Maybe we can just show like two numbers or just one
number after the decimal, even though it's
not a great fix. But in order to fix this, it's a meticulous task. I'm going to try and
find an easier one. I haven't done so so far. So that's why I'm going to
keep things the way they are. But somewhere down the line
when I update this course, I will make sure to
get rid of this issue in the most simple way possible. With that, out of the way, there is something that we
need to look at right here. You might have noticed that we actually have duplicate code. We have the same exact code
with only small changes. What should we do
when we have that? We need to extrapolate this
information into a function. I'm going to create a new
function in here which is going to be right under the
in it. It's going to be. Right here. Define underscore,
save, underscore update. And we're going to have self
and the amount sent in. I'm actually going to
base this right here. We're going to create
the new balance which will be the self balance plus the amount you'll see when it comes
to the withdrawal, we're going to be sending in the negative amount which
will translate into a minus amount right here,
which is going to work. And the code in here
will stay exactly the same inside of the deposit. Instead of writing all of this, we can simply do self save, update and send in the amount. And do the same. All right
here, update the amount. But what do we do in here? We send in a negative amount, so the only difference
is going to be the use of minus one. And before we test things out, I want to take back the balances
of our accounts to zero. Michael right now
has 55.6 You can see that it's reflected
correctly in the database. Okay. So in the database
we don't have any issues, which is actually the
most important part where we do have issues is
in the display of Python. I don't think that's
a huge problem, to be honest with
you right here. All that we need to do
is just type in zero and we need to make sure
to write the changes. If I write click and I run, you'll see that the
balance goes back to zero. Now, unfortunately I forgot Actually, let's go to account. As you can see, 11.5 it is accurate in the transactions,
we still have these. What we can do is we can select
all of these and delete. Wait. Select all of these
and delete, There we go. Write the changes
back in the account, set this to zero,
write the changes. Now when I write
click and I run, I should see officially we Michael has zero,
okay? No problem. We should see in the
transactions, 10.5 deposited, 6.3 deposited, 2.5 withdrawn,
and 2.8 withdrawn. If I go to the
transactions, there we go. We have everything
represented accurately. So I hope you're enjoying
what you're seeing. We are actually doing
very advanced stuff, so you'll probably be facing similar things when
you are working with a computer or real Python
developing environment. In your work, of course, it will be much more complicated with its own intricacies, but this is the basics of it. You have objects,
you have databases. You are updating
things here and there, everything is working together. In the next video, we're
going to be looking at rolling back transactions and seeing what would
happen if we have some kind of issue when
we're doing our updates. So I will see you in the
next video. Bye bye for now.
154. 20. Rolling Back In SQL: Welcome back my favorite Python programmers to a
brand new video. And in this one
we're going to be trying to break our
database to see what happens and looking at rolling back transactions in databases. So let's go ahead
and get started. First of all, we're going
to delete everything in our database to
start from scratch. So I'm going to select all the transactions
and delete them. Make sure to write the
changes and the accounts also select everyone and delete
that and write the changes. So we're going to start
simulating all things that can go wrong as we
are saving our database. So the first thing we need to understand is that we
have primary keys. And the primary keys
should be unique. Our primary key is a combination
of time and account. When we are working
with transactions, this must always be unique. Let's try making our
primary keys not unique. And the easiest
way to do this is by simply changing the
time that we have. For example, in here we
have return YZ, whatever. This is always
going to be unique. I will duplicate it and I'm
going to change it to one. And I will comment this one out. So now we are going
to get multiple ones. So I'm going to run my database and you'll see
that we have an issue. We made the deposit
and that worked. But when we tried
to make wait, wait. Let me check. When we tried
to make another deposit, we got an error. And that error was
integrity error, where the unique constraint
failed transaction time and the transaction
account were the same. If we go back into
our database and we refresh the data right here, you can see that we have
Michael 10.5 and it worked. So the deposit worked. We committed the changes. If we look at the transactions, we do have one deposit, but you can see that
the time is one. And when we tried to
make a second deposit, that did not work
because there was a time with one in there. In order to avoid
having this issue, we need to create a Tri except block inside of our safe update. Right here we have new
balance plus amount. We need to add a tri block
on the execute because it was a matter of
unique key integrity. We're going to try this
and before we commit, we are going to try and catch
an exception which will be esculite three error. Just any error that can come
up from the esculite three. And if we do have an
error we're going to get DB roll back. Then finally we will commit. What is the dot rollback? First of all, now we
are going to execute the code and if there's an
exception that is raised, we're going to do this rollback and we will always commit. But let's understand
why we always commit, because we're doing a rollback. So what is the rollback? If I hover over it, do
we get any information? Rollback, The
current transaction, okay? Makes a lot of sense. Basically, this is a function
that is used to undo any uncommitted changes made
to a database transaction. If I right click and I run, you'll see that at
least my program doesn't crash. Doesn't crash. But you'll see that there are a few things that
have gone wrong. Especially if you open up the
database and you refresh, what are the things
that went wrong? The things that went
horribly wrong. Is that right now
in the database, if I look at the account, you'll see that I
have Michael 10.5 but right here I have that
Michael has 24.8 and then 22. So the deposits and the
withdrawals are actually working, but they are not registered
in the database, which is a huge problem. It's a huge problem. So what we need to
do is we need to fix the way we are setting
the balance right here. We set the balance
regardless of what happens. And that is not correct
right before the finally, we need to add an L's
because remember, the Ls only works when there are no errors or no exceptions. And then we will have the following, what's
the issue here? Just one line, okay? So now we should, let's try and take back this zero and write changes
in the transactions. I will also delete this
one. Write the changes. Now if I write click and
I run, boom, there we go. We have 10.5 for Michael. And if I refresh and
go into the account, yes, they are the same. We've fixed one of the errors. But something to
consider here is that we wouldn't even want to
commit our database anyway. This would be a good idea for many reasons because
the less we do unnecessary transactions or get unnecessary accesses to
our database, the better. Because there could be leaking, there could be data
damage, whatever. So we're going to do the
following right here. We're not going to commit unless we have made
sure that there are no exceptions so we can get rid of the Finally and I kept it purposefully because
I wanted you to see the process of
our understanding. If I had put the Db.com directly on else you might
have been thinking like, why didn't we do it in? Finally, why don't
we commit anyway? So that's why I
did it right here. But as a final touch, it's a good idea to move
the DB commit above the update of our balance
attribute. Now why is that? This makes sure that the
balance is not updated in case the commit failed for some reason. It
can happen a lot. Sometimes you're trying
to access the database. You might think that
everything is working. In our case right
now because it's a local database and
we're using Sqlite, accessing the database
is not a huge problem. But when you're
interacting with a server and you're doing SQL commands, there might be hiccups along the way because you're
working through the Internet. You know, sometimes not everything works as
smoothly as intended. So making sure that
you first have an error on the commit
before you update the balance attribute is a good idea because
you don't want to have discrepancies between the
balance that the person sees, the user that's
using this ATM or this account sees the
underscore balance. They don't see the
actual database. The database is the back end. This is the front end. So you might be asking yourself, why would we want to roll back a transaction if commit is no longer being
called anyways, we were using the
rollback in order to make sure that none of the
committed changes work. So why should we roll
back this anyway? Well, let's run the code and look at Thomas in our accounts. Boom, If you look right here, we have Thomas that has
400 if we delete him, and then we try to
run this again. As you can see,
nothing really much changed except for something
weird happening in here. Why is it slowing down? I think there was some kind of error or some kind of slow. Okay, let me try this
again. What's happening? Stop bank account. Okay.
Keyword interrupted, line 29. Okay, let me just delete this, right click and run again. So you might be asking yourself, why would we want to roll back our transactions if the commit
is no longer being called? Because now we've
moved the commit from the finally into the else. So it will not execute unless we have everything working
and there are no errors. And as I told you,
the rollback function is used to undo any
uncommitted changes. So what is its use currently? Well, let me show you. First of all, I want to
move the creation of these three people control shift and move them down to the end. Okay? This is going
to be very crucial. Holding down control shift and moving these three
people to the bottom. Now I'm going to go
into my database and I'm just going
to delete Thomas. And I'm going to
write this change. Now if I write Click and I run, you will see that we have everything working
normally, right? So we have Michael 10.5 If we look at the
database and we refresh, you'll see that we
have Thomas and again the transactions
haven't changed. What is the actual
issue in here? Well, if I try to
remove the roll back, so I will comment this line out. I'm going to add a pass because you cannot keep the accept
without anything in it. So I'm just going to add a pass. If I now go back to my database and I delete Thomas and
I write the change, and I try to run this again. If you look at the output, we can see that Michael
has 10.5 which is, you know, it's
acceptable because we haven't made any
changes in here. Why? Because there's no correct primary key,
blah, blah, blah. But we did not make a
rollback and nothing changed. Right? Well, if I look at
my database and I refresh, there's something horrible
that, that just happened. Michael actually now
has 7.7 instead of 10.5 Which is a big,
big deal with me. When you look at the code, it looks like normal, right? There shouldn't be
any problems in here. Well, I'm not going to
tell you what it is. I'm going to issue
you a challenge. To find the problem,
you need to go through the code
step by step and understand what happens at every line of code in
order to find the problem. Yes, this is a huge challenge, but if you can figure this out, I can say with 100%
certainty that you have finally understood how to
work with Python and SQL. So pause the video right now
and go do the challenge. Welcome back. How did
you get on with that? So in order to understand
what is happening in here, we need to examine our
code very carefully. Now, a hint should
have been very obvious here that it happens
when we delete Thomas, and then Thomas
is created again. Let's go and look
at what happens when Thomas gets created, or any object for that matter, inside of the construction
or constructor. The constructor is called,
the cursor executes. Okay? We get the
row, we fetch one. If the row is there, then we have the name and the
balance equal to the row. And we say that the
account was retrieved is the account is already there in the database. Great. Perfect. No problem. But
what happens when the account is actually
created from scratch? We have the name, we have the balance we insert into
the account, and we commit. And the account is created. If you haven't gone through or weren't able to
complete the challenge, try to think which line. The problem is obviously here because it's when the
object is created, where do you, which
line has the issue? Which line is creating the terrible thing
that's happening? It should be pretty
obvious that it's happening on the
commit, on this line. What we're doing
is right here we are doing the execution
of these lines. We are updating the
account balance and we are inserting
into the transactions. Now the transactions
aren't working because we have one right here. We've made sure to
avoid this issue, but what's happening is the balance is actually
being updated. We're doing the command, we're not committing, but
we're also not rolling back. When Thomas gets created, after we've made the
deposits and withdrawals, It means that every single thing that we've done
right here actually gets updated in the database because it's
committed right here. When you commit a change, it doesn't just happen
exactly where you've said, all the commands are
written down and then boom, when you commit, everything
is committed with it. Again, let me re
explain this even though we're not committing right here in the safe update. Because Thomas is created after all of these
withdrawals and deposits. And when Thomas is
created, we have a commit, which means that
everything that we've done with the update
and the insert and everything we've done
throughout this entire database will get committed eventually because we're creating Thomas. And inside of Thomas, we're not committing
Thomas especially. We're just committing all the command lines
that we've tried to do on this connection
right now in this session. That's very important
to understand. Having the rollback is super important because
in this situation, when we do have a rollback, we roll back these
transactions right here. So let me try and
delete everything to go so that we have
everything working smoothly. I need to write the changes, write click, run, okay? Now let's go back. Right, click accounts refresh, Michael is 10.5 All right.
Everything is good. If I write click
and I run again, this shouldn't be an
issue because we still haven't recreated thomas anyway. So if we try to delete
thomas from the database, for him to be recreated again, right changes, right click run. Thomas was created
again, not retrieved. Now if we go back
into the database, we should see when we refresh that the value on
Michael hasn't changed. Why? Because we are rolling back the latest transactions
that we did. I hope that was obvious. The next video, we are going to be changing to a
different project, which is going to be
the Netflix browser, which will have TK Enter. Which is something that
at the moment where I'm recording we
haven't covered yet. But if you follow the steps, it's a very easy
thing to understand, very basic stuff, the minute details are
not going to manage. So don't freak out when
you get that part. The more important part
is to understand how we can recreate gooey. Thank you so much for
watching and I will see you in the next video. Bye bye for now.
155. 21. Creating Netflix (sort of): Welcome back my favorite Python programmers to a
brand new video. And in this one we're
going to be starting with our Netflix browser. The Netflix browser
is going to be obviously not as sophisticated
as the one that you watch. But we are going to be using our movie database that we've
seen before in order to create a graphical
user interface where we will be able
to choose a genre, choose a movie in that genre, and then select
one of the actors. Obviously, these
things will just be displayed onto our
screen using the Gooey. I'm not going to delve too deep into the small intricacies
of using K inter, which is the tool or
the module that we're going to be using to create this graphical user interface. I will later on be creating
separate projects. Maybe by the time you're
watching this current section, I will have a full
TK intercourse. But to be honest with you, it's not something that I find is worth really
talking about. Because most people that create a graphical user interface use other tools than TK
Inter and there are more modern ways of creating
graphical user interface. But I just wanted to have the simplest thing
because our main focus here is going to
be the connection between a database and Python. Without any further ado, let's go ahead and get
started by creating a new project right
here at the top, which is going to be the
Netflix browser Browser. Browser, Is that have
you, right browser? Yes, I think so. I will open it in this
window right now. The first thing we need
to do is we need to go to the movie database that
we've seen before. And we need to click and
open this in the Explorer, inside of the Netflix browser. In here, I'm going to send in
the database that we have. Where is the database? Right here, the movies. And actually I'm going to
copy and paste it right here. Now we have VDB inside
of the Netflix folders, and you should see right
here that we have VDB. Just as a cool exercise, I'm going to open this database right here in the database browser so
we can take a look at it, so we can drag in the movies. Boom. And there we go. So as you can see, we
have all of our actors, We have our genres, and we have our movies, and we also have the views
that we've created as well. So how cool is that? You can go through the
database that we had, the movie database
through this DB browser, but make sure that you don't
delete or add anything. Be careful with that. With that out of the way, let's
now continue on. The first thing we need to do is to create a new dot py file, which will be the movie browser. So we'll be the movie
underscore browser. And IntellJ just crashed. Excellent. Use the power of editing to see you
in a few seconds. Hey, welcome back. So it took me a while. With the power of editing. It should have been a
minor inconvenience, so I'm importing SQA Lit and
I'm also importing TK Inter. This is going to be the
tool that we use to create our Gooey stands for
graphical user interface, just in case it wasn't clear. So in here we're going to create the connection
which is equal to Schulte three connect and we are connecting to the Netflix or to the movies
file right here. The only issue is if we
keep on using movie B, it's not going to
connect correctly. It's going to have
some issues Now, I'm going to use
it anyway, okay? Because I like to take risks and I want to see
what would happen, and in case we
have to change it, The next thing we want to
do is we want to start creating the window for our
graphical user interface. This video will be all
about creating that window, but first we need to
actually see this window. And this is the final
result that we should have. We will have the genres, movies and actors, and we're going to have
the list of genres. The list of movies and
the list of actors. And every single time we
click on one of these, we're going to get the others. I know, not that impressive, but hang in with me. So first of all, this
is the dissection. We are going to have 1234 rows. So these are the numbers
012.3 these are our rows. The first row will
indicate the label, so the genre, movie and actors. The second row is going to be, or the row number
one will indicate the actors and the
movies. Row number two. Combined with row number one
will indicate the genres. Now the reason I did this is not for anything
in particular, but I just wanted to
show you how we can create a big list box
that spans two rows. Just some extra stuff in here. I know this doesn't
look pretty at all, but hang in with me. And then three is just going to be this
empty space in here, so it doesn't look bad. And we also have the columns, so we're going to have 012.3, Obviously, of course
the three will just be for expansive purposes. And we are going to have the
first column for the genre, second column for the movies, Third one for the actors. Without any further ado, let's go ahead and create
this window back in here. First thing we need
to do in K inter is create the main window. And we'll say that the
main window is equal to K terk K and it's a function. Then we're going to say that the main window
title is going to be net flicks rouser. Every main window also
needs a size geometry, and it's going to
be 1024 by 768. There we go. This is the
creation of the main window. Just to start
testing things out, we need to make the main loop. I will add a comment in here, equal sign or h, should we use dashes
or equal signs, We'll use equal signs here. We'll have the main loop
and 31234567, Right? Do we have seven here? Just copy so we
can have symmetry. Okay, we do have seven in here. We will say that the
main window mainloop. And then we'll print out that we are closing the connection. And connection, close. Add an extra line when I write, Click and I run,
boom, there we go. We've created the
Netflix browser. Now, obviously we still
have a lot to do in here. But this is a start. Let's close this down, and let's continue closing the connection. I can close this right here, and I can close this right here. The next thing we want to do
is we want to create all of these columns and rows
right here under this. We're going to say that we have main window column,
column configure. On the column configure, we're going to have zero
with a weight of two. Then we are going to
duplicate this four time. This is going to be the
spacer column on the right. This is the last one, and these three are going
to be the main ones. I'm going to have 012.3
with a weight of two. Now using weights and changing weights around will depend on, or will affect when we make this window
smaller and bigger. How it will affect
these columns, it will become more evident when we start adding things in there. Now other than the columns, we also need to
create the roles, I will say main window
roll configured in here. I'm going to have zero and the weight will
be equal to one. And I will duplicate
this three times. The windows in the middle
will have a weight of five. In here we're going
to have 012.3. There we go. These
are our columns. Obviously, they are not going
to be apparent when we run the program because these are just dissections of
our main window. There's nothing more
much to it right now, but we're going to see it
once we start creating, first of all, the labels. Again, I will add this
comment right here to distinguish between labels. Is it the labels? Yes. Okay. So, as I told you, I'm not the best at
pronunciations at the English K, inter label. And we're going to put
it in the main window, The text is going to be grid in order to
set it somewhere. And we're going to say
that we have row equal zero and the column
will be equal to zero. Now when I write,
click and I run, we should see at the
top, Genre is excellent. As you can see, we've
anchored to the main window. It should be in the main window. The text is genres on the grid. We set it to row
zero, column zero. The grid allows us to set it in the correct rows and columns. I will duplicate this because we are also going to
have the movies. And the actors, the role is going to stay
the same because, well, obviously we
are on the same road. The only difference is
going to be the column, so this will be column
one and column two. When I write Click and I
run bone, There we go. Now I think we can start testing how this is going
to change. Look at that. So as you can see, these are all because of the way that we've
dissected the weights. So we make sure that we can
never really crush them. From the bottom,
we can crush them, but from the side we cannot. It will always have some space. Notice how when we expand
it, it's not symmetrical. It's because of the extra column that we added on the side. Let's continue on, and now let's create the genres list box. The genres list box. First of all, we need
to create a list box. We're going to have
the list equal to K enter list box. It's going to be in
the main window. Now we need to set it properly. We're going to have
Genre list grid and we're going to set it in row number one, column zero. We have to set something
that is the sticky and we will set it to southeast west. It means we want to expand it on the entire column that we have. Then we're going to make sure
that the row span is two because remember the genres
is going to span both rows. Also we set it to northeast. It's going to cover this
entire diagonal in here, at diagonal, it's
going to cover the, let's just call it the
entire box that we have. By the way, if you're asking why are these two not symmetrical, It's because of the shape
that I've created for this browser in order to
take a screenshot out of it. Row span is two, because
it spans two rows. And finally, we have
to add a bit of padding on the right hand side, 30.0 You can always hover over these things to see
what they mean or you can always go search for
them and the documentation. Now it's giving me an
error expected type union. I think it will solve itself. I don't think there's
any huge issues. Finally, we need
to configure this. We're going to add a
small border and relief. All of these are just
small minute details about the style that
we're going to have. So when we write,
click and we run, boom. Look at that. As you can see it
spans two columns. It would have been symmetrical, but what I did when I took a screenshot is I
made it like this. Okay. Now, as you can
see things are starting to get funky in here when
we start adding things. K inter is not the most friendly
beginner, friendly thing. Honestly, I don't
like it too much, but I just wanted to stick with the basics for this lesson. The next thing we want
to do is we want to create the movies list box. The movies list
box is going to be just slightly different in here. I'm going to have
the movies list box. We're going to have the
movie list variable because the genres are always
going to stay the same. We're not going to
be changing genres, but the movies are
going to change. If you select the action genre, for example, you're going
to have different movies. If you select the documentary, you're going to get
different movies. There is going to
be a list variable which is going to be equal to the K inside of the main window. And then we're going to have
the movie variable set. And we're going to
set it for now to just choose the genre in here. I'm going to open this
up and I'm going to say choose a genre, obviously. First of all, the movie
list is going to be empty. And then once we choose a genre, we are going to have
all of the movie list. Then we're going to
do the same thing that we've done with
the genre list. But of course this is going
to be the movie list. Copy and paste it in
these two places. The list box is the main window. The row is going to stay one, the column is going to be two, and the row span is
going to be one. We're going just remove it, then we have movie configure
border two sunken. I think all of this
is good except for, I think this one is going to
cause us a bit of a problem. But when we run, we should
see that it's in the act. Interesting. Why do we
have it in the actors? Let's see, you said column two. It should be column one, right click run, and there we go. But as you can see, we
don't have choose a genre. Why is that? Because
as I suspected, we need this to be a couple. We need to stop this from
running and now run it again. We still don't get
anything in the movies. I apologize. This is why it's better not to copy
and paste code because we forgot on the list box to add the list variable
equals list variable. Now it will show. There we go. Let's try not to have a top because that was not the
issue. Okay, There we go. So it does not work
because now we have three elements
instead of just one. So we do need to have
a topple in here. There we go. Because
it's one element. If we don't provide
it with the topple, it just thinks that
each one of these is a separate element and
prints it out. There we go. Now we have the
movie's list box. Now obviously the last
thing to do is to create the act actors list box. It's going to be a challenge for you to create the actors use the same code with the
necessary adjustments to create the actors list box, close the database
connection at the end, or we've already done that. Pass the video right now
and go do the challenge. Welcome back. How did
you get on with that? I'm just going to select all of this and paste it in here. And I'm going to have
actors list box in here. Change this to to then
copy paste. Paste in here. And then this will
be the actors list. Yeah. All right,
copy paste, paste. And of course the column
is going to be two north, south, east and west, so we are putting
them to all sides. Padding 30, border two relief
sunken list variables, Close what we choose. We choose a movie, right click, run,
and there we go. Ladies and gentlemen,
some of you might be going crazy right now. But trust me, this is not something that's
too complicated. If you do want to go
deep into TK inter there are a lot of documentations
but as you can see, like these are very elementary things to
be honest with you. Like I don't see the real need to explain every single
small minute detail here. Our focus is not on creating
a graphical user interface, it's focused on creating a solid database and
this was the start. Thank you so much for watching. I will see you in the next
video where we will be adding the scroll bar
next to our list, which is a complicated topic. As you'll see, I will see you
in a few. Bye bye for now.
156. 22. Adding Scrollbars to Lists: Welcome back my favorite
Python developers. And this video
we'll start adding scroll bars in order to
scroll through our data. First things first, in
the genre list box, we're going to add
the genre scroll. In here I'm going to
have genre scroll. And it will be
equal to K scroll, scroll bar. There we go. Then we're going to
have the main window. We need to set the
orientation to be vertical, K, enter vertical. Then we are going to have
the command be equal to general list y view. Just the y view without
the function parentheses. Then we're going to have
the genre scroll grid. And we're going to
set it, of course, on row number one. It will be column column zero, sticky, north, south, east, this we're not expanding
to the west of the side. And then the row
span will be two, because remember the
genre span two rows. The genre list is
going to have this y scroll command which will allow us to actually scroll
through the data that's in the genre list and
then scroll set. That is how we
would create this. Now if I right click
and boom, look at that. I have a scroll bar right here on the right hand
side of the genres. Now before we continue on, I just wanted to
show you how we can add some information to
the movie list variable. For example, we've already seen it for any variable
for that matter, because it will be part
of your challenge. For example in here I
can add 12345, okay? So when I write click and
I run, this is what I get, 1,234.5 inside of
the movie list. And this is going to be
crucial when we want to start testing out our scroll bars. With that out of the way, now it's time for a bit
of a challenge for you to add scroll bars to the
other two list boxes, create a couple of 100 elements added to the genres to check if the scroll bar is
actually working. Pause the video right now
and go do the challenge. Welcome back. How did
you get on with that? Just like we had in the genres. I will copy this and I will
paste it in the movies. And this will be the movie
scroll, copy, paste. And then the list in here. And then the movie scroll. And what else do
we need to change? Of course, the column
is going to be one, the rose pan will not
be present in here. We also need to change
this to the movie list. And I think that is all,
if I'm not mistaken. Yes, I think we're going
to copy this as well. Put it in the actors. This will be the actors scroll. Copy based actor. Actor scroll actors list. We should be good to go. If I write click and I
run nice, our weight. We forgot the
column. Here is two. There we go. We have our
scroll bars, very nice. Now the next thing is
to add a topple of 100. And this is going
to be very simple. All that we need to do is
we need to first of all, create in here the test list. And it will be equal
to a range of 100. Oh my God, 100. And then we are going
to convert this into a couple of the test list. And I think I told
you in the genres. Okay, you can put
it in the genres, we can put it actually
in the genres. We can't put it, we need
to create a variable for the genres which is
a mistake that I did. We'll put it in the movies Red
click run and there we go. You can see that now we have a scroll bar that we can use, even the mouse wheel on. Thanks so much for watching.
I hope you enjoy it. In the next video,
we will be importing our database and actually representing the
movies that we have. I will see you there.
157. 23. Importing Our Database: Welcome back my fellow Python programmers to a
brand new video. And in this one
we're going to be importing our database
and populating our list boxes with actual information
from that database. The first thing we need
to do is we need to go into our genres
list box and well, just import data to it. So we already opened
the connection with the movies Dob and as I told
you in the first video, we might need to
change it to ask you a light for this to work. But first of all, we'll try with the B and we'll see if it works. Because sometimes things
change from time to time. And when I use
different folders, different databases, it works, sometimes it doesn't,
we'll just test it out. We're going to do four Genre in Connection Execute and then
I'm going to select Genres, Genre name from order, order by genres. That is our first command. And then for every single one, we're going to get genre
list, insert, boom. And then we are going
to put it at the end. So we'll do end, end, end. There we go. Then we're going to put in the first element
that we receive. Basically what we want to
make sure of is that there, once we bring the genres
from the database, we want to put them at the end of the list, not
at the beginning. This ensures that we do this, that we put it
always at the end. We are also extracting
from the genre, the first element that we receive when I
write, Click Iron. Boom. How cool is that? We have crime drama,
comedy and documentary. And obviously the comedy and
documentary are from what we've added before we
should remove them. I do recommend that you
remove them so we have cleaner looking
Netflix browsers. But that is up to you next. Have the ability to click on
one of these genres and have all of the movies
appear in front of us. To do it, we need to have a
way to actually select them. We're going to create
a new function that is going to
be the get movies. I'm going to actually create
it right here at the top. I'm going to define get movies where I'm going
to send in an event. And you're going to understand
what I mean by event. The event is going
to be the click. I'm going to have LB
equal event widget. I'm going to have the index. Trust me, all of
these lines are going to be explained in
slides. Don't worry. Next we're going to have the LB, which is the actual
reference to the list box. It's going to be the
cursor selection, but for some reason I'm not getting data in here
any references. Anyways, no worries.
Then we'll have the genre underscore
name equal to LB. Get no indications at all index because this will be Apple, that's
why we've added a. Then we're going to have
the genre underscore ID equal to connection execute. I will select genre ID from genre where genres name is
equal to the placeholder. In here we'll have
the genre name, that's why it was Apple. We will just fetch one. Then we're going to
create a genre list. And it will be equal
to just an empty list. And we're going to say four
row in connection execute. And now we're going to connect
it with the movie titles. I'm going to select
movies, title from movies. Let's just enter here because it's going to
be a long line where the movie genre ID is equal
to what to replacement field. And then we're going to order by movies, title genre ID. In here we're going to have
the genre list populated with the first element that we get from these roles which are going
to be the movies. Then finally in here
we're going to have the movie list variable set. And we're going to convert the genres list
into a population. We're also going
to set the actors list variable to choose a movie, even though we've
already done it, but we want to take
it always back. Choose a movie. Once we populated, come on. All right. So add a space in
here. Add a space in here. This is our get movies. What is happening in here? Now I want you to
open this code in front of you and then look
at the following slide. So first of all, we have
LB equals event widget. This gives us the
list box reference, so we can use it. So this is a reference to said list box when we actually click on
one of the elements. Next, we want to
fetch this element. Which element have we actually clicked inside of
the list list box. The or selection function used on a list gives us a
topple of the elements. And we want to get the ID's out by accessing
the first element. We click on one of the
items inside of our list. We get access to that element, and now we have a
reference to it. We have to extract from that index the name of the
genre that we clicked on. We do the following
LB, get index. This line retrieves the value of the selected item at the
specified index using the get. And the trailing comma
converts it into a topple with a single element, because remember we're
going to be using it later on in our placeholder. Then we have the genre D
equals connection execute. And everything
inside this selects the genre ID from
the genre table, filtering based on the
provided genre name and the fetch one method that you
see at the end is going to retrieve the first row of the result and then the value of the genre ID is assigned
to the genre ID variable. Finally, we have
the four loop which selects the name
column from the movie stable or the title filtering based on the genre
ID obtained earlier. And the results are ordered
by the name column. The four loop iterates over
each row and we receive the query result TLDR
too long to read. Basically what's happening is we are referencing the list box, that's why I called
it LB, by the way. Then we access the index. Where did we click
on that list box? Then we get the information
from that index. We click somewhere
in the list box, we extract the information. And now we can use
that information, which is the genre name, to go through our database
and find the genre ID. Once we find the genre ID, we can go into the movie table
and based on the genre ID, get all of the movies
that we have in there. For row D connection, we are going to append our
list, our genres list. Actually I'm thinking here, maybe we should change this
to the movie genre list. The movie genre list, I think it's better
because we are populating the movies list. This should make more sense. The movie list variable set. We convert this into
a couple and then we change on the final, which is the on the
actors list variable set. Choose a movie in order
to populate the actors. Let's see if this works. If I write click and I run, then you can see that
if I click on Crime, Interesting, I still
don't get any. Well, we actually need to
bind this method or call it in the genres right
here at the bottom. I'm going to say
that the genre list, but I will the clicking of the box select. And this is an event
that happens when we do, we get movies, but we're
not calling the function, this is the actual event, the list box select. When I click on Adventure, I don't get anything
because I have an error, which tells me that. Not rock. There we go. So now when I write,
click and I run. Hopefully this time when
I click on Adventure, I get Pulp Fiction and
Lord of the Rings, Return of the King. If I click on the crime, I get the Godfather
drama, Comedy Action. Of course, in comedy and documentary we don't
have anything. And you can see right here on the actors, we choose movie. So if I choose movie, well I don't get anything. I just get an error. And this error will always
be common for some reason. I just can't figure
out how to fix it. But anyway, we have
a working selection. The next thing to
do is to do the same for our get actors. So it will be a
challenge for you, which is to create
the get actors. So use the same code as in the get movies to create
the method actors. Make sure to make the
necessary adjustments in the code and the query. And pass the video right now
and go do the challenge. Okay, welcome back. So I am going to select all of this and just control
D to duplicate. I'm going to call
this Get Actors. I'll be event widget course. Select the movie name, sorry, the movie name get
index the movie ID. And we're going to
have movie name here and we're going
to have movie ID here. Select the movie ID. Movies do movie ID
from the movies where movies title is equal to the movie
name and we fetch one. We have the actors
movie list actors list. Copy this and paste it in the, in these two places. And then we select the act first name from actors. And where the movies
where the actors do movie ID order by the act
first name we go. Then on this one I don't
think we need to add anything on the actors variable. We will be setting
it right here. We'll be actually setting
the actors movie list to a list variable, to a couple of the
actors movie list. Yes, this is, I
think everything. The last thing to do is
to actually bind it. Acts are actually
movies in here. I'm going to have the list bind. We're going to list box select. Come on the get actors
not calling it. Everything is set, I believe. I don't think we
have anything else. Right, Click, run. We have an error because
this is badly formed. Where are we talking about? Okay, Binds here. It doesn't, I'll, Right, there we go. So we select action, we
select the dark night, and we get all of the
actors except for this still error that
I cannot just get over because it just
doesn't make any sense. We are selecting
everything properly, but unfortunately, as you
can see, we don't get. Now, the last thing I
would like to change is, for example, if I
click on Drama. Okay. I have a
different list or is it good actually know what I
think we are all done in here. Ladies and gentlemen, thank
you so much for watching. I hope you enjoyed and
this is basically the end. I'm not sure if we are going to do anything extra later on. Actually, no. I do believe
that we are going to be adding much more projects
to this master class. Thank you so much for watching. Thank you for going through
this entire course. Trust me now, with
all the knowledge, if you really took the
time to understand everything that we've
done so far, I mean, there's nothing
stopping you from becoming an amazing, amazing, amazing Python developer in whichever field that you want, whether it be data science, data analytics, or anything
else for that matter. Ladies and gentlemen, thanks
so much for watching. It has been an
honor teaching you. And I will see you anywhere
that we can see each other, any social media, anywhere else. I will always be there. Thank your instructor. Be grateful for their help
and I will. Yeah, that's it. I'm not sure what to say. This is the end. We're
just wrapping up. I hope we got to know each other on a deeper level.
Bye bye for now.