Afrikaans
Akan
Albanian
Amharic
Arabic
Armenian
Azerbaijani
Basque
Belarusian
Bemba
Bengali
Bihari
Bosnian
Breton
Bulgarian
Cambodian
Catalan
Cebuano
Cherokee
Chichewa
Chinese (Simplified)
Chinese (Traditional)
Corsican
Croatian
Czech
Danish
Dutch
English
Esperanto
Estonian
Ewe
Faroese
Filipino
Finnish
French
Frisian
Ga
Galician
Georgian
German
Greek
Guarani
Gujarati
Haitian Creole
Hausa
Hawaiian
Hebrew
Hindi
Hmong
Hungarian
Icelandic
Igbo
Indonesian
Interlingua
Irish
Italian
Japanese
Javanese
Kannada
Kazakh
Kinyarwanda
Kirundi
Kongo
Korean
Krio (Sierra Leone)
Kurdish
Kurdish (Soranî)
Kyrgyz
Laothian
Latin
Latvian
Lingala
Lithuanian
Lozi
Luganda
Luo
Luxembourgish
Macedonian
Malagasy
Malay
Malayalam
Maltese
Maori
Marathi
Mauritian Creole
Moldavian
Mongolian
Myanmar (Burmese)
Montenegrin
Nepali
Nigerian Pidgin
Northern Sotho
Norwegian
Norwegian (Nynorsk)
Occitan
Oriya
Oromo
Pashto
Persian
Polish
Portuguese (Brazil)
Portuguese (Portugal)
Punjabi
Quechua
Romanian
Romansh
Runyakitara
Russian
Samoan
Scots Gaelic
Serbian
Serbo-Croatian
Sesotho
Setswana
Seychellois Creole
Shona
Sindhi
Sinhalese
Slovak
Slovenian
Somali
Spanish
Spanish (Latin American)
Sundanese
Swahili
Swedish
Tajik
Tamil
Tatar
Telugu
Thai
Tigrinya
Tonga
Tshiluba
Tumbuka
Turkmen
Twi
Uighur
Ukrainian
Urdu
Uzbek
Vietnamese
Welsh
Wolof
Xhosa
Yiddish
Yoruba
Zulu
hi my name is mosh and i'm going to be
your instructor in this python course in
this course you're going to learn
everything you need to get started
programming in python python is one of
the most popular programming languages
and every day people use it to do cool
things like automation they use it in ai
as well as building applications and
websites like instagram and dropbox so
if you're looking for a job python is
for you in this course i'm going to
teach you everything you need to get
started with python we're going to talk
about all the core concepts in python
and then we're gonna build three python
projects together here's the first
project we're gonna build you're gonna
learn how to create this beautiful
website for an imaginary grocery store
here on the home page we can see all the
products in the shop and we also have an
admin area for managing the stock we're
going to build this using a popular
python framework called django now if
you have never built a website before
don't worry i will teach you everything
from scratch you're also going to learn
how to use python in machine learning or
artificial intelligence so you will
learn how to write a python program that
will predict the kind of music that
people like based on their profile just
like how youtube recommends videos based
on the videos you have watched before
i'll also teach you how to use python to
automate boring repetitive tasks that
waste your time you will write a python
program that will process thousands of
stretches in under a second i've
designed this python course for anyone
who wants to learn python if you're a
beginner don't worry i will hold your
hands through this entire course you're
not too old or too young and python is
super easy to learn you can write your
first python program in literally
seconds plus i'm going to give you
plenty of exercises to help you build
your confidence writing cool python
programs my name is mosh i'm a software
engineer with two decades of experience
and i've taught over 3 million people
how to code i'm super excited to be
teaching you python in this course so i
hope you stick around and learn this
beautiful and powerful programming
language
this tutorial i'm going to show you how
to download and install python on your
computer so the first thing i want you
to do is open up your browser and head
over to
python.org
on this page click on downloads here you
can see the latest version of python
currently at the time of recording this
video the latest version is python 3.7.2
chances are in the future when you're
watching this tutorial there is a newer
version of python available don't worry
all the materials you're going to learn
in this course will apply to the latest
version of python as well so let's go
ahead and download python 3.
all right now look at your downloads
folder here we should have python 3
installer simply double click that
if you're on windows you're going to see
this checkbox here
add python to path this is really
important make sure to tick this box
otherwise you're not going to be able to
follow this tutorial
if you're on a mac you're going to see
an installer like this with this setup
wizard we can install python 3 on our
computer so simply click continue and
again and again i agree with the license
agreement
and install it
this is going to take a few seconds so
i'm going to pause the recording
all right we have successfully installed
python3 on our computer let's close this
all right next we need to install a code
editor we use a code editor to write our
code just like how we use microsoft word
to write documents we use a code editor
to write code now there's so many code
editors out there the one that i'm going
to show you in this tutorial is pycharm
that is one of the most popular code
editors for writing python code you can
get it from jetbrains.com
pycharm
now more accurately pycharm is
considered an ide which is short for
integrated development environment and
that's basically a code editor on
steroids it has some additional features
that makes it really easy to rate code
so let's go ahead and download pycharm
now here on the download page you can
see two versions of pycharm one is the
professional edition which has
additional features and you'll have to
pay for them the other is the community
edition that is absolutely free and
that's what we're going to use in this
tutorial so go ahead and download this
as well
now once again look at your downloads
folder here you should have pycharm so
double click this
now if you're on windows you're going to
see an installation wizard simply click
next next next until you install pycharm
if you're on mac you need to drag and
drop this icon onto the applications
folder so drag and drop
all right now let's double click this to
run it
the first time you run pycharm you're
gonna get this warning because this is
an application that you download from
the internet so let's go ahead and open
it
next you're gonna see this dialog box
for importing some settings leave this
to do not import settings it doesn't
really matter
okay on this page select i've never used
pycharm you can see some keyword
shortcuts that might be useful in the
future just accept this and down the
bottom click the next button
and then next again
one more time and finally start using
pie chart
so here's the main page of pie chart
that you're going to see every time you
open it click on create new project
this is the location for our project
let's call this project hello
world
now before clicking create expand this
item here
make sure that base interpreter is set
to python 3.
python interpreter is basically a
program that knows how to execute python
code it will interpret or translate
python instructions into instructions
that a computer can understand now mac
computers by default come with an older
installation of python that is python 2.
it's considered legacy which means it's
no longer maintained or supported so
earlier we downloaded python3 make sure
that this is set to python3 if not from
this list select python 3.7
all right now let's go ahead and create
this project
now here right click on hello world
folder and go to new
python file
call this file app.pi
so by convention all python files should
have this pi extension
all right let's go ahead
now let's collapse this project panel by
clicking here and write our first python
program simply type print pr int all in
lowercase open and close parenthesis and
inside this parenthesis add quotations
you can either use single quotes or
double quotes
now in between the codes write your name
i am mash hamadani so let's write that
here
so this is your first python program
with this piece of code you can print
your name on the screen
now to run this go on the top
under the run menu click run also note
that there is a shortcut associated with
this command when i program i always use
shortcuts because that increases my
productivity so here on a mac computer
the shortcut is control option and r on
windows is different so let's go ahead
with that now it's asking where you want
to run this click on app
now down below
you should see this little terminal
window this is like a little window into
our program so here we can see the
results or output of our program in the
future as you learn more python you'll
be able to build applications that have
a graphical user interface or gui that
is a little bit complicated so for now
we're going to use this little terminal
window to see the results of our program
so as you can see my name is printed
here now as you write code this window
might get in the way so you can always
resize it or minimize it by clicking
this icon here
so this was our first python program now
if you didn't see the result i showed
you in this video use the comment box
below and tell me what error you
encountered i'll do my best to help you
move forward
in this python tutorial we're going to
take this program to the next level
we're going to make it more interesting
so i'm going to show you how to draw a
dog here
as part of this tutorial you will learn
how python code gets executed and you
will also learn about a few programming
terms
so press enter and on line two write
another print statement so print open
and close parenthesis add a quotation
now here we want to draw a dog so i
don't know that is the head of our dog
followed by four hyphens one two three
four so this is the body all right now
one more time
another print statement with quotations
now we need to draw the legs so add a
space
followed by four vertical bars so like
this
so here's a little imaginary dog now
let's run this program and see what we
get so in the top right corner you
should see this play button click that
there you go so we have our name and
right below that we have our imaginary
dog
now what you need to understand here is
that our python code gets executed line
by line from the top
so earlier i told you about python
interpreter that is the program that
knows how to translate or interpret our
python code into instructions that a
computer can understand so when we run
this program by clicking this icon here
python interpreter starts executing or
running our program line by line from
the top so first it executes line one
then moves on to line two and so on
so this is how python programs get
executed now let me show you something
cool let's add another print statement
with quotations now in between the
quotations add a star or an asterisk
like this now after the quotation and
before the parenthesis add a space once
again add an asterisk space
10.
what is going on here
well
anywhere we have quotations like here or
here we're defining a string a string is
a programming term which means a series
of characters so here we have a string
we also have a string on line three
as well as line two and line one
now here we are multiplying the string
by number 10. so this is the
multiplication operator just like the
multiplication operator we have in math
so with this piece of code we can draw
10 asterisks on the terminal let me show
you so let's run this program one more
time there you go
so we have 10 asterisks
now what we have here this piece of code
here
is called an expression an expression is
a piece of code that produces a value so
when py's interpreter tries to execute
line 4
first it will evaluate the code that we
put in between parentheses so it will
evaluate our expression our expression
will produce 10 asterisks and then those
asterisks will be printed on the
terminal
now as an exercise you can use this
print statement to draw another shape
you can draw a heart a ball whatever you
like i will see you in the next tutorial
one of the questions i get a lot on my
channel is how long does it take to
learn python and become job ready well
there is no single answer it really
depends on you and how much effort and
commitment you want to put into this but
i would say if you spend two hours every
day consistently
after about three months you should be
able to write basic python programs but
quite honestly that doesn't get you a
job
in order to get a job you need to
specialize in one area what do you want
to use python for do you want to use it
to build web applications or desktop
applications or do you want to use it in
machine learning and artificial
intelligence so whatever you want to do
you need to take additional courses for
example if you want to become a web
developer in addition to learning python
you should also learn about html css
some javascript and django which is a
popular python framework for building
web applications learning all these
things would take you another six months
so in total you need nine to 12 months
to become job ready at that point you
can get a junior developer job with a
salary of about 50 to 60 000 a year now
as you work more as you do more python
projects your resume starts to build and
you can ask for 100 000 a year or 120
000 a year depending on where you are
what company what geographical area it
really depends so there is no single
answer so are you excited to learn
python and get started on this career
path
if you are i would encourage you to make
a commitment and spend two hours every
day practicing python and use the
comment box below and let me know why
you're learning python what do you want
to do with it what's your dream job i
would love to hear your story
in this python tutorial you're going to
learn about variables which are one of
the most fundamental concepts in
programming they're not specific to
python they exist in pretty much every
programming language out there
we use variables to temporarily store
data in a computer's memory here's an
example let's type price equals 10.
when python interpreter executes this
code it will allocate some memory then
it will store the number 10 in that
memory and finally it will attach this
price label to that memory location
as a metaphor imagine we have a box in
that box we have number 10 and price is
the label that we put on the box
now we can use this label anywhere in
our program to access the value that we
have in that box this is a very
simplified explanation
so now let's print price on the terminal
print now this time we're not going to
add quotations because if we put
quotations here we will see the text
price on the terminal not the value of
the price variable so delete quotations
and type price
now let's run this program one more time
there you go so we see 10 on the
terminal
so this is how we define variables we
start with an identifier which is the
name of our variable then an equal sign
and finally a value now more accurately
when this number 10 is about to be
stored in the memory first it will get
converted to its binary representation
so this number 10 that we have is in the
decimal system which has all the digits
from 0 to 9. computers don't understand
all these digits they only understand
zeros and ones so when we store the
number 10 in the computer's memory first
it will get converted to its binary
representation which would be a bunch of
zeros and ones like zero zero one zero
zero one whatever i don't know then it
would get stored in the computer's
memory so let's take this program to the
next level
on the second line we can update the
value of this price variable so we can
reset it to a new value like 20. now
when we run our program we should see 20
because as i told you before python
interpreter executes our code line by
line from the top so first we set price
to 10 then we reset it to 20 and finally
we print it on the terminal let's run
the program
there you go so we see 20 here okay
now these numbers that we have here are
whole numbers without a decimal point in
programming we refer to these numbers as
integers so an integer is a number
without a decimal point
we can also use numbers with a decimal
point for example here on line 2 we can
define another variable called rating
and we set it to 4.9
now in programming refer to this kind of
number as a floating point number or
float for short so we have integers and
floats
we can also define a variable and set it
to a string for example
name equals mosh
we also have another kind of value which
is called boolean which can be true or
false they are like yes and no in
english here's an example i'm going to
define a variable is underline published
so we use an underscore to separate
multiple words in our variable's name
we set this to
true
or
false these are the boolean values
now note that python is a case sensitive
language which means it's sensitive to
lowercase and uppercase characters so
when defining variables we should always
use lowercase letters but here false and
true are special keywords in the
language so if we spell it with a
lowercase f python doesn't understand it
you can see we have a red underline here
which indicates an error so make sure to
spell this with a capital f or if you
want to set this to true make sure
t is capital
so in this program we are storing simple
values in our computer's memory simple
values can be numbers which can be
integers or floats or they can be
strings or booleans but in python we can
also store complex values like lists and
objects and that's what i'm going to
show you in the future
so before going any further i want you
to do a little exercise imagine we're
going to write a program for a hospital
so we're checking a patient named john
smith he's 20 years old and is a new
patient i want you to define three
variables here for his name his age and
another variable to tell if this is a
new or an existing patient so pause the
video and spend one minute on this
exercise when you're done come back
continue see my solution
all right so here we need three
variables the first one is the patient's
name
we said that to
john smith we can also call this full
name these are both valid names for our
variables
the second variable is for the age of
our patient so age is 20
and finally we need a variable to tell
if this is a new or an existing patient
that's where we can use a boolean value
so we define a variable is new and we
set it to true
so you have learned how to print
messages on the terminal window in this
tutorial i'm going to show you how to
receive input from the user so we're
going to write a small program that asks
the user's name and then it will print a
greeting message customized for that
user
so instead of prints we're going to use
input
now both this input and print are
functions that are built into python as
a metaphor think of the remote control
of your tv on this remote control we
have a bunch of buttons these are the
functions built into your tv you can
turn it on turn it off change the volume
and so on in python we also have a bunch
of functions for common tasks such as
printing messages receiving input and so
on so we're going to use the input
function
now whenever we have this parenthesis we
say we're calling or executing that
function it's like pressing a button on
a remote control so we're going to call
the input function
and in between parentheses we want to
add a string to print something on the
terminal
what is your name
with a question mark followed by a space
you will see why in a second
so this input function will print this
message on the terminal and then it will
wait for the user to enter a value
whatever the user enters this input
function will return so now we can get
that value and store it in the memory
using a variable so we get the result
and put it in a variable called name
okay
now on the second line we want to print
a message like hi john or hi mosh
whatever so print
quotations hi
with a space now after the quotation we
want to dynamically print
what we have in the name variable so we
add
a plus sign and then name
so here we have hi which is a string
we're concatenating or combining the
string with another string that is what
we have in the name variable
so here's another example of an
expression remember what is an
expression it's a piece of code that
produces a value so this expression
concatenates or combines two strings
let's run this program and see what
happens so run
okay here's the question what is your
name
mosh now note that earlier we added a
space after the question mark we did
this so
here in the terminal window the cursor
is separated from the question mark
otherwise it will be so close so let's
type whatever here press enter now we
get this message hi mosh
now here's a little exercise for you i
want you to extend this program and ask
two questions first ask the person's
name and then their favorite color and
then print a message like mosh likes
blue
so pause the video do this exercise and
then come back continue watching
all right so here's the first question
right after that we're going to call the
input function one more time this time
we're going to ask a different question
what is your favorite
color
now we get the new value and store it in
a variable called color or we could call
it favorite underline color either works
and finally we're going to change what
we pass to the print function
so first we print the name
then we concatenate this with a string
here we're going to type likes
we also put one space before and after
likes and once again we concatenate this
with the favorite color so
favorite color
now let's run this program
so what is your name
mosh enter favorite color blue enter
we get this message mosh likes blue
hey guys marsh here i just wanted to let
you know that you really don't have to
memorize anything in this course because
i put together a cheat sheet with
summary notes so you can quickly review
the materials in this course the link is
below this video
so i have done my best to create the
best possible python course on youtube
and i really appreciate it if you
support my hard work by liking this
video and sharing it with others so they
can learn as well and be sure to
subscribe to my channel for more
tutorials like this alright now let's
move on to the next tutorial
in this python tutorial we're going to
write a program that will ask the year
we were born in and then it will
calculate our age and print it on the
terminal so let's start with our input
function input
let's print birth year followed by a
colon and a space
now let's get the return value and store
it in a variable called birth underline
year
so as i told you before we use an
underscore to separate multiple words
next we need to calculate the age so we
define another variable called age
and here we do some basic math currently
we are in 2019. so let's write an
expression like this 2019 minus birth
year
now finally let's print
age on the terminal let's run our
program and see what happens so
my birth year is 1982.
enter oops we got an error what is going
on here
so whenever you say this red message
that means there is something wrong in
your program with the information here
we can find exactly where the error
occurred so
next to the file you can see the file
that generated this error in this case
that is
app.pi so currently our program has only
a single file but real complex programs
often have hundreds or even thousands of
files so in this file on line two this
is where we got this error and right
below that you can see
the piece of code that generated this
error so that is where we're calculating
the h and right below that you can see
the type of the error in this case we
have a type error and here's the message
unsupported operand types for
subtraction
and and
stir
so int is short for integer and that
represents a whole number
and stir is short for string so here
we're subtracting a string from an
integer and python doesn't know what to
do with it let me explain so i'm going
to close the terminal window
so after the first line is executed we
have this birth year variable set to a
string so whatever we type in the
terminal is always treated as a string
even if we type a number in other words
when we run this program this burst year
variable will be set
to a string
with four characters one nine eight two
this string is different from the actual
number 1982 one is an integer the other
is a string
right so
back to line two
where this error occurred
at runtime which means when we run our
program this expression on the right
side of the assignment operator is going
to look like this
2019
minus
string 1982.
python doesn't know how to interpret or
how to evaluate this expression
to fix this problem we need to convert
this 1982 into an integer and then we'll
be able to subtract it from 2019 and
that is very easy so far you have
learned about two built-in functions one
is print the other is input we have a
few more functions for converting values
into different types so we have int for
converting a string into an integer we
also have float for converting a string
into a float or a number with a decimal
point and we also have bool for
converting a string into a boolean value
so
to fix this problem
we need to go back on line two
and
pass this birth year variable to the int
function like this
int parenthesis like this
so we pass this string to the in
function int will convert it to an
integer and then
python interpreter will be able to
evaluate this expression now let's run
this program one more time
so birth here is 1982 enter so i am 37
years old
in python we have a useful function for
getting the type of variables for
example let's print the type of birth
year so right after line one let's print
now here we're going to call another
built-in function called type
and now let's pass
birth year
okay now similarly after line three
let's also print the type of h so print
type of age
okay let's run our program
so birth here one more time 1982
okay here's the result so the type of
burst year as you can see
is a class of stir or string
we'll look at classes in the future so
for now don't worry about them and also
below that you can see that the type of
the age variable is int or integer
so here's what you need to take away
whenever you use the input function you
always get a string so if you're
expecting a numerical value you should
always convert that string into either
an integer or a float
but here's a little exercise for you i
want you to write a program ask the user
their weight and then convert it to
kilograms and print it on the terminal
so pause the video do the exercise and
when you're ready come back continue
watching
all right so let's use our input
function
and ask for the weight
in pounds
here we get the weight
in lbs or pounds
now we need to convert this into
kilogram that is very easy so we define
another variable weight underline
kilogram or kg we set this to
weight underline lbs
times
0.45
and finally let's print weight
on the line kilogram let's run this
python program and see what happens
so my weight is 160.
all right once again we got an error
can't multiply sequence by non-end of
type float so as i told you before this
input function returns a string so we
cannot multiply a string by a float
python doesn't know what to do with it
so in this case we should convert this
number to an integer or a float and then
multiply it by 0.45
so let's call the int function
and pass weight underline lbs and run
our program one more time
160
okay so i am 72 kilograms
in this tutorial you're going to learn
more about python strings so i've
defined this course variable and set it
to python for beginners now earlier i
told you that you can use both single
and double quotes to define a string but
there are times that you have to use a
specific form otherwise you're going to
run into issues here's an example
imagine we want to change this string
into python's course for beginners so we
want to add an apostrophe like this
pythons
course
for beginners you can immediately see
this is going crazy
because our string starts here and then
terminates here all these characters
that we have after the second apostrophe
python interpreter doesn't know what
they are so to solve this problem we
need to use double quotes to define our
string so we can have a single quote in
the middle of the string so let's change
this to double quotes now you can see it
adds another double quote to close it we
have to manually remove this
and also one more time at the beginning
of the string
we need to add another double quote now
you can see the error is gone so if we
course
we see
python scores for beginners
beautiful now let's say we don't want
this apostrophe here so we have python
for beginners but we want to put
beginners in double quotes
once again if you add a double quote
here python interpreter gets confused
because it assumes the second double
code indicates the end of our string so
it doesn't know what these characters
are
so to solve this
we need to change our double quotes to
single quotes like this and then we can
add double quotes in the middle of the
string
now let's run this program
there you go so we get python for
beginners
so these are the cases for using single
or double quotes now in all the examples
i've shown you so far we only deal with
short strings but what if you want to
define a string that is multiple lines
for example what if you want to define a
string for the message that we send in
an email in that case we need to use
triple quotes so let me delete this
now we add three quotes so one two three
there you go
so we have three quotes to start our
string and three to terminate it again
these codes can be single or double
quotes okay
now with this we can define a string
that spans multiple lines for example we
can say hi john
here is our first email to you
thank you
the support team
like that
now
let's run this program and
here's the result so
we get this beautiful multi-line string
now let's change this back to something
simple
so we can look at other characteristics
of strings in python so i'm going to use
single quotes and set the course name to
python for beginners
here we can use square brackets to get a
character at a given index in this
string let me show you so to get the
first character we use square brackets
and type zero so the index of the first
character in this string is zero in
other words this is how
python strings are indexed zero one two
three 4 and so on so the index of the
first character is 0 the second
character is 1 and so on so let me
delete this and run this program
we get p
we can also use a negative index here
and this is one of the features that we
don't have in other programming
languages as far as i know so with the
negative index we can get the characters
starting from the end so if i pass
negative 1 here assuming that 0 is the
index of the first character negative
one is the index of the last character
so when we run this program we should
see s let's run it
there you go we get s if we pass
negative two this will return the second
character from the end let's run it one
more time
now we get r because that is the second
character from the end okay
so pay close attention to this square
bracket syntax because quite often it's
the topic for online python tests or
university exams so if you're preparing
for a python test make sure to watch
this tutorial one more time and
understand exactly how this square
bracket syntax works
you can also use a similar syntax to
extract a few characters instead of just
one character for example
if we type
0 colon 3 python interpreter will return
all the characters starting from this
index all the way to the second index
but it does not return the character at
this index in other words
back to these indexes
so we have 0 1 2 3 and so on
when we run this program python
interpreter will return the characters
starting from index 0
all the way to index 3 but excludes the
character and index 3. so when we run
this python program we're going to see
pipe let me show you so i'm going to
delete this line
run this program there you go we get
pipe
now here we also have default values for
the start and end index so if we don't
supply
the end index python will return all the
characters to the end of the string
let's take a look so run this program
there you go we get python for beginners
but if we change the start index to
1
this will exclude the first character so
when we run this program we see
y-t-h-o-n so p is removed okay
now similarly we have a default value
for the start index so if we don't
supply the starting index
but add an end index like 5 python
interpreter will assume 0 as the
starting index so let's run this program
there you go we get python
now what if we leave
both the start and end index well i told
you that in this case 0 will be assumed
as the start index and the length of the
string will be assumed as the end index
so with this syntax we can basically
copy or clone a string in other words if
i define
another variable here let's call it
another and set it to course square
brackets with just a colon now this
expression will return all the
characters in the course variable so
this second variable will be a copy of
our first variable let's take a look so
let's print another
and run our program there you go we get
python for beginners
so once again this square bracket syntax
is pretty important
if you're preparing for online python
tests or college exams make sure to
watch this tutorial again
now here's a little exercise for you i'm
going to delete all this code
define a variable called name and set it
to jennifer
now when we print
name
of
one
colon negative one what do you think
we're going to see on the terminal i
want you to use your knowledge to tell
what we're going to see on the terminal
without running this program so pause
the video think about it for a few
seconds and then come back continue
watching
so this expression will return the
characters starting from index 1 which
is the second character
all the way to the first character from
the end but excluding the character at
this index in this case the first
character from the end is r so r will be
excluded in other words we're gonna see
all the characters starting from e all
the way
to the second e
let's take a look so i'm gonna run this
program
there you go this is what we get and i
hope you guessed you're great
in this tutorial we're going to look at
formatted strings in python programming
language formatted strings are
particularly useful in situations where
you want to dynamically generate some
text with your variables let me show you
let's say we have two variables first
name and last name so first we set this
to john
and last we send this to smith now it's
better to call these variables first
name and last name because they're more
descriptive but here i'm using shorter
names because i want you to see the
entire code on the screen
so let's say with these two variables we
want to generate some text like this
john
in square brackets smith
is a coder let's say we want to print
this on a terminal how do we do this
well we define another variable like
message
now here we add the first name now we
need to concatenate this with a string
that contains a space and a square
bracket
next we need to add the last name
then we need to add a string that
contains the closing square bracket
followed by is a coder
okay so then
if we print message
and run this program
we see john smith is a coder right
now
while this approach perfectly works it's
not ideal because as our text gets more
complicated it becomes harder to
visualize the output
so someone else reading this code they
have to visualize all these string
concatenations in their head this is
where we use formatted strings they make
it easier for us to visualize the output
so
i'm going to define another variable
let's say msg short for message and set
this to a formatted string a formatted
string is one that is prefixed with an f
so f
quotes
now in between the quotes first we want
to add the value of the first name
variable so
we add curly braces and here we type
first
next we add a space we add our square
brackets in between the square brackets
we want to display the last name so once
again we add curly braces
and type last and finally here we type
is a coder so this is what we call a
formatted string
with these curly braces we're defining
placeholders or holes in our string and
when we run our program these holes will
be filled with the value of our
variables so here we have two
placeholders or two holes in our string
one is for the value of our first name
variable and the other is for the value
of the last name variable
now compare this format a string with
string concatenation with this formatted
string we can easily visualize what the
output looks like right now let's print
this on the terminal to make sure we get
the exact same output so let's print
message there you go so john smith is a
coder
so to define formatted strings prefix
your strings with an f and use curly
braces to dynamically insert values into
your strings
in this python tutorial i'm going to
show you some really cool things you can
do with python strings
so let's start by defining a variable
course
and we set that to python
for beginners
now to calculate the number of
characters in this string we can use a
built-in function called len so len
we give it this course variable and then
we can print the result let's run this
program
so as you can see we have 20 characters
in this string this is particularly
useful when we receive input from the
user for example you have noticed that
when you fill out a form online
each input field quit often has a limit
for example you might have 50 characters
for your name so using this len function
we can enforce a limit on the number of
characters in an input field if the user
types in more characters than we allow
them we can display an error okay
now
this len function
is another function built into python
it's a general purpose function so it's
not limited to counting the number of
characters in a string in the future
when we look at lists i'm going to show
you that we can use this function to
count the number of items in a list so
it's a general purpose function
now we also have functions specific to
strings for example we have functions
for converting all these characters to
uppercase or lowercase to access these
functions we use the dot operator let me
show you so
first we type course then dot
look these are all the functions that
are specific to strings
now in more accurate terms we refer to
these functions as methods this is a
term in object-oriented programming that
we'll look at in the future but for now
what i want you to take away is that
when a function belongs to something
else or is specific to some kind of
object we refer to that function as a
method for example here we have this
function
upper for converting the string into
upper case now more accurately because
this function is specific to strings we
refer to this as a method in contrast
len and print are general purpose
functions they don't belong to strings
or numbers or other kinds of objects
okay
so this is the difference between
functions and methods
now let's look at this upper method so
let's print the result
and run our program there you go we get
all these characters displayed in
uppercase now note that this method does
not change or modify our original string
in fact it creates a new string and
returns it so
if we print
our course variable right after we call
the upper method you can see that our
course variable still has its original
form so let's run this program one more
time there you go look this is our
original course variable it's not
modified
now similar to the upper method we have
another method for converting a string
into lowercase so let me show you print
course dot lower
now let's run the program
so on the second line you can see all
characters are in lower case
now there are times that you want to
find a character or a sequence of
character in a string in those
situations you can use the find method
so let me delete this reliance
we call course dot find
here we pass a character let's say p
and this will return the index of the
first occurrence of that character let
me show you so let's print the result
we get zero
because the index of the first capital p
in our string is zero
as another example if we pass a
lowercase o here
let's see what we get
we get four
because the index of this o here is 4.
now note that the find method is case
sensitive so it's sensitive to lowercase
and uppercase characters as an example
if we pass an uppercase o here and run
this program we get negative 1 because
we don't have an uppercase o anywhere in
the string
okay we can also pass a sequence of
characters for example we can pass
beginners
with a capital b
let's run this program
we get 11 because the word beginners
starts at index 11.
now we also have a method for replacing
a character or a sequence of characters
and that is called replace so let's
change find to replace let's say we want
to replace beginners with absolute
beginners so we add a comma to pass a
second value to this function or more
accurately this method we add a string
here i'm going to pass absolute
beginners
okay
now let's run this program
so we get python for absolute beginners
again this method like the find method
is case sensitive so if we pass
beginners all in lowercase this method
is not going to find this exact word in
our string so it's not going to replace
it with absolute beginners let's take a
look so i'm going to run the program one
more time look we still get python for
beginners we can also replace a single
character for example we can replace
capital p with
let's say capital j
now when we run this program we get
jython for beginners so these are the
find and replace method
and one last thing i want to show you in
this tutorial there are times that you
want to check the existence of a
character or a sequence of characters in
your string in those situations you use
the in operator so let's say we want to
know if this string contains the word
python we can write an expression like
this
string python
space
in space course so we're checking to see
if python is in the course variable now
this is an expression that produces a
boolean value like a true or false so we
refer to this expression as a boolean
expression
now if we print this on the terminal
we should get true and by the way let me
delete the second line we don't need it
anymore so run the program we get true
but if i change this capital p to a
lowercase p
and run the program we get false because
we don't have this exact sequence of
characters in our string now note that
the difference between the in operator
and define method is that our find
method returns the index of that
character or sequence of characters but
the in operator produces a boolean value
do we have this or not
so that's the difference now let's
quickly recap all the cool things you
learn to do with strings in this
tutorial
we can use the len function to count the
number of characters in a string this is
a general purpose function built into
python we also have specific functions
for strings which we referred to as
methods these include
upper for converting a string into
uppercase we also have lower
and title methods
you learn about the find method which
returns the index of a character or
sequence of characters we have the
replace method for replacing characters
and words in a string and finally you
learned about the in operator so
some characters in
a string
so you have learned that in python
programming language we have two types
of numbers integers which are whole
numbers like 10 they don't have a
decimal point and floating point numbers
or floats which are numbers with a
decimal point
now in this tutorial we're going to look
at the arithmetic operations supported
in python language these are the same
arithmetic operations that we have in
math we can add numbers multiply them
and so on so let's look at a few
examples we can print
10
plus 3.
so this is the addition operator we also
have subtraction we have multiplication
we have two kinds of division here's one
with a forward slash let's run this
program and see what we get
we get a floating point number but we
also have another division operator for
getting an integer so
if we add another slash here and run
this program
we get an integer
we have another operator called modulus
which is a percent sign and this returns
the remainder of the division so when we
run this program we should get 1.
there you go
and one last operator we have here is
exponent which is the power
so that is indicated with two asterisks
and this will return 10 to the power of
three so let's run this program we get a
thousand
so these are the arithmetic operators in
python programming language now for all
these operators that you learned we have
an augmented assignment operator that is
very useful let me show you so
let's say we have a variable called x we
set it to 10. now we want to increment
this by three we'll have to write code
like this x we set this to x plus three
so python interpreter will add 10 to
three the result is 13 and then it gets
stored into x again so when we print x
we should see
13. there you go
so this is how we can increment a number
right now augmented assignment operator
is a way to write the same code but in a
shorter form this is how it works
we type x
plus equals three what we have on line
three is exactly like what we have on
line two
so this is what we call the augmented
assignment operator we have augmented or
enhanced the assignment operator
now in this particular case we are
incrementing a number using the
augmented assignment operator but we can
also subtract or multiply a number by a
given value for example let's delete
what we have on line two
we can type
subtract equal three so here we are
subtracting three from x
when we run this program we should see
seven
there you go
now let me ask you a question
i'm going to clear all this code here
define x and set it to 10
plus 3 times 2. what do you think is the
result of this expression this is a very
basic math question that unfortunately a
lot of people fail to answer
the answer is 16. because in math we
have this concept called operator
precedence which means the order of
operations
so the multiplication operator has a
higher precedence so it's applied first
which means three by two is executed
first the result is six and then it's
added to 10. that is why x should be 16
after we run this code let's verify that
so print x run the program x is 16.
so this is what we call operator
precedence it's just a basic math
concept it's not about python
programming language so all the other
programming languages behave the same
way
so here's the order first we have the
exponentiation which is the power like 2
to the power of 3 then we have
multiplication
or
division
and finally we have addition or
subtraction
this is the order of operations let me
show you another example here i'm going
to add
the exponentiation operator so
2 to the power of 2. once again what do
you think is the result of this
expression pause the video and think
about it for a few seconds
the answer is 22
because the exponentiation operator
takes precedence so first 2 to the power
of 2 is executed the result is 4. then 4
is multiplied by 3
that is 12 and finally 12 is added to
10. so x should be 22.
so let's run this program and verify
this so i'm going to delete these lines
here
run the program there you go x is 22.
now let me bring back these rules here
we can also use parentheses to change
the order of operations so if we have
parenthesis
it always takes priority
in this case we can add parenthesis
around 10 plus 3 so this piece of code
will be executed first the result is 13
then the exponentiation operator will be
executed so 2 to the power of 2 is 4 and
finally 4 is multiplied by 13.
now here's a little exercise for you
i'm going to set x to parenthesis 2 plus
3 times 10 minus 3. what is the result
of this pause the video and think about
it for a few seconds
so you learn that parenthesis always
overwrites the order so this piece of
code is executed first the result is 5.
then between the multiplication and
subtraction you know that multiplication
takes precedence so next 5 will be
multiplied by 10 the result is 50 and
finally we have the subtraction so 50
minus 3 will be 47. let's verify this
print x
run the program there you go i hope you
guessed it right
so this is all about operator precedence
it's a very important topic and i see it
quite often in python tests so if you're
preparing for a python test make sure to
watch this tutorial one more time
in this tutorial we're going to look at
a few useful functions for working with
numbers let's start by defining a
variable like x and set it to
2.9 now to round this number we can use
the built-in round function so we call
the round function give it x and then
print the result let's run this program
so we get three we have another useful
built-in function called abs which is
short for absolute and this is the
absolute function that we have in math
we give it a value and it always returns
the positive representation of that
value even if that value is negative
here's an example let's call
the abs function and give it negative
2.9 when we run this program we're going
to see 2.9 on the terminal so let's go
ahead there you go so absolute always
returns a positive number now
technically in python we have a handful
of built-in functions for performing
mathematical operations if you want to
write a program that involves complex
mathematical calculations you need to
import the math module
a module in python is a separate file
with some reusable code we use these
modules to organize our code into
different files as a metaphor think of a
supermarket when you go to a supermarket
you see different sections for fruits
and vegetables cleaning products junk
food and so on each section in the
supermarket is like a module in python
so in python we have this math module
which contains a bunch of reusable
functions for performing mathematical
calculations so let me show you how to
use this module on the top
we type
import
math all in lowercase with this we can
import the math module now math is an
object like a string so we can access
its functions or more accurately its
methods using the dot operator so if you
type math dot look these are all the
mathematical functions available in this
module for example we can call the seal
method to get the ceiling of a number so
if we pass 2.9 here
and then print the result we should see
three let me delete all this other code
here all right let's run this program
there you go so we get three
another useful method is the floor
method so let's give that a try floor of
2.9 what do you think we're gonna get
we get two
now there's so many functions built in
this module and we don't really have
time to go through all of them but let
me show you how you can learn about them
on your own
open up your browser and search for
python3 math module make sure to add the
version python3 because the mass module
in python 2 is slightly different from
the math module in python 3.
so python 3 math module
now here you can see the documentation
for this module let's go
let's have a look if you scroll down you
can see the list of all the functions
and their explanation
so as an exercise i encourage you to
spend five minutes have a quick look at
this documentation see what functions
are there for you in case you need them
in this tutorial i'm going to talk to
you guys about if statements in python
if statements are extremely important in
programming and they allow us to build
programs that can make decisions based
on some conditions so if some condition
is true we're going to do certain things
otherwise we're going to do other things
here's an example
over here i've got this text file with a
bunch of rules for our program
if it's a hot day perhaps you want to
tell the user it's a hot day so make
sure to drink plenty of water
otherwise
if it's cold so here's another condition
if this condition is true we're going to
tell the user it's a cold day so wear
warm clothes
and otherwise if it's neither hot or
cold we want to tell the user it's a
lovely day
so let me show you how to write a
program that simulates these rules
so
back to our program here we start by
defining a boolean variable
is underline hot we set this to true
next we add an if statement so if
here we need to add a condition in this
case we're going to use our boolean
variable so is underline hot
now if this evaluates to true then we're
going to do certain things in this case
we want to tell the user hey it's a hot
day drink plenty of water
so back to our program
after our condition we add a colon
now note that when i press enter pycharm
automatically indents our cursor
now any code that we write here will be
executed if this condition is true
otherwise it will be ignored here's an
example
let's write a print statement
here i'm going to use double quotes
because i want to use an apostrophe in
our string so
it's a hot day
now let's press enter you can see the
cursor is still indented that means we
can write more code that will be
executed if this condition is true in
this case let's say we don't want to
write any extra code so to terminate
this block we need to press shift and
tab now the cursor is at the beginning
of the line so let's write a print
statement with a message like enjoy your
day
now when we run this program because
this condition is true we're going to
see this message followed by the second
message take a look so run
there you go it's a hot day enjoy your
day but if i go over here
and change this boolean value to false
and run the program again
our first message disappears and we only
see the second message enjoy your day so
this is how if statements work now back
here we can add another print statement
let's say
drink
plenty
of water now because this print
statement is also indented it will be
executed if this condition is true so
i'm going to revert is hot to true and
run the program one more time
there you go so it's a hot day drink
plenty of water and enjoy your day
all right now let's add a second rule
here if it's hot we're going to execute
these two lines otherwise if it's not
hot we want to print a different message
so here
we remove the indentation
and type else
colon
now when we press enter
once again our cursor is indented so the
code that we write here will be executed
if this condition is not true
so here we can print
it's a cold day
wear
warm clothes
now let's run our program one more time
so we get the messages about a hot day
followed by enjoy your day we don't see
any messages about a cold day now if we
go back here on the top
and
change this boolean value to false and
run our program
we see different set of messages it's a
cold day wear warm clothes and enjoy
your day
but there's a problem with our program
if it's not hot it doesn't necessarily
mean that it's cold maybe it's a lovely
day so the absence of heat doesn't mean
it's cold
back to our conditions
here on line four we have this rule that
says if it's a cold day then print these
messages otherwise if it's neither hot
or cold then say it's a lovely day so to
implement this rule we need to go back
to after pi
and define another variable so
let's say is underline called
we set this to
true
now here we need to add a second
condition so after
our first if statement we can use an
elif statement to define a second
condition here's how it works
so l if which is short for else if or
otherwise if now here we add another
condition so is called
so if it's cold you want to execute
these two lines
so let's cut these from here and move
them
under our second condition
and finally if none of these conditions
are true you want to print a different
message
it's a lovely day
so
right now
is hot is false is cold it's true so
when we run this program python
interpreter is going to execute the
first if statement in this case because
our condition is false these two lines
will be ignored then python interpreter
will look at line seven it will evaluate
this condition in this case is called is
true so we're going to see these two
messages on the terminal
now in this case because one of these
conditions was true this else statement
will be ignored so we are not going to
see this message and finally as before
we are always going to see this message
so let's run our program there you go
it's a cold day
wear warm clothes and enjoy your day
now
back to the top if we change is cold to
false
it's neither hot nor cold so it's going
to be a lovely day let's run the program
and
here you go it's a lovely day enjoy your
day
so this is the basic of using ip
statements as you can see they're very
useful in programming and with this we
can build all kinds of rules into our
programs
okay here's an exercise for you imagine
the price of a house is one million
dollars now if the buyer has good credit
they need to put down 10
of the price of this property otherwise
they need to put down 20
write your program with these rules and
display the down payment required for a
buyer with good credit you will see my
solution next
all right let's define a variable for
the price of this house so price we set
this to 1 million so one with six zeros
next we need a variable to tell if this
buyer has good credit
so has
good
credit and we set this to true
now we need an if statement so
if has
good credit is true
colon
here we need to calculate the down
payment so down underline payment
should be equal to 0.1 times the price
that is 10
of the price of this property
otherwise
colon
the down payment should be
0.2
times price
and finally we remove the indentation
and print
here we can use a formatted string
first we add a label
down payment colon and right after that
we add a placeholder or a hole for our
down payment variable so
curly braces
down payment
let's run this program
so down payment for a buyer with good
credit is 100 000
now let's improve this by adding a
dollar sign before this number so
back to our formatted string just before
the curly brace
i'm going to add a dollar sign let's run
this one more time that is better
in this tutorial i'm going to talk to
you guys about the logical operators in
python we use these operators in
situations where we have multiple
conditions here's an example
let's say we're building an application
for processing loans if an applicant has
high income
and good credit then they're eligible
for loan so in this example we have two
conditions one is having high income and
the other is having good credit so if
both these conditions are true then the
applicant is eligible for loan so this
is where we use the logical
and operator we use this operator to
combine two conditions and by the way
this is not specific to python
programming language pretty much any
programming language that supports if
statements also supports the logical
operators so back to our program let's
define two variables
has high income
we set this to true
and another one has
good
credit we also set this to true
now our if statement if
has high income is true
and
has
good credit is also true
then
we're going to print
eligible
for loan
so this is where we're using the and
operator
so if both these conditions are true
then this message will be printed if one
of them is false we're not going to see
this message let's try this out so i'm
going to run this program
so we see eligible for loan but if we
change
either of these conditions to false
and run the program again
look the message disappeared so this is
the logical and operator we also have
the logical or and we use that in
situations where we want to do certain
things if at least one of the conditions
is true for example let's change
the rule for this program such that
if the applicant has high income
or good credit then they're eligible for
loan
so if either or both these conditions
are true then the applicant is eligible
now
back to our program we can implement
this rule by using the logical or
operator so we simply replace
and with or
now when we run this program we're going
to see this message because at least one
of our conditions is true
let's take a look
so the applicant is eligible for loan
because they have good credit if we
change this to false
but set the other condition to true
and run the program we still see the
same result but if both these conditions
are false
then we're not going to see this message
anymore
so this is the difference between these
operators with the logical and operator
both conditions
should be true
with the logical or operator at least
one condition should be true
we also have another logical operator
called not and that basically inverses
any boolean value we give it if we give
it a true boolean value it converts it
to false for example let's make up a new
rule
if applicant
has good credit
and doesn't have
a criminal
record
then they're eligible for a loan let me
show you how to implement this so we go
back to our program
in this example we don't need the first
variable so let's delete that let's set
this variable to true
we also define another variable like has
criminal
record
and we set this to false
now we want to check to see if this
applicant has good credit and not a
criminal record this is where we use the
nut operator so
if they have good credit
and
not
criminal
record
so in this example
has criminal record is set to false when
we use the not operator this basically
gets changed to true so we'll have two
conditions that are true here's one and
here's another one so our applicant is
eligible for loan
and when we run this program we see
this familiar message
however
if an applicant has criminal record so
let's change this to true
now when we run this program we can see
our applicant is not eligible because
when we apply the not operator on this
variable
will get false so true changes to false
and will end up with two conditions one
is true and the other is false so the
result is false and that's why this
message is not printed
so this is all about the logical
operators in python
in this tutorial i'm going to talk to
you guys about the comparison operators
in python we use comparison operators in
situations where we want to compare a
variable with a value for example if
temperature is greater than 30 then we
want to print it's a hot day
otherwise if it's less than 10 it's a
cold day
otherwise it's neither hot nor cold and
by the way here i'm talking about
celsius not fahrenheit so to build these
rules into our program we need to use
comparison operators
back to app.pi
i'll define this temperature variable
let's write an if statement if
temperature
now we want to check to see if this is
greater than 30. so we use the greater
than operator if this is greater than 30
we want to print
it's a hot
day
otherwise
let's just print it's
not a hot day
now when we run this program we're going
to see the second message because 30 is
not greater than 30. so our first
condition
evaluates to false
let's verify that's a run
it's not a hot day okay
now if we change the temperature to 35
and run this again
we're going to see a different message
it's a hot day so this is where we use
comparison operators now what we have
here as you know is an expression
because it's a piece of code that
produces a value so more accurately this
is a boolean expression
so this is the greater than operator we
also have greater than or equal to
we have less than
less than or equal to
here's the equality operator so if the
temperature equals to 30 then we can say
it's a hot day note that this is
different from the assignment operator
that has only one equal sign you can see
if we use one equal sign here we
immediately get this red underline
because this is simply an assignment
statement we're changing the value of
the temperature we're setting the value
of the temperature variable to 30. we're
not comparing it with something else so
we don't have a boolean expression we're
not producing a boolean value okay so
our equality operator has two equal
signs and finally we have not equal
which is an exclamation followed by an
equal sign
now here's an exercise for you you've
probably seen that when you fill out a
form online sometimes the input fields
have validation messages for example
let's say we have an input field for the
user to enter their name now if the name
is less than three characters long we
want to display a validation error like
name must be at least 3 characters
otherwise if the name is more than 50
characters long then we want to display
a different validation error like name
can be a maximum of 50 characters
otherwise if the name is between 3 and
50 characters
then we just want to tell the user that
name looks good
so go ahead and write a program to
implement these rules
all right let's define a variable called
name and set it to let's say j so we're
assuming this is what the user types
into an input field
now we want to get the number of
characters in this string so we use the
len function right
lan of name
when we print this
we get one right you have seen this
before now here we want to use an if
statement so if len of name
is less than three
then
we want to print
name must be
at least
three characters
like here we need a second condition to
check the upper limit so l if
len of name
is greater than 50
then we want to print a different
message name
must be a maximum
of 50
characters
okay
and otherwise so else if none of these
conditions is true that means the name
looks good so print
name looks good let's run our program
so in this case we get this message
because our name is too short
if you go back here
and
type something really really long
and then run our program
we're going to see a different message
name must be a maximum of 50 characters
and finally
if we type a proper name here like john
smith
and run our program
we get name looks good
here's another good exercise that
combines many of the materials you have
learned so far so earlier you built a
program to convert someone's weight from
pounds to kilograms now we want to
extend this program and allow the user
to enter their weight in either
kilograms or pounds and then we'll
convert it to the other unit here's how
our program is going to work so i enter
my weight in pounds so 160.
now it's telling me is this in pounds or
kilograms so here i need to enter l for
pounds or k for kilograms and by the way
this program is not case sensitive so
whether i enter a capital l or a
lowercase l it takes it as pounds
now it tells me you are 72 kilos
let's run this program one more time
this time i'm going to enter my weight
in kilos so
72 is the weight
and the unit is kilograms okay
and it says you are 160 pounds so go
ahead and spend a few minutes on this
exercise you will see my solution next
all right first let's ask the user their
weight so we use the input function
weight colon
we get the return value and store it in
a variable called weight now the second
question
so one more time we use the input
function
l for pounds
lps or
k
for kilograms
so let's get that 2 and store it in a
variable called unit
now we need an if statement so if
unit
equals l
then we need to convert this weight into
kilograms however with this
implementation we are only allowing the
user to enter a capital l if they enter
a lowercase l this code is not going to
work
so this is where we use the upper method
of string objects so this unit is a
string because as i told you before the
input function always returns a string
so we can use the dot operator to access
all its methods or functions here we
call the upper method this will convert
whatever the user enters to uppercase
and then we'll compare it with a capital
l
now if this condition is true
then we need to get the weight and
multiply it by 0.45
however as you know this weight is a
string object and we cannot multiply a
string by a floating point number we
talked about this earlier in this course
so first we need to convert this weight
to a numerical value
so right here when we call the input
function we can get the return value and
pass it to the int function
so we call the in function
and
give it the return value of the input
function
now the in function will return an
integer so we can store it in this
weight variable
so here's the converted weight let's
store it in a variable called converted
then we print
here we can use a formatted string so
we prefix the string with f
u r
we add curly braces
to dynamically insert the value of
converted variable
and finally we add kilos
otherwise
if the unit is kilogram we need to
divide the weight by
0.45
so once again we type converted equals
to
weight divided by
0.45 and just to refresh our memory this
division operator returns a floating
point number but if we use double
slashes we'll get an integer
in this case i want to get a floating
point number
so
finally let's print
a formatted string
ur
curly braces
converted
pounds
okay
now let's run this program and see what
happens
weight is 160
in pounds
and that equals to 72 kilos perfect if
we run it one more time
and enter 72
kilos
we get 160 pounds
in this tutorial i'm going to show you
how to use while loops in python we use
while loops to execute a block of code
multiple times and they're often useful
in building interactive programs and
games in a future tutorial i'm going to
show you how to build a simple game
using a while loop
so let's get started with the basics
we write a wild statement and right
after that we type a condition followed
by a colon
as long as this condition is true the
code that we write in this block will be
repetitively executed here is an example
we can define a variable
like i as in short for index and set it
to 1.
now we set our condition to i less than
or equal to 5. so as long as i is less
than or equal to 5 we can print i
on the terminal and then we need to
increment i by one so we set i to i plus
one the reason we do this is that if we
don't do this i will be one forever so
we'll end up with an infinite loop
because this condition will always be
true 1 is always less than 5. so in
every iteration of this loop we
increment i by 1 so at some point i is
going to be 6 and then that is when this
condition will be false and then we'll
jump out of this loop okay
now to demonstrate how everything works
after this loop i'm going to add a print
statement
say done so note that these two lines
are indented so they are part of the
while block
okay now let's go ahead and run this
program to see what happens
so
take a look we get the numbers 1 to 5
followed by
done
so here's how this program gets executed
first we set i to one now python
interpreter executes line two this
condition is true because i is less than
five so
i is printed on the terminal and then
incremented by one
then the control moves back to the
beginning of the while loop so it
doesn't go to the next statement
so we come back here now we are in the
second iteration in the second iteration
i is 2 and because 2 is less than 5 our
condition is still true so i will be
printed on a terminal and once again it
will be incremented by 1. so at some
point i is going to be 6 and that's when
this condition will be false so our loop
will be terminated and then this dom
message will be printed on the terminal
so this is the basics of while loops now
let's make this program a little bit
more interesting
here we can write an expression like
this
we add a string
and in this string we add an asterisk
and then we multiply this string by i
so with this expression we can repeat a
string when we multiply a string by a
number that string will be repeated for
example if i is 2
this expression would produce
a string with two asterisks
okay now let's run the program and see
what we get so we get this little
triangle shape here because in the first
iteration i is one so
one times an asterisk produces one
asterisk
in the second iteration i is two so when
we multiply two by one asterisk we'll
get two asterisks
in this tutorial i'm going to show you
how to use a while loop to build a
guessing game like this
so we have this secret number which is
currently set to nine now the computer
is asking me to make a guess so let's
say one
it's not right because the secret number
is nine i can try again two
no it's not right let's try again so i
only have three chances to make a guess
if i can't guess the number the program
tells me that i failed let's run the
program one more time this time i'm
gonna guess the number so it's nine
there you go it says you win so let's go
ahead and build this program using a
while loop
all right let's start by defining a
variable to store our secret number so
we call that secret underline number and
set it to 9.
now we need a while loop to repeatedly
ask a user to make a guess
so while
condition cola
what is our condition here
well we want to give our user a maximum
of three guesses so similar to the last
tutorial we can define a variable like i
set it to zero and assume this
represents the number of guesses the
user has made
and then we can write our condition as i
less than
3.
note that here i'm not using less than
or equal to operator because with this
condition our loop will be executed four
times while i is 0 1 2 and 3.
so here we should use the less than
operator now if we give this code to
someone else it's not quite clear what
does i represent here it's only in r
head that i represents the number of
guesses the user has made so as a best
practice always use meaningful and
descriptive names for your variables so
it's better to rename this variable to
guess count let me show you how to
rename
so right click on i variable
and then go to refactor
and rename look at the shortcut on a mac
computer that's shift and f6
now in this dialog box we can easily
rename a variable and pycharm will
update all the references to that
variable so we don't have to manually
update each instance okay let's change
this to
yes underline count
enter there you go now that is better
also it's better to store three in a
separate variable to make our code more
readable because it's not quite clear
what does three represent here so
let's define a variable called guess
limit and set it to three
and then we can change three to guess
underline limit now our code is more
readable while guess count is less than
guess limit see it reads like a story
this is how you should write code
all right
so while this condition is true you want
to ask the user to make a guess so here
we use our input function
guess
now whatever the user enters comes out
as a string so we need to convert it to
an integer so right here we pass the
result to the end function
and then get it and store it in a
separate variable called guess
so at this point the user made a guess
now we need to increment guess count so
guess count
we set it to plus equal one okay now we
need to check to see if the user made
the right guess so here we need an if
statement
if
what the user guessed
equals
our secret number again see our code is
so readable it's like a story you can
read it like plain english
so if this condition is true you want to
tell the user they won so print
you one
now let's go ahead and run our program
up to this point so
okay it's asking me to make a guess i'm
gonna make the wrong guess of one it
asks me again beautiful two one more
time three
okay what is missing in this
implementation is the message that tells
me that i failed we're going to take
care of it momentarily but let's run the
program one more time and make the right
guess so nine
okay it says you won but it's still
asking me to make a guess because our
while loop is going to get executed
three times look one and two
so we need to change our program such
that if the user makes the right guess
we need to terminate our while loop we
need to jump out of it
how do we do that
so over here if the user makes the right
guess
after we print this message we can use
the break statement to terminate a loop
when python interpreter sees this it's
going to immediately terminate our loop
it's not going to evaluate this
condition again
now let's run our program and see what
happens
so
i'm going to guess the right number
you want and look we were not asked to
make two more guesses beautiful
now the last thing that we need to add
here is the message that tells the user
that they failed if they couldn't guess
the right number
how do we do that well in python our
while loops can optionally have an else
part similar to the if statements so
earlier you learned that our if
statements can optionally have an else
part
like here
so
if this condition is true do this
otherwise do something else right in
this case our if statement doesn't have
an else part
now
similar to the if statements our while
loops our while statements can also have
an else part
so
right at this level
we can add an else block so else colon
and the code that we write here will get
executed if this while loop completes
successfully without an immediate break
in other words if the user guesses the
right number we break this loop we jump
out of it so the code that we write in
the else block will not get executed but
if the user cannot guess this number
we're never going to break out of this
loop so this load will be executed to
completion until this condition becomes
false in that case the code that we
write in the else block will get
executed and this is the perfect
opportunity for us to tell the user hey
you made three guesses but none of them
were right so
print sorry
you failed
now let's test our program one more time
so guess one two three
sorry you failed let's run it one more
time this time i'm going to make a wrong
guess
and then the right guess
we won and our loop terminated
immediately
all right now it's time for you to
practice what you have learned so far so
once again we're going to build a game
this game is a simulation for a card
game now our game doesn't have a
graphical user interface or gui and it
doesn't really matter for now our focus
is entirely on building the engine for
this game
so let's see how this program works when
we run this we get this little symbol
here
and our program is waiting for us to
enter a command
if we type help either in lowercase or
uppercase it doesn't matter we get the
list of commands that our program or our
game currently supports so we can type
the start command to start our car we
can type the stop command to stop our
car and quit to terminate the game any
other commands that we type our program
is going to tell us hey i don't
understand that for example if i type
asd here
it says i don't understand that if we
type start
we get this message car started ready to
go if you type stop
it says car stopped and finally if we
type quit
our program terminates this is a
fantastic exercise for you to practice
what you have learned so pause the video
and spend five to ten minutes to build
this program
all right we're going to start with a
while loop
with a condition
what is our condition here
we want to run this loop until the user
types quit so we can define a variable
for storing the command that the user
enters and then we can run this loop as
long as the command does not equal to
quit
so right before the loop we define a
variable command and initially we set it
to an empty string an empty string is a
string that has no characters in it we
only have the quotes okay
so
then we type out our condition as
while command does not equal to
quit then
do something
now immediately we have a problem here
because we're assuming that the user
types the command in lower case so if
they type this in uppercase our program
is not going to behave properly so to
fix this problem we need to call the
lower method of the string object and
then compare the result
with this quit we could also call upper
and then type quit in uppercase it's a
matter of personal preference in this
demo i'm going to use lowercase
characters so okay
now in this loop we need to ask the user
to enter a command so once again we're
going to use our input function
we add a greater than symbol
followed by a space whatever the user
enters we get it and store it in our
command variable
now apart from the quit command there
are three other commands that we need to
support start stop and help so here we
need an if statement to compare what the
user enters with one of the supported
commands
so
if command
that lower
equals start
then you want to print a message like
the car started so print
car started
ready to go it doesn't matter
now the second condition what if it's
not start maybe it's stop so
alif command that lower
equals
stop there you go then we print a
different message car stopped
now look at our code we have repeated
this lower lower lower multiple times
this is bad in programming we have a
term called dry which is short for don't
repeat yourself
so whenever you have duplicating your
code that means you are doing something
wrong so how can we solve this problem
well instead of calling the lower method
in each condition we can call it right
here when we get the input from the user
so this input function as you know
returns a string we can immediately call
the lower method on that string and with
this our command will always be in lower
case so we don't need to
call this method in every condition
look
we remove the duplication and also our
conditions are shorter and easier to
read there's also one more place we need
to modify so it's right here
that is better
now the third command we need one more
alif
if the command equals help
then
we want to show the commands that we
support so here we're going to print a
multi-line string
so we use triple quotes
like this
and give the user a guideline like this
so start
to start the car
stop
to stop the car
and quit
to quit
now finally we need an else part so if
what the user enters is none of these
commands we're going to tell them hey we
don't understand this
so
else colon
sorry i don't understand that
and by the way
note that here because i'm using double
quotes i can easily use a single quote
as an apostrophe okay
so
let's run our program up to this point
and see what happens
all right let's type start car started
beautiful stop
car stopped
help
we get this guideline but there's so
much indentation before our commands
we'll fix that in a second and finally
let's test the quit command
oops our program didn't work properly
here's the reason with this if statement
we're comparing the command with start
stop and help anything else will end up
here so that's why our program says it
doesn't understand that
so that's why our program says it
doesn't understand that command however
after this else statement the control
will be moved to the beginning of the
loop at this point our command is quit
so our loop will complete and the
program terminates in other words when
we run this program
and type quit
our program actually quits but we still
see this message which shouldn't appear
here how can we solve this problem well
we can come back here
and just before the else block add
another alif
something like this alif command
equals
quit
then we can immediately break
this will solve our problem but note
that we have kind of repeated this
expression in two places
the reality is we don't really need this
condition on the top because with this
if statements well more accurately with
this alif we can jump out of this loop
and terminate our program so we can
simplify our condition
to something like this true
so while true means this block of code
is going to get executed repeatedly
until we explicitly break out of it okay
now let's test our program one more time
so
quit
now our program terminates and we don't
see that message beautiful
so let's fix the last problem you saw
that when we typed help
these guidelines appeared with so much
indentation and here's the reason look
right here in our code they're already
indented so when we use triple quotes
what we type here will be printed
exactly as is
so because we have indentation here this
indentation will also be printed on the
terminal so let's delete
these
okay run the program one more time
type help
the annotation is gone beautiful now
here's a challenge for you i want you to
take this program to the next level so
right now if we type start we get this
message car started and if we type start
again
we get the same message it would be
better if we got a message like car is
already started so it doesn't make sense
to store the car twice similarly
if we type stop
it says car stopped if we type it again
we get the exact same message it doesn't
make sense to stop a car twice so here's
what i need you to do if the car is
stopped and the user tries to stop it
again the program should say hey the car
is already stopped what are you doing
and similarly if the car is already
started and the user tries to start it
again the program should yell at the
user so go ahead and make the necessary
changes to implement this scenario
all right to add this to our program we
need to know if the car is started or
not so there is one more piece of
information that we need to store in the
memory what is the kind of data we need
to store here a boolean is the car
started or not it's a matter of yes or
no true or false so on the top
here we can define another variable like
started and initially we set it to false
so the car is not started right
now
when the user types the start command
here we need to check to see if the car
is already started if not we'll start it
otherwise we'll yell at the user so in
this block we write another if statement
if it's already started
then we print
car is already started
otherwise so we add an else statement
here
and at this point we set started to true
so we start the car and print this
message okay
now we need to make a similar change
for the stop command so if the car is
already stopped
we need to print a different message
if
not started so here we're using the not
operator to see if the car is stopped
so if it's not started that means it's
stopped okay
so if it stopped your print
car is already stopped
with double p's
otherwise so else
we need to stop the car how do we do
that we set started to false and then
we'll print this message
as easy as that let's go ahead and run
our program
so
initially our car is stopped so i'm
going to type stop
it says the car is already stopped so
let's start it
okay now our car is started let's start
it one more time
the program is yelling at us so we
cannot start a car twice beautiful now
let's stop it
it says the car is stopped let's stop it
one more time we get this message again
in this tutorial i'm going to talk to
you guys about for loops in python in
the last tutorial you learned about
while loops you'll learn that we use
while loops to execute a block of code
multiple times in python we have another
kind of loop that is a for loop and we
use that to iterate over items of a
collection such as a string because a
string is a sequence of characters so it
looks like a collection so we can use a
for loop to iterate over each character
in a string and then do something with
it here's an example we type out four
then we define a variable this is what
we call a loop variable in each
iteration this variable will hold one
item
so let's call it item
in here we type out a string like python
and then colon
so with this for loop we can iterate
over this string and in each iteration
this item variable will hold one
character at a time in the first
iteration it will be set to p then in
the second iteration it will be set to y
in the third iteration it will be set to
t and so on okay
so here we are inside our four block
because of the indentation here so
whatever we type here will be executed
in each iteration for now we can simply
print this item
now let's run this program and see what
happens
so you can see each character in our
string is printed on a new line
let's look at another example
in python we can define lists using
square brackets so let me remove this
string from here
and define a list using square brackets
a list is simply a list of items like a
list of numbers a list of customers a
list of emails products blog posts
whatever so here we can define a list of
names like mosh
john
sarah
and then go ahead run our program so you
can see in each iteration we get one
name
and print it on a new line
we can also loop over a list of numbers
for example
[Music]
one two three four let's run it
again we see each number on a new line
but what if we want to iterate over a
large list of numbers we don't want to
explicitly type out a list with let's
say a hundred or a thousand numbers but
i want to type 567 all the way to 100
that is when we use the range function
so let me delete this
in python we have a built-in function
called range for creating a range of
numbers so
we give it a number let's say 10. let's
run this program
now we can see here on the terminal we
have numbers 0
all the way
to 9. so 10 is not included so basically
when we call the range function this
range function creates an object it's
not a list it's a special kind of object
that we can iterate over in each
iteration this object will spit out a
new number we can also work with a range
of numbers here let's say we want to
start from 5
and go all the way to 10.
so
let's run our program
now we have the numbers 5 6 7 and 9.
also this range function can optionally
take a step so we can pass
to
as the step to this function
and when we run our program
you can see that our first number is
five now we go two steps forward to get
seven once again we go two steps forward
we get nine and that is the end of our
range so this is the basics of using for
loops in python
now here's an exercise for you i want
you to write a program to calculate the
total cost of all the items in a
shopping cart so let's say we have a
list of prices
like 10
20 and 30.
i wanted to use a for loop to calculate
the total cost of all the items in our
imaginary shopping cart so calculate
that and then print it on a terminal
that's pretty easy and you should do it
in a couple of minutes
so as you learned we use for loops to
iterate over all the items in a
collection a collection can be a string
it can be a list it can be a range
object that is returned from the range
function anything any kind of object
that has multiple items
so in this example we're going to use a
for loop to iterate over the list of
prices so for item in
prices colon and by the way this loop
variable we don't have to call this item
we can call it anything for example in
this case we can rename it to price so
for price
in prices
now in each iteration this price will
hold one value in the first iteration
it's going to hold 10 then it's going to
be 20 and then it's going to be 30.
so we need to define another variable to
calculate the total
so
we define that outside of a for loop
let's call it total and initially we set
it to zero
now in each iteration we get the current
price and add it to the total so
rate total equals total plus price or as
you learned earlier we can use the
augmented assignment operator to
simplify this code
so
after our for loop this total variable
has the total of all the prices we can
simply print it here
or we can use a formatted string so
a string prefix with f
we add a label like total curly braces
to dynamically include some value in our
string in this case our total
variable
so let's go ahead and run this program
there you go so the total cost of all
the items in our imaginary shopping cart
is 60.
in this tutorial i'm going to talk to
you guys about nested loops in python
using a nested loop basically means
adding one loop inside of another loop
and with this technique we can do some
amazing things for example we can easily
generate a list of coordinates so a
coordinate as you know is a combination
of an x and y value let's say 0 and 0.
now let's say we want to generate a list
of coordinates like this so we have 0
and 0 then we'll have 0 and 1 then 0 and
2
next
we're going to change x so we're going
to use 1 for the x and once again we're
going to use these three values for the
y coordinates so 1 and 0 then
1 and 1 and 1 and 2.
you got the point we can easily generate
these coordinates using nested loops let
me show you so we'll start with one loop
let's say for x in range four
with this loop we can generate values
for the x coordinate let's print this on
the terminal
okay
so we get the values 0 to 3.
now for each x like 0 we should generate
a few y values
so that is where we use a nested loop so
inside of this loop we're going to add
another loop so instead of just printing
x first we want to add
another loop
for y in range let's say 3
now we can print x and y together
so print here we use a formatted string
to display coordinates like this so we
add parenthesis
inside of this parenthesis first we need
to add x so curly braces x
then a comma
followed by
another set of curly braces and
y
let's run this program and see what we
get
there you go so we have these
coordinates 0 and 0 0 and 1 0 and 2.
then we have 1 and 0 1 and 1 1 and 2 and
so on so let me explain exactly how this
program gets executed
so in the first iteration of our outer
loop x is zero right
now we are on line two here we have a
new loop which we call an inner loop in
this inner loop in the first iteration y
is going to be zero
so we print 0 and 0 on the terminal now
the control goes back to line 2 or our
inner loop in this second iteration y
will be set to 1 but we're still in the
first iteration
of our outer loop so x is still 0 but
now y is incremented to one
so that is why we see zero and one on
the terminal once again the control goes
back to line two we are in the third
iteration of our inner loop so this will
continue until this inner loop completes
that is when y reaches two because this
range function generates number zero to
three but not including three so we'll
have zero one and two
after this inner loop completes then the
control goes back to line one at this
point we're going to be in the second
iteration of our outer loop so x will be
one then the control will be moved to
line two or our inner loop at this point
this range function is going to generate
the numbers 0 to 3 one more time so this
inner loop will be executed three times
and then we'll go back
to our outer loop so this is how nested
loops get executed
okay here's an exercise for you but this
one is a little bit more challenging
than the exercises you have done so far
so i really don't expect you to do it
but if you do it wow i will be so proud
of you
so see what i have done here
using nested loops i've written some
code to draw this f shape can you see
that
so let me give you a hint
first of all
we have this list
called numbers
in this list we have these values 5 2
five two two
these values determine the number of x's
we have on each line so for example the
first item in this list this tells us
that we should have five x's on the
first line there you go so one two three
four five
on the second line we're gonna have two
excess
on the third line we're gonna have five
excess like this
so i've written code to convert
a simple list of numbers into a shape
like this
now here's a tip for you
using a for loop you need to iterate
over this list in each iteration you get
one number this determines the number of
excess to be displayed on that
particular line so if you want to cheat
you can get this number and multiply it
by a string that contains x so if you
multiply x by five you'll get five x's
that's not what i want you to do i want
you to use an inner loop here to
generate a string that contains five x's
so imagine in python we cannot multiply
a string by a number so to solve this
problem we need a nested loop
so go ahead and spend five minutes on
this exercise and by the way do your
best to solve this it is a little bit
challenging but it's not extremely
difficult it just requires a little bit
of focus you'll see my solution next
all right so first we need to iterate
over all the items in this list
so for item in numbers
or we could rename this variable to
x underline count that is the number of
x's on each line okay
now i told you that if you want to cheat
you can write code like this print x
times x underline count if we run this
program
we get the same output
so this is the beauty of python with
python we can write expressions like
this we can multiply a string by a
number to repeat it a lot of other
programming languages don't support this
feature but for this exercise i wanted
you to imagine that we don't have this
feature in python so you would have to
use an inner loop to solve this problem
here's how it works
in the first iteration xcount is going
to be 5. so we need to generate five x's
how can we do that well let's say we
define a variable called output and
initially we set it to an empty string
now we need to add five x's to the
string so we can use another loop for
count
in range
of x underline count so we're using the
range function to generate a sequence of
numbers from 0
up to x count
so in our first iteration x count is
going to be five so range of five would
generate the numbers zero one two three
four so this inner loop will be executed
five times that is exactly what xcount
represents
so now
in each iteration we simply need to
append an x to our output variable so we
said output
plus equals x
and then
after this inner loop we simply print
the output
with this we'll print five excess on the
first row then we go to the second
iteration of our outer loop at this
point xcount is going to be 2.
now
on line 3 we're going to reset our
output variable to an empty string so we
start over
then we go to our inner loop this loop
will be executed two times so we'll
append two access to the output variable
and then print it
as simple as that so see it wasn't
really that difficult but it was
slightly more difficult than the
previous exercises
so let's run this program there you go
now if you're adventurous i want you to
modify the values that we have
in our
numbers list
to print an l here
now in this tutorial we're going to take
a closer look at lists
so i'm going to define a list of names
let's send them to john
bob
marsh
sarah and mary
so if we print
this list here
what we see on the terminal looks
exactly like how we define our list so
we have square brackets and in between
these square brackets we have our items
so we have five strings in this list
now we can also access an individual
element using an index just like how we
can access an individual character in a
string using an index
so here we type out square brackets and
specify an index the index of the first
item in this list is zero
so let's run this program there you go
we get john now if you want to print out
the third element in this list its index
is two
so
names of two
returns mosh
now we can also pass a negative index
here so negative one refers to the last
item in this list that is mary let's run
the program
there you go we see mary if you pass
negative 2 this returns the second item
from the end of the list
so let's run the program there you go we
get 0. so this is exactly like accessing
individual characters in a string we can
also
use a colon to select a range of items
for example if we pass
to colon this will get all the items
starting from the index of two that is
mosh here all the way to the end of the
string so let's run this program
there you go
we get this list with three items mosh
sarah and mary
we can also specify an end index let's
say 4 so this will return all the items
up to this index but it doesn't include
the item at this index so when we run
this program we only see mosh and sarah
the item at index four which is the
fifth element or the fifth item in this
list is not returned so mary is not
returned okay and also here we have
default values so if we leave out the
end index this expression is going to
return all the items starting from the
index of two to the end of the list or
if we leave out the start index this
expression assumes zero as the default
index so it will return all the items
from the beginning to the end of the
list okay and by the way just like
strings these square brackets here don't
modify our original list they simply
return a new list for example if we pass
two here
you can see this returns a new list with
three items so if we go back here and
print our original list of names right
after
you can see it's not affected so
whenever we use square brackets with a
colon to select a range of items we get
a new list and by the way we can also
modify any of the elements in this list
for example let's say we made a mistake
and the first item shouldn't be spelled
john with an h so we want to remove the
h that is very easy so we access it
using an index that is names of zero and
we set it to a new value
like this
now let's print our list
so you can see
the first item in this list is now
updated so this is the basics of lists
and here's an exercise for you i want
you to write a program to find the
largest number in the list this is a
fantastic exercise for beginners so go
ahead and spend a few minutes on this
and then come back continue watching
all right let's define a list of numbers
numbers
with a bunch of random numbers 3 6 2 8 4
and 10.
now to find the largest number in this
list we need to define another variable
let's call it max this variable will
hold the largest number now initially we
want to assume that the first item in
this list
is the largest number so we set max to
numbers
of zero we're only assuming that the
first item is the largest number chances
are our assumption is wrong so we need
to iterate over this list we need to
loop through it
get each item and compare it with max
if it's greater than max then we need to
reset max to that number so in the first
iteration we get 3 and max is also 3.
is 3 greater than 3 no so we move on we
get the second number is 6 greater than
3 it is so we need to reset max to 6.
once again we continue we get 2 is 2
greater than 6 no it's not so we move on
then we get 8 is 8 greater than six it
is so we should reset max to eight that
is pretty easy
so here we need a for loop for number
in numbers colon
now we need to check to see if this
number is greater than max
so
if number
is greater than max colon
then we need to reset max so we set max
to this new number
that's all we had to do so let's print
max
and run our program
we can say the largest number in this
list is 10. it doesn't matter whether
this number is at the end of the list or
at the beginning so if i move 10
and put it right at the beginning
we should still see the same result
let's run our program we still see 10 if
i put this somewhere in the middle
our program should still work let's put
it right after
two
run the program we still get 10.
in this tutorial i'm going to talk to
you guys about two-dimensional lists in
python two-dimensional lists are
extremely powerful and they have a lot
of applications in data science and
machine learning here's an example in
math we have a concept called matrix
which is like a rectangular array of
numbers let me show you so yeah one two
three four five six seven eight nine so
we have a rectangular array of numbers
we have rows
and columns so this is a three by three
matrix in math now we can model this in
python using a two-dimensional list a
two-dimensional list is a list where
each item in that list is another list
so
you want to define a matrix we set it to
a list
each item in this list is going to be
another list and that list represents
the items in each row
so the first item in our list is going
to be another list and in this list
we're going to have the values 1 2 and
3.
now the second item in our matrix list
once again we have a list this list
represents the items in the second row
so
4 5 and 6 and finally
7 8 9.
so as you can see we have a
two-dimensional list each item
in our outer list is another list
okay so this is how we can implement a
matrix in python now to access an
individual item in our matrix once again
we use square brackets let me delete
this stuff
all right
so how do we access one here well
we start with our list
then we add square brackets first we
need to go and get the first item in
this list right so we pass zero now this
expression returns another list that is
the inner list
in this list let's say we want to access
the second item
so
once again we add square brackets and we
pass one that is the index
of two in this list right
so if we print this on the terminal
we get two okay so using two square
brackets we can access individual items
in our matrix and also we can modify
these values using this syntax so
before printing this let's change it to
20. so matrix of 0 and 1 let's change it
to 20
and then print it there you go it's
modified
now here we can also use nested loops to
iterate over all the items in this
matrix let me show you so
we start with the rows for row
in matrix
so with this loop we are iterating over
our matrix list in each iteration row
will contain one list one item okay
now
here we need to use an inner loop
so we need to loop over this row which
is a list of items
we can type out four
item in row colon
and print item
okay
so let's run this program
there you go we get all the items
in our list
hey i just wanted to make a quick
announcement in case you haven't seen my
website yet head over to
codewithmosh.com this is my coding
school where you can find plenty of
courses on web and mobile application
development in fact recently i published
a comprehensive python course that goes
way beyond this beginner's course on
youtube and if you're serious about
learning python and getting a job i
highly encourage you to enroll in this
course just like this tutorial you can
watch it anytime anywhere as many times
as you want and you will also receive a
certificate of completion that you can
add to your resume and the course comes
with a 30-day money-back guarantee so if
you're not happy we give all your money
back no questions asked the price for
this course is 149
but the first 200 students can get it
for only 15 dollars so if you're
interested the link is below this video
click the link and get started
in this tutorial i'm going to talk to
you guys about the list methods or list
functions these are the operations that
we can perform on a list so let's define
a list of numbers
here we pass a bunch of random numbers
like 5
2
1 7 and 4.
now there are a number of things we can
do with this list we can add new items
to it we can remove existing items we
can check for the existence of an item
these are the operations that we can
perform on a list so when we type
numbers
dot we can see all these functions or
more accurately the methods that are
available in our list objects
so we can call the append method to add
a new item to this list let's say
13 actually no it's not a good number
i'm joking i'm not superstitious so
let's add 20.
it doesn't really matter and then print
our list
when we run the program you can see
20 is added at the end of this list but
what if you want to add a number
somewhere in the middle or at the
beginning of our list for that we use a
different method that is called insert
so
insert now this method takes two values
let me show you so when we open
parenthesis
look at this little tooltip above the
insert method
you see the first value that we need to
pass here is an index so this is the
index at which we want to insert this
new item let's say we want to add an
item at the beginning of our list so we
pass the index position of zero
and then the second value is the actual
object we want to add to this list let's
say we want to add the number 10.
now when we print this list you can see
that the number 10
is placed at the beginning of the list
and all the other items are pushed to
the right
we can also remove an item so we call
remove and pass the item that we want to
remove let's say we want to remove five
now we print our list so you can see
five is gone and we have two one seven
four if you wanna remove all the items
in the list you can call the clear
method so
clear
this method doesn't take any values so
we simply call it and it empties our
list
all the items are removed
we also have another useful method
called pop
and with this we can remove the last
item in a list let me show you so run
our program you can see the number four
is removed from the end of our list
now if you want to check for the
existence of an item in a list you can
call the index method so
we call index
and pass the value here like five and
this returns the index of the first
occurrence of this item so let's print
this on the terminal
we don't need this line anymore
so the index of five is zero what if we
pass a number that doesn't exist in this
list let's say 50.
run the program
we get an error we got a value error 50
is not in the list
there is also another way to check for
the existence of an item we can use the
in operator so
let me show you we type out 15 in
numbers
earlier we used the in operator with a
string we could check for the existence
of a character or a sequence of
characters in a string
now here we're checking for the
existence of 50 in the list of numbers
so let's print this
we get a boolean value false so unlike
the index method this expression doesn't
generate an error so it's safer to use
this we also have another method for
counting the occurrences of an item
let's say we have another five
over
here now we can call
numbers that count and pass five and
this should return two because we have
two fives in this list take a look there
you go
that is pretty useful now if you want to
sort your lists you can call the sort
method so
we call the sort method here this method
doesn't take any values so
look at the return value that is none
none is an object in python that
represents the absence of a value
so this sort method doesn't really
return any values it simply sorts this
list in place so instead of printing the
return value of this method
we simply call it to sort our list and
then print our list
take a look
now all the items are sorted in
ascending order we can also sort the
items in descending order so after we
sort the list we can call
the reverse method and this simply
reverses our list
now let's go ahead and run our program
take a look
our numbers are sorted in descending
order
and one last method i want to show you
here that is pretty useful is the copy
method so copy
with this method we can get a copy of
our list so let's define another
variable called numbers2
now numbers2 is a copy of our original
list so if you make any changes to our
original list if you add new items to it
if you remove existing items these
operations are not going to impact our
second list let me show you so after we
take a copy of our numbers list
let's add a new item to this list some
numbers that append 10.
so the first list is updated so now we
have a new item in our first list
then let's print the second list
take a look we don't have the number 10
here because these are two independent
lists
so these are all the operations that we
can perform on lists we can add new
items to a list we can remove existing
items we can check for the existence of
an item we can sort our lists and copy
them
now here is the exercise for this
tutorial i want you to write a program
to remove the duplicates in a list again
this is a fantastic exercise so spend a
few minutes on this and then come back
continue watching
all right let's say we have a list of
numbers with a bunch of duplicates so 2
2
4 6 3 4
6 1.
we want to remove the duplicates
so we need to define another list let's
call that unix
initially we set it to an empty list
then we need to iterate over
our first list get each item and if we
don't have that number in this unix list
then we'll add it to the second list as
simple as that so
for number in numbers
now we need to check to see if we have
this number
in the second list
so we use the in operator
if
number
not in unix
so note that here we are using the not
operator so if we don't have this number
in this unix list
then we'll need to add it so
unix dot append
number
that's all we have to do
so let's go ahead and print the unix
list
there you go so we have two four six
three and 1. the duplicates are removed
in this tutorial i'm going to talk to
you guys about another important
structure in python called topo tuples
are similar to lists so we can use them
to store a list of items but unlike
lists we cannot modify them we cannot
add new items we cannot remove existing
items we say tuples are immutable we
cannot mutate or change them let me show
you so i'm going to start by defining a
list of numbers one two three
so we use square brackets to define
lists and parentheses to define tuples
so if we change this to
parenthesis one two three now we have a
tuple so if we type numbers dot look
here we don't have the append or insert
methods so we cannot add new items to
this tuple we also don't have remove
clear and pop we cannot remove any of
these items here
we only have two methods count and index
we use count to count the number of
occurrences of an item and index to find
the index of the first occurrence of an
item so we can only get information
about a tuple we cannot change it and by
the way these other methods that you see
here they start with two underscores we
refer to this as magic methods they're
more of an advanced topic so they go
beyond the scope of this tutorial if
you're interested to learn about them
you can get my python course i've
covered them in detail
so similar to lists we can access
individual items using square brackets
so we can get the first item like this
and then print it on the terminal
there you go the first item is one
but if you try to change the first item
we'll get an error so numbers of zero we
set it to 10
and run our program there you go we get
this type error because the tuple object
does not support item assignment
so we cannot mutate or change tuples
they are immutable
now practically speaking most of the
time you will be using lists but tuples
are also useful if you want to create a
list of items and you want to make sure
that nowhere in your program you
accidentally modify that list then it's
better to use a tuple
in this tutorial i'm going to show you a
powerful feature we have in python
called unpacking so let's define a tuple
called coordinates
and here we pass three values one two
three so imagine these are the
coordinates for x y and z
now let's say we want to get these
values and use them in a few expressions
in a few complex expressions in our
program maybe we want to include them as
part of a large complex formula so
together we'll have to write code like
this coordinates of zero then let's say
we want to multiply this by coordinates
of one and then multiply it by
coordinates of two
our code is getting a little bit too
long this is just a very simple example
but let's say we want to use these
values in quite a few places in our
program so a better approach is to get
these values and store them in separate
variables like
we can get coordinates of 0 and store it
in x
then we get coordinates
a 1
and store it in y
and similarly we get coordinates of 2
and then store it in z
now instead of repeating coordinates of
2 or coordinates of 0 multiple times we
can simply work with these variables x
times y times z
that is better right
so nothing new so far but in python we
have a powerful feature called unpacking
and with that we can achieve the same
result with far less code so we can
define our variables x y
and z
and set them to our tuple
what we have on line six is exactly
identical to what we have on lines two
to four
so this is a shorthand to achieve the
same result
so let me delete this and explain how
this code works when python interpreter
sees this statement it will get the
first item in this tuple and assign it
to this variable then it will get the
second item in this tuple and assign it
to the second variable and similarly it
will get the third item in this top hole
and assign it to the third variable we
have here
so we are unpacking this tuple into
three variables
now if we print
x you can see
x is one similarly y
is two there you go
so this is unpacking and by the way this
is not limited to tuples we can use this
feature with lists as well so if i
change parenthesis
to square brackets
now coordinates is a list so we can
unpack this list into three variables
now
run our program you can see y is two
in this tutorial i'm going to talk to
you guys about dictionaries in python we
use dictionaries in situations where we
want to store information that come as
key value pairs here's an example think
of a customer a customer has a bunch of
attributes like name
phone number address and so on but each
of these attributes has a value for
example the name can be john smith the
email can be john gmail.com
the phone can be whatever so what we
have here is a bunch of key value pairs
so in this example our keys are name
email and phone and each key is
associated with a value so this is where
we use a dictionary with a dictionary we
can store a bunch of key value pairs
so let me show you how to define a
dictionary in python back to our program
i'm going to define a variable customer
and here we set it to curly braces with
these curly braces we can define a
dictionary in this example we have an
empty dictionary that doesn't have any
key value pairs now we can add one or
more key value pairs in between the
braces so let's add a key value pair
here
i'm going to set the key to name
and the value to john smith
then we add a comma to add another key
value pair so let's set
age to 30.
let's add another key value pair is
underline verified
and we set this to a boolean
now what matters here is that these keys
should be unique so if i add another key
value pair here
let's set age
to
40.
now look pycharm has highlighted the h
key because we have duplicated that and
that's not allowed so each key should be
unique in a dictionary just like the
dictionaries we have in the real world
in a real dictionary we have a bunch of
words and their definition each word is
listed only once in a dictionary we
don't have the word book twice
so let's delete this second duplicate
key value pair
so the keys should be unique and in this
example i'm using strings but they can
also be numbers we're going to look at
that later
but the value can be anything it can be
a string a number a boolean a list
literally anything
now we can access each item in this
dictionary using square brackets so
we type customer
square bracket and then specify a key
like name
and this will return the value
associated with the name key let's print
it on the terminal have a look
there you go so
the name is john smith now what if we
pass a key that doesn't exist
let's say
birth date
run the program we get a key error
because we don't have a key called birth
date also
if we spell name
with let's say a capital n we get the
same error because we don't have a key
with the exact
same sequence of characters in this
dictionary
now to get around this we can use the
get method let me show you
so instead of using the square brackets
we call the get method and specify
our key
now if we use a key that doesn't exist
here it doesn't yell at us for example
if you pass birth date
it simply returns the non-value earlier
i told you that none is an object that
represents the absence of a value
so instead of getting a key error we get
none now we can also optionally supply a
default value for example if this
dictionary doesn't have this key we can
supply a default value let's say
january 1st 1980.
let's run the program
now instead of getting none we get this
default value
so this is how we can access the value
associated with the key in a dictionary
we can also update these values for
example before our print statement we
can write code like this customer
of name
let's update the name to
jack smith
now this little warning here is telling
us that we could simply put jack smith
here instead of defining it once and
then update it don't worry about that it
doesn't really matter now with this line
if we print the name of this customer we
should see jack smith let me show you so
i'm going to use the square bracket
notation again let's print the name of
the customer you can see
that is updated here we can also add a
new key here
let's set the birth date
to some value like
january 1st 1980
and then we can print it here
so as you see we can easily add new key
value pairs to a dictionary
so this is the basics of using
dictionaries in python they're extremely
important and they have a lot of
applications in the real world
okay here's an exercise for you so here
we have this program that asks our phone
number let's type one two three four we
type it in digits and then this will
translate it to words take a look enter
it prints one two three four that's a
pretty cool program so go ahead and
spend a few minutes on this exercise
it's pretty easy i'll see you next
all right so first we need to get the
user's phone number we call the input
function
with the label phone we get the result
and store it
in this variable
now let's say the user enters one two
three four so we need to loop through
this string get each character and
translate it to a word
so what we need to implement this
scenario is a dictionary because a
dictionary is a structure that allows us
to map a key to a value so we can have a
dictionary with keys like one two three
four and we map each of these keys
to a word so we can map the digit one to
the word
one we can map two
to two you got the point so let's define
a dictionary we can call it digits
underline mapping
now this dictionary i'm gonna add a few
key value pairs
one we map it to one
two
to two
three to three and finally
four to four now technically we should
add all the digits from zero to nine but
i don't wanna waste your time typing
repetitive things here you got the point
so let's move on now we need to loop
through the phone string so
for
character
in phone
we get each character and then use it to
access a key value pair in our
dictionary so
digits underline mapping
we can use square brackets or call the
get method i would prefer to use the get
method so in case the user enters some
character that is not part of our
dictionary our program is not going to
yell at them
so
we call the get method
and pass this character as the key
and if we don't have this key we can
supply
a default value like an exclamation mark
so with this we'll get a word now we
need to add this word to an output
string so we can define an output string
initially we set it to an empty string
in each iteration we get this and add it
to our output string so we type output
plus equals
this
and we should also add a space at the
end
so the words are not close to each other
okay
that's all we have to do
now finally let's print this output
run our program so i'm going to type one
three four
five let's see what we get we get one
three four with an exclamation mark
in this tutorial i'm going to show you
something really cool that you can do
with dictionaries so here we have this
program we can type a message like good
morning
followed by a smiley face when we press
enter we get this beautiful smiley face
or
we can type
i am sad with the sad smiley face and it
gets translated to this beautiful emoji
so this is another application of using
dictionaries we have a dictionary that
maps these characters into smiley faces
so let's go ahead and build this program
together
we start by calling the input function
here we pass a greater than symbol as an
indicator for the user to type a message
we get that message store it here
as you know that is a string now we need
to split the string by a space
so if the user types good morning with a
smiley face we want to break this down
into three words good
morning
and smiley face
to do that we can call the split method
so
we call message dot split
and pass
a string with one space as the separator
what this method does is basically it
goes through the string and anywhere it
finds this character in this case a
space it uses that as a boundary to
separate this string into multiple words
and then it will return a list let me
show you so let's store that here words
and then print it
on the terminal
let's go ahead and run our program so if
we type good morning sunshine enter we
get a list with three items each item is
a string okay
now
back to our program we need to define a
dictionary for mapping special
characters like these two into a smiley
face
so
we can call that emojis
set it to curly braces here we add a key
value pair
a smiley face and we map that to
a string in the string we want to add an
emoji
if you're on a mac keyboard you can
press ctrl
command and space and this should bring
up this emoji box if you're on windows
honestly i really don't know how you can
do this but there must be applications
that do this for you so let's go ahead
and pick this
happy smiley face good now let's add
another key value pair for a sad face
we map this to
this
face here
good
so we have a list of words now we need
to loop through this list get each word
and potentially map it to an emoji so we
can write a for loop for word in words
now we want to go to our dictionary and
see if you have an item with this word
as the key
if you have an item with that key then
we'll get its value otherwise we want to
use the same word so if the user types
good morning we don't want to translate
those words we just want to return those
so that is the case where we use the get
method to supply a default value so we
want to get an item with the key
word and if we don't have an item with
that key we simply use that word as the
default value now similar to the
exercise that we did in the last
tutorial we need an output variable so
let's define that here output set it to
an empty string
now back to line 9
we get the return value of the get
method and add it to our output variable
so output
plus equals whatever we get from the get
method and finally we need to append a
space at the end
that's it we're done so let's print the
output
and run our program
i'm gonna type good morning sunshine
with a smiley face
we get that beautiful let's try a sad
face as well i am sad
too bad
beautiful so as you can see dictionaries
have a lot of use cases in real
applications
here's the solution from the last
tutorial where we created an emoji
converter now so far we've been writing
all our code right here in app.pi but as
our programs grow we need a better way
to organize our code we need to break up
our code into smaller more manageable
and more maintainable chunks which we
call functions
so a function is a container for a few
lines of code that perform a specific
task for example you have learned about
if you have the built-in functions in
python like print and
input each of these functions have a
purpose they know how to perform a
specific task
so when building large complex programs
we should break up our code into smaller
reusable chunks which we call functions
to better organize our code and that's
what i'm going to show you in this
tutorial so let's write a simple program
for printing a greeting message so we're
going to do a print
hi there
and let's add another message welcome
aboard
so here we have a simple program with
only two lines of code now let's say
these two lines potentially we're going
to need them in other programs so we can
put them in a function that we can reuse
let me show you how to do that so
we start
typing out def that is a reserved
keyword in python and it's short for
define when python interpreter sees this
it knows that we're defining a function
next we need to give our function a name
let's say greet
underline
user so all the best practices you learn
about naming your variables also apply
here which means you should name your
functions with lowercase characters if
there are multiple words you need to
separate them using an underscore and
you should always always always always
use meaningful and descriptive names for
your functions
so here we're defining a function called
createuser after that we need to add
parentheses followed by a colon now you
know that whenever we add a colon at the
end of a line we're telling python that
we're defining a block of code so when
we press enter the next line is indented
now any code that'd be right here will
belong to this function
so
i'm going to move these two lines these
two print statements inside of our
function we can simply press tab to
indent them beautiful also let's remove
this extra line break that is better so
these two lines
now are part of our greet user function
so whenever we call this function these
two lines will be executed okay now
let's remove indentation so here we are
outside of our function
let's do a print statement
and print start
after that let's call our function so
greet user
and finally let's do another print
statement
and print finish
now we have this little warning here
this underline
if you hover your mouse over this line
this tooltip is telling you that we
should add two blank lines after
function definition this is coming from
pep8 which is a document that defines
the best practices for formatting our
code we'll look at that in the future so
for now to make pycharm happy let's add
an extra line break after this function
so whenever we define a function we need
to add two line breaks after okay
so
now let's run our program and see what
happens all right so we get four
messages on the terminal first we get
the start message then we get the
messages coming from our create function
so hi there and welcome aboard and
finally we see the finished message
so let me explain the flow of our
program when python runs this code it
doesn't actually print these two
messages on the terminal because these
lines of code are inside of this
function so they will only get executed
if we call this function if we don't
call this function these lines will not
get executed okay
so the execution of our program actually
starts here the first message that we
see on the terminal is the start message
after that python sees that we're
calling the greet function so it will
jump over here and then execute these
two lines
then it will jump outside of this
function and continue the normal
execution of our program so it will
print the finished message on the
terminal
so this is how functions work
also note that the order of this code
matters so here we're calling the grid
function after we have defined it if you
try to call it before you define it you
will see an error for example
if we call
greet user function right here see we
immediately get this red underline which
says unresolved reference greet user
which basically means python doesn't
know what is this great user it's not
defined anywhere
so we always define our functions first
and then call that
here's the function we created in the
last tutorial now i got a question for
you what is the difference between
calling this function
and the print function of python
the difference is that the print
function takes some information in this
case the message that we want to print
but our grid function doesn't take any
information wouldn't that be nicer if
you could pass the name of the user here
and then instead of saying hi there we
could print the name of the user so in
this tutorial i'm going to show you how
to pass information to your functions
and that is pretty easy
so
back to the definition of our great user
function
inside of this parenthesis we can add
parameters these parameters are
placeholders for receiving information
for example we can add a name parameter
and with this we can pass the name of
the user when calling this function so
let's pass john here
now when we call this function and pass
this value this name parameter will be
set to john
so it will act like a local variable
that we define inside of this function
just imagine we didn't have this
parameter and instead we had a variable
like name that was set to john now here
we could simply print the name of this
user so we could use a formatted string
and print the value of the name variable
right now we don't really have this
local variable defined in this function
we have a parameter
it's exactly the same thing so with
these parameters we can receive
information in our functions now let's
go ahead and run this program
so take a look we get hi john welcome
aboard we can take this to the next
level now we can call this function one
more time
so greet user and this time supply a
different name let's say mary
so we are reusing our grid function and
passing it a different value
imagine if we didn't have this function
we would have to repeat this line twice
once for high john and another time for
hi mary so this is the benefit of
defining functions we can take a few
lines of code that have a specific
purpose and put them inside of a
function
so now let's run our program one more
time
there you go so we get hi john welcome
board then we get high mary welcome
aboard
now note that when a function has a
parameter we are obligated to pass a
value for that parameter so if we remove
john
from here
and run our program we get this type
error grid user missing one required
positional argument
argument in programming is the value
that we supply to a function so
back to this example
mary in this case is an argument that we
pass to the name parameter a lot of
programmers don't know the difference
between parameters and arguments and
think they are the same but they are not
parameters or the holes or placeholders
that we define in our function for
receiving information
arguments are the actual pieces of
information that we supply to these
functions okay
so let's bring back
this john string okay now we can also
define multiple parameters for example
let's rename this parameter to first
name as i told you before you can right
click here go to refactor and then
rename or preferably you can use a
shortcut so the shortcut for this on mac
is shift and f6
and this brings up the rename dialog box
here we can change this to first
underline name
now we can add a second parameter so
comma
followed by last underline name
so back to our formatted string let's
also print the last name beautiful so
here when calling this function then we
can supply
another argument
so john smith and let's delete
this line we don't really need it
anymore run our program take a look hi
john smith
so in the last tutorial you'll learn
that whenever we define parameters for
our functions we should always supply
values otherwise we'll get an error
let's look at that there one more time
so i'm going to delete the second
argument and only pass john
run our program
we get this message
greet user missing one required
positional argument
so these are arguments that we have here
like john and smith we refer to these as
positional arguments which means their
position or order matters in other words
the first argument we add here is the
value for the first parameter and the
second argument is the value for the
second parameter so if we change their
position or order we'll get different
result let's take a look let's pass
smith first and then
john okay
delete that's good let's go with this
so instead of getting high john smith we
get high smith john
so that is the reason we refer to these
arguments as positional arguments their
position or order matters but in python
we also have keyword arguments and with
those the position doesn't matter let me
show you how they work so let's say here
we want to pass john as the value for
the first name parameter we can simply
specify that here so first name equals
john
now what we have here is a keyword
argument
so this combination of having the
parameter name followed by its value is
what we call a keyword argument and with
these keyword arguments the position
doesn't really matter
so here we're supplying john as an
argument for the first parameter
now similarly we can use a keyword
argument for smith let me show you so
last name equals smith's
so now we have two keyword arguments so
with these keyword arguments we don't
have to worry about the order of the
parameters that doesn't mean we should
always use keyword arguments not really
most of the time we use positional
arguments but in certain situations
these keyword arguments help us improve
the readability of our code
so on line 7 it's quite clear that we're
supplying smith as the last name and
john as the first name
now in this particular example even if
we didn't have the keyword arguments
just passing two positional arguments
like john and smith would be sufficient
because it's easy to guess what is the
purpose of this argument but sometimes
you're dealing with functions and you're
passing numerical values to them in
those situations it may not be quite
clear what these values represent let me
show you an example let's say we have a
function for calculating the total cost
of an order so we can call that
calculate underlink cost
so when calling this function we need to
supply three pieces of information
one is the total cost of all the order
items let's say fifty dollars
the other is the shipping cost let's say
five dollars and the last piece is a
discount let's say 0.1
someone reading this code may not be
sure what these three values represent
in this case we can improve the
readability of this code by using
keyword arguments so we can prefix each
value with the name of the parameter
they target for example we can set total
to 50 and then shipping to 5 and
discount to 0.1
now if we give this code to someone else
they can immediately tell what these
values represent so that is the power of
keyword arguments so here's what i want
you to take away for the most part use
positional arguments but if you're
dealing with functions that take
numerical values see if you can improve
the readability of your code by using
keyword arguments you simply prefix the
arguments that you pass with the name of
their parameters and this will increase
the readability of your code now there
is one more thing you need to know about
keyword arguments these keyword
arguments should always come after
positional arguments let me show you
what i mean so
back to our simple create user function
let's use a keyword argument for the
first name
so
let's set first name to john and see
what happens look we immediately get
this error take a look positional
argument after keyword argument so when
calling this function we're supplying
one keyword argument and one positional
argument and python doesn't like this
so if you're mixing positional and
keyword arguments you should always use
the positional arguments first and then
the keyboard arguments
in other words let's remove this keyword
argument here
so john is now a positional argument is
targeting the first parameter right now
after this position argument we can
supply any number of keyword arguments
so if we set last name to smith look
python doesn't have any problem with
this because we're adding a keyword
argument after a positional argument so
let's quickly recap for the most part
use positional arguments if you're
dealing with functions that take
multiple numerical values and it's not
quite clear what those values represent
use keyword arguments to improve the
readability of your code and finally if
you're passing both positional and
keyboard arguments use the keyword
arguments after the positional arguments
so far you have learned how to create
functions and send them information
using their parameters
in this tutorial i'm going to show you
how to create functions that return
values this is particularly useful if
you're doing some kind of calculation
your function and you want to return the
result to whoever is using your function
let me show you so
let's start by defining a function
called square this function simply
calculates the square of a number
so we need to add one parameter here
that is our number
now here we want to calculate number
times number that is the square of a
number
now to return this number outside of
this function we simply use the return
statement so return
now our square function is very simple
it only has one line of code but in a
real program you might have a function
that has 10 lines of code to calculate
something so
this return statement is very valuable
with that we can return values to the
colors of our function
so with this when we call
the square function let's say we give it
3
now this function returns a value just
like the input function of python this
input function waits for the user to
type something and press enter and then
it will return the user's input as a
string so we can get it and store it
in a variable like this right we have
the same story with our square function
so our square function returns a value
we can simply get it and store it in a
variable let's call that result
now we can print
result on the terminal
there you go so result is nine we could
also
pass this function call directly inside
of the print function without defining a
separate variable sometimes this is
useful for writing shorter code so in
this case we don't really need this
result variable we simply want to print
the square of three
so we could simply pass this function
call
right here as an argument for the print
function
so let's delete this variable now our
code is shorter so with this we're
calling the square function this returns
a value and we'll pass that value as an
argument to the print function
okay
when we run this program we get the
exact same result there you go
now what happens if we don't use a
return statement in our function so in
the last example we simply used a print
statement let's temporarily
remove this return statement and
print the result on the terminal like
this
so let's run our program one more time
and see what we get we get two things on
a terminal the number nine and none what
is happening here
well when python interpreter executes
this code first it will call the square
function
so the control moves to the square
function here we calculate the square of
this given number and then print it on
the terminal that is the reason we see 9
right here
now by default all functions return the
value none
so if we don't have a return statement
here
by default python returns
none none is an object that represents
the absence of a value it's like nothing
or null in c c plus plus java and
javascript
so
in this example we didn't have a return
statement and by default python returned
none from this function
so after the square function is executed
the value none is returned and passed as
an argument to the print function that
is the reason we see
none on the second line
so here are the two things you need to
take away from this tutorial by default
all functions in python return none you
can change that so if you have a
function that calculates something you
can return the result using the return
statement
here's the code for our emoji converter
program that we wrote earlier if you
missed that tutorial make sure to go
back and watch it as i told you before
there is a table of content right below
this video in the description so you can
simply click on the emoji converter
tutorial to watch it
now your exercise is to reorganize this
code using a function so i want you to
extract a function in this code because
this algorithm for converting these
smiley faces into emojis is something
that we probably want to use in a lot of
different applications you can use it in
a chat application in an email
application and so on we don't want to
write all this code every time we want
to convert these characters into smiley
faces
so out of all these lines of code that
we have from line 1 to line 10 the lines
2 to 9 belong to our algorithm
all these lines together implement this
feature
so you should put these lines in a
separate function
now why don't we have the input in that
function because the input can come in
different forms currently we're using
the input function to receive the input
from the terminal but in other
applications we might receive the input
from a graphical user interface so the
input can come in different forms we
don't want to put that in our function
because this line will not be reusable
we want to give our function
the actual message as a string we don't
care how we got that message in one
program we might get it from the
terminal in another program we may get
it from a graphical user interface
so that is the reason this line of code
should not be in that function by the
same token
you shouldn't include the last line in
that function because what we do with
the output is different from one program
to another in this program we're
printing the output in another program
we might send that output as an email or
as a response in a chat application so
as a general rule of thumb your
functions should not worry about
receiving input and printing it these
lines of code should not belong to your
functions so go ahead and reorganize
this code by extracting a function
all right on the top first we need to
define our function so we type def
give our function a name like emoji
underline converter so the name of this
function clearly tells me what it does
each function should be responsible for
one and only one task and that task
should be clearly explained in the name
of the function okay
so our emoji converter function should
take a parameter we call that message
that is a string right
colon
now we need to move the lines five
all the way
to the end of our four block
into that function so
let's select all these lines
we can cut them from here by pressing
command and x on mac or control and x on
windows
then we paste them here
as you can see these lines are
automatically indented so they are part
of the emoji converter function if this
didn't happen on your computer make sure
to select these lines and use the tab to
indent them
all right so here's our emoji converter
function beautiful
now
after that
in the main flow of our program first we
get the input from the user
we store it in this variable message
and then
we call
emoji converter and pass this message
this function should return a value that
is what we calculate
at the end of this function so right
after this 4 block we need to add a
return statement return output
now that our function returns a value
we can get it and store it in a separate
variable let's call that result and then
we can simply print that here
or we can make this code shorter we
don't really need this variable here so
we can simply
call the emoji converter
and print the result
like this now here we have another line
because
as i told you before we need two blank
lines after our function definitions so
currently we have only one black line we
need to add
another black line
let's go ahead and run this program to
make sure everything works as before
so i'm going to type a message like good
morning with a smiley face
good let's run it one more time
i'm sad too bad okay beautiful
so here's the final
result we defined this function called
emoji converter this function takes a
parameter called message
and finally returns the output
in this tutorial i'm going to teach you
guys how to handle errors in your python
programs so let's start by writing a
small program to get the user's age from
the terminal so we call the input
function
input
add a label here
like age
this returns a string so we need to pass
it to the end function
and then store the result
in a variable called h
now let's print h to make sure we have
implemented everything properly
run our program
we type 20
20 is printed here beautiful now look at
the exit code of this program exit code
0 means our program terminated
successfully there were no errors but
what if we run this program
one more time and instead of entering a
numerical value we enter something like
asd
we get a value error
with this message invalid literal for
end with base 10. basically what this
message is telling us is that this
string asd does not contain a valid
whole number that can be converted to an
integer now look at the exit code of
this program exit code one means our
program crashed so zero always means
success and anything but zero means
crash
now as a good python programmer you
should anticipate these situations you
don't want to let your entire program
crash just because the user entered an
invalid value
so instead of letting the program crash
you should handle this situation and
print a proper error message and that's
what i'm going to show you in this
tutorial
now if we're going any further
look at the type of the error we get
here value error so remember this we're
going to get back to this shortly
now how can we handle these errors
in python we have a construct called try
accept
we use that to handle errors let me show
you how it works so
on the top we type try colon
now as you know we're defining a code
block so i'm gonna move these two lines
inside of our try block so press tab
here
and remove this blank line
now these two lines are part of our try
block right
so
after try we type accept
and then we add the type of the error
that our program may encounter
that is value error
okay
then we add a colon
and in this block we can define what
should happen if our program encounters
an error of type value error
in this case we want to print a proper
error message so print
invalid value
so we just try and accept we're telling
python hey go ahead and try running
these two lines of code if you encounter
an error of type value error then
instead of crashing the program
print this error message on the terminal
so this is how this works
now more accurately in programming terms
we refer to this kind of error as an
exception so an exception is a kind of
error that crashes our program so if the
user enters
an invalid value this line of code line
two will raise an exception and on line
four we'll catch it
and print this error message so our
program will no longer crash let me show
you so let's go ahead and run this
age 20
everything works just like before and
the exit code is zero beautiful let's
rerun this program and
enter asd
so we get this proper error message
invalid value and once again the exit
code is zero so that means our program
completed successfully didn't crash
now we can also handle different kinds
of errors or exceptions for example
right after we get the age
let's define a variable income and set
it to 20 000
and then define another variable called
risk and set it to income
divided by h
let's run this program and enter 0 as
the age to see what happens
so
0 is obviously a numerical value so when
we enter this value technically we
shouldn't get any exceptions
take a look
our program crashed with a zero division
error because we cannot divide the
number by zero once again look at the
exit code so we couldn't catch this kind
of error or this kind of exception
with this except block this except block
is only caching exceptions of type value
error and this happens when we try to
convert a non-numerical value to an
integer
so in a situation like this we should
handle different kinds of exceptions
we can add another accept statement for
an exception of type zero division error
now in this block we can print a
different kind of message
like age cannot be
zero
let's run our program one more time
now i'm going to enter 0 as the age
so we get this error message h can not
be 0 and look at the exit code
it's 0 so our program didn't crash
so to recap we used try except blocks to
handle exceptions that are raised in our
programs as a good programmer you should
always anticipate this kind of
exceptions and handle them properly
in this tutorial i'm going to talk to
you guys about comments in python we use
comments to add notes or comments to our
programs for example here i'm going to
make a print statement
sky is blue now before that
i can add a comment using a height sign
and then whatever i type here
it's going to get ignored it's not going
to get executed let me show you so let's
run this program
look we only see this message sky is
blue
so with this comment we can explain
something about our code we can use that
as reminders to fix things or clean
things up or we can use it to
communicate things with other developers
reading our code why we have written
this code in a certain way these are
good use cases for using comments we can
also have comments over multiple lines
so we can simply add more comments
each line should start with a new high
sign now one thing you need to avoid
when using comments is explaining what
the code does so here's an example of a
bad comment let me just delete these two
lines
and with this comment i'm going to say
print sky is blue
why is this a bad comment because it's
telling me the obvious it is obvious
that the next line is going to print sky
is blue now the problem with this
comment is that apart from being verbose
and repetitive if we come back here and
change sky to ocean
now this comment gets outdated so every
time we change this code then we'll have
to come back and modify the
corresponding comment so i've seen some
developers add comments in front of
their functions for example they define
a function let's say square that takes a
number and simply returns
number times number well it is obvious
that this function calculates and
returns the square of the given number
so there is really no need to add a
comment and explain that calculates
and returns the square of a number
this is very repetitive and it creates
noise in your code someone else reading
your code they get distracted with all
these unnecessary comments so use
comments to explain whys and how not
what's if you have made certain
assumptions you can use comments to
explain those assumptions or you can use
them to add notes to remind yourself or
other developers to do something in the
code
so comments are good but too much of a
good thing is a bad thing
in this tutorial i'm going to talk to
you guys about classes in python classes
are extremely important in programming
and they're not specific to python in
fact a lot of other programming
languages do support the notion of
classes we use classes to define new
types for example so far you have
learned about the basic types in python
like numbers strings and booleans these
are the basic or simple types in python
you also learn about a couple of complex
types like lists and dictionaries
while these types are extremely useful
they cannot always be used to model
complex concepts for example think of
the concept of a point or a shopping
cart a shopping cart is not a boolean
it's not a list it's not a dictionary
it's a different kind of thing so we can
use classes to define new types to model
real concepts
now in this tutorial i'm going to show
you how to define a new type called
point and this new type is going to have
methods for working with points for
example back to our main program let's
create a list numbers one two three
you know that here when we type dot we
get access to these functions or methods
available in list objects now similar to
this we're going to create a new type
called point this point is going to have
methods like move draw get distance from
another point these are the operations
that we can perform on points
so let me show you how to do this we
start by defining a class using the
class keyword and right after that we
give our class a name
now look at the naming convention i have
used here i've capitalized the first
letter here this is what we call pascal
naming convention so the convention we
use for naming our classes is different
from the convention we use for naming
our variables and functions
for variables and functions we always
use lowercase letters and we separate
multiple words using an underscore but
when naming classes we don't use an
underscore to separate multiple words
instead we capitalize the first letter
of every word so in this case our class
has only a single word if it had
multiple words let's say email client
look i've capitalized the first letter
of every word once again this is called
pascal naming convention and it comes
from the old pascal language that you
might have heard of
so
back to our point class
here we have a colon which means we're
going to define a block
now in this block we can define all the
functions or methods that belong to
points
for example we can define a function
called move for moving a point
now note that as soon as we type open
parenthesis pycharm automatically adds
self here this is a special keyword and
we're going to get back to this shortly
so
for now in this method let's print
move on the terminal
now let's define another method like
draw
so define draw
and in this method let's print draw on
the terminal
now let's remove the indentation
we're done with the definition of our
point class so we need to add two line
breaks
okay
so with this class we defined a new type
with this new type we can create new
objects so an object is an instance of a
class a class simply defines the
blueprint or the template for creating
objects and objects are the actual
instances based on that blueprint so we
could have tens or hundreds of points on
the screen these are the objects or the
instances
so to create an object we type out the
name of our class
and then call it like a function
this creates a new object and then
returns it so we can store that object
in a variable let's call that point one
there you go
now when we use the dot operator
look we have
these two methods that we defined draw
and move we also have a bunch of other
methods that start with two underscores
these are called magic methods we'll
look at them later in the course
so now let's call the draw method of our
point object and
run our program so you can see draw is
printed on the terminal
now apart from methods these objects can
also have attributes and these
attributes are like variables that
belong to a particular object for
example here
after we define point one
we can set point 1 dot x to 10 and point
1 dot y to 20.
now we can easily print out this
attributes let's print
0.1.x
and run our program one more time take a
look so the x coordinate of point one is
ten now we can create another object
let's call that point two
so point two
once again we type out the name of our
class and then call it like a function
now this object is completely different
from the first object so if we print
point 2 dot x
flow can we get this attribute error
because this point object doesn't have
an attribute called x
so each object is a different instance
of a point class
and here we can assign a value to point
two dot x
let's set that to one and then run our
program so we can see the x coordinate
of 0.2 is 1.
so to recap
we use classes to define new types
these types can have methods that we
define in the body of the class and they
can also have attributes that we can set
anywhere in our programs
you have learned how to create new types
using classes now there is a tiny
problem in this implementation
we can create a point object without an
x or y coordinates let me show you so
point
we create this object here and before we
set
point.x let's print point.x
run our program
we get this attribute error that you saw
in the last tutorial so point object has
no attribute called x
this is the problem we have here it is
possible to have a point object without
an x or y coordinates and that doesn't
really make sense because whenever we
talk about a point we need to know where
that point is located to solve this
problem we use a constructor a
constructor is a function that gets
called at the time of creating an object
so here on line 9 when creating this
point object we want to pass values for
x and y coordinates let's say 10
and 20 and with this this point object
that we get here will have its x and y
coordinates initialized so how do we do
this we need to add a special method in
this class called constructor
so on the top
we define a new function
look at the name of this function double
underscore
init double underscore
so init is short for initialize and this
is the function or the method that gets
called when we create a new point object
now press enter
so this automatically adds
self in parenthesis we're going to come
back to this shortly
now right after self we want to add two
extra parameters x and y so let's type
out x and y
and then in the body of this method we
should read the values passed here and
use them to initialize our object so
when we pass 10 and 20 these arguments
will be used for
x and y parameters
now to initialize our object we type out
code like this self dot x equals x
and then self.y equals y what is going
on here
this self that you see here is a
reference to the current object
so
back to line 13 when we create a new
point object self references that object
in memory the same object that we are
referencing using this variable
so earlier we typed point that x equals
10 with this code we set the x attribute
of this point object now what we have in
the constructor is exactly the same
we're using self to reference the
current object and then we set the x
attribute to the x argument passed to
this function
so using this init method we can
initialize our objects
and we refer to this method as a
constructor this method is used to
construct or create an object okay
so
now
let's remove line 14. so we create a
point object with these values and then
print point.x let's run our program
there you go x is 10. we can also change
these values later so just before
printing point.x we can set point.x to
11 and then run our program so x is
updated beautiful
all right here's an exercise for you i
want you to define a new type called
person
these personal objects should have a
name attribute as well as a talk
method
this is a very easy exercise so you can
tackle it in probably a couple of
minutes
all right so first we start with the
class keyword we define this person
class once again look at the naming
convention i have used here the first
letter of the first word in this case
the only word is uppercase
now in this class we define all the
methods that we need currently we have
only one method that is the talk method
so define talk
pycharm automatically adds self we come
back to this shortly
for now let's just print talk
so this is the body of our person class
we remove the indentation
and add two line breaks after defining
our classes
now we can create a personal object
let's call that john
we set it to person
we can call john.talk
let's run the program
so we get this message beautiful but our
personal objects should also have
a name attribute it doesn't make sense
to have a person without a name so that
is when we use the constructor function
so on the top we add a new method
the name of this method is double
underscore init double underscore
so we call this method a constructor
now in this method we need to add
another parameter that is name
so we simply set self.name to name
once again self references the current
object so we're setting the name
attribute of the current object to the
name argument passed to this method
with this we can go back to line nine
and when creating a personal object we
pass the name let's say john smith
now let's print john dot name
and run our program there you go so john
smith is printed on the terminal
beautiful so this is all you had to do
as part of this exercise but let's make
this program a little bit more
interesting
instead of printing this boring message
here let's print hi i am john smith
so we can use a formatted string with a
message like hi
i am now we want to dynamically add the
name of this person how do we do that
well look at the parameter
of this talk method as i told you before
every method in our class should have
this parameter self and this should be
the very first parameter of every method
okay so with itself we can get reference
to the current object
so
we can add curly braces and type out
self dot name
this returns the name attribute of the
current person object
with this we can remove
line 10
where we print john.name and simply call
john.talk
let's run our program
hi i am john smith beautiful
now we can create another personal
object let's say bob
it's a new person
called bob smith
when we say
bob.talk
and run our program
we get a different message hi i'm bob
smith so each object is a different
instance of a person class
in this tutorial i'm going to talk to
you guys about inheritance in python
inheritance is a mechanism for reusing
code and once again it's not limited to
python most languages that support
classes also support inheritance so let
me show you how it works let's say we
have this dot class with a simple walk
method in this method we're simply
printing the walk message on the
terminal now let's say in a real program
instead of just one line of code here
we're going to have 10 lines of code
now what if in the future we want to
define another class let's say cat
and we want to add this walk method
there as well we'll have to repeat all
that code in this new class
walk
this is bad because we have repeated or
duplicated our code in programming we
have a principle called dry which is
short for don't repeat yourself and
here's the reason
let's say sometime in the future we
discover a problem in our walk method if
we have repeated or duplicated this
method in many other places then we'll
have to come back and fix that problem
in every single place we have duplicated
this code so that's why in programming
we should not define something twice
so how can we solve this problem
well there are different approaches one
approach which is easier to understand
for beginners is inheritance and here's
how it works we define a new class
called mammal and move the walk method
right there
then we'll have the dog and cat classes
inherit that method from their parent
just like how humans inherit certain
attributes or behaviors from their
parents it's exactly the same
so
on the top we're defining a new class
let's call it mammal
then we need to move the walk method
there so we select it cut it using
command x on mac or control x on windows
and then paste it here
beautiful
now we want our dot class to inherit
this method from the mammal class so
right after the class name we add
parenthesis and then type out the name
of the parent class in this case mammal
that's all we had to do
so with this the dot class will inherit
all the methods defined in the mammal
class now there's a tiny problem here
if you look at line 9 there is a red
underline here
the reason this is happening is because
python doesn't like an empty class
so right now our dot class is empty it
doesn't have anything we either need to
add methods specific to dogs or just to
make python happy we can use the pass
statement and that basically means
nothing we're telling python interpreter
hey pass this line don't worry about it
but with this we don't have an empty
class okay
now as i told you before after each
class you should have two line breaks so
right now we only have one line break
and that is the reason we have this
little warning here so let's add another
black line beautiful
so our dog class is inheriting the walk
method from the mammal we need to apply
the same change to the cat class so
we'll have cat
inherit from mammal
and then
we use the pass statement here
with these changes now we can create
either a dog or a cat object let's say
dog one
we set it to a dog object
and when we type
dot look we have the walk method that is
defined in the mammal class we can
easily call it let's run our program
there you go we see the walk message
so both the dog and cat classes are
inheriting all the methods defined in
their parent class now here we can add
methods specific to dogs for example we
can define
a method called bark
and then print bark
now we don't need the pass statement
because we already defined one method in
our dog class
so now when we type out dog one dot
look we have two methods one is the walk
method that we inherited and the bark
method that we just defined in the dog
class similarly we can add a method
specific to a cat for example we can
define a method called be
annoying yeah i hate cats so
let's print
annoying
now when we create a cat object let's
remove that cat one
and type out cat one dot we have these
two methods walk and bnoy
so these are the basics of inheritance
in python now there is more to this that
really goes beyond the scope of this
beginner's tutorial if you're interested
to learn more about inheritance and
other mechanisms for reusing code i
encourage you to get my complete python
course
in this tutorial i'm going to talk to
you guys about modules in python a
module in python is basically a file
with some python code and we use modules
to organize our code into multiple files
just like sections and a supermarket
when you go to a supermarket there are
different sections for fruits vegetables
cleaning products and so on we don't
have one section with all the products
in the supermarket we have the same
concept in programming so instead of
writing all of our code instead of
writing all the functions and classes in
app.pi we want to break up our code into
multiple files we refer to each file as
a module with this not only is our code
better organized and structured but
we'll also have the ability to reuse our
code for example over here in app.pi
i've defined two functions for
converting weight from pounds to
kilograms and vice versa
now we can take these two functions and
put them in a separate module called
converters and then we can import that
module into any program that needs this
converter functions let me show you how
to do this so
let's open up our project panel and
right click the project
go to new and add a new file
we're going to call this file converters
dot pi
then we go back to app.pi
select all this code cut it and then
paste it into our new module
converters.pi
with this we have cleaned up our app
module it's not bloated with different
functions so as we write more functions
and classes we put them in their
corresponding modules
a module should contain all the related
functions and classes okay
now you want to import the converters
module into our app module and that is
really easy on the top right
import
converters
without the extension so we don't add
dot pi we only type out the name of the
file
let me close the project panel
now this converter is an object so we
can use the data operator to access its
members so currently we have defined
these two functions inside of our module
kilogram to pounds and pounds to
kilogram
so we can easily call one of these
functions let's pass 70 kilos get the
result and print it out
run our program
so
that is 155 pounds
now there is also another syntax for
importing modules let me show you so
instead of importing the entire module
we can import specific functions from
that module here's how it works we type
out from
then we add the name of our module so
converters
import now here if you press control and
space you can see the list of all the
functions defined in this module so here
we can grab one of these functions let's
say kilogram to pounds and with this we
can directly
call this function just like a function
defined in this file app.pi
compare what we have on line 4 with what
we have on line 6. on line 6 we'll have
to prefix this function call with the
name of an object converters so we have
to type converters dot and then we'll be
able to access this function
in contrast when we import a specific
function from our module then we can
easily call that function without
prefixing it with the module name so
here's what you need to take away we use
modules to better organize our code
instead of writing all the code instead
of writing all our functions in one file
we break up our code across multiple
files each file is called a module and
it should contain all the related
functions and classes
then we can import a module into another
module in this case we are importing the
converters module into our app module
and as you saw there are two ways to
import a module we can import the entire
module and then we'll get an object with
the same name as the module so we can
type converters dot and then we'll be
able to access all the functions and
classes defined in this module the other
approach is to import a specific
function or class from a module using
the from import statement
now here's your exercise earlier in the
course we had an exercise for finding
the largest number in the list
so here on the top we have a list of
numbers initially we set max for the
first number in this list
then we loop through this list get each
number
if the current number is greater than
max then we reset max and finally when
we're done with our loop we print max on
the terminal now here's what i wanted to
do this code currently has no
organization we don't have any functions
we don't have any modules we wrote all
the code in app.pi and that is okay for
small programs but as your programs grow
you need to properly organize your code
into functions classes and modules
so as part of this exercise i want you
to write a function call it find
max
this function should take a list and
return the largest number in that list
now after you do this go ahead and put
this function in a separate module so
extract it from here and put it in a
module called utils
so in this module we're going to have a
bunch of utility functions
okay
then
import the utils module into the current
module and call this function
finally get the result and print it on
the terminal this is a fantastic
exercise to teach you how to properly
organize your code so go ahead and spend
a couple of minutes on this exercise
so the first step is to define a
function called find max
so on the top i'm going to define a
function
find max
this function should take a list of
numbers so we add a parameter called
numbers
now instead of this function we want to
have these few lines this is the
algorithm for finding the largest number
in the list we don't want to bring the
first line because this is where we
create a list so somewhere in our
program we're going to create this list
and then pass it as an argument to find
max function okay so
let's go ahead and grab these few lines
cut them and
put them inside of find max function
all right so we find the largest number
in this list finally we need to return
it so
return
max
so here's our function now we need to
move this into a separate module so
let's go to the project panel
right click the project
and add a new file we can also add a new
python file is the same
let's call that utils
so if you add a new python file pycharm
automatically adds dot pi extension but
if you go to
new file we'll have to explicitly type
out dot pi
so make sure to get the extension right
now back to app.pi
let's cut this code and paste it into
this new module
okay beautiful
now we go back to app.pi and import our
new module we can either import the
entire module
so import utils and then access
individual functions so we can call
utils dot find max or we can explicitly
import this function from the utils
module it doesn't really make a
difference so
we could type from utils import
find max
and then
we don't need to prefix this with the
name of its object so we simply call
find max
now we need to call this after we
initialize our list
so first we need to define the list of
numbers
then
we pass that list as an argument to find
max we get the result which is max and
finally we print it on the terminal
let's go ahead and run our program
so the largest number in this list is
10. beautiful now one last thing before
we finish this tutorial
here we have this little warning under
max and the tooltip says shadows
built-in name max the reason we see this
is because in python we actually have a
function called max and it does the
exact same job as our find max function
so this is actually built into python
but i ask you to do it as an exercise
because it's a great exercise for
beginners now back to the warning
this warning is basically telling us
that we are overwriting the built-in max
function in python so we're changing the
meaning of this function and this is
considered a bad practice let me show
you what i mean so let's comment out
what we have on line four by putting a
heist line here we can also use
a shortcut command and slash on mac or
ctrl and slash on windows
so now this line is commented out look
at the color max here it's purple it's
the same color as print and this is the
color used to identify the built-in
functions
so now we can call this function
and give it
our list of numbers
run our program
we get the exact same result however
if we bring this line back once again we
can use the same shortcut that is
command and slash on mac or ctrl slash
on windows
now we are redefining max so up to this
line max used to be a function but after
line 4 is executed max is set to an
integer that is the largest number in
this list
so we'll no longer be able to call it
on line 5.
let's run our program and see what
happens
so there you go we get this type error
int object is not callable because max
is now an integer it's not a function so
we cannot call it
so to solve this problem we can rename
this variable to something else
so right click here
go to refactor
and rename
and rename this to maxi mum
so you can see the warning is gone
also we have the same warning in our
utils module
so here we're redefining max and as i
told you before this is a bad practice
we're changing the meaning of built-in
functions in python so
let's rename this as well i'm going to
use the shortcut that is shift and f6
there you go
and here we can change this to maximum
enter done
in this tutorial we're going to talk
about packages in python packages are
basically another way to organize our
code so currently we have only three
files or three modules in our project
but a real project can contain hundreds
or even thousands of modules we don't
want to add all those modules here
because over time this directory will
get bloated with so many files so a
better approach is to organize related
modules inside of a package so a package
is a container for multiple modules in
file system terms a package is a
directory or folder
so in our project we can add a new
directory and in that directory we can
add all the related modules as a
metaphor think of a mall when you go to
a mall or a shopping center there are
different sections for men's women's and
kids clothing so that is like a package
now when you go to the men's section
there are different areas for different
kinds of products we have a section for
shoes t-shirts jackets and so on so each
of these is like a module
so in this tutorial i'm going to show
you how to create and use packages in
python
here in our project panel right click
the project and add a new directory
let's call this directory
e
commerce
so we're going to create a package
called e-commerce and in this package
we're going to have all the modules
related for an e-commerce application
for example we can have modules for
sales shipping customer service and so
on so let's go ahead
now here we have an empty directory
in order to convert this to a package we
need to add a special file in it so
right click this directory and add
a new python file
call that file double underscore in it
double underscore
this is a special convention in python
when python interpreter sees
a file with this name in a directory it
treats this directory as a package we
also have a shortcut for that in pycharm
so let me delete this directory and
start again
so delete
once again right click the project
and go to new but instead of creating a
new directory we can create a new python
package
let's call our package ecommerce
as you can see pycharm automatically
creates this file for us so we don't
have to manually create it okay
now in this package let's add a new
module so a new python file
let's call it shipping
okay
now in this module we want to add a
function for calculating the shipping
cost
so define
calculate underline shipping
and don't worry about parameters or the
implementation we simply print
calculate underline shipping
now let's say we want to import this
shipping module into our app module
with this new structure the shipping
module is now part of the e-commerce
package so we cannot import it directly
we have to start from the e-commerce
package okay
so
back to app.pipe once again there are
two ways to import this module we can
import the entire module or we can
import one of its functions or classes
so let me show you both approaches first
we're going to import the entire module
import
now what is the name of our package that
is e-commerce right so e-commerce dot
shipping
so instead of typing import shipping we
type import e-commerce dot shipping we
have to prefix it with the name of its
package
now to access any of the functions or
classes in this module we'll have to
type out ecommerce.shipping
dot
and there you go now we can access the
calculate shipping function
so let's go ahead and run our program
we see this message printed on the
terminal beautiful however with this
approach every time you want to call one
of the functions in this module we'll
have to prefix it with e-commerce dot
shipping dot that is very verbose so
when working with packages we often use
the second approach using the from
statement
so we can type from
ecommerce.shipping
import
calculate shipping
now we don't have to prefix this
function with ecommerce.shipping
and we can call it multiple times in
this module so our code is a little bit
shorter but what if you want to use
multiple functions in the shipping
module
we can either import them all here so
calculate shipping
comma let's say calculate underline tags
or we can import the entire module and
then access all the functions or classes
in that module
so let me revert this back
to import the entire module we type from
e-commerce so we remove dot shipping
so from this package import
the shipping
module
now this shipping module is an object
so we can access
all the functions and classes defined
here using the dot operator so shipping
dot there you go calculate shipping
so to recap when using the from
statement we can either start from the
package and import a specific module
or we can start from package dot
module and then import a specific
function
like calculate shipping
so this was the basics of using packages
in python as i told you before packages
are extremely important especially when
you want to work with a framework like
django we use django for building web
applications with python and i'm going
to show you that later in this course
so in django we have quite a few
packages and each package contains
several modules so make sure to watch
the tutorials about modules and packages
one more time otherwise you're going to
get confused later when we get to django
in this tutorial i'm going to talk to
you guys about the built-in modules in
python so python comes with a standard
library that contains several modules
for common tasks such as sending emails
working with data and time generating
random values and passwords and so on
there are so many modules already built
into python and that means there is
already lots of functionality that we
can reuse we don't have to code all of
that from scratch let me show you where
you can find the standard library so
open up your browser and search for
python 3 module index
make sure to add the version number
because the modules in python 2 are
different from modules in python 3. so
here we search for python 3 module index
and the first page here you can see it's
python module index for python 3.
let's go ahead so these are all the
modules
built into python for example we have
modules for working with data and time
we have modules for sending emails for
encoding values there are so many
modules here now the explanation of all
this is beyond the scope of this course
that really requires its own course
because we have so many modules here but
don't let this list intimidate you this
is not something that you need to learn
right now as you work with python as you
build more applications gradually you'll
get more familiar with various modules
here in fact nobody knows all the
modules in python standard library
everybody knows some modules based on
the applications they have built
so in this tutorial i'm going to show
you how to use one of the built-in
modules for generating random values so
on the top we import
the random
module
now because random is a built-in module
we don't need to have a file here called
so python interpreter knows that random
is a built-in module and it knows where
to find it now if you're curious where
this random module is stored on the disk
let me show you so here in the project
panel
expand external libraries
then expand python 3
and then one more time python 3.7
library root
so this is a folder somewhere on your
computer in this folder we have all the
built-in modules in python so if you
scroll down
you should be able to find
the random module there you go it's
right here it's a random.pi you can open
this
and
this shows you the source code of this
module there you go
now in this tutorial we don't want to
worry about that so let's go back to our
app.pi and use this module to generate
random values
so when we import this module now we
have this object random so we can use
the dot operator to access its methods
one method that is very useful here is
the random method and every time we call
it it generates a random value between 0
to 1.
so here we can do a for loop
let's say four
i
in
range three so just to refresh our
memory we are using the range function
to create a range object we can loop
through this range object and in each
iteration this object will spit out a
value
so with this for loop we can execute
this code three times now let's indent
this okay and finally let's print the
result
there you go so we can see that in each
iteration we get a new random value
between 0 to 1. now what if we want a
random value for a particular age let's
say random values between 10 to 20. well
there is another method here around and
we passed two arguments here to specify
our range let's say 10 and 20.
run our program one more time
now we have the numbers 20 13 and 18. if
we run our program one more time we get
different values so 20 19 11 one more
time
look
we also have another powerful method for
randomly picking an item from a list
let's say we have a list of team members
and we want to randomly pick someone as
the leader let me show you how to do
that so we define the list of team
members
we set it to
john
mary
bob
and marsh
now
we can call random the choice
and pass
our members list
this method randomly picks an item from
this list and returns it so we can store
the result in leader and then print it
on the terminal
let's run our program
so now the leader is merry if we run our
program one more time this time it's
mosh now it's march again one more time
it really likes much
now it's bob you got the point so the
random module is very powerful and it
has a lot of applications
now here's a very cool exercise i wanted
to write this program to roll a dice so
every time we run this program we get
different values now we have three and
one next time we get three and six one
more time five and six four and three
double one that's a very cool exercise
so before we get started i want you to
pay attention to a few things
i want you to define a class called dice
in this class we're going to have a
method called roll
so every time we call this method we get
a tuple a tuple remember is a list of
values but that list cannot be changed
we cannot add a new item to it we cannot
remove it so it's like a read-only list
so every time we call the roll method we
should get a tuple of two random values
so go ahead and do this exercise you'll
see my solution next
all right we start by importing the
random module on the top
then we define a class called dice
colon in this class we want to have a
method called role so define role
parenthesis this automatically adds self
now in this method we want to generate
two random values between one to six so
we call
random
dot rand int
and pass one and six so this generates
the first number
we can put that here
now let's call this one more time so i'm
going to copy what we have on line five
put it here and change this variable to
second
so we have two variables first and
second with two random values finally we
need to return them in a tuple so return
parenthesis instead of square brackets
first and second
now in python when you want to return a
tuple from a function you don't have to
add this parenthesis so you can simplify
your code and python will automatically
interpret this as a tuple okay
so we're done with the definition of our
class we remove the indentation and add
two line breaks now we create an object
of this type so
we set dice to dice
next we roll the dice so dice.roll and
print the result on the terminal
that's all you have to do let's run this
program
so now we get two and five let's run it
one more time three and two one on one
beautiful
now we have this little warning here
that says expected to black lines found
one once again this is coming from pep8
pep is short for python enhancement
proposal we have so many python
enhancement proposals or peps pep8 is a
very famous one and in this document we
have
all the best practices for formatting
our code so pep8 says that after we
define our classes we should have two
line breaks we already done that so the
reason this is complaining is because we
have one line break before the class so
let's add one more line break now pie
charm is happy so basically pycharm is
following all the best practices defined
in pep 8.
now you don't have to memorize any of
these best practices as you code in
pycharm pycharm gives you little
warnings and gradually you will learn
how to properly format your code so it's
readable by other people
in this tutorial i'm going to show you
how to work with directories in python
so here on python 3 module index you can
see we have a module called pathlib
which provides an object oriented file
system patch that basically means it
provides classes that we can use to
create objects to work with directories
and files so if you click here you can
see how this module works you can see
all kinds of examples for example here
under basic usage you can see this is
how we import the past class from the
passlip module let me zoom in so you can
see clearly okay so look from passlip
that's our module import path note the
naming convention p is capitalized that
means path is a class
so we need to create an instance of this
class as you can see
right here
now there is so much documentation here
you can read this on your own but let me
quickly show you a few examples to help
you get started
so back in pycharm
on the top
from the passlip module let's import the
past class
now we need to create a path object to
reference a file or a directory on our
computer
so there are basically two ways to do
this we can use an absolute pass
or a relative path which basically means
a path starting from the current
directory for example if you want to
reference
this ecommerce directory in our project
we can use the relative path so we start
from the current directory and then go
somewhere else
with absolute paths we start from the
root of our hard disk
for example if you're on windows you
might have an absolute path like this c
drive backslash program
files
backslash microsoft so these are
directories
in c drive on windows we use a backslash
to build a path
if you're on mac or linux your paths
look a little bit different so instead
of a backslash we have a forward slash
let's say user
local slash bin
so these are examples of absolute paths
in this tutorial we're going to work
with a relative pass to work with this
ecommerce directory that we have in our
project now if you didn't create this
directory earlier simply right click on
the project and then go to new
directory
okay
so
let's close this panel
we create a path object
now if we don't pass an argument here
this will reference the current
directory
alternatively we can pass a string in
this string we can add a file or a
directory let's say the e-commerce
directory
now this returns a pass object so you
store it here
now this pass object has a few
interesting methods for example we can
check to see if a path exists by calling
the exist method this simply returns a
boolean so let's print it on the
terminal
there you go
so this path exists but if we change
this to let's say e-commerce 1 and run
our program we get false
we can also create a new directory for
example let's change this path to emails
now when we run this program obviously
we don't have this directory but we can
create it by calling the mkdir
method so make directory
let's run our program
all right this method returns none which
basically means it doesn't return any
values now if you look at the project
panel you can see here we have a new
directory called emails we can also
delete this directory so
instead of mkdir we call rm dir which is
short for remove directory
let's go ahead
now you can see that directory is gone
we can also find all the files and
directories in a given pass that is very
useful if you want to write a little
program to automate something for
example you can iterate over all the
spreadsheets in a directory open them
and process them
let me show you so first we change the
path
to the current directory
and then we call the glob method
with this method we can search for files
and directories in the current path so
as the first argument we need to pass a
string that defines a search pattern we
can type an asterisk and that means
everything all files and all directories
we can optionally add an extension
so to get all the files we use star dot
star
with this pattern we'll only get the
files in the current directory but not
the directories we can also search for
all the pi files or all the excel
spreadsheets anything
so let's search for all the pi files and
the current directory
now when we run our program
we get this generator object generator
objects are kind of an advanced topic
and they are beyond the scope of this
beginner's python course but for now all
you need to know is that we can iterate
or loop through these generator objects
so
instead of printing this generator
object let's just
iterate over it using a for loop so
for
file in
the generator object that is returned
from the glob method
let's print
file
run our program there you go
so these are all the pi files in my
current directory this could be
different on your machine if you didn't
follow the exercises i gave you earlier
for example this utils.pi we created
this as part of one of the exercises
earlier in this course so don't worry if
the files you see here are different on
your machine
so we can use the glob method to search
for files using a pattern we can also
get all the files and directories in the
current path
so we just use one asterisk
run our program take a look
so we have this ecommerce directory we
have notes.txt
this is a file i added earlier just to
write notes as part of my presentation
so you're not going to have this file
you also have a bunch of other
directories and files
even though python's standard library is
very comprehensive and has so many
modules for common tasks it's not
complete by any means that's why we have
this directory called python package
index or pypi and in this directory you
can find thousands of packages for doing
awesome things these are the packages
that people like you and i have built as
part of their projects and then they
published it in this directory for other
people to use so that's why we have a
fantastic community in python there are
so many python developers out there and
there's so many packages right in front
of us to reuse in our programs let's say
you want to send text messages in your
programs you don't have to build this
functionality from scratch you can
simply come to
pipi.org and search for
sms
as you can see there are so many
projects or packages that give you this
functionality of course not every
package not every project is complete or
bug-free some of them are still in
development or they have bugs but if you
look around i'm pretty sure for any kind
of functionality you can imagine there
is a good reliable and well-documented
package for you in my complete python
course i will show you some of the most
useful packages on pi pi for example you
will learn how to access the information
on yelp.com in your programs so you can
write your program and search for
businesses registered on yelp let's say
you want to search for the best barbers
in new york city i will show you how to
do that you also learn about the
technique called web scraping which
means you can build an engine and have
that engine browse a website
and extract information from html files
this is the same technique that google
does to index various websites so they
have several engines or web crawlers
these crawlers are continuously looking
at various websites and extracting
information from their pages when you
publish a blog post google's web crawler
finds the title of your post it's
keywords and so on so i'm going to show
you how to do that with python we'll
also look at browser automation and this
is extremely powerful because you can
automate testing of your web
applications so you might get a job as a
test engineer and your daily job is to
browse a website click here and there
fill out this form that form and ensure
that the website is functioning properly
you can automate all of that with a
powerful python package called selenium
as i've shown in my complete python
course
now in this tutorial i'm going to show
you how to install packages from
pipi.org
so here on pipi.org let's search for
open pi
xl this is a package that we use for
working with excel spreadsheets so let's
search for this package
there you go so currently it's at
version 2.5
on the top you can see this instruction
pip install open pi excel
this is the command that we need to type
into a terminal window to install this
package into our program
so back to pie chart here on the status
bar we can open up a terminal window for
executing various commands so let's open
it
now if you're on windows you're probably
going to see something different instead
of this dollar sign don't worry about
that just execute this command i'm going
to show you so pip
install open
pi excel make sure to spell everything
properly so pip is the tool that comes
with python installation and we use it
to install or uninstall packages
registered on
pipi.org so here we're using pip to
install this package open pi xl
enter let's go ahead with that it's
going to take a few seconds okay done
now we can import this package and its
modules just like the built-in modules
in python or the modules that we have in
our project
now if you're curious where this package
is stored on disk let me show you so
open up the project panel and then
expand external libraries
next expand python3
and then expand site packages this is
where all these packages that we
installed with pip are stored so here we
have open pi excel you can open this
in this folder we have another folder
called cell
now look what we have here we have this
init pi area i told you that whenever we
add this file to a folder python treats
that folder as a package so cell is a
package and in this package we have
these modules cell interface read-only
and text so as you can see this package
open pi excel has several sub packages
like cell chart chart sheet and so on
and in each package we have several
modules
in the next tutorial i will show you how
to work with excel files
so we have covered all the core concepts
in python i hope you learned a lot
please support my hard work by liking
this video and sharing it with others
and be sure to subscribe to my channel
for more tutorials like this
next we're going to work on our first
python project that involves automation
you're going to write a python program
that can process thousands of
spreadsheets in under a second are you
excited let's get started
in this tutorial i'm going to show you
something really awesome you can do with
python you're going to learn how to
process spreadsheets and this is
extremely valuable in situations where
you have hundreds or thousands of
spreadsheets that need to be updated if
you want to do this by hand it may take
hours days weeks or even months you can
simply build a python program in less
than half an hour and have that python
program automatically process thousands
of spreadsheets in under one second
so here we're going to work on this
excel spreadsheet you can download this
below this video in this spreadsheet we
have three columns transaction id
product id and price
now don't worry about the fourth column
yet so in a spreadsheet we record all
kinds of transactions but let's say due
to an error it could be a human error or
a system error the price that we have
here is wrong let's say we need to
decrease this by 10 percent if you want
to do this manually we'll have to come
back here
and add a formula so we type out equal
sign let's say we want to recalculate
the value of this cell that is c2 so
we'll have to get that and then multiply
it by
0.9 so that is like the 90
of the original price we are reducing
the price by 10
now when we hit enter you can see the
updated price
next we'll have to come back here select
the cell and then apply the same formula
to all the other rows now what if we
have thousands of rows here we'll have
to scroll up and down this is going to
be very tedious so we're going to write
a python program that will do this for
us it's going to automate this process
and not only that it will also
add this beautiful
chart
right here
once again if you want to open up
hundreds or thousands of spreadsheets
and add a chart to each one this is
going to take at least a week or two our
python program is going to do all of
this in a matter of seconds so let's get
started
all right the first thing i want you to
do is to download this transactions file
and add it to your project i'll put the
link below this video for you to
download
so if you're wondering how to put this
in this project you can simply right
click the project
and
if you're on mac you have this item
reveal in finder if you're on windows
you should see something like reveal in
explorer or file explorer or windows
explorer whatever it's called when you
click this
this opens up the directory on your
machine where this project is stored so
you can simply copy and paste the
transactions file right here
now here on the top first we need to
import the open pi excel package so
import open pi excel we can give it an
alias to make our code shorter so as
excel this is not required but it just
makes our code a little bit cleaner let
me show you so now instead of typing
open pi excel dot
we type x l dot okay so that's an alias
for this package
now in this package we have a function
for loading an excel workbook so let's
call load workbook
and
as the argument we pass transactions dot
xlsx
so this will load our excel workbook and
return a workbook object
okay
now if you open this workbook you can
see you have only one sheet and that is
called sheet one so to access that we
use square brackets
and specify the name of the sheet that
is sheet one make sure to spell this
with a capital s because this is case
sensitive if you don't split it properly
you're going to get an error
so this returns
our first sheet
now in this sheet we have various cells
so next you need to learn how to access
a particular cell and that is very easy
back to pycharm
with this sheet object we can use square
brackets and give the coordinate of a
cell
the coordinate is the combination of the
column and the row for example this cell
its coordinate is a one
so back to pycharm here we can type a1
and this returns
our first cell
there is also another approach to get a
cell instead of using square brackets
with a string
we can use
the cell method of the sheet object so
sheet that cell we pass the row and the
column so row one and column one
this returns the exact same cell
now let's print the value of the cell so
cell that value
and run our program
so the value is transaction id beautiful
so now we need to iterate over all these
rows and for each row we need to get the
value in the third column that is the
price we'll get that and then multiply
it by 0.9
so first we need to know how many rows
we have in this spreadsheet we can get
that from the sheet object so sheet
has
an attribute called max underline row
let's print this
so in this sheet we have four rows
and you can verify that here so we have
a total of four rows
so we need to add a for loop that would
generate the numbers one to four so
let's delete this print statement
and add a for loop for row in we're
going to use the range function to
generate a range of numbers
starting from 1
all the way to sheet dot max underline
row
plus one the reason we're adding one to
this is because as i told you before
this range function would generate
numbers starting from this value all the
way to this value but it will not
include the second value so currently
max row returns four if we use range of
one to four this would generate the
numbers one two and three but not four
so to include four we need to add one to
it
let's go back here
so we type sheet.max underline row plus
1.
now before going any further let's just
print row and make sure our program is
working up to this point
so
let's run this we get the numbers one to
four beautiful so now we can easily get
the cells in the third column however we
don't really want this first cell that's
the heading so technically we want to
ignore the first row
back here we want to change our range
function and start from two
okay
now
we're going to use sheet dot cell
to get access to the cell at this row
and the column should be three
we get a cell object let's print its
value and make sure
we're on the right track
so run our program
these are the values we get
5.95 6.95 and 7.95
these are the values in the third column
beautiful next we need to multiply each
value by 0.9
so instead of printing cell.value we
multiply it by 0.9 and this is the
corrected
underlying price
so this is the mistake we're going to
fix with our program
now we need to add a new cell to our
worksheet
so we want to add all the corrected
prices in a new column we could also
overwrite the values in this column but
in this tutorial i'm going to show you
how to add a new column
so using the same method now we need to
get a reference to the cell in the given
row but in the fourth column
so we call
sheet.cell and pass row and 4 as the
arguments
once again this returns a cell object
let's store that in a separate variable
and call it corrected
underline price underline cell
so note that my variable names are very
descriptive there is no guesswork
we have corrected price which holds the
actual value and we have corrected price
cell which is a sell object in this
spreadsheet
next we need to set the value for this
cell so we set corrected price sell dot
value to this corrected price
with these view lines we can easily
update our spreadsheet but first we need
to save it so
after our for loop we call workbook dot
save now let's save this in a new file
so we don't want to accidentally
overwrite the original file in case our
program has a bug
so i'm going to call that
transactions2.xlsx
now finally let's run our program
so you can see that happened in a split
of a second now here we have a new file
transactions2 when we open this we get
something like this so you can see we
have this fourth column with the updated
prices beautiful so half of the problem
is solved now we need to add a chart
here
to add a chart we need to import a
couple of classes on the top
so
after this import statement let's type
out from
open pi excel dot chart
import
bar chart
comma
reference
so let's see what's going on here
in this package we have a module called
chart and from this module we're
importing two classes bar chart and
reference again look at the naming
convention used here the first letter of
every word is capitalized
also it's better to add a line break
after our import statement to make our
code cleaner
so
before we save our workbook we need to
add a chart to the current sheet
first we need to select a range of
values for this exercise i'm going to
select the values in the fourth column
so all the values in rows 2 to 4. these
are the values i'm going to use in our
chart
now in this particular example it
doesn't really make sense to add a chart
per transaction but that doesn't really
matter we just want a bunch of numbers
to create a chart
so after our for loop we're going to use
the reference class to select a range of
values now the first argument in the
constructor is the sheet
so we pass our sheet here
then we add four keyword arguments the
first one is min underline row we set
this to two
the second one is max underline row we
set this to the maximum row in this
sheet that is sheet dot max underline
row so we want to select the cells in
row two
to four okay
now to make this code a little bit
cleaner i'm going to put this on a new
line so you can see clearly
now this is going to select all the
cells in all the columns in these rows
that's not what we want we only want the
values in the fourth column
so back here we need to set a couple
more keyword arguments min underline
call or column we set that to four and
also max underlying call we set that to
four as well
so we're limiting the range of cells
we're selecting to the fourth column
okay now
we're creating an instance of the
reference class let's store the result
in a variable called values so this
values object will have all these values
in the fourth column now we are ready to
create a chart
so we create an instance of the bar
chart class
and store it in this object
next we call chart that add underlying
data and pass our values
that is pretty straightforward finally
we need to add this chart to our sheet
so we call sheet that add underline
chart
and pass this chart object we should
also specify where we want to add this
chart
let's say we want to add it here on row
2 after the fourth column so the
coordinates of this cell is e 2 and this
is going to be the top left corner of
our chart
so as the coordinate i'm going to pass
e2 that's all we had to do done
let's run our program one more time
beautiful let's open up the updated
workbook
and here's the end result so right after
the fourth column we have this beautiful
chart now we could take this to the next
level we could add a legend here we
could change the color of these bars we
could even use a different kind of chart
it doesn't have to be a bar chart so to
learn more about this you can read the
documentation for open pi excel so our
program is complete but our code is
dirty it's not clean it's not organized
we don't have any functions here we have
written all the code in app.pi so let's
go ahead and organize this code like a
professional software developer
so on line four we're loading our
workbook then we're getting a reference
to the first sheet but we don't really
need these two lines here this was
purely for demonstration to show you how
you can access a cell so let's delete
these unnecessary lines this is a very
important practice as you're coding
always look at your code always review
it see if you have some code that is not
used always delete those
okay next we're iterating over all the
rows fixing the prices and then we
select these values to add a chart and
finally we save the workbook now if we
were going to use this to automate the
process of updating thousands of
spreadsheets this program wouldn't work
because it's only relying
on this file so we want to reorganize
this code and move it inside of a
function this function should take the
name of the file as an input so let's
define a function
let's call it process underline workbook
it gets a file name now we move all the
code inside of this function so let's
select everything
and then
press tab beautiful
now
back to our function
instead of loading this transactions
file we're going to load
this file name that's better
also now that our program is working
properly there is really no need to
store the result in a separate file so
here we can simply overwrite the same
file
so
let's pass file name
that is the end of our function
so now we have this reusable function we
can simply reuse this to process
thousands of spreadsheets
earlier in this python course you
learned how to find all the files in the
directory so you can get each file in a
directory and pass the name of the file
to this function this function will go
ahead and update that spreadsheet in
just a second or less
so that was just one example of using
python to automate repetitive boring
tasks that waste your time but
automation is not just about processing
excel spreadsheets there are so many
things we can automate here's a question
for you what do you want to automate how
do you want to use python to make your
life easier use the comment box below
and let me know i love to hear about
your ideas
next we're going to work on a project
that involves machine learning which is
a subset of artificial intelligence are
you excited let's get started
in this section you're going to learn
about machine learning which is a subset
of ai or artificial intelligence it's
one of the trending topics in the world
these days and it's going to have a lot
of applications in the future here's an
example imagine i ask you to write a
program to scan an image and tell if
it's a cat or a doc
if you want to build this program using
traditional programming techniques your
program is going to get overly complex
you will have to come up with lots of
rules to look for specific curves edges
and colors in an image to tell if it's a
cat or a dog but if i give you a black
and white photo your rules may not work
they may break then you'll have to
rewrite them or i might give you a
picture of a cat or a dog from a
different angle that you did not predict
before so solving this problem using
traditional programming techniques is
going to get overly complex or sometimes
impossible now to make the matter worse
what if in the future i ask you to
extend this program such that it
supports three kinds of animals cats
dogs and horses once again you'll have
to rewrite all those rules that's not
gonna work so machine learning is a
technique to solve these kind of
problems and this is how it works we
build a model or an engine and give it
lots and lots of data for example we
give you thousands or tens of thousands
of pictures of cats and dogs our model
will then find and learn patterns in the
input data so we can give it a new
picture of a cat that it hasn't seen
before and ask it is it a cat or a dog
or a horse and it will tell us with a
certain level of accuracy the more input
data we give it the more accurate our
model is going to be
so that was a very basic example but
machine learning has other applications
in self-driving cars robotics language
processing vision processing forecasting
things like stock market trends and the
weather games and so on so that's the
basic idea about machine learning next
we'll look at machine learning in action
a machine learning project involves a
number of steps the first step is to
import our data which often comes in the
form of a csv file we might have a
database with lots of data we can simply
export that data and store it in a csv
file for the purpose of our machine
learning project so we import our data
next we need to clean it and this
involves tasks such as removing
duplicated data if you have duplicates
in the data we don't want to feed this
to our model because otherwise our model
will learn bad patterns in the data and
it will produce the wrong result so we
should make sure that our input data is
in a good and clean shape if there are
data that is irrelevant we should remove
them if they are duplicated or
incomplete we can remove or modify them
if our data is text based like the name
of countries or genres of music or cats
and dogs we need to convert them to
numerical values so this step really
depends on the kind of data we are
working with every project is different
now that we have a clean data set we
need to split it into two segments one
for training our model and the other for
testing it to make sure that our model
produces the right result
for example if you have a thousand
pictures of cats and dogs we can reserve
eighty percent for training and the
other twenty percent for testing the
next step is to create a model and this
involves selecting an algorithm to
analyze the data there are so many
different machine learning algorithms
out there such as decision trees neural
networks and so on each algorithm has
pros and cons in terms of accuracy and
performance so the algorithm you choose
depends on the kind of problem you're
trying to solve and your input data now
the good news is that we don't have to
explicitly program an algorithm there
are libraries out there that provide
these algorithms one of the most popular
ones which we're going to look at in
this tutorial is scikit-learn
so we build a model using an algorithm
next we need to train our model so we
feed it our training data our model will
then look for the patterns in the data
so next we can ask it to make
predictions back to our example of cats
and dogs we can ask our model is this a
cat or a dog and our model will make a
prediction
now the prediction is not always
accurate in fact when you start out it's
very likely that your predictions are
inaccurate so we need to evaluate the
predictions and measure their accuracy
then we need to get back to our model
and either select a different algorithm
that is going to produce a more accurate
result for the kind of problem we're
trying to solve or fine-tune the
parameters of our model so each
algorithm has parameters that we can
modify to optimize the accuracy
so these are the high-level steps that
you follow in a machine learning project
next we'll look at the libraries and
tools for machine learning
in this lecture we're going to look at
the popular python libraries that we use
in machine learning projects the first
one is numpy which provides a
multi-dimensional array very very
popular library the second one is pandas
which is a data analysis library that
provides a concept called data frame a
data frame is a two-dimensional data
structure similar to an excel
spreadsheet so we have rows and columns
we can select data in a row or a column
or a range of rows and columns again
very very popular in machine learning
and data science projects
the third library is matplotlib which is
a two-dimensional plotting library for
creating graphs and plots
the next library is scikit-learn which
is one of the most popular machine
learning libraries that provides all
these common algorithms like decision
trees neural networks and so on
now when working with machine learning
projects we use an environment called
jupiter for writing our code technically
we can still use vs code or any other
code editors but these editors are not
ideal for machine learning projects
because we frequently need to inspect
the data and that is really hard in
environments like vs code and terminal
if you're working with a table of 10 or
20 columns visualizing this data in a
terminal window is really really
difficult and messy so that's why we use
jupiter it makes it really easy to
inspect our data
now to install jupiter we're going to
use a platform called anaconda so head
over to anaconda.com
download
on this page you can download anaconda
distribution for your operating system
so we have distributions for windows mac
and linux so let's go ahead and
install anaconda for python 3.7
download
all right so here's anaconda downloaded
on my machine let's double click this
all right first it's going to run a
program to determine if the software can
be installed so let's continue
and once again continue
continue pretty easy continue one more
time i agree with the license agreement
okay
you can use the default installation
location so don't worry about that just
click install
give it a few seconds now the beautiful
thing about anaconda is that it will
install jupyter as well as all those
popular data science libraries like
numpy pandas and so on so we don't have
to manually install this using
pip right now as part of the next step
anaconda is suggesting to install
microsoft vs code we already have this
on our machine so we don't have to
install it we can go with continue
and close the installation now finally
we can move this to trash because we
don't need this installer in the future
all right now open up a terminal window
and type jupyter
with a y space
notebook
this will start the notebook server on
your machine so enter
there you go this will start the
notebook server on your machine you can
see these default messages here don't
worry about them now it automatically
opens a browser window pointing to
localhost port 888
this is what we call jupiter dashboard
on this dashboard we have a few tabs the
first tab is the files tab and by
default this points to your home
directory so every user on your machine
has a home directory this is my home
directory on mac you can see here we
have a desktop folder as well as
documents downloads and so on on your
machine you're going to see different
folders so someone on your machine you
need to create a jupyter notebook i'm
going to go to desktop here's my desktop
i don't have anything here
and then
click new
i want to create a notebook for python
3. in this notebook we can write python
code and execute it line by line we can
easily visualize our data as you will
see over the next few videos so let's go
ahead with this
all right here's our first notebook we
can see by default it's called untitled
let's change that to
hello world so this is going to be the
hello world of our machine learning
project
let's rename this
now if you look at your desktop you can
see this file
helloworld.i pi
nb this is a jupyter notebook it's kind
of similar to our pi files where we
write our python code but it includes
additional data that jupiter uses to
execute our code
so back to our notebook
let's do
a print
hello world
and then click this run button here
and here's the result printed in jupiter
so we don't have to navigate back and
forth between the terminal window we can
see all the result right here
next i'm going to show you how to load a
data set from a csv file in jupyter
all right in this lecture we're going to
download a data set from a very popular
website called
gaggle is basically a place to do data
science projects so the first thing you
need to do is to create an account you
can sign up with facebook google or
using a custom email and password once
you sign up then come back here on
kaggle.com here in the search bar
search for
video game sales this is the name of a
very popular data set that we're going
to use in this lecture so
here in this list you can see the first
item with this kind of reddish icon so
let's go with that
as you can see this data set includes
the sales data for more than 16 000
video games
on this page you can see the description
of various columns in this data set we
have
rank name platform year and so on so
here's our data source it's a csv file
called vgsales.csv
as you can see there are over 16 000
rows and 11 columns in this data set
right below that you can see the first
few records of this data set so here's
our first record the ranking for this
game is one it's the wii sports game for
we as the platform and it was released
in year 2006
now what i want you to do
is to go ahead and download this data
set and as i told you before you need to
sign in before you can download this
so this will give you a zip file as you
can see here
here's our csv file now i want you to
put this right next to your jupiter
notebook on my machine that is on my
desktop so i'm going to drag and drop
this onto the desktop folder
now
if you look at the desktop you can see
here's my jupyter hello world notebook
and right next to that we have
vgsales.csv
with that
we go back to our jupiter notebook
let's remove the first line and instead
import
pandas
as pd with this we're importing pandas
module and renaming it to pd so we don't
have to type pandas. several times in
this code
now let's type pd dot
read underline csv
and
pass the name of our csv file that is vg
sales.csv now because this csv file is
in the current folder right next to our
jupyter notebook we can easily load it
otherwise we'll have to supply the full
path to this file so
this returns a data frame object which
is like an excel spreadsheet let me show
you so
we store it here
and then we can simply type df to
inspect it so one more time let's run
this program
here's our data frame with these rows
and columns so we have rank name
platform and so on
now this data frame object has lots of
attributes and methods that we're not
going to cover in this tutorial that's
really beyond the scope of what we're
going to do so i'll leave it up to you
to read panda's documentation or follow
other tutorials to learn about pandas
data frames but in this lecture i'm
going to show you some of the most
useful methods and attributes
the first one is shape
so shape let's run this one more time
so here's the shape of this data set we
have over 16 000 records and 11 columns
technically this is a two dimensional
array of 16 thousand and
okay
now you can see here we have another
segment for writing code so we don't
have to write all the code in the first
segment so here in the second segment we
can call one of the methods of the data
frame that is df dot describe
now when we run this program
we can see the output for each segment
right next to it so here's our first
segment here we have these three lines
and this is the output of the last line
below that we have our second segment
here we're calling the describe method
and right below that we have the output
of this segment so this is the beauty of
jupyter we can easily visualize our data
doing this with vs code and terminal
windows is really tedious and clunky so
what is this describe method returning
basically it's returning some basic
information about each column in this
data set so as you saw earlier we have
columns like rank year and so on
these are the columns with numerical
values now for each column we have the
count which is the number of records in
that column you can see our rank column
has 16
598 records whereas the year column has
16
327 records
so this shows that some of our records
don't have the value for the year column
we have null values so in a real data
science or machine learning project
we'll have to use some techniques to
clean up our data set one option is to
remove the records that don't have a
value for the year column or we can
assign them a default value that really
depends on the project now another
attribute for each column is mean so
this is the average of all the values
now in the case of the rank column this
value doesn't really matter but look at
the year
so the average year for all these video
games in our data set is 2006 and this
might be important in the problem we're
trying to solve
we also have standard deviation which is
a measure to quantify the amount of
variation in our set of values below
that we have min
as an example the minimum value for the
year column is 1980. so quite often when
we work with a new data set we call the
describe method to get some basic
statistics about our data
let me show you another useful attribute
so in the next segment let's type
df.values
let's run this
as you can see this returns a
two-dimensional array this square
bracket indicates the outer array
and the second one represents the inner
array so the first element in our outer
array is an array itself these are the
values in this array which basically
represent the first row in our data set
so the video game with ranking one which
is called wii sports
so this was a basic overview of pando's
data frames in the next lecture i'm
going to show you some of the useful
shortcuts of jupyter
in this lecture i'm going to show you
some of the most useful shortcuts in
jupyter
now the first thing i want you to pay
attention to is this green bar on the
left this indicates that this cell is
currently in the edit mode so we can
write code here
now
if we press the escape key
green turns to blue and that means this
cell is currently in the command mode so
basically the activated cell can be
either in the edit mode or the command
mode depending on the mode we have
different shortcuts so here we're
currently in the command mode
if we press h
we can see the list of all the keyboard
shortcuts
right above this list you can see
mac os modifier keys these are the extra
keys that we have on a mac keyboard if
you're a windows user you're not going
to see this so as an example here is the
shape of the command key this is control
this is option and so on
with this guideline you can easily
understand the shortcut associated with
each command let me show you
so here we have all the commands when a
cell is in the command mode for example
we have this command open the command
palette this is exactly like the command
palette that we have in vs code here's a
shortcut to execute this command that is
command shift and f
okay so here we have
lots of shortcuts of course you're not
going to use all of them all the time
but it's good to have a quick look here
to see what is available for you with
this shortcut you can write code much
faster so let me show you some of the
most useful ones
i'm going to close this
now
with our first cell
in the command mode i'm going to press b
and this inserts a new cell below this
cell
we can also go back to our first cell
press escape now the cell is in the
command mode we can insert an empty cell
above this cell by pressing a
so either a or b a for above and b for
below okay now if you don't want this
cell you can press d twice to delete it
like this
now in the cell i'm going to print a
hello world message so
hello world
now to run the code in this cell we can
click on the run button here
so
here's our print function and right
below that you can see the output of
this function but note that when you run
a cell this will only execute the code
in that cell in other words the code in
other cells will not be executed let me
show you what i mean so in the cell
below this cell i'm going to delete the
call to describe method
instead i'm going to print
ocean
now
i'm going to put the cursor back
in this cell where we print the hello
world message and run this cell
so we can see hello world is displayed
here
but the cell below is still displaying
the described table so we don't see the
changes here
now to solve this problem we can go to
the cell menu on the top and run all
cells together
this can work for small projects but
sometimes you're working with a large
data set so if you want to run all these
cells together it's going to take a lot
of time that is the reason jupiter saves
the output of itself so we don't have to
rerun that code if it hasn't changed
so this notebook file that we have here
includes our source code organized in
cells as well as the output for each
cell that is why it's different from a
regular pi file where we only have the
source code
here we also have auto completion and
intellisense so in the cell
let's call df dataframe
dot now if you press tab we can see all
the attributes and methods in this
object
so
let's call describe
now with the cursor on the name of the
method we can press shift and tab
to see this tooltip that describes what
this method does and what parameter it
takes so here in front of signature you
can see the described method these are
the parameters and their default value
and right below that you can see the
description of what this method does
in this case it generates descriptive
statistics that summarize the central
tendency and so on
similar to vs code we can also convert a
line to comment by pressing command and
slash on mac or control slash on windows
like this
now this line is a comment we can press
the same shortcut one more time
to remove the comment
so these were some of the most useful
shortcuts in jupyter now over the next
few lectures we're going to work on a
real machine learning project but before
we get there let's delete all the cells
here so we start with only a single
empty cell so here in this cell first
i'm going to press the escape button now
the cell is blue so we are in the
command mode and we can delete the cell
by pressing d twice
there you go now the next cell is
activated and it's in the command mode
so let's delete this as well
we have two more cells to delete there
you go
and the last one
like this
so now we have an empty notebook with a
single cell
over the next few lectures we're going
to work on a real machine learning
project imagine we have an online music
store
when our users sign up we ask their age
and gender and based on their profile we
recommend various music albums they're
likely to buy so in this project we want
to use machine learning to increase
sales
so we want to build a model we feed this
model with some sample data based on the
existing users our model will learn the
patterns in our data so we can ask it to
make predictions when a new user signs
up we tell our model hey we have a new
user with this profile what is the kind
of music that this user is interested in
our model will say jazz or hip hop or
whatever and based on that we can make
suggestions to the user
so this is the problem we're going to
solve
now back to the list of steps in a
machine learning project
first we need to import our data then we
should prepare or clean it next we
select a machine learning algorithm to
build a model we train our model and ask
it to make predictions and finally we
evaluate our algorithm to see its
accuracy if it's not accurate we either
fine tune our model or select a
different algorithm so let's focus on
the first step head over to bit.li
music csv this is a very basic csv that
i've created for this project it's just
some random made-up data it's not real
so we have a table with three columns
age
gender and genre gender can either be
one which represents a male or zero
which represents a female here i'm
making a few assumptions i'm assuming
that men between 20 and 25 like hip-hop
men between 26 and 30 like jazz and
after the age of 30 they like classical
music
for women i'm assuming that if they're
between 20 and 25 they like dance music
if they're between 26 and 30 they like
acoustic music and just like men after
the age of 30 they like classical music
once again this is a made-up pattern
it's not the representation of the
reality
so let's go ahead and download this csv
click on this dot dot icon here and
download this file
in my downloads folder here we have this
music.csv
i'm going to drag and drop this onto
desktop because that's where i've stored
this hello world notebook so i want you
to put the csv file right next to your
jupyter notebook
now back to our notebook we need to read
the csv file so just like before first
we need to import the pandas module so
import pandas as pd
and then we'll call pd that read
underline csv
and the name of our file is music.csv
as you saw earlier this returns a data
frame which is a two-dimensional array
similar to an excel spreadsheet so let's
call that music
underline data
now let's inspect this music underline
data to make sure we loaded everything
properly so run
so here's our data frame beautiful next
we need to prepare or clean the data and
that's the topic for the next lecture
the second step in a machine learning
project is cleaning or preparing the
data and that involves tasks such as
removing duplicates null values and so
on now in this particular data set we
don't have to do any kind of cleaning
because we don't have any duplicates and
as you can see all rows have values for
all columns so we don't have null values
but there is one thing we need to do
we should split this data set into two
separate data sets
one with the first two columns which we
refer to as the input set and the other
with the last column which we refer to
as the output set so when we train a
model we give it two separate data sets
the input set and the output set the
output set which is in this case the
genre column contains the predictions so
we're telling our model that if we have
a user who's 20 years old and is a male
they like hip hop
once we train our model then we give it
a new input set for example we say hey
we have a new user who is 21 years old
and is a male what is the genre of the
music that this user probably likes as
you can see in our input set we don't
have a sample for a 21 year old male so
we're going to ask our model to predict
that
that is the reason we need to split this
data set into two separate sets input
and output
so back to our code
this data frame object has a method
called drop
now
if you put the cursor under method name
and press shift and tab
you can see this tooltip so this is the
signature of this drop method these are
the parameters that we can pass here
the parameter we're going to use in this
lecture is columns which is set to none
by default with this parameter we can
specify the columns we want to drop
so
in this case we set columns
to an array with one string genre
now this method doesn't actually modify
the original data set in fact it will
create a new data set but without this
column
so
by convention we use a capital x to
represent that data set so capital x
equals this expression
now
let's inspect x
so as you can see our input set or x
includes these two columns age and
gender it doesn't have the output or
predictions
next we need to create our output set
so
once again we start with our data frame
music data
using square brackets we can get all the
values in a given column in this case
genre
once again this returns a new data set
by convention we use a lowercase y to
represent that so that is our output
data set
let's inspect that as well
so
in this data set we only have the
predictions or the answers
so we have prepared our data next we
need to create a model using an
algorithm
the next step is to build a model using
a machine learning algorithm there are
so many algorithms out there and each
algorithm has its pros and cons in terms
of the performance and accuracy in this
lecture we're going to use a very simple
algorithm called decision tree now the
good news is that we don't have to
explicitly program these algorithms
they're already implemented for us in a
library called scikit-learn
so
here on the top
from sklearn.3
let's import the decision
tree
classifier
so sklearn is the package that comes
with scikit-learn library this is the
most popular machine learning library in
python
in this package we have a module called
tree and in this module we have a class
called decision tree classifier this
class implements the decision tree
algorithm okay
so
now we need to create a new instance of
this class
so
at the end let's create an object called
model and set it to a new instance of
decision
tree
classifier
like this
so now we have a model next we need to
train it so it learns patterns in the
data and that is pretty easy we call
model
that fit
this method takes two data sets the
input set and the output set
so
they are capital x and y
and finally we need to ask our model to
make a prediction so we can ask it what
is the kind of music that a 21 year old
male likes now before we do that let's
temporarily
inspect our initial data set that is
music data
so
look what we got here
as i told you earlier i've assumed that
men between 20 and 25 like hip-hop music
but here we only have three samples for
men aged 20
23 and 25. we don't have a sample for a
21 year old male so if you ask our model
to predict the kind of music that a 21
year old male likes we expect it to say
hip hop
similarly
i've assumed that women between 20 and
25 like dance music but we don't have a
sample for a 22 year old female so once
again if you ask our model to predict
the kind of music that a 22 year old
woman likes we expect it to say dance
so
with these assumptions let's go ahead
and ask our model to make predictions
so
let's remove the last line
and instead we're going to call model
dot predict
this method takes a two dimensional
array so here's the outer array in this
array each element is an array so i'm
going to pass another array here and in
this array i'm going to pass a new input
set a 21 year old male so 21 comma 1.
that is like a new record
in this table
okay so this is one input set let's pass
another input set for a 22-year female
so here's another array
here we add 22 comma zero
so we're asking our model to make two
predictions at the same time
we get the result and store it
in a variable called predictions and
finally let's inspect that
in our notebook
run look what we got
our model is saying that a 21 year old
male likes hip hop and a 22 year old
female likes dance music
so our model could successfully make
predictions here beautiful but wait a
second building a model that makes
predictions accurately is not always
that easy as i told you earlier after we
build a model we need to measure its
accuracy and if it's not accurate enough
we should either fine-tune it or build
the model using a different algorithm so
in the next lecture i'm going to show
you how to measure the accuracy of a
model
in this lecture i'm going to show you
how to measure the accuracy of your
models now in order to do so first we
need to split our data set into two sets
one for training and the other for
testing because right now we're passing
the entire data set for training the
model and we're using two samples for
making predictions that is not enough to
calculate the accuracy of a model a
general rule of thumb is to allocate 70
to 80 percent of our data for training
and the other 20 to 30 percent for
testing then instead of passing only two
samples for making predictions we can
pass the data set we have for testing
we'll get the predictions and then we
can compare these predictions with the
actual values in the test set based on
that we can calculate the accuracy
that's really easy all we have to do is
to import a couple of functions and call
them in this code let me show you so
first on the top
from sklearn
that model underline selection module we
import a function called train test
split with this function we can easily
split our data set into two sets for
training and testing
now right here after we define x and y
sets we call this function
so
train
test split
we give it three arguments x
y and a keyword argument that specifies
the size of our test data set so test
underline size we set it to 0.2 so we
are allocating 20 of our data for
testing
now this function returns a tuple so we
can unpack it into four variables right
here x underline train
x underline test
y underline train
and y underline test
so the first two variables are the input
sets for training and testing and the
other
are the output sets for training and
testing
now
when training our model
instead of passing the entire data set
we want to pass only the training data
set so
x
underline train
and y
underline train
also when making predictions instead of
passing these two samples we pass
x underline test
so that is the data set that contains
input values for testing
now we get the predictions to calculate
the accuracy we simply have to compare
these predictions with the actual values
we have in our output set for testing
that is very easy first on the top we
need to import a function
so from sklearn that metrics
import
accuracy
underlying score
now at the very end we call this
function so accuracy score
and
give it two arguments y underline test
which contains the expected values and
predictions
which contains the actual values
now this function returns an accuracy
score between 0 to 1. so we can store it
here
and simply display it on the console
so let's go ahead and run this program
so the accuracy score is one or a
hundred percent but if we run this one
more time we're going to see a different
result because every time we split our
data set into training and test sets
will have different data sets because
this function randomly picks data for
training and testing
let me show you so put the cursor in the
cell now you can see this cell is
activated note that if you click this
button here it will run this cell and
also insert a new cell below this cell
let me show you so if i go to the second
cell
press escape button
now we are in the command mode press d
twice
okay now it's deleted
if we click the run button
you can see this code was executed and
now we have a new cell
so if you want to run our first cell
multiple times every time we have to
click this and then run it and then
click again and run it it's a little bit
tedious so i'll show you a shortcut
activate the first cell
and press ctrl and enter
this runs the current cell without
adding a new cell below it so back here
let's try it multiple times okay now
look the accuracy dropped to 0.75 it's
still good so the accuracy score here is
somewhere between 75 percent to 100
but let me show you something
if i change the test size from 0.2
to 0.8 so essentially we're using only
20 of our data for training this model
and we're using the other 80
for testing now let's see what happens
when we run this cell multiple times so
control and enter
look the accuracy immediately dropped to
0.4 one more time
now 46 percent 40
26
it's really really bad
the reason this is happening is because
we are using very little data for
training this model this is one of the
key concepts in machine learning the
more data we give to our model and the
cleaner the data is we get the better
result so if you have duplicates
irrelevant data or incomplete values our
model will learn bad patterns in our
data that is why it's really important
to clean our data before training our
model
now let's change this back to 0.2
run this one more time
okay now the accuracy is one
seventy-five percent
now we drop to fifty percent again the
reason this is happening is because we
don't have enough data some machine
learning problems require thousands or
even millions of samples to train a
model the more complex the problem is
the more data we need for example here
we're only dealing with a table of three
columns but if you want to build a model
to tell if a picture is a cat or a dog
or a horse or a lion we'll need millions
of pictures the more animals we want to
support the more pictures we need in the
next lecture we're going to talk about
model persistence
so this is a very basic implementation
of building and training a model to make
predictions
now to simplify things i have removed
all the code that we wrote in the last
lecture for calculating the accuracy
because in this lecture we're going to
focus on a different topic
so basically
we import our data set
create a model
train it and then ask it to make
predictions
now this piece of code that you see here
is not what we want to run every time we
have a new user or every time we want to
make recommendations to an existing user
because training a model can sometimes
be really time consuming in this example
we're dealing with a very small data set
that has only 20 records but in real
applications we might have a data set
with thousands or millions of samples
training a model for that might take
seconds minutes or even hours so that is
why model persistence is important once
in a while we build and train our model
and then we'll save it to a file now
next time we want to make predictions we
simply load the model from the file and
ask it to make predictions that model is
already trained we don't need to retrain
it it's like an intelligent person so
let me show you how to do this it's very
very easy
on the top from
sklearn.externals
module
we import
joblib
this joblib object has methods for
saving and loading models
so
after we train our model we simply call
joblib.dump
and give it to arguments
our model
and the name of the file in which we
want to store this model
let's call that music
dash recommender
dot
job lib
that's all we have to do now temporarily
i'm going to comment out this line we
don't want to make any predictions we
just want to store our trained model in
a file so
let's run the cell with control and
slash
okay
look
in the output we have an array that
contains the name of our model file so
this is the return value of the dump
method
now back to our desktop right next to my
notebook you can see our job live file
this is where our model is stored it's
simply a binary file
now back to our jupyter notebook as i
told you before in a real application we
don't want to train a model every time
so
let's comment out these few lines so
i've selected these few lines on mac we
can press command and slash on windows
control slash
okay these lines are commented out now
this time instead of dumping our model
we're going to load it so we call the
load method
we don't have the model we simply pass
the name of our model file this returns
our trained model
now with these two lines we can simply
make predictions so
earlier we assumed that men between 20
and 25 like hip-hop music
let's print predictions and see if our
model is behaving correctly or not
so ctrl and enter there you go
so this is how we persist and load
models
earlier in this section i told you that
decision trees are the easiest to
understand and that's why we started
machine learning with decision trees in
this lecture we're going to export our
model in a visual format so you will see
how this model makes predictions that is
really really cool let me show you
so
once again i've simplified this code so
we simply import our data set
create
input and output sets
create a model and train it that's all
we are doing
now i want you to follow along with me
type everything exactly as i show you in
this lecture don't worry about what
everything means we're going to come
back to it shortly
so on the top
from sklearn
import tree
this object has a method for exporting
our decision tree in a graphical format
so after we train our model
let's call tree
dot export underline graph viz
now here are a few arguments we need to
pass the first argument is our model
the second is the name of the output
file so here we're going to use keyword
arguments because this method takes so
many parameters and we want to
selectively pass keyword arguments
without worrying about their order
so
the parameter we're going to set is out
underline file
let's set this to
music dash recommender
dot dot this is the dot format which is
a graph description language you'll see
that shortly
the other parameter we want to set
is feature underline names we set this
to an array of two strings
age
and gender these are the features or the
columns of our data set so they are the
properties or features of our data okay
the other parameter
is class names so class underline names
we should set this to the list of
classes or labels we have in our output
data set like hip hop jazz classical and
so on
so this white data set includes all the
genres or all the classes of our data
but they're repeated a few times in this
data set so
here we call y dot unique
this returns the unique list of classes
now we should sort this alphabetically
so we call the sorted function
and pass the result a y dot unique
the next parameter
is label
we set this to a string all
once again don't worry about the details
of these parameters we're going to come
back to this shortly so set label to all
then round it
to true and finally
filled to true
so this is the end result
now let's run this cell using ctrl and
enter
okay
here we have a new file music
recommender dot dot that's a little bit
funny so we want to open this file with
vs code so drag and drop this into a vs
code window
okay here is a dot format it's a textual
language for describing graphs
now to visualize this graph we need to
install an extension in vs code so on
the left side click the extensions panel
and search for dot d o t
look at the second extension here
graphviz or dot language
by staphon vs
go ahead and install this extension and
then reload vs code once you do that you
can visualize this dot file so let me
close this tab
all right
look at this dot dot here on the right
side click this you should have a new
menu open preview to the site so click
that
all right here's the visualization of
our decision tree let's close the dot
file
there you go this is exactly how our
model makes predictions so we have this
binary tree which means every node can
have a maximum of two children on top of
each node we have a condition if this
condition is true we go to the child
node on the left side otherwise we go to
the child node on the right side so
let's see what's happening here
the first condition is age less than or
equal to 30.5 if this condition is false
that means that user is 30 years or
older so the genre of the music that
they're interested in is classical
so here we're classifying people based
on their profile that is the reason we
have the word class here so a user who
is 30 years or older belongs to the
class of classical
or people who like classical music
now what if this condition is true that
means that user is younger than 30. so
now we check the gender
if it's less than 0.5 which basically
means if it equals to zero then we're
dealing with a female so we go to the
child node here
now once again we have another condition
so we're dealing with a female who is
younger than 30. once again we need to
check their age so is the age less than
25.5 if that's the case then that user
likes dance music otherwise they like
acoustic music
so this is the decision tree that our
model uses to make predictions now if
you're wondering why we have these
floating point numbers like
25.5 these are basically the rules that
our model generates based on the
patterns that it finds in our data set
as we give our model more data these
rules will change so they're not always
the same also the more columns or more
features we have our decision tree is
going to get more complex currently we
have only two features age and gender
now back to our code let me quickly
explain the meaning of all these
parameters we set fill to true so each
box or each node is filled with a color
we set rounded to true
so they have rounded corners
we set label to all
so every node has labels that we can
read
we set class names to the unique list of
genres and that's for displaying the
class for each node right here
and we set feature names to age and
gender so we can see the rules in our
notes
so that was a short and sweet
introduction to machine learning now you
can use the materials that you learned
in this section and apply them to solve
a different sort of problems now here's
a question for you what ideas do you
have for machine learning what kind of
problems do you want to solve with
machine learning use the comment box
below and let me know i love to hear
about your ideas
next we're going to use python and a
popular framework called django to build
a web application are you ready let's
get started
in this tutorial i'm going to show you
how to create your first website with
python at a very popular framework
called django so it's spelled with a
silent d and it's pronounced django it's
a web framework for perfectionists with
deadlines so if you're a perfectionist
and you want to quickly put together a
website that is fast scalable and secure
django is your best friend
and here are the popular websites built
with django like instagram spotify
youtube washington post and so on now
you might ask what is a framework and
why do we need a framework to build a
web application or a website
well a framework is essentially a
library of reusable modules these
modules provide functionality for common
tasks for example in case of a web
framework like django we have modules to
work with http requests urls sessions
cookies and so on these are the concerns
of pretty much every website or web
application out there so all this
functionality is already baked into
django we don't have to code it from
scratch that is why we use a framework
like django
now technically a framework is more than
a library so apart from providing these
modules it also defines a structure for
our application it tells us what folders
and files we should have in our project
so this provides a consistency amongst
various django projects so as you move
from one company to another and work on
different projects you can easily
transition from one project to another
because all these applications follow
the same structure
now with that introduction let's create
our first django project
so back to pycharm close the hello world
project and create a new project
okay let's call this new project pi
shop
go ahead
all right now down the bottom
let's open up a terminal window
in this window we're going to install
django so we use pip to install django
but be sure to add two equal signs here
followed by 2.1 with this we're telling
pip that we want to install django
version 2.1 the reason i'm doing this is
because in the future when you're
watching this video chances are there is
a newer version of django out there i
want to make sure that you can easily
follow these tutorials even though what
i'm going to show you in these tutorials
will most likely work with the latest
version of django i just want to be on
the safe side so let's go ahead with
this
all right django is installed next we
need to create a django project so here
press ctrl and l this cleans up our
terminal window you don't have to do it
but it's just easier to see
to create a django project we need to
execute this command django
dash admin
space start
project
space
we're going to call this project pi
shop
space period
so when we install django django brings
a command line utility called django
admin so this is a utility or program
that we can execute from the command
line or terminal right here
now this program takes various arguments
in this case we want to use this
argument start project with this we're
going to create a project called pi shop
in the current folder so this period is
important here that means the current
folder
if you don't add this period this
utility is going to create an extra
folder and that looks a little bit
repetitive so let's go ahead with this
all right
now back to the project panel if you
expand pi shop
you can see that this is our project
that we created in pycharm and in this
folder we have
these files
so in it that pi you have seen this
before that means this folder is a
package so we can import various modules
from this package into other modules so
here we have the settings module in this
module we defined various settings for
our application you're going to see this
later in this course we also have the
urls module and with this module we
define what should the user see when
they go to let's say slash about slash
contact slash products
shopping cart again we're going to work
with this zone and finally we have this
module ws gi that is short for web
server gateway interface the purpose of
this module is to provide a standard
interface between applications built
with django and web servers this is an
advanced topic so for now don't worry
about it
the outside of this folder we also have
this new file in our project that is
manage.pi
as the name implies we use this module
to manage this django project with this
we can start our web server we can work
with our database again we're going to
work with this soon
so let's open up the terminal window one
more time
now type out this command python if
you're on windows or python 3 if you're
on mac because as i told you at the
beginning of the course mac by default
comes with an installation of python
that is python 2. but in this course
we're using python 3. so python 3 space
manage dot pi
space
run server
what is going on here so with python
interpreter we are running this program
manage.pi and passing run server as an
argument this manage.pi is essentially
the same program that we worked with
here django admin
but we use django admin before creating
a django project now we have a django
project so in this project we work with
manage.pipe this is a module that
contains some python code so we use this
module to manage our django project
so let's go ahead and run our
development web server
as you can see this started a
development web server at this address
http colon forward slash forward slash
127.0 0.0.1 that is the address of your
current machine now note that after this
we have colon 8000 unfortunately the
link below this address has a problem as
you can see the port is excluded so if
we click this
it opens up our web browser and points
it to this address so we don't have the
port number let's add colon 8000 at the
end and here's our first django website
so we created this django project
now this django project can contain
multiple apps these apps don't represent
the entire application there are small
functional areas in our django project
here's an example imagine you want to
build a website or a web application
like amazon amazon is a big website it
has so many different functions instead
of implementing all these functions in a
django project we divide this project
into small functional areas that are
focused on one concern for example we
could have functional areas like product
management order management customer
management these are completely
different functional areas the functions
we have for managing the customers are
different from the functions for
managing the products by the same token
when you go to an organization there are
small departments or small offices
specializing in different areas so with
this analogy we divide the django
project into multiple django apps each
app is focused on one functional area
so in this tutorial i'm going to show
you how to add a new app to manage the
products in our imaginary shop in the
future let's say we want to add a blog
to our online shop we could come back
here and create a new app that
represents a blog now the beauty of
these apps is that we can reuse them
across different django projects because
each app is essentially a python package
let me show you so back to our project
let's open up a terminal window
so this is the terminal window we opened
earlier where we started our web server
now up here we have this plus button for
creating a new terminal window so let's
click that
now let's type out this command python
on windows or python 3 on mac
manage dot pi so we're using the same
program the same module but this time
with a different argument start app
and we're going to call that app
products
let's go ahead all right now
here we have a new folder called
products
let's see what we have in this folder we
have a subfolder called migrations we'll
look at this later below that we have
this init.pi so products is a package we
can take this package and reuse it in
another django application or more
specifically django project we can also
publish this package to pi pi for other
people to reuse in their django projects
for example if someone else wants to
build an online shop they can reuse this
package for managing the list of
products they don't have to build this
functionality from scratch okay we have
this module admin and this is used for
defining how the administrative panel of
this app will look like again we're
going to come back to this later
below that we have this module apps
unfortunately the name is a little bit
confusing because right now we are
inside of one app that is the products
app and it doesn't make sense to have a
module called apps inside of an app so i
don't know why django creators decided
to call this module apps but basically
we use this module to store various
configuration settings for this app so
it would be better to call this config
but that aside let's move on
next we have models and this is where we
define classes or new types for modeling
the concepts in this app in this domain
for example in the domain of products
you probably have concepts like product
category review and so on so we could
model these concepts using classes again
we're going to come back to this and
define a new class here
next we have tests.pi and this is where
we write automated tests for this app
that's an advanced topic beyond the
scope of this course so don't worry
about it and finally we have the views
module and this is where we define what
should the user see when they navigate
to a certain page
in this tutorial i'm going to show you
how to create your first view or view
function in django what is the view
function a view function is basically a
function that gets called by django when
the user navigates to a particular page
for example here we are on the home page
of our website
when we go to slash products our browser
sends an http request to our web server
at this point django takes that request
it inspects the url or the address it
figures out that we want to see the list
of products then it will call a function
which we call a view function and the
job of this function is to return the
response to the browser or to the client
so this function should generate some
html markup to be returned to the client
our browser will get this html content
and display it as a page right here
now technically if you want to be a web
developer you need to know html css and
javascript i'll try to do my best to
hold your hand throughout this course
but in the future be sure to watch a
tutorial about html css and javascript
on my channel i have plenty of
javascript tutorials i recommend you to
start with my javascript tutorial for
beginners
so back to our project
inside the products app let's open up
the views module
so here on the top we have some
boilerplate code from django.shortcuts
we are importing the render function so
django is a package shortcuts is a
module and we are importing the render
function you will see this soon below
that we have this comment we don't need
it let's create our first view function
so define we call this function index it
doesn't really matter but by convention
we use the word index for the main page
of an app
so when we go to slash products this
will be the main page of our products
app now potentially in the future we
could support additional urls inside of
this app for example products slash new
or training and so on
so we call this function index
now all our view functions should always
take a parameter and
that is the http request that is passed
to this view function
so as i told you before when we navigate
to slash products our browser sends an
http request to our web server django
takes this request and sends it to our
view function
with this request object we can find
information about the client
now in this tutorial we don't want to
worry about html we just want to return
some plain text to the browser like
hello world so on the top
from django.httpmodule
we need to import a class called http
response
with this class we can create an http
response to return to the client or the
browser so back to our view function
here we return an http response object
so we're creating an instance of this
class right
now as an argument to the constructor we
pass hello world
now we need to add an extra blank line
above the index function to make python
happy beautiful
as simple as that
so we are done with this view function
but nowhere django knows that it should
call this function when we send a
request to slash products
so we need to tell django that hey
whenever there is a request to slash
products call this index function we
need to map this url to this function
a url is short for uniform
resource locator and that basically
means address
okay
so let's do the mapping we're done with
this module close it
back to our products app right click
this folder and add a new python file
call that urls the name is very
important here this is one of the
conventions that django framework
defines so we need to follow this
convention to structure our project
okay so this adds urls.pi inside of the
products app now in this module once
again by convention we should define a
variable called url patterns
make sure to spell it exactly as you see
here so there is no underscore between
these two words and all characters are
in lower case
so we set this to a list object
in this list we map various urls to
their view functions
now to reference a url we need to import
the path function
so on the top
from
django.urls let's import the path
function
with this function we can map a url to a
view function so we call the path
function
the first argument is a string that
specifies our url endpoint
here we pass an empty string that is a
string with no characters in it and this
represents the root of this app let me
show you what i mean so
imagine our app starts
at slash products
so if the user sends a request to this
endpoint they will be at the root of
this app potentially here we could have
other urls like slash products slash one
slash detail or slash products slash new
or trending or whatever so all the urls
in this app start with slash products
okay now back to the first example
what happens if we take away this slash
products we are left with nothing and
that is why we use an empty string here
now as the second argument to this
function we need to specify our view
function
so we defined that view function inside
of the views module
so first we need to import this module
into the urls module
now
this is how we do this from
period import views
period means the current folder so from
the current folder we are importing the
views module
so with this syntax we're telling django
to import the views module that we have
in this folder now you might ask wash
why didn't we import the views module
like this import views because views is
actually in the current folder so why do
we have to use the from import syntax
the reason for this is because views is
kind of a generic name so it is possible
that our project has a dependency to
another library called views
with this syntax python will end up
importing that module instead of the
views module in the current folder
because that will take priority
so
to remove these potential issues we use
the from import syntax
so now we imported the views module as
you know when we import a module that
module will end up being an object so we
can use the dot operator to access the
functions defined in that module so here
we want to reference the index function
okay let's delete it from here back to
our path function
as the second argument we type out
views.index
now note that i'm not calling this
function i'm simply passing a reference
to it django will take care of calling
this function at runtime when the client
sends an http request to the server so
here we should not call this function
so let's quickly recap what we have done
up to this point
in the views module
we created this view function and in
this view function we simply return some
plain text to the browser or the client
now i told you that nowhere django knows
that it should call this function so
that's why we added the urls module to
our app
and in this module we mapped the root
url to this view function
there's one more step left we need to
tell django about this app because up to
this point django is not aware of this
app
so
let's collapse the products folder and
open up the pie shop folder
in this folder we have another urls
module and this is like the root or the
parent urls module in our django project
let's open this
and scroll
down once again you see this url
patterns variable that is set to a list
in this list again we're calling the
path function
as the first argument we're telling
django that hey any urls that start with
admin delegate them to the admin app so
every django project by default comes
with this admin app which gives us a
beautiful administrative panel we're
going to work with that soon
so in this module we should also tell
django about our products app so let's
add another object to this list once
again we call the path function
now we tell django that hey any paths or
any urls that start with products slash
delegate them to the products app
so we want django to delegate the
handling of that request
to this urls module that we defined in
the products app
okay how do we do that very easy
back to the main or the parent urls
module on line 16 we have this import
statement let's expand it
so basically we have two import
statements look at the second one from
django.urls module we're importing the
pass function there is another function
that we need to import and that is the
include function
now we're going to use this function on
line 21 so as the second argument to the
path function we call include
and here we need to reference the urls
module in the product app so we type out
products dot urls
so take a look
in the products app
we have this module
urls that is why we type
products.urls but we don't type out dot
pi django will automatically take care
of that
now at this point you might be a little
bit confused or intimidated by all these
various steps that you have to follow
they may look foreign to you but trust
me this becomes second nature as you
practice building django applications
it's actually very easy it's just the
first time that you have to follow these
conventions defined in django framework
once you understand the concept it
becomes really easy
so basically because we created a new
app the products app only once ever we
need to write this line of code to tell
django that hey any urls that start with
products
send them to the urls module in the
products app
so we write this line of code only once
anytime in the future we want to define
a new view function first we go to the
views module we create a new function
and then we go to the urls module in
that app
and define a new url pattern to map that
view function to a url endpoint that is
really easy
all right now let's test our application
so back to the browser
let's head over to slash products
there you go you see our hello world
message here beautiful but if we
navigate back to the home page
we get this error page not found so our
beautiful django homepage disappeared
and the reason for this is that that
home page is automatically generated and
is only displayed when we first create a
django project
as soon as we define a new url pattern
and register it in our project that
homepage disappears but don't worry
we're going to come back and create a
new function for our home page later in
the course
now here is your exercise i want you to
modify this django project such that
when we navigate to products
slash new we'll see a page here with
some text like new products i strongly
encourage you to do this exercise
because it makes it really easy for you
to follow the future tutorials
alright here in the products app let's
open up the views module
in this module we define a new view
function so define let's call that
function new
as i told you before every view function
should take this request parameter
like here we want to return an http
response
with the text new products
that's it now to make pycharm happy we
add
another line break here so we have two
line breaks after the index function and
also two line breaks after the new
function these are the best practices
defined in pep 8 to format our code
so we're done with this view function
now we need to map it to a url endpoint
so we go back to the products app and
open up the urls module
here we need to add another url pattern
so we call the path function
the first argument should be new you
want to map this url endpoint to
views dot new function that's all you
have to do now back to our browser let
me navigate to products new we get this
message in the browser beautiful
in this tutorial i'm going to show you
how to create a model in a django
project a model is a representation of a
real world concept for example in an
online shop we could have models like
order customer shopping cart product
review and so on so let's go ahead and
create our first model
here in the products app
open up the models module
in this module we're going to create a
new class called product so let's delete
this comment we don't really need it
class
product
now we need to inherit this class from
the model class in django so in
parenthesis we type out models dot model
let's see what's going on here so on
line one from django.db package we are
importing
the models module
in this module we have a class called
model and this class defines all the
common characteristics and behavior for
models in a django application for
example we want to be able to store
these models in a database or read them
from a database or delete them these are
all the common operations that we need
to perform on these model objects
so by inheriting this product class from
this model class our product class will
have all these capabilities built into
it we don't have to code it okay so
colon now in this class we need to
define a few attributes what are the
attributes of a product that we need to
know in an online shop we need to know
their name
price
stock image and so on so let's define a
new attribute
we call it name and we set it to an
instance
of models the char field class
so once again in this module we have a
class called char field which is short
for character field and this represents
a field that can contain textual data
now here as a best practice we can
supply a maximum length to prevent a
malicious user or hacker from
accidentally storing a product with an
enormously large name this can mess up
with our application
so let's pass a keyword argument max
length and we set it to 255 characters
now let's define the price attribute so
we set price to models dot
float field so this represents a field
that can contain floating point numbers
that's it
now let's define the stock
we set this to an instance of
integer field
and finally let's define
image underline url
to an instance of models dot
one second char field
so in this course we're gonna use google
to find an image for our products for
example we can find this image
right click it
and copy its link address which is the
url
now if you open up a new tab and paste
that url you can see this is a very long
string
so we don't want to enforce a maximum
length of 255 characters
instead we want to use
2083
characters that is the standard maximum
length for urls so our product class or
product model has these four attributes
now to make pycharm happy and remove
this warning let's put the cursor at the
end of this line press enter then
backspace to remove the indentation
beautiful we should also add
two line breaks before this class so
here's one press enter the second line
break beautiful so our code is formatted
according to pep8 standards next i'll
show you how to use this model to create
a database table for storing products
in this django project we have created
you can see we have this file
db.sqlite3 this is an empty database
file that django creates and we use this
to store our data now sqlite is a kind
of database and it's the same place for
small applications but it's not suitable
for large enterprise web applications so
if you want to build a real enterprise
web application with django you need to
use a proper database engine like sql
server mysql oracle postgres and so on
the good news is that django supports
all of these database engines but sqlite
is the easiest to get started so we're
going to work with this for now and in
the future i will show you how to use a
proper database engine
now for the purpose of this tutorial i
want you to open up your browser and
search for db browser for sqlite
so on this page sqlitebrowser.org
you can find a very simple and free
application for opening sqlite databases
and as you can see here on the right
side there are executables for windows
mac and so on
so when you open it you get something
like this we can create a new database
here on the top or open an existing one
now here i'm going to drag and drop our
database file right here
you can see we don't have any tables in
this database so to store data first we
need to create a table for example to
store the list of products we need to
create a table called product and the
fields or columns we have in this table
should be exactly the same as the
attributes we have
in our product class
so in this tutorial i'm going to show
you how to use django to automatically
create this table we don't have to do
this by hand we can just tell django hey
here's our model go ahead and
automatically create a database table
for storing our products
that is very easy
so here down the bottom let's open up a
new terminal window and run python on
windows or python 3 on mac
manage.pi
make migrations
make sure to spell this properly so make
migrations in one word
now when you run this you get this
message no changes detected because by
default django doesn't know about our
product model
to solve this problem
we need to go back to our project
and open the pie shop package
in this package we have this settings
module for storing various configuration
settings for our project
so let's open this
and scroll down
on line 33 you can see a variable called
installed apps set to a list of strings
these are applications or apps that are
automatically installed with every
django project for example we have this
admin app which gives us a beautiful
administrative panel we're going to work
with it soon you also have this auth app
and we use this to authenticate users we
can put them in different roles give
them different permissions it's all
about authentication and authorization
we'll look at the other installed apps
in a future tutorial so for now let's
register our products app in this list
how do we do that
first we go to our project
inside the products app earlier i told
you about the apps module take a look
here
the name of this module is a little bit
misleading because we're in the boundary
of one app and we have a module called
apps
that aside all we have here is a class
called products config where we store
configuration settings for this
particular app
okay
now we need to go back to our settings
module and add the complete path to this
class including its package and module
so this class is defined in the apps
module and this module is inside of the
products package
so back to the settings file
in the list of installed apps we need to
type out a string like this
products that's our package
dot
apps that's our module
and then products
config
again make sure to spell this properly
so
p and c are capitalized because here we
have a class but products and apps are
all in lower case okay
so now django knows about our product
app so when we go back to the terminal
and run the last command we'll get a
different result
so use the up arrow to bring up the last
command and enter
there you go
now we get this message migrations for
products so inside the products folder
inside the migrations folder we have a
new module with this sequence number
called initial
let's have a quick look at the code
inside this module so back to our
products app let's expand the migrations
folder
here's our initial migration let's have
a quick look here
so we have a class called migration and
in this class
we have this attribute called operations
which is set to a list of operations so
every migration can contain multiple
operations look at the first operation
we have here migrations that create
model
so with this operation we can create a
new database table called product and in
that table we're going to have these
fields id name price stock and image url
these are the attributes that we created
in our product class but we didn't have
this id attribute django automatically
generates this because every database
table must have an id field and we use
this to uniquely identify records in our
database now let's go back to the
terminal
so we have a new migration but our
database is still in its previous state
we don't have a new table here yet
so we need to run this new migration to
generate our product table and that is
very easy
so one more time python
manage the pi
migrate
when we run this command django will
look at our project it will look at
every app and it will run the pending
migrations for that app against our
database so take a look when we run this
we get several messages
so if you scroll up you can see applying
content
types.001 initial so in the content
types app which is one of the apps
installed by default we have this
migration so django ran this migration
and this created a database table for
this app similarly in the auth app which
is used for authenticating users we have
this initial migration we also have a
bunch of migrations for the admin app so
django run all of these migrations and
down the bottom you can see
applying products initial migration
so every app can contain multiple
migrations and each migration will make
a slight change to the database to add a
new table or modify an existing one
so back to db browser for sqlite let's
drag and drop our database file one more
time here to reload it there you go now
we have 12 tables in this database each
table is prefixed with the app it
belongs to for example you can see we
have a table for storing our users we
have another table for storing the
groups a user belongs to we have another
table for storing permissions and so on
now here down the bottom you can see
is table products underlined product so
this product table is prefixed with the
name of our app which is products
now if you expand this you can see
these fields in this table id name price
stock and image url so this is the
beauty of django we didn't have to come
here and manually create these tables by
hand that's very time consuming we
simply created a model with these
attributes and then we ran two commands
in the terminal one for creating a new
migration based on the changes we have
made in our code and the other to run
the pending migrations so now all the
migrations in this project are run
against our database which means if we
go back to the terminal and run python
manage.pi migrate
we get this new message no migrations to
apply
so here's the workflow next time we
create a new model or modify an existing
one we should come back here in the
terminal create a new migration and then
run it
alright here's your exercise we want to
have the concept of offering discounts
in our imaginary online shop
so i want you to create a new model
class called offer
and in this class we should have three
attributes
one is code which is a textual field for
example our offers code could be vca2142
it's just a coupon code
here we should also have an attribute
called description
again this is going to be a textual
field for example we can say 20 percent
of all products and then we can display
this text somewhere on the home page in
the future
and finally we need another attribute
called discount which is going to be a
floating point number like 0.2 for 20
discount so go ahead create this model
class next create a migration and run it
to bring our database up to date this is
an awesome exercise for you to get your
hands dirty in django so spend three to
five minutes on this exercise when
you're done come back see my solution
so here in the models module right after
our product class i'm going to define a
new class
class offer
this class should also derive from the
model class in django
here we add the attributes so
the first one is code which is going to
be an instance of models dot char field
and we set the max length to let's say
10 characters
next we add the description
once again we're going to have a chart
field with max length of 255 characters
is sufficient and finally we need
discount
and we're going to set this to an
instance of models that float filled
so here's our offer class now we need to
create a migration so over here i'm
going to open up a terminal window
this is the main terminal window where
our web server is running so i'm going
to create a new terminal window and run
python
manage dot pi
make
migrations django detected a change in
our models so it created this new
migration migration number two called
offer and this migration will create the
offer table in our database so let's go
ahead and run it
python3
manage.pi migrate
beautiful
now let's drag and drop our database
here one more time
our database is refreshed as you can see
in the products app we have this new
table offer with these four columns
id code description and discount
in this tutorial i'm going to talk to
you guys about the administrative panel
of django applications so here in the
browser if we head over to slash admin
we get this beautiful login screen to
log into our administrative panel so
every django application by default
comes with an administrative panel we
don't have to create this from scratch
we don't have to code this it gets
auto-generated and this is one of the
fantastic features of django that
increases your productivity so let me
show you how to work with this
administrative panel
here in pycharm we need to create the
first user of this application we call
that super user
so here in the terminal window let's run
python
manage dot pi
create
super
user all in one word
so let's go ahead with that it asks for
username let's type admin
next we need to enter an email address
i'm going to enter my email address next
we need to enter a password i'm going to
type one two three four
and repeat it one more time
note that it complains because this
password is too short it's too common
and it's entirely numeric
so at the end it asks if you want to
bypass password validation for
simplicity let's go with that but of
course in a real scenario you'll want to
create an admin user with such a simple
password
all right we successfully created the
super user
now back in the browser let's log in
with admin and one two three four
there you go
so this is our administrative panel as
you can see we can manage the users and
groups we can add new users or modify or
delete existing ones let's have a quick
look here so here we have this search
bar on the top we can quickly search for
users below that we have this table of
users with this columns username email
first name last name and status we can
sort this table by any of these columns
we also have these filters on the right
side
so we get all these beautiful features
for free with every django application
we don't have to code this
earlier in this course we talked about
this settings module let's have a quick
look here
in this module we have
a setting or variable called installed
apps and one of the apps that is
installed by default is the admin app
so this app is the piece that is
responsible for generating these views
now the beautiful thing about the admin
app is that it is easily extensible so
back to the home page of our
administrative panel so far we can only
manage the users and groups but using
one line of code we can also manage our
products let me show you
let's expand our products app
inside of this app we have this module
admin and in this module we register the
models that we need to manage in the
admin section
so let's open this module
now on the top
first we need to import our product
model so we can type out some code like
this from period models that means the
models module in the current folder
so from this module we want to import
the product class or the product model
right
now you can see this comment here
register your models here let's delete
this comment we don't need it anymore
instead we're going to write code like
this so admin
dot site dot register
and we pass this product class as an
argument what is going on here
we're using this admin object that is
imported
on line one this object has an attribute
called site which is an object itself
this object has a method called register
we're calling this method and passing
our product class as an argument with
this we're telling django that we want
to manage our products in the admin area
so now with only one line of code or
more accurately two lines if we go back
to our administrative panel and refresh
this page
we see this new table products that
represents our products app and in this
app currently we only have one model
called product so here we can manage all
our products currently we don't have any
products in our database so let's go
ahead and add a new product look we get
this beautiful form for free we didn't
write any code to create this form and
handle the click event of these buttons
to insert a product into our database
all this is automatically generated by
django
so let's go ahead and add a new product
call that orange let's say 1.99 each
and
set the stock to 50.
now we need an image url so open up a
new tab here
and in google search for orange
then
go to images
click on tools
from the user rate menu select for
labeled for reuse this way we don't have
problem with copyright issues so these
are the three images that we can use in
our application
let's pick this one
click on it again
now on this page right click the image
copy a link address
and then back to our product form
paste it here
and then save
so we successfully added a product and
that product is listed here in the
product table but what we see here is a
little bit confusing it says product
object one it's not clear what product
this is is it an orange is it a
strawberry what price is it so in the
next tutorial i will show you how to
customize this table and add columns
specific to products
in this tutorial i'm going to show you
guys how to customize this products
table in the admin area that is very
easy so back to pycharm
here in the admin module where we
register the product class for
administration we need to create a new
class called product admin so
we create a class
called product admin so this is the
convention we follow in django we start
with the name of our model that is
product and then we add the suffix admin
now we should inherit this class from
admin
dot model admin what is going on here
well this admin is a module that we have
imported on line one
in this module we have a class called
model admin which provides all the
common functionality for managing models
in the admin area so with deriving this
class from the model admin this class
inherits all this common functionality
now
in the body of this class we can
overwrite or change some of this
functionality or attributes for example
in this class we have an attribute
called list
underline display and this attribute
specifies the columns that should be
visible in this table
so we set this to a tuple
and in this tuple we add one or more
attributes of our product class
so let's quickly open up our product
class
it's here in the models module
okay there you go so our product class
has these attributes name price stock
and image url now image url as you saw
is a long string so we don't want to
display that in our table so in this
tutorial let's add these three
attributes to our products table
back to the admin module
in this tuple we add three strings name
price
and stock
now we have this little warning here
because we haven't added two line breaks
before and
after this class
that is better
finally when registering our product
class for administration
as the second argument we need to pass
this new class product admin
so django will use the information in
this class to decide how to present the
list of products
so back in the browser let's refresh
this page there you go here's our
products table now we have three columns
name price and stock you can see we have
this orange the price is set to 1.99 and
currently we have 50 items in the stock
beautiful let's go ahead and add a new
product here
let's say strawberry
and the price 2.99
30 for the stock and finally we need an
image url i'm going to paste this
address that i just copied before
recording this video okay let's go ahead
save the changes
the product is added beautiful and now
we have two products in our table now
here's what i want you to do i want you
to pause the video and add a few more
products to our database somewhere
around 5 to 10. in the next tutorial i'm
going to show you how to display these
products to the public users of our
website because this admin panel is only
visible to admins so anonymous users or
other registered users are not going to
have access to this panel instead
they're going to go to
slash
products
and currently we're displaying a hello
world message we're going to change this
page and display the list of our
products in a beautiful grid so pause
the video and add five to ten products
then come back continue watching
currently in the admin area we can only
manage the products in the products app
so there is no way to manage the offers
so as an exercise add the ability to
manage the offers here when we click the
offers link we should see a table with
two columns code and discount
so go ahead and implement this and then
create a new offer
all right here's my solution
in the admin module of the products app
on line two first we need to import
the offer class
next
we create a new class called offer admin
we derive this from admin that model
admin
and here we set the list display
attribute to a tuple with two items
code
and discount
and finally we need to register our
offer model for administration
so admin.site.register
offer and offer admin
that's it
now if we go back to the admin area
and refresh the home page we see the
offers link here beautiful currently we
don't have any offers so let's go ahead
and add a new offer
i'm going to use the code like vca 1010
let's say 10
off all products
and discount i'm going to set this to
0.1
now technically in a real application
this code should be unique but that's a
topic for a future tutorial so for now
don't worry about it let's go ahead and
save this offer
okay our offer is saved successfully
beautiful as you can see in this table
we have two columns code and discount
in this tutorial i'm going to show you
guys how to replace this hello world
message with the list of products in our
database and that is super easy
so here in pycharm in the products app
let's open up the views module
area i told you that in this module we
define our view functions which are
functions that get called when the
browser sends an http request to the
server
for example when the user navigates to
slash products page our browser sends an
http request to our django application
django takes that request and hands it
off to this function the index function
and here we're simply returning a hello
world message we want to replace this
with the list of products in our
database
so the first step is to get the products
stored in the database and then we need
to format them using some html template
so let's go ahead and
on the top import our product class from
the models module so
from
period models
import product so we're importing the
product class in the models module in
the current folder so period means the
current folder
now this product class has a bunch of
useful methods for getting data from our
database for example we can call
product.objects.all
and this returns all the products we
have in our database we also have filter
for filtering products let's say we want
to get products that are more expensive
than two dollars or products that are
out of stock we can use the filter
method we also have the get method for
getting a single product and we also
have the save method for inserting a new
product or updating an existing one now
in this tutorial we're going to use the
all method to get all the products from
our database
then we store them here in this variable
so we have done the first step next we
need to create an html template for
presenting this list of products to the
user so back to the project panel
inside the products app
let's add a new folder a new directory
and by convention we should call that
templates make sure to spell it properly
because this is a special directory that
django looks at the load templates
so let's go ahead with that now we want
to create a template for the index
function so inside of this folder let's
add a new file
and call that file index
dot html
now here we can write some html code if
you're not familiar with html don't
worry just follow along with me it's
super easy to learn
so first let's type h1 and then press
tab
this inserts an h1 tag into our html
document and we use this to display a
big bold heading so inside these tags
let's type products
now below this h1 let's type ul and
press tab
now this inserts a ul tag and we use
this to display a list of items now we
need to surround each item with an li
tag so type out li press tab
and in between the tags let's type item
1 then copy and paste this a couple
times so item 2 and item 3. now instead
of item 1 item 2 and item 3 we want to
display the name of our products but
before we get there let's simply return
this html markup to the client instead
of the hello world message
so back to the views module
here in the index function we need to
change the return statement on line 8.
so
you want to call the render function
this function is already imported on the
top on line 2. we use this function to
render a template
so
let's call this function as the first
argument we need to pass
this request object that we get as an
argument to this function
so let's pass the request here
as the second argument we need to
specify the name of our template so we
pass a string what is the name of our
template that is
index.html right now before going any
further let's go back to the browser
and
refresh this page
so instead of hello world we see this
product's heading this is the result of
an h1 tag and with ul and li tags we see
these bullet points over here beautiful
now finally we need to replace item one
item two and item three with the list of
our products
so back to our view function
as the third argument to the render
function we need to pass the list of
products that we loaded from the
database so here we need to pass a
dictionary
in this dictionary we're going to add
one key value pair we're going to call
the key products but we could call it
anything it doesn't really matter
the value for that key should be the
products object that we define on line
7.
so
here in our dictionary let's add this
key product
colon and the value should be
this product object
so let me break up what we have on line
eight
over multiple lines so you can see it
clearly
recording the render function with three
arguments the request object the name of
our template and a dictionary that
contains the data to be passed to this
template
and finally we're going to go to this
template
index.html
and replace these items with our
products that is very easy
so just after the ul tag i want you to
type out a curly brace followed by a
percent a space a percent one more time
and a closing brace
this is what we call a template tag in
django so in between these markers we
can write dynamic code for example we
can add loops to repeat some
instructions or write if statements to
conditionally render some content
so here we want to write a for loop for
product
in
products
so earlier in our view function we
passed these products here using a
dictionary back to the view function
look
as the third argument to the render
function we passed is dictionary this
dictionary is called the context so it
provides data to be used in our
templates in this case we have a
property called products and that is the
reason we can access it here so we are
looping over this product
now for each product you want to render
a list item so let's indent this item
here
and
replace item 1 with the name of the
product so here we want to dynamically
render the name attribute of this
product object
to do that we use double curly braces so
open two curly braces and close them and
in between them type out product dot
name so whenever we use double curly
braces in a django template django will
evaluate the expression that we put here
and render it in html
now the last step is to end this four
block because django unlike python
doesn't rely on indentation to determine
the scope of a block
so
right after this for loop once again we
add curly braces eight percent and type
out and four
and then we close it here
now we no longer need these items here
so let's delete them
now back to the browser let's refresh
our page
so instead of item 1 to 3 we see the
name of the products stored in our
database
now let's take this to the next level by
displaying the price of each product
right next to it
so
back to our template this is where we're
rendering the name of the product
after the curly braces let's add
parenthesis now inside of the
parenthesis we want to dynamically
render the price of each product so once
again we use
the double curly brace syntax to render
some value dynamically that is the value
of product dot price
like this
now back here let's refresh the page
now we can see the price of each product
right here beautiful we could also
prefix that with a dollar sign so before
the curly braces we add a dollar sign
and then when we refresh the page we see
the actual dollar value
so this is what i want you to take away
in this tutorial in django templates we
have two special syntaxes one is a curly
brace and a percent this is called a
template tag and we use this to
dynamically execute logic
so in between these template tags we can
write for loops to repeat some code or
we can use if statements to dynamically
render content
the other syntax we have is the double
curly brace syntax and we use this to
dynamically render values in our html
markup so whatever we put in between
them will get evaluated and written to
the html markup
now this page is pretty boring so far in
the next tutorial i will show you how to
convert these bullet points into
beautiful cards
over the next few tutorials we're going
to replace this boring list of bullet
points with a beautiful modern card like
this so on the top we're going to
display the image for each product below
that we're going to display the title or
the name of the product as well as the
price and potentially a button to add
that product to a shopping cart now to
present something like this we're going
to use a framework called bootstrap it's
a very popular framework for building
modern and responsive applications so
head over to getbootstrap.com
on the home page
you should see something like this and
then go to the documentation
on this page you can see how you can add
this bootstrap framework to your web
applications so if you scroll down
here you should see a starter template
so here we have some basic html markup
we want to bring all this html markup
and store it in a template called
base.html so over here you should see
this copy button click that to copy this
then back to pycharm
in the project panel
inside of the templates folder let's add
a new html file so a new file we call
this base.html
now
with command and v on mac or ctrl and v
on windows paste all this markup that we
copied from bootstrap website
now
here on line 13
we have the body tag and this is the
container for what the user sees in a
given web page
now in this example we have an h1 tag
for displaying a hello world title we
want to replace this with something
dynamic so for each page in our
application we want to render something
different for example when the user goes
to the products page over here instead
of this h1 tag we want to render what we
defined in index.html here
okay
so back to base.html let's delete this
h1 tag once again we're going to use a
template tag so curly brace percent
percent curly brace
now the template tag we're going to use
is called block and with this we can
define a block or a hole in this
document so we're going to create a
block called content we could call it
anything but here we're defining the
content area of our website
so that's why we call this block content
now after this once again we need to add
another template tag
and this is called end
block now we should go to index.html
on the top we should tell django that we
want to extend this base template which
means we're going to use all the markup
defined here
and this gives our applications a modern
look and feel
so back to index.html once again we're
going to use another template tag
this one is called extends so extend
what are we extending
the template defined in base.html so
here we add a string base
dot html
now we want to fill the block or the
hole that we defined in base.html
with
these view lines
so once again we add a template tag
block what is the block that we're
filling that is the content block right
and we close it here
so now all this markup is going to go
in the content block
now finally we need to close this block
so after the last line
let's add another template tag
and block
now to make this code cleaner i would
prefer to select these few lines that
belong to the content block and
indent them like this this is not
required but it just makes our code
easier to read
so with these changes that we made in
this tutorial when django tries to
render this page
first it will look at base.html so it
will take all the markup defined in that
file and then it's going to fill
this content block with the markup we
have defined here
now if we go back to our browser
and
refresh this page we're going to see
something a little bit better so refresh
you can see the fonts are changed and
there is a little bit more space in
between the bullet points
now you're ready to replace each bullet
point with a bootstrap card and that's
what i'm going to show you next
in this tutorial i'm going to show you
how to display these beautiful cards on
our products page now note that this
page is responsive so if you view it on
a small mobile device we're going to
have one card on each row
like this
and if you view this on a bigger screen
we're going to have more columns or more
cards on each row so let me show you how
to build this
first head over to get bootstrap.com
click on the documentation
here on the left side you can see a link
called components
on this page you can see all the
components that are defined in bootstrap
these are the components that we can add
to our web pages to make them beautiful
and modern
so the component that we're going to use
is called a card
over here you can see
an example of a card
and right below that you can see the
markup that we need to use to render
something like this
so
let me resize this screen okay on the
top right corner we have this button
copy this markup
now back to index.html
instead of rendering a ul and a bunch of
lis we want to render a bunch of divs
because with ul and li we'll get bullet
points but we don't want to display
bullet points here
so
right below the h1 tag
type out div dot row and then press tab
so this creates a div with the class row
now in this row we want to repeat
multiple columns so type out div
dot
call as in short for column and then
press tab
so we use this divs to create a layout
like this we have multiple columns in a
row
okay
now inside of a column
we want to render a card so now we
should paste the markup for rendering a
bootstrap card
so paste that here
now we can see our code looks a little
bit ugly because it's not indented
properly so on the top go to the code
menu
here we have this item reformat code and
look at the shortcut that is associated
with this command so let's click that
now our code is beautifully formatted
and it's easier to read and modify
so we have a row inside this row we have
a column and inside this column we have
a card
now we're going to take our for loop and
put it above this column
so for each product we want to render a
column
so scroll down
and
grab this line of code cut it
and then
paste it right above
this column
now we should close this for loop so
let's collapse this div below it
okay now right after this div we want to
add a template tag
and type out and four
with these changes we don't need the
code from before we don't need the ul
and li tags so let's delete all of these
so this is the final result
inside the content block we should have
these tags
we have an h1 on the top for the heading
below that we have a row
then we have our for loop and in each
iteration we render a column so let's
also indent this line to go inside the
for loop that's better and finally we
close our for loop and after that we
close our row
with this change if we go back to the
browser
and refresh
we get something like this we're
basically repeating all that static or
fixed markup from bootstrap over here
so we're not rendering the actual name
or the image of each product but that is
a very easy fix
so back to our markup let's expand this
column
so here's our card
inside this card we have an image on
line nine look at the source attribute
of this image
we need to change this
and dynamically render the image url
attribute of each product so let's
delete this
and inside the quotes we add double
curly braces to render some value we
want to render product dot image
underline url
like this
now over here on line 11 we have this
text card title we want to replace this
with the name of each product so delete
double credit braces and we add product
dot name
next we need to replace this text
with the price of each product so delete
here we have a paragraph tag inside this
tag we add double curly braces to render
product dot price and just before these
braces we want to add a dollar sign
and the last change
is the label for this button
it's called go somewhere we want to
change that to add to cart
now back to this page refresh we should
get something like this beautiful
in this tutorial i'm going to show you a
couple of techniques for improving the
look and feel of this page first we're
going to add a navigation bar on the top
and then we're gonna add some padding
around with elements currently this
product card is way too close to the
left side of the screen so we should add
some padding to let this page breathe
now to add a navigation bar
once again we go to the bootstrap
website look at the documentation for
the navbar component so here's the
navbar
now if you scroll down
you can see a typical nav bar so we can
have these links we could have a drop
down we could have a search bar now this
looks a little bit clunky because i've
resized the screen so it doesn't look
pretty but below that you can see
another
simple navigation bar with only the
brand or the name of the application
so over here we have the markup to
render this navigation bar so let's go
ahead and copy this
now back to pycharm where should we add
this markup
we should add it to base.html because
this is supposed to be a base template
for all pages in our application
so
here's the opening body tag right below
this body tag we want to paste the
markup for rendering a navigation bar
now the code is not formatted properly
it looks clunky so once again go to the
code menu and then reformat code as you
can see the shortcut for mac is alt
command and l so i'm going to use a
shortcut here
there you go that is better
so here's our navigation bar
now let's change this text from navbar
to
pi shop that's the name of our
application right
now back to the browser
let's refresh this page we have this
navigation bar on the top let's go back
to pycharm and make a slight change in
the structure of our application
so here in the products app we created
the templates folder and in this folder
currently we have two templates the base
template for our application and the
template for the products page the
problem with this structure is that this
base html is not reusable because we
have added it inside the template of the
products app what if in the future we
want to add another app to this project
we don't want to recreate this base.html
in every app that just doesn't make
sense so we want to reuse this across
multiple apps and that's why we need to
move this outside of this folder and put
it somewhere central so
in the root of our project
here we need to add a new folder called
templates so right click the project and
add
a new directory
called templates
now we want to go back to the products
app
inside the templates folder
we drag this base.html file and drop it
into the main templates folder
okay
good now our base template is somewhere
central so we can reuse it in multiple
apps
however if we go back to the browser and
refresh this page we get this error
template does not exist
if you scroll down you can see why we
get this error
so over here you can see this red line
let me zoom in
this error happens because django
couldn't load
base.html
now if you scroll up
you can see the paths that django
searches for to find this template
here's the first path
admin slash templates slash base.html so
django is looking for this template
inside the admin app
here's the second path aus slash
templates slash base.html so django
couldn't find it in the admin app it
thinks maybe it's in the us app and
finally here's the last pass products
slash templates slash base.html that is
our products app so what is going on
here django is looking for this template
only inside of the installed apps
but this templates folder that we
created it's not really part of any apps
it's just a standalone folder
so we need to tell django to look inside
this folder in addition to the installed
apps and that is very easy
so
in the main package pi shop
you have seen the settings file before
let's have another look here if you
scroll up
you can see this variable base directory
this variable is set to the complete
path of where you have stored this
django project on your disk
we're going to take this directory and
append templates to it
so
scroll down
on line 55 you can see the configuration
for loading templates
look at the settings we have here the
first setting is back end and this is
the engine that is used to parse our
templates so all those template tags as
well as the double curly braces this is
the engine
that knows how to interpret those
look at the second setting
directories this is set to an empty list
so here we need to reference the
templates folder in this project
so let's type out os
dot path so we're using the path object
defined in the os or operating system
module that is important on the top now
this path object has a method called
join and with this we can join multiple
parts of a path
the first part
is base underlined
which is the variable that i showed you
earlier it's set to the complete path of
your django project
now we want to take this and append
templates to it
that's all you have to do so back to the
browser let's refresh the page there you
go the problem is fixed so now our base
template is somewhere central and we can
reuse it across multiple apps beautiful
and one last change
currently as you see these items are so
close to the left side of the screen so
i'm going to add some padding to make
this page breathe and that is very easy
back to pycharm
here in our base template
where we define
this content block we need to wrap this
with a div with the class container this
is one of the classes defined in
bootstrap that we use to define a
container area in our application this
container area has some padding so type
out div dot container and press tab okay
and then move these template tags inside
of this div
that's it now back to the browser let's
refresh
so this is our container area as you can
see we have some padding to the left and
right side of this container area
beautiful
so that brings us to the end of this
django tutorial in this python course i
hope you learned a lot and thank you for
watching
so that was a short and sweet
introduction to django but django really
requires his own course and i'm planning
to create a comprehensive course on the
topic in the near future now here's a
question for you
what kind of applications do you want to
build with django use the comment box
below and let me know i will take your
ideas into consideration as part of
creating my upcoming django course
so that brings us to the end of this
course i hope you learned a lot please
support my hard work by liking this
video and sharing it with others and
also subscribe to my channel for more
tutorials like this thank you so much
for watching and i hope to see you again
soon
[Music]
you
Can't find what you're looking for?
Get subtitles in any language from opensubtitles.com, and translate them here.