in this course you're going to learn
everything you need to get started with
Python just be aware that I've designed
this course for beginners so if you have
some programming experience check out my
other Python course for developers you
can see the link on the top right corner
of this video so python is the world's
fastest-growing and most popular
programming language not just amongst
software developers but also amongst
mathematicians data analysts scientists
accountants network engineers and even
kids in fact it's the ideal programming
language to learn first but what makes
Python so special here are six reasons
with Python you can solve complex
problems in less time with fewer lines
of code than many other languages
that's why huge companies like Google
Spotify Dropbox and Facebook have
embraced this beautiful and powerful
language here is an example let's say we
want to extract the first three
characters of the text hello world this
is the code we would have to write in
c-sharp this is how we would do this in
JavaScript and here's how we would do it
in Python see how clean and simple the
language is and that's just the
beginning
Python is a multi-purpose language and
you can use it for a wide range of jobs
such as data analysis AI and machine
learning writing automation scripts
building web mobile and desktop
applications as well as software testing
or even hacking so if you want a
high-paying long lasting career in any
of these areas especially AI and machine
learning Python is the language to put
those opportunities at your fingertips
in fact according to indeed.com
the average salary of a Python developer
in the US was over one hundred and
fifteen thousand dollars in March 2018
and here are four more reasons that make
Python the most desirable language
Python is a high-level language so you
don't have to worry about complex tasks
such as memory management as you do in
C++
it's cross platform which means we can
build and run Python apps on Windows Mac
and Linux it has a huge community so
whenever you get stuck there is someone
out there to help and it has a large
ecosystem of libraries frameworks and
tools whatever you want to do it is
likely that someone else has done it
before because python has been around
for over 20 years there are two versions
of Python out there Python 2 which is
the legacy version of Python and is
going to be supported until year 2020
and Python 3 which is Python for the
future in this course you're gonna learn
Python 3 hi my name is Muhammed Ani and
I'm going to be your instructor in this
course I'm a software engineer with 18
years of experience and I've taught way
over a million people how to code or how
to become top professional software
engineers to learn more about me and my
courses head over to code with mass comm
alright now let's get started
[Music]
all right now we were ready to download
and install Python the first thing I
want you to do is to open up your
browser and head over to python org on
this page under the downloads you can
see the latest version of python
currently the latest version is 3.7
chances are in the future when you're
watching this video there is a newer
version available don't worry all the
materials in this course will continue
to apply with the future versions of
Python so go ahead and download Python
then run it if you're on Windows we're
going to see this checkbox here add
Python to path this is very important
make sure to take it otherwise you're
not going to be able to follow the
course so now go ahead and install it
now let's verify that we have installed
Python properly if you're on Windows
here in this search bar type CMD which
is short for command prompt dr. in
command prompt type Python you can see
we have successfully installed Python
version 3.7 now to exit press ctrl-z
and then enter
if you're on Mac press command and space
this opens up the spotlight search so
here type terminal
terminal and Mac is like command prompt
on Windows now Mac and Linux by default
come with an older version of Python
that is version 2 so if you type Python
you can see Python 2 here let's start
what we want so press control D to exit
and then run Python 3 and this verifies
that we have successfully installed
Python 3.7
so this environment you see here is what
we call Python interpreter which is
basically a program that executes Python
code we can type our Python code in a
file and give it to this interpreter or
we can type our code directly here in
this interactive shell so here we can
write an expression like 2+2 in
programming an expression is a piece of
code that produces a value so here when
we add two plus two we get a value that
is why we refer to this piece of code as
an expression so enter we get four let's
try a different kind of expression let's
see if two is greater than one we get
true which is an example of a boolean
value you're gonna learn about these
boolean values in the next section now
what if we type 2 is greater than 5
enter we get false so in programming we
have true and false which are similar to
yes and no in English now what if we
type 2 is greater than but we don't add
a second value here just press Enter
we get a syntax error in programming
syntax means grammar so just like we
have the concept of grammar in the
languages that we speak we have the
exact same concept in programming if we
write a sentence that is not
grammatically correct chances are some
people may not understand that sentence
so in this example we have this
expression which is incomplete it
doesn't have the right grammar or syntax
that is why Python interpreter is
complaining by returning an error so
this interactive shell is a great way to
quickly experiment with a bit of Python
code but that's not how we build real
world applications to do that we need a
code editor and that's what I'm gonna
show you in the next lecture
[Music]
when it comes to typing Python code you
have two options you can use a code
editor or an IDE which is short for
integrated development environment an
IDE is basically a code editor with some
fancy features like auto completion
which means as you type code this
feature helps you complete your code so
you don't have to type every character
by hand
it's a productivity boosting feature it
also gives you additional features like
debugging which means finding and fixing
bugs in your programs testing and so on
for both code editors and IDs are so
many options out there the most popular
code editors are vs code atom and
sublime you can use the code editor that
you prefer in terms of the idea is again
there are so many options out there the
most popular one is pie chart in this
course I'm gonna use vs code or Visual
Studio code because that's my favorite
code editor later in the course I will
show you how to install a plugin or an
extension that will convert vs code to a
powerful ID so before going any further
head over to code that visual studio
comm and download the latest version of
vs code
now it vs code open on the top from the
file menu go to open
and somewhere on your desk create a new
folder let's call this folder hello
world and then open it beautiful now
click this icon on the top this opens up
the Explorer panel in this panel you can
see all the files and folders in your
project so let's add a new file and call
that app that PI so all our Python files
should have the PI extension press Enter
now let's close this and type a bit of
Python code in this lecture we're gonna
use one of the built-in functions in
Python called print so in Python we have
a lot of built-in functions for
performing various kinds of tasks for
example as a metaphor think of the
remote control of your TV on this remote
control you have a bunch of functions
like turn on turn off change the channel
change the volume and so on these are
the built-in functions and your TV we
have the same concept in Python and many
other programming languages so one of
these built-in functions that comes with
Python is print and we can use this to
print something on the screen now
whenever you want to use a function you
should open and close parenthesis in
programming we say we're calling the
print function calling a function means
executing it now let's display the hello
world message on the screen whenever you
want to work with text you should put
your text in between quotes either
double quotes or single quotes now I'm
gonna go with double quotes and add
hello world and then put a happy Persian
cat here
beautiful save the changes with command
and s on Mac or ctrl + S on Windows now
to execute this code we need to go back
to command prompt on Windows or terminal
on Mac but the good news is that we
don't have to switch programs here in vs
code we have an integrated terminal so
press ctrl + backtick that is the key
before number 1 on your keyboard that is
just below the escape button so this is
our integrated terminal now you front
windows type Python if you're on Mac or
Linux type Python 3 and next to that at
the name of our file that is up at PI
and here's our hello world message in
the terminal beautiful now let's take
this to the next level and make it a
little bit more interesting let's close
this terminal window by pressing ctrl
and backtick and add a second line of
code so one more time print this time
let's add quotes with a star in between
them now let's see if you want to repeat
this star ten times so here we can
multiply this by 10 save the changes
open up the terminal and run our program
and you can see this star is repeated 10
times so as you see the instructions on
our program are executed from top to
bottom in order in the next lecture I'm
going to show you how to convert this vs
code to a powerful IDE for building
Python applications
[Music]
in this lecture I'm gonna show you how
to convert vs code to a powerful IDE by
using an extension called Python with
this extension or plugin we get a number
of features such as linting which
basically means analyzing our code for
potential errors
you also get debugging which involves
finding and fixing errors we'll look at
this later in the course we also get
auto completion which basically helps us
write code faster so we don't have to
type every character we get code
formatting which is all about making our
code clean and readable just like how we
format our articles newspapers books to
make them clean and readable we get unit
testing which involves writing a bunch
of tests for our code we can run these
tests in an automated fashion to make
sure our code is behaving correctly and
finally we get code snippets which are
reusable code blocks that we can quickly
generate so we don't have to type them
all by hand now don't worry about
memorizing any of these as we go through
the course you're going to learn about
these features now here in vs code on
the left side click this icon this opens
the extensions tab so these are the
extensions that we can install in vs
code to bring in additional
functionality here under the recommend
the tab you can see the python extension
if you don't see this simply type Python
here on the top
and here's the extension to go ahead and
install this and then you'll have to
reload
yes code
now here on the bottom right corner you
can see this message linter pilant is
not in stock so as I told you before
linting is about finding potential
errors in our code linter is a program
or a tool that analyzes our code and
finds these potential problems now for
Python there are several interceptor
pilant is one of the most popular ones
that this Python extension uses by
default so we need to go ahead and
install pylons as well now to do this
first we need to change our Python
environment so if you look here on the
bottom left corner you can see the
current python that is used in vs code
that is python 2 point 6 point 9 on my
machine
chances are you see a different version
here so click here and in this list make
sure to select python 3 point 7 so this
changes our Python environment to Python
3 point 7 and then we can install pilant
by clicking this button ok pilant is
installed beautiful in the next lecture
I will show you how linting works
in this lecture I'm gonna show you
linting and action so let's start by
writing some invalid code like this
print space with no parentheses and then
hello work earlier I told you that print
is a built-in function and whenever you
want to use or call a function you
should always use parentheses now to be
more precise this is actually valid
Python 2 code but because we're using
Python 3 here this is invalid code from
Python 3 point of view so now when I
save the changes you can see this red
underline here let's hover our mouse
over this underline you can see this
tooltip it's coming from Pyland and
here's the error message missing
parentheses in call to print did you
mean print with parentheses so this is
the benefit of linting as you're writing
code you can see potential problems in
your code you don't have to wait to run
your program to see these errors so now
if we put parentheses here and save the
changes you can see that red underline
is gone let's look at another error
let's type two plus and then save the
changes
earlier we run this code in Python
interpreters interactive shell there
we got a syntax or grammar error so if
you hover your mouse here one more time
you can see pylons is telling us that
this is invalid syntax or invalid
grammar it's like an incomplete sentence
so this is linting in action now let me
show you a couple useful shortcuts here
on the top look at the View menu here we
have this problems menu look at the
shortcut on Mac is shift command and M
on windows is probably shift control M
so as you're working with vs code try to
memorize these shortcuts because they
really help you write code faster now
let's take a look at these problems
panel so this problems panel lists all
the issues in your code in one place so
if you have an application with multiple
files this is really useful because some
of those files may not currently be open
so this linter Pyland will analyze all
your files and if it finds any issues it
will list them here in the problems
panel now you can also put this on the
right side of your screen so let's put
it here so as you write code these
problems will appear here now let's fix
this issue so I'm gonna add three here
save the changes and you can see the
problem disappear and one last thing
before we finish this lecture once again
on the top let's go to the View menu the
first item is command palette this is a
very important feature in vs code once
again look at the shortcut that is shift
command and P on Mac or shift control P
on Windows
this command palette you can execute
various commands in vs Co if you type
lint here you can see all commands
related to linting as you can see all
these commands are prefixed with Python
because these commands come with a
Python extension that we installed
earlier so these are additional features
available to us in vs code the first
command here is select linter in this
list you can see various linters
available for pilot so as you're reading
tutorials or talking to other people you
will hear about linters such as flake
ate my pie pep 8 and so on different
developers prefer different linters I
personally prefer pilant that is the
most popular one and that's the default
linter set and the Python extension of
vs code if you're adventurous you can
try using other linters on your own the
difference between these linters is in
how they find and report errors some
error messages are more meaningful or
more friendly the others are more
ambiguous so that's all about linting in
the next lecture we'll talk about
formatting code
in Python community we have a bunch of
documents called Python enhancement
proposals or peps here on Google if you
search for Python peps you can see the
list of all these paps under python.org
slash dev slash paps let's have a quick
look here
so here are the paps you can see each
PAP has a number and a title the one
that is very popular amongst Python
developers is pep 8 which is a style
guide for Python code a style guide is
basically a document that defines a
bunch of rules for formatting and
styling our code if you follow these
conventions the code that you write will
end up being consistent with other
people's code now if you have time you
can go ahead and read this PAP 8
documentation but if not don't worry
because throughout this course I'm gonna
explain the key things in pep 8 in this
lecture I'm gonna show you a tool that
helps you automatically format your code
according to pap 8
so back in vs code let's write some
Python code x equals one here I'm
declaring a variable and setting it to
one if you're not familiar with
variables don't worry
in the next section you're gonna learn
about them so according to pep 8 this
code is considered ugly because by
convention we should add a space around
this equal sign or the assignment
operator now since you're starting out
with Python you probably don't know
these rules so let me show you a tool
that helps you automatically format your
code let's revert this back to its
original state now we need to go back to
the command palette remember so it's
right here under view and the shortcut
is shift command and P here if you
search for format you can see this
command format document the first time
you execute this command you're going to
see this message here formatter Auto
kept 8 is not installed so there are a
bunch of tools for formatting Python
code the most popular one is auto kept 8
and this is the tool that this Python
extension we installed uses to format
our code so let's go ahead and install
this good now one more time let's open
up the command palette and execute
format document see is tool
automatically formats our code beautiful
let's take a look at another example I'm
going to declare another variable Y and
set it to two and a variable with a long
name like unit underlined price I'm set
this to 3 now some developers have this
habit of formatting their variable
declarations like this so they put all
these equal signs in the same column
according to pepp 8 this is considered
ugly so once again let's format our code
that is better beautiful now let me show
you a trick opening up this command
palette and searching for format
document every time is a little bit
time-consuming so I want to show you how
to have your file automatically
formatted as soon as you save the
changes
on the top let's go to the code menu
preferences and settings here in the
search box search for format on save
so we have this option editor format
unsaved take this now back to app top I
I'm gonna change the formatting of these
lines make them really ugly now as soon
as I save the changes you can see my
code is reformatted beautiful
so you have learned that in order to run
this Python program we'll have to open
up the terminal window and run Python on
windows or Python 3 on Mac and an app
that pi this is a little bit tedious so
let me show you a shortcut once again
let's go to the extensions panel here
search for code runner
there are multiple code runners out
there the one that I'm talking about is
this one with the yellow icon so go
ahead and install this and then reload
yes code now instead of opening up the
terminal and manually typing Python
after pi all you have to do is to press
ctrl alt and in
you can see the output here beautiful
just be aware of that if you make any
changes you'll have to save the changes
before using this shortcut otherwise
you're going to see the old result now
there is a tiny problem here so you can
see this is the command that is executed
to run this Python program so by default
this command is using Python - U and
here is the name of our file if you're
on Windows
that's perfectly fine but if you're on
Mac you know that Python refers to
Python - here we want to change this to
Python 3 this is very easy once again on
the top under the code menu let's go to
preferences settings and then here
under this dot go to open settings that
JSON
now here in the search bar type code
- runner dot executors map so these are
the default settings used by this code
runner extension you can see this
extension support executing code in a
lot of languages like JavaScript Java
and so on now if you scroll down here we
can see Python and in front of that you
can see the command that is used to
execute Python code we need to change
this however we cannot change the
default settings we should change the
user settings so on the right side after
the last setting type a comma and then
in quotes type code - runner dot
executors map and then press enter this
will automatically copy all the settings
on the left side to the right side now
we can easily change one of this
so here's Python let's change the
command to Python 3 you only have to do
this if you're on Mac and by the way
sorry if I have mentioned Windows and
Mac a few times throughout this course
that's pretty much it we are not going
to differentiate between Windows and Mac
in the future so save the changes and
we're done
so I've got a few questions for you guys
I want to see if you have been really
paying attention to this video or not
you better have so here is the first
question for each question I want you to
pause the video think about the answer
for a few seconds when you're ready
continue watching so here's the first
question what is an expression an
expression is a piece of code that
produces a value here's an example of an
expression what do you think is the
value of this expression well here we
have this string we're multiplying this
by 3 so the result will be a string of
three asterisks like this here's another
question what is a syntax error a syntax
error is a kind of error that is due to
bad syntax or bad grammar in the code
and finally the last question what does
a linter do a linter is a tool that
checks our code or potential errors
mostly in the category of seen tactical
errors so if you have grand medical
issues in our code the linker will tell
us before running our program okay
that's it for now if you like more
quizzes and programming exercises look
at the link below this video and if you
enjoyed this video I hope you have
please support me by giving a thumbs up
please like this video and share it with
others in the next section we're going
to look at the fundamentals of Python
[Music]
you
[Music]
well hello Marsh here thank you for
watching my Python tutorial I wanted to
let you know that this tutorial is the
first two hours of my complete Python
course where you will learn how to use
Python in real-world scenarios such as
data analysis and visualization
automating repetitive boring tasks that
involve working with files and folders
spreadsheets PDFs data compression
sending emails web crawling consuming
API is like Yelp to get information
about businesses and much much more this
course comes with a 30 day no questions
asked money back guarantee and a
certificate of completion if you're
interested click the link below this
video to access the course
let's start this section by a discussion
of variables which are one of the core
concepts in programming we use variables
to store data in computer's memory here
are a few examples I'm gonna define a
variable called students under line
count and setting it to a thousand when
we run this program python interpreter
will allocate some memory and store this
number thousand in that memory space
then it will have this variable
reference that memory location so this
variable is just like a label for that
memory location we can use this variable
or this label anywhere in our program to
get access to that memory location and
the data is stored there so now if we
print students count and run our program
we will get the number of thousand so
this is the basic of variables now what
kind of data can be a store in
computer's memory well we have several
different kinds of data in this section
we're going to look at the built-in
primitive types in Python primitive
types can be numbers boolean and strings
let me show you so here we have a whole
number we refer to this as an integer in
programming we can also have numbers
with a decimal point let's take a look
so rating we set this to four point nine
nine this is what we call a float or a
floating-point number and this
terminology is not specific to Python in
the future when you learn a new
programming language you're going to
hear these terms again now let's take a
look at an example of a boolean is
published we set this to true or false
these are examples of boolean values in
programming so boolean values can either
be true or false and these are exactly
like yes and no in English later in the
course you will learn that will use
these boolean values to make decisions
in our programs
for example if the user is an admin user
perhaps we want to give them extra
permissions so these are the boolean
values now take into account that Python
is a case sensitive language which means
lower case and upper case characters
have different meanings
so boolean values should always start
with a capital letter like what you see
here if we type false or false these are
not accepted boolean values in Python
only what you see here is a valid
boolean value so false or true and
finally let's take a look at an example
of a string so course under line name we
set this to your string like Python
programming so string as I told you
before is like text whenever you want to
work with text in your programs you need
to surround your text with quotes so
these are the basics of variables
so these are the variables from the last
lecture now I've got a question for you
there are four things that have
consistently used in this program can
you spot them if you want you can pause
the video think about this for a few
seconds and then continue watching
so here are those four things the first
thing is that all my variable names are
descriptive and meaningful so students
count represents the number of students
for a course or course name clearly
explains that this variable holds the
name of a course one of the issues that
I see a lot amongst beginner programmers
is that they use mystical names for
their variables something like this CN
has ensured for course name when someone
else reads this code they have no idea
what CN stands for or they use variable
names like c1 when I look at that code I
wonder where is c2 and what is the
difference between c1 and c2 so these
variable names are very mystical that's
a bad practice make sure your variable
names are always descriptive and
meaningful because this makes your code
more maintainable now there are times
that you can use short variable names
like X Y Z if you're dealing with things
like coordinates so that's an exception
now the second thing that I have
consistently used in this code is that I
have used lowercase letters to name my
variables so here we don't have course
name all in capital or in title case all
letters are lowercase right let's delete
this the third thing that I've
consistently used here is that I have
used an underscore to separate multiple
words and I've done this to make my
variable names more readable because in
Python we cannot have a space in
variable names so we cannot have course
name and if you put these two words
together it's a little bit hard to read
that's why we use an underscore and the
fourth thing that I have used
consistently here is that I have put a
space around this equal sign again
that's one of the issues I see a lot
amongst beginners they write code like
this this is a little bit ugly this is
what we call dirty code dirty stinky
smelly
you should write code that is clean and
beautiful so other people can read it
like a story like a newspaper article
it should be formatted properly and
that's why we have pep 8 in Python now
the good thing is if you forget these
rules when you save the changes auto-pay
8 kicks in I didn't automatically
reformat your code but that aside you
should always give yourself the habit of
writing clean code without relying too
much on the tooling so these are all the
best practices about naming your
variables next we're going to look at
strings in more detail
so here we have this course variable set
to Python programming as I told you
before whenever you work with text you
should surround your text with quotes
you can either use double quotes or
single quotes that's more of a personal
preference but quite often we use double
quotes
you also have triple quotes and we use
them to format a long string for example
if you have let's say a variable message
that is the message we want to include
in the body of an email
you can use triple quotes to format it
like this hi John this is Marsh from
code with marsh comm blah blah blah so
that's when we use triple quotes now we
don't need this in this lecture so
delete let me show you a few useful
things you can do with strings first of
all we have this built-in function in
Python for getting the lengths of
strings what is a function a function is
basically a reusable piece of code that
carries out a task as a metaphor think
of the remote control of your TV on this
remote control you have buttons for
different functions like turn on turn
off change the channel and so on these
are the built-in functions in your TV in
Python and many other programming
languages we have the exact same concept
so we have functions that are built into
the language on the platform you can
reuse these functions to perform various
tasks so here we can use the built-in
Len function to get the length of a
string which means the number of
characters in that string now whenever
you want to use a function you should
use parentheses now we say we're calling
this function which basically means we
are using this function now some
functions take additional data which we
refer to as arguments these arguments
are inputs to these functions so this
Len function takes an input or an
argument here we pass our course
variable and this will return the number
of characters in this string so let's
print that and see what we get run the
program we get 18 because we have 18
characters here let's look at another
example if you want to get access to a
specific character in this string you
use the square bracket notation so here
we add course square brackets to get the
first character you use the index 0 so
in Python like many other languages
strings are 0 index which means the
index of the first cat
or the first element is zero so now when
we print this will get P okay now you
can also use a negative index like minus
one what does that mean
well if zero represents the first
character here what do you think
negative one represents that takes us
back to the end of this string so that
returns the first character from the end
of this string let's run this program
you will see it will get G there you go
using a similar syntax you can slice
strings let me show you so I'm gonna
duplicate this line and remove negative
one now let's say we want to extract the
first three characters in this string so
here we need two indexes the start index
colon the end index so this will return
a new string that contains the first
three characters in this course variable
that will be P Y and T so the index of
these characters are 0 1 and 2 so that
means the character at the end index is
not included ok let's run the program
and make sure we get the right result
there you go py T now what if we don't
include
the end index what do you think we're
gonna get
it's common sense we start from index 0
and go all the way to the end of this
string so this will return a new string
that is exactly the same as the original
string let's take a look so we get
Python programming now what if we don't
include the start index but include the
end index what do you think we're gonna
get once again it's common sense so by
default Python will put 0 here so it
will start from the beginning of this
string so when I run this program we
should get py t one more time there you
go and finally as the last example if we
don't include the start
and the end index this will return a
copy of the original string let's look
at this so we get Python programming now
you don't have to memorize any of these
just remember we use the Len function to
get the length of a string we use
bracket notation to get access to a
specific element or a specific character
and we use this notation to a slice a
string
so we have this string here Python
programming now let's say we want to put
a double quote in the middle of this
string there is a problem here
Python interpreter sees this second
string as the end of the string so the
rest of the code is meaningless and
invalid how do you solve this problem
well there are two ways one way is to
use single quotes for our string and
then we can use a double code in the
middle of this string
but what if for whatever reason perhaps
for being consistent in our code we
decided to use double quotes how can we
add another double code in the middle of
this string well we can prefix this with
a backslash backslash in Python strings
is a special character we have a jargon
for that called
escape character we use it to escape the
character after let me show you what I
mean so let's print this course and run
this program what's going on here we
don't have the backslash because we use
that to escape this double code and
basically displayed here so backslash is
an escape character and backslash double
quote is an escape sequence in Python
strings we have a few other escape
sequences that you should be aware of
let me show you so in Python we use high
sign to indicate a comment a comment is
like additional note that we add to our
program it's not executed by Python
interpreter okay so here are the escape
sequences you have seen backslash double
quote we also have backslash single
quote so we can use that to add a single
code here let's run the program here it
is beautiful we also have double
backslash so if you want to include a
backslash in your strings
you should prefix it with another
backslash let me show you so when we run
this
we get python one backslash programming
and finally we have backslash n which is
short for newline so now if I add a
backslash n here see what we get we get
a new line after Python so programming
will end up on the second line so these
are the escape sequences in Python
here we have two variables first and
last let's say we want to print my full
name on the console so we can define
another variable full set it to first
then concatenate it with a space and one
more time concatenate it with last now
when we print full we get my full name
on the console beautiful now this
approach are using concatenation to
build a string is okay but there is a
better and newer approach we can use
formatted strings so here we can set
full to this string and prefix it with
an F which can be lowercase or uppercase
this formatted string doesn't have a
constant value like these two strings
here it's actually an expression that
will be evaluated at runtime so here we
want to add our first name we use curly
braces to print the value of the first
variable after that we had in your space
and then we add curly braces one more
time to print the last name so at
runtime this expression will be
evaluated what we have in between curly
braces will be replaced at runtime now
let's run this program one more time we
get the exact same result just be aware
that you can put any valid expressions
in between curly braces so earlier you
learned about the built-in Len function
we can call Len here to get the length
of this string let's run this program
one more time so we get four
we can also replace last with an
expression like this 2+2 let's run this
program we get 4 & 4
so when using formatted strings you can
put any valid expressions in between
curly braces
in this lecture we're going to look at a
few useful functions available to work
with strings so earlier you learned
about this built-in Len function this
function is general-purpose so it's not
limited to strings
later I will show you how to use this
function with other kind of objects but
in Python we have quite a few functions
that are specific to strings
let me show you so here if we type
course dot C all these are functions
available on strings now in precise
terms we refer to these functions as
methods this is a term in
object-oriented programming that you
will learn about later in the course for
now what I want you to take away is that
everything in Python is an object and
objects have functions we call methods
that we can access using the dot
notation so here course is an object we
use the dot notation to access its
functions or more accurately methods
let's take a look at a few of these
methods we have upper to convert a
string to uppercase now let's print this
and run the program here is what we get
beautiful now note that the metals that
you call here return a new string so the
original string is not affected let me
show you
so print course run the program one more
time look this is our original string
right so course the upper returns a new
string a new value we can store it in a
variable like course underlined capital
like this now to keep this demo simple
and consistent I'm gonna revert this
back and use a print statement we also
have the lower method to convert a
string to lowercase we also have title
which will capitalize the first letter
of every word so if our string was like
this when we call the title method we
get Python
programming as you see here okay another
useful method is strip and we use it to
trim any white space at the beginning or
end of a string this is particularly
useful when we receive input from the
user let me show you so let's imagine
the user entered a couple of white
spaces at the beginning of their string
when we call course that strip those
white spaces will be removed
take a look so note that in the first
three examples we have those white
spaces but in the last one it is removed
so a strip removed the whitespace from
both the beginning and end of a string
we also have L strip which is short for
left strip and our strip which is short
for right strip so it will remove the
white space from the end of a string if
you want to get the index of a character
or a sequence of characters in your
string you should use the find method
and mosura
so course that find so as an argument
here we pass another string we can pass
a character or a series of characters
let's find the index of Pro run the
program so the index of Pro is 9 so if
you start from 0 here all the way to 9
this is the index of Pro ok now as I
told you before python is a case
sensitive language so if I pass a
capital P here obviously we don't have
these exact characters in our string so
let's see what we get we get negative 1
that means this string was not found in
the original string another useful
method is replaced so we call replace
with this we can replace a character or
a sequence of characters with something
else so let's say we want to replace all
lowercase Peas with J with this we get
jython Jeremy
whatever that means and finally if you
want to check for the
existence of a character or a sequence
of characters in your string you can use
the in operator let me show you so print
rewrite an expression like this pro in
chorus so this is an expression as I
told you before an expression is a piece
of code that produces a value so this
expression checks to see if you have Pro
in course the difference between this
expression and calling the find method
is that the find method returns the
index of these characters in our string
but as this expression returns a boolean
so it's a true or false let me show you
so run the program we get the boolean
true and finally we have the not
operator and we use that to see if our
string does not contain a character or
sequence of characters so let's change
this to swift not in course when this
expression is evaluated what do you
think we're gonna get well we don't have
Swift in this string so not in we'll
return true let's take a look there you
go
so these are the useful string methods
next we'll look at numbers
in Python we have three types of numbers
two of these you have already seen
before they are integers and floats we
also have complex numbers so complex
numbers in math are in the form a plus
bi where I is the imaginary number now
if you're not familiar with this concept
don't worry this is something that is
used a lot in mathematics and electrical
engineering if you want to use Python to
build web applications you're never
gonna use complex numbers but let me
quickly show you the syntax for
representing complex numbers instead of
i we use J so here is an example 1 plus
2 J so X now is a complex number and by
the way as I told you before this is
just a comment or an additional note in
our program when we run this program
anything after this hash sign will be
ignored so these are the three types of
numbers we have in Python for all these
types of numbers we have the standard
arithmetic operations that we have in
math let me show you so we have addition
subtraction multiplication division but
we actually have two different types of
divisions let me show you first let's
run this program so with this division
operator which is a slash we get a
floating-point number if you want an
integer you use double slashes let me
show you so double slash run the program
we get 3 ok we also have modulus which
is the remainder of a division and
finally exponent which is left to the
power of right so 10 to the power of 3
will be a thousand these are the
standard arithmetic operators now for
all these operators we have a special
operator called augmented assignment
operator let me show you so let's
imagine we have X set to 10
we want to increment X by let's say
three we can write an expression like
this x equals x plus three or we can use
an Augmented assignment operator that is
a little bit shorter so we write x plus
equal three these two statements are
exactly the same now here I'm using
addition as an example you can use any
of these operators here next I'm going
to show you some useful functions to
work with numbers
in this lecture we're going to look at a
few useful functions to work with
numbers so we have this built-in
function round for rounding a number so
if we pass 2.9 here and print the result
we'll get 3 we have another useful
built-in function called ABS which
returns the absolute value of a number
so if you pass negative 2.9 here we'll
get positive 2.9 technically we have
only a handful of built-in functions to
work with numbers if you want to write a
program that involves complex
mathematical calculations you need to
use the math module a module is like a
separate file with some Python code so
in Python we have this math module which
includes lots of mathematical functions
or working with numbers but we need to
import this module so we can use it on
the top we type import math now math in
this program is an object so we can use
the dot notation to see all the
functions or more accurately all the
methods available in this object as an
example we have math dot seal for
getting the sealing of a number so if
you pass 2.2 here and run this program
we get 3 now in this math module we have
lots of functions let me show you how to
find the conflict list here on Google
search for Python 3 make sure to add the
version number math module on this page
you can see all the functions in the
math module so in this lecture we looked
at math dot seal we also have math but
copy sign fabs and so on as an exercise
I encourage you to play with a couple of
functions in this module
alright now let's take a look at another
useful built-in function in Python we
use the input function to get input from
the user as an argument to pass a string
this will be a label that will be
displayed in the terminal you will see
that in a second so let's add X :
now this function returns a string so we
can store it in this variable now let's
imagine that Y should be X plus 1 save
the changes now don't run this program
using the code runner extension because
code Runner by default runs your program
in the output window which is read-only
so you won't be able to enter a value so
open up the terminal using ctrl +
backspace once again if you're on
Windows type Python if you're on Mac or
Linux type Python 3 and then app that PI
so here's our label let's enter a value
like fun we got an error type error what
is going on here well when we receive
input from the user this input always
comes as a string so this expression at
runtime will look like this string 1
plus 1 note that the number 1 is
different from string 1 because these
are two different types
now when Python sees this expression it
doesn't know what to do because two
objects can be concatenated if there are
of the same type so here we need to
convert this string 1 to a number in
Python we have a few built-in functions
for type conversion we have int for
converting a number to an integer we
have float
we have bull and stir or string now in
this case we don't need to convert eggs
to a string because X is already a
string if you don't believe me let me
show you so I'm gonna comment out these
few lines now let's print type of X so
type is another built-in function we
pass an object as an argument and it
returns its type also I'm gonna comment
out this line because that's the bad boy
we don't want to execute this save the
changes back in the terminal let's run
this program one more time enter 1 look
this is what the type function returns
don't worry about the class we'll talk
about classes later in the course so the
type of X is histor or string so let's
delete this line to fix this problem we
need to convert X to an integer and then
we can print both x and y using a
formatted string remember so we had an F
close now here we add a label like X
then we'll add a field so here we want
to print the value of X variable after
that we add some more text and finally
we want to print the value of y let's
run this program one more time so here
in the terminal let's enter 1 and here's
the result X is 1 and Y is 2 beautiful
now all these built-in functions are
self explanatory the only tricky one is
bull because in Python we have this
concept of truthy and falsy values these
are values that are not exactly a
boolean true or false but they can be
interpreted as a boolean true or false
so here are the false if values in
Python empty strings are considered
false e so they're interpreted as a
boolean false number zero is also false
e we have an object called nan which
represents the absence of a value we'll
look at this later in the course so
whenever we use
these values in a boolean context will
get false anything else will be true let
me show you a few examples so in this
interactive shell in Python let's
convert number 0 to bull that's false II
so we get false
what about pool of 1 we get true if you
pass a negative number will also get
true if we pass a number larger than 1
like 5 we still get true so we only get
false when we try to convert 0 to a
boolean now it strings I told you that
an empty string is false e so here we'll
get false anything else is true so even
if I have a string that is false
we'll get true because this is not an
empty string it's a string with a few
characters that's why it's evaluated as
true
all right once again it's time for
another quiz let's see if you have been
really paying attention to this tutorial
so here's the first question what are
the built in primitive types in Python
we have strings numbers and boolean
numbers can be integers floats or
complex numbers here's the second
question you have this variable fruit
set to Apple what do you think we will
see on the terminal when we print fruit
of one well using square brackets we can
access individual characters the index
of the first character is zero so this
expression returns the second character
which is P what if you add a colon and
negative one here
well using the syntax we can slice a
string re stored index is one and our
end index is negative one which refers
to the first character from the end of
the string
now when slicing a string the character
at the end index or negative one is not
included so with this expression we'll
get all the characters starting from the
second character which is P all the way
until we get to e so the result of this
expression is ppl here's another
question what is the result of this
expression
well this is what we call the modulus
operator and it returns the remainder of
a division which is in this case one and
finally the last question what do you
think we will see when we print wool of
FOSS well earlier I told you about
faulty values in Python so number zero
an empty string and the non object these
are all false if values
anything that is not false is considered
true see here we have a string that has
five characters it doesn't matter what
those characters are this is not an
empty string so it's not fall see it's
true see so when we convert it using the
bull function we'll get a boolean true
and this brings us to the end of this
section in the next section you're going
to learn the fundamentals of computer
programming I hope you have enjoyed this
section and thank you for watching
[Music]
we're gonna start this section by
exploring comparison operators we use
comparison operators to compare values
here are a few examples so 10 is greater
than 3 we get true so what we have here
is a boolean expression because when
this expression is evaluated we'll get a
boolean value that is true or false here
is another example 10 is greater than or
equal to 3 once again we get true we
also have less than so 10 is less than
20 we have less than or equal to here's
the Equality operator so 10 is equal to
10 what about this expression what do
you think we're gonna get we get false
because these values have different
types and they're stored differently in
the computer's memory and finally we
have the nut equal operator so now with
this expression we should get true
beautiful we can also use this
comparison operators with strings let me
show you so we can check to see if bag
is greater than Apple we get true
because when we sort these two words bag
comes after so it's considered greater
now what about this one bag equals
capital bag we get false
here is the reason every character you
see here has a numeric representation in
programming let me show you so we have
this built-in function called Ord don't
worry about memorizing this because
you're probably never gonna use this in
the future but let me show you the
numeric representation of the letter P
so that is 98
in contrast capital B is represented as
66 that is the reason these two strings
are not equal so these are the
comparison operators in Python next
we'll look at conditional statements
in almost every program there are times
you need to make decisions and that's
when you use an if statement here is an
example let's say we have a variable
called temperature we set it to 35 now
if temperature is greater than 30
perhaps we want to display a message to
the user so we use an if statement if
after if we add a condition which is
basically a boolean expression an
expression that produces a boolean value
so if temperature is greater than 30
here we have a boolean expression if
this expression evaluates to true the
following statements will be executed
let me show you now here is the
important part that a lot of beginners
miss when you use an if statement
you should always terminate your
statement with a colon now let's see
what happens when I press ENTER our
cursor is indented so here we have two
white spaces this is very important
because using these indentations Python
interpreter will know what statements
should be executed if this condition is
true here we want to print a message
like it's warm we can print another
message as well drink water so we can
have as many statements as we want here
as long as they are indented they belong
to this if block now when we finish here
we should remove indentation to indicate
the end of this if block so here we can
add a print statement with a message
like done this statement will always be
executed whether this condition is true
or not now note that when I save the
changes this indentation you see here is
going to be doubled up take a look
save there you go so when we save the
changes auto kept eight reformat our
code and uses four white spaces for
indentation so one two three four it
uses four white spaces because that's
what pepp eight recommends alright now
let's run this program so because
temperature
is greater than 30 we see the first two
messages and we see the dawn message
regardless so if I change the
temperature to let's say 15 and run the
program one more time look this dawn
message is executed whether our
condition is true or not so pay great
attention to these indentations that's
one of the issues I see in beginners
code let's say they want both these
print statements to be executed if the
condition is true accidentally they
remove the indentation on the fourth
line and that's why their program
doesn't work as they expect so be
careful about this now what if you want
to have multiple conditions we use an
elephant so L if that is short for LS if
here we can add another condition
another expression so temperature is
greater than 20 once again : enter a by
default here vs code is using two white
spaces so don't worry about this as soon
as you save the changes those two white
spaces will be converted to four white
spaces so let's print a different
message
it's nice save the changes now look all
these lines are indented consistently
you can have as many Elif statements as
you want and optionally you can also
have an else statement so if none of the
previous conditions are true then what
you have in the else block will be
executed once again we add the colon
annotation print here we can add a
message like it's called saying the
changes in this case temperature is 15
so none of these two conditions will be
true and we will see it's called let's
run the program there you go
in this lecture I'm going to show you a
technique for writing cleaner code so
let's say we're building an application
for University and we want to check to
see if the person who's applying for
this university program is eligible or
not so we start by defining a variable
called age set it to 22
now if H is greater than or equal to 18
colon print eligible remove the
indentation else colon print not
eligible let's run the program make sure
it works beautiful now there is nothing
wrong in this piece of code but I want
to show you a cleaner way to achieve the
same result instead of having a print
statement here we can define a variable
like message and set it to this string
that is the first step so message equals
this string and then we will print this
message now when you have an if-else
statement with this structure where
you're basically assigning a value to a
variable you can rewrite this in a
simpler way so this is how it works all
we want to do over these few lines is to
assign a value to this message variable
right so we start with message we set it
to eligible if age is greater than or
equal to 18 else we set it to not
eligible
this statement is almost like plain
English so what we have on line 7 is
exactly equivalent to these four lines
of code
delete save the changes run the program
you can see this person is eligible if I
change the age to 12 and run the program
we get not eligible
so what we have here is called ternary
operator
in Python we have three logical
operators and we use these operators to
model more complex conditions so these
operators are and or and not let's see a
real-world example of using these
operators so imagine we're building an
application for processing loans so we
need two variables high income we can
set this to true and good underline
credit we set it to true now here's the
condition we want to implement if the
applicant has high income and good
credit score then they are eligible for
the loan
so if high income and good credit we add
the colon and print eligible now note
that here I have not compared the value
of this variable with true that is one
of the issues I see in a lot of
beginners code this is redundant and
unprofessional because high income is a
boolean so it's either true or false we
don't need to compare true with true so
if this condition is true and this
second condition is true then we will
print eligible in the terminal so save
the changes and run the program
obviously this person is eligible
however if one of these conditions is
false we will not see eligible in the
terminal so let's add an else statement
here and print not eligible run the
program we see not eligible so this is
how the and operator works with and
operator if both conditions are true the
result will be true in contrast with the
or operator as long as at least one of
the conditions is true the result will
be true so if I replace and with or here
we should see eligible in the terminal
let's run it one more time there you go
so these are the and and or operators
now let's take a look at an example of
the nut operator so I'm going to define
another variable student set it to true
temporarily I'm gonna remove this
expression and simplify it we'll come
back to this later so let's say if the
person is eligible if they are not a
student
the nut operator basically inverses the
value of a boolean so in this case
student is true when we apply the not
operator the result will be false so in
this case our condition will be false
and that's why this print statement will
not be executed let me show you so save
run the program they are not eligible if
student was false when we apply the nut
operator will get true so our condition
will be true and we'll see it eligible
let's run it one more time
there you go with this operators we can
model even more complex conditions here
is an example a person can be eligible
if they have either high income or good
credit and they should not be used to do
that let me show you how to implement
this condition so if high income or good
credit we want at least one of these
conditions to be true so we put these in
parentheses we want to separate these
from the other condition which is not a
student now the result of this should be
true which means at least one of these
conditions should be true after that
we'll add and not student
and finally caught so with this
operators you can model all kinds of
real-world scenarios
so here's the example from the last
lecture a person is eligible for a loan
if they have high income and good credit
and they are not a student
now one thing you need to know about
these boolean operators is that they're
a short circuit what do we mean by that
well when Python interpreter wants to
evaluate this expression it starts from
the first argument if this is true it
continues the evaluation to see if the
second argument is also true so it
continues the evaluation all the way to
the end of this expression however as
soon as one of these arguments is false
the evaluation stops let me show you
what I mean so if I change high-income
to false when Python interpreter sees
this expression it starts here it knows
that high-income is false so it doesn't
matter what comes after the result of
this entire expression will always be
false because at least one of the
arguments or one of the operands is
false this is what we call
short-circuiting just like the
short-circuit concept we have in
electronics so the evaluation stops as
soon as one of these arguments evaluates
to false we have the same concept with
the or operator so if I change these and
operators to or let's see what happens
with the or operator we know that at
least one of the arguments should be
true so the evaluation stops as soon as
we find an argument that evaluates to
true in this case when Python
interpreter evaluates this expression it
sees that high-income is false so it
continues the evaluation hoping that the
next argument will be true here good
credit is true so evaluation stops and
the result of this entire expression
will be true so in Python logical
operators are short-circuit
in this lecture I'm gonna show you how
to chain comparison operators this is a
very powerful technique for writing
clean code here's an example let's say
we want to implement a rule that says
age should be between 18 and 65 here's
how we can implement it so we define a
variable like age set it to 22 now
if age is greater than or equal to 18
and age is less than 65 then we print
eligible now here's a question for you
how do we write this rule in mass we can
write it like this
well more accurately we shall have an
equal sign here so age should be between
18 and 65 this is how we write this rule
in math now I've got some good news for
you we can write the exact same
expression in Python so I'm going to
move this up put an if statement here
line 4 and line 3 are exactly equivalent
but as you can see line 4 is cleaner and
easier to read so let's get rid of line
3
this is what we call chaining comparison
operators
all right here is a little quiz for you
I want you to pause the video and think
about this quiz for 10 to 20 seconds
what do you think we'll see on the
terminal when we run this program so
pause the video figure out the answer
when you're ready come back continue
watching
all right let's see what happens when we
run this program first we get this if
statement in this case we're comparing
two different objects for equality and
these objects have different types we
have a number compared for this string
so number 10 and string 10 are not equal
that is why a will not be printed on the
terminal so the control moves to the
Elif part here we have two boolean
expressions here's the first one here is
a second one and they are combined using
the logical end so if both these
expressions are evaluated to true then
this entire expression will be true and
we will see beyond the terminal let's
see if both these expressions are
evaluated to true here's the first part
bag is greater than Apple that is true
because when we sort this words bag
comes after Apple but look at the second
part this expression is evaluated to
false because bag is not greater than
cat so when we applied the logical end
between true and false the result will
be false that is why this statement will
not be executed so the control moves to
the else part and when we run this
program the letter C will be printed on
the terminal
there are times that we may want to
repeat a task a number of times for
example let's say we send a message to a
user if that message cannot be delivered
perhaps we want to retry three times now
for simplicity let's imagine this print
statement is equivalent to sending a
message in a real-world program to send
a message to a user we have to write
five to ten lines of code
now if you want to retry three times we
don't want to repeat all that code that
is ugly that's when we use a loop we use
loops to create repetition so here is
how it works we start with four number
in we have a built-in function called
range now how many times we want to
repeat this task let's say three times
so we call range and pass three as an
argument now similar to our if
statements we need to terminate this
line with a colon enter we get
indentation so in this block we can
write all the statements that should be
repeated three times let's do a print a
message like attempt save the changes
run the program so we have attempt
printed three times beautiful now what
is this number let's take a look it's a
variable of type integer so let's pass
it as the second argument to the print
function number run the program this is
what we get zero one two so here we have
a for loop this for loop is executed
three times in each iteration number
will have a different value initially it
will be zero in the second iteration it
will be one and finally in the last
iteration it will be two now here we can
do something fun we can add one to this
run the program and now the message is
that the print are kind of more
meaningful or more user-friendly like
attempting number one attempting number
two and so on we can take this to the
next level so we can pass another
argument here I'm gonna add an
expression one more time number
plus one so we'll get one two three now
I want to put this expression in
parentheses so let's select this put it
in parentheses and then multiply it by a
dot so here we have a string that is
multiplied by a number the result will
be that string repeated that number of
times let's take a look around the
program see that's pretty cool isn't it
now let me show you one more thing
before we finish this lecture as you saw
this range function generates numbers
starting from zero all the way up to
this number here but it doesn't include
this number here we can pass another
argument say start from 1 and finish
before 4 with this change we don't need
to add 1 to number every time because in
the first iteration this number variable
will be set to 1 so we can simplify our
code and make it clean air let's run it
one more time we get the exact same
result we can also pass a third argument
as a step so I'm going to change the
second argument to 10 and pass two as a
step look at the result these are the
numbers we get 1 3 5 and so on so pretty
useful you're going to use this function
a lot in real-world applications
continuing with the example from the
last lecture let's imagine the scenario
where after the first attempt we can
successfully send the message in that
case you want to jump out of this loop
we don't want to repeat this task of
sending a message three times let me
show you how to implement this so in
this demo I'm gonna simulate the
scenario where we can successfully send
a message so we define a variable
successful and set it to true
now here after this print statement
we'll have an if statement if successful
:
then perhaps we can print successful now
here we want to jump out of this loop
for that we use the break statement
let's run this program and see what
happens
so there you go after the first attempt
we are successful and there are no more
attempts so once again I want you to pay
great attention to the indentation here
because that's one of the common issues
amongst beginners so here's our for loop
these two lines are indented with four
spaces and they belong to our for loop
in every iteration these two lines will
be executed now when we get to line four
if this condition is true then these two
lines will be executed because both
these lines are indented below this if
statement now let's take this program to
the next level what if we attempt three
times and we still cannot send an email
perhaps we want to display a different
message to the user we say hey we tried
three times but it didn't work so I'm
gonna change successful to false now at
the end here we can add an else
statement this is what we call a for
else statement what we put under this
else statement will only be executed if
this loop completes without an early
termination so if we never break out of
this loop then the else statement will
be executed so here we can print a
message like
attempt at three times and failed so run
the program
see what we get three attempts followed
by this message attempted three times
and failed in contrast if we change
successful to true because we terminate
this loop using this break statement
what we have in the else block will not
be executed take a look
run the program we have one attempt
successful done
in programming we have this concept
called nested loops so we can put one
loop inside of another loop and with
this we can get some interesting results
let me show you so I'm going to start
with this loop for X in range 5 : now
inside of this loop I'm gonna add
another loop so for Y in range 3 :
and then in our second loop I'm gonna
add a print statement here we can use
formatted strings to display coordinates
remember formatted string so we have F
followed by quotes now here we add
parentheses for our coordinate first we
want to display X and then comma
followed by Y let's run this program and
see what happens there you go pretty
cool isn't it so we get 0 + 0 0 1 0 & 2
then we get 1 & 0 1 & 1 1 & 2 and so on
now let me explain how exactly Python
interpreter executes this code so here
we have two loops this is what we call
the outer loop and this is the inner
loop so the execution of our program
starts here in the first iteration of
this loop X is 0 now we get to this
statement which is a child of this for
statement because it's indented four
times this statement itself is a loop so
what we have inside of this loop will be
executed three times in the first
iteration X is 0 because we're still in
the first iteration of the outer loop
and Y is also 0 because we're in the
first iteration of the inner loop that
is why we get 0 and 0 now we go to the
second iteration of this inner loop in
this iteration Y will be 1 whereas X is
still 0 that is why we get 0 and 1 and
similarly in the third iteration of our
inner loop we'll get 0 and 2 in the turn
now we're done with the execution of the
inner loop so the control moves back to
our outer loop here we'll be in the
second iteration so X will be one and
then we start here again so we have to
execute this inner loop three times in
the first iteration y will be 0 and X is
1 so here we have 1 and 0 then we'll get
one on one and one and two you got the
point so this is all about nested loops
so you have learned how to use four
loops to repeat one or more statements
in your programs now let's dive deeper
and see what this range function returns
so earlier you learn about the built in
type function with this function we can
get the type of an object so if I pass
five here and run this program this is
what we get so the type of this number
or this object is int or integer now
let's look at the type of the value that
we get from the range function so as an
argument we pass range of a number let's
run this program so this range function
returns an object of type range so in
Python we have primitive types like
numbers strings and boolean but we also
have complex types range is an example
one of those complex types throughout
this course you're going to learn about
a lot of other complex types now what is
interesting about this range object is
that it's iterable which means we can
iterate over it or use it in a for loop
that is why we can write code like this
so this range function returns a range
object which is interval which means we
can iterate over it in each iteration X
will have a different value now range
objects are not the only iterable
objects in Python strings are also
iterable so here we can add a string
like Python now in each iteration X will
hold one character in this string let me
show you so print
Peg's and I'm gonna delete these two
lines here let's run this program so in
each iteration we'll get one character
and print it we have another complex
type called list which we use to store a
list of objects so we add square
brackets this indicates a list
now we can add a list of numbers or a
list of strings like a list of names you
will learn about lists later in the
course so let's run this one more time
as we can see we can iterate over lists
in each iteration we'll get one object
in this list now later in the course I
will show you how to create your own
custom objects that are eatable for
example you will learn how to write code
like this for item in shopping cart
print item so shopping cart is going to
be custom object that you will create
it's not going to be an integer or a
string or boolean it's a custom object
it has a different structure and we'll
make it eatable so we can use it in a
for loop and in each iteration we can
get one item in the shopping cart and
print it on a terminal
so you have learned that we use for
loops to iterate over each ruble objects
in Python we have another kind of loop
that is a while loop and we use that to
repeat something as long as a condition
is true here's an example so let's
define a variable number and set it to a
hundred now we use while and here we add
a condition as long as number is greater
than zero we add a colon once again we
have indentation so we can repeat one or
more statements we can print this number
and then we can divide it by half so
number equals number use the integer
division to divide it by two or we can
use the augment and assignment operator
to shorten this code like this now let's
run this program so here is what we get
initially our number is a hundred we
divide it by half we get 50 then 25 and
so on so as you can see in this example
we are not iterating over an iterable
like a range object or a string or a
list we are evaluating a condition and
repeating a task let me show you a real
world example of a while loop in this
interactive shell Python is waiting for
an input we can type something like 2
plus 2 it will evaluate it and ask for
the next input we can add another
expression like 10 is greater than 2 so
these steps will continue until we press
control-d so behind the scene we have a
while loop that continuous execution
until we press control-d
that is the condition that causes the
while loop to terminate let me show you
how to build something like this in
Python so let's define a variable
and set it to an empty string now here
we need a while loop we want this while
loop to execute as long as command does
not equal to quit so command does not
equal to quit : in this loop we want to
continuously get input from the user so
we use the built-in input function we
add a label like this get the result and
store it in the command variable now at
this point python interactive shell will
evaluate this command we are not going
to do that in this lecture because
that's way too complex for simplicity we
can just echo back what the user entered
so print echo and as the second argument
we pass this command so this is our
while loop it will execute until we type
quit now as I told you before don't run
this program using the code runner
extension because by default it will run
your program in the output window which
is read-only so open up a terminal using
ctrl + back take and run Python or
Python 3 AB dot pi so here's our command
prompt let's type 2 + 2 it it goes back
let's type 3 times 2 there you go if we
type quit our program terminates now
let's try it one more time what if we
type quit an upper case the program
doesn't terminate because as you learned
before lower case and upper case
characters have different numeric
representations so quit in lower case is
different from quit in upper case now to
solve this problem
an amateur programmer may do something
like this and command does not equal to
capital quit so while command does not
equal quit in lower case and quit in
upper case continue getting input from
the user
let's run this program in terminal and
see what happens so one more time
Python after pie which I've quit
beautiful it
works we type quit an uppercase that
would work too but what if I type quit
with an uppercase Q and lowercase uit
our program doesn't terminate so this is
a poor way of checking for the quit
command what is a better way let me show
you so we don't need this and operator
here instead because command is a string
we can call the lower method so whatever
the user types in first we'll convert it
to lowercase and then compare it with
quit in lower case with this change it
doesn't matter how the user types the
word quit will always terminate the
program
now the last thing I want to discuss in
this section is the concept of infinite
loops an infinite loop is a loop that
runs forever so if I change this
condition to true because true is always
true this while loop will run forever so
to jump out of this we need a break
statement so after we get the input from
the user we can get the command convert
it to lowercase and see if it equals to
quit if that's the case we want to break
now with this change we no longer need
to initialize command to an empty string
previously we needed this because we had
a wild statement like this while command
does not equal quit so we had to define
this command variable and that's why we
have set it to an empty string without
this line when Python interpreter
tries to execute this code it doesn't
know what command is so now that we have
an infinite loop we no longer need to
define command and set it to an empty
string so in terms of functionality this
program is exactly the same as the
program we wrote in the last lecture
just be aware of these infinite loops
because they run forever you should
always have a way to jump out of them
otherwise your program will run forever
and this can sometimes cause issues
because if you're executing operations
that consume memory at some point your
program may run out of memory and crash
[Music]
alright time for an exercise I want you
to write a program to display the even
numbers between 1 to 10 so when you run
this program you should see 2 4 6 and 8
and after these I want you to print this
message we have 4 even numbers now here
is a quick hint before you get started
you should call the range function with
1 and 10 do not use this third argument
which is called step so basically I want
you to iterate over all the numbers we
can want to tab check if each number is
an even number and then print it on the
terminal so pause the video spend two
minutes on this exercise when you're
done come back continue watching
so it started with a four loop for a
number in range one to ten : we check to
see if the remainder of division of this
number by two equals zero
so if number modulus two equals zero
then we print this number
now let's run this program so we get two
four six eight beautiful now to count
the even numbers we need a separate
variable so let's call that count
initially we set it to zero now in this
if block every time we find an even
number we need to increment count so we
set count plus equals one and finally
after our for loop we can print a
formatted string we have count even
numbers let's run the program and here's
the result so that brings us to the end
of this section in the next section
you're going to learn how to create your
own functions I hope you enjoyed the
section and thank you for watching
[Music]
so far you have learned how to use some
of the built-in functions in Python such
as print round and so on in this section
you're gonna learn how to write your own
functions now you might ask but why do
you even need to write our own functions
well when you build a real program that
program is going to consist hundreds or
thousands of lines of code you shouldn't
write all that code in one file like we
have done so far you should break that
code into smaller more maintainable and
potentially more reusable chunks we
refer to these chunks as functions so
let me show you how to create your own
custom functions we start with the DEF
keyword which is short for define next
we need to give our function and name so
let's call this greet all the best
practices you'll learn about naming your
variables also apply to naming your
functions so make sure your function
names are meaningful descriptive use
lowercase letters to name your functions
and an underscore to separate multiple
words now after the name we need to add
parentheses you will see why shortly and
then we'll add a colon now what is going
to happen you know it you're gonna get
indentation which means the following
statements will belong to this function
so here I'm gonna add two statements hi
there and welcome aboard both designs
belong to this function because they're
indented now we're done with this
function we need to call it so we remove
the indentation and we add two line
breaks after this function this is what
Papp 8 recommends to keep our code clean
and maintainable now if you forget to
add two line breaks don't worry as soon
as you save the changes auto-pay of
eight will automatically add these line
breaks for you let me show you so I'm
gonna remove these line breaks and call
this function create with parentheses
just like how we call the built-in
functions now save the changes there you
go
so we
two line breaks after our function now
let's run this program so we get these
two messages on a terminal
now here's a question for you what is
the difference between the greed and
trent functions the difference is that
this print function takes an input
whereas our greet function doesn't take
any inputs so let me show you how to
pass inputs like first name and last
name to this function when defining a
function in between parentheses will
list our parameters so here we add two
parameters like first underline name and
last underline name now when calling
this function we need to supply two
values for those parameters we refer to
them as arguments so maash Madani these
are the arguments to the greet function
that's one of the terms that a lot of
developers out there don't know they
don't know the difference between
parameters and arguments a parameter is
the input that you define for your
function where as an argument is the
actual value for a given parameter okay
now let's change line two and instead of
saying hi there we can greet a person by
their full name so we can convert this
to a formatted string and pass two
fields here first name as well as last
name save the changes run the program
and this is what we get in terminal now
this function is more useful we can
reuse it and call it with different
arguments so let's create John Smith as
well run the program so we get hi
Muhammad on e and hi John Smith now note
that by default all the parameters that
you define for a function are required
so here our greet function takes two
parameters if I exclude one of these
arguments and save the changes you can
see we have this red underline so pilant
is complaining and saying there is no
value for argument last name also if we
run the program we get this type error
greet missing one required positional
argument
so let's put this back now later I will
show you how to define optional
parameters
so this is the simplified version of
this greet function we created earlier
now in programming we have two types of
functions functions that perform a task
and functions that calculate and return
a value here are some examples both the
print and greet functions are examples
of type 1 the performing a task which is
printing something on the terminal
in contrast the brown function is an
example of a function that calculates
and returns a value so the functions
that you create fall into these two
categories now let me show you how to
rewrite this greet function but in the
second form so instead of printing this
string on the terminal we simply return
it let me show you so I'm going to
delete all this code define a new
function but call it get underline
greeting we add the name parameter and
simply return this formatted string high
name that's all we have to do so we use
the return statement to return a value
from this function now we can call this
function get underlined greeting has a
name like Maj because it returns a value
we can store that value in a separate
variable like message now you might be
curious which form of these greeting
functions is better well with this first
implementation we are locked to printing
something in the terminal in the future
if you want to write that message in a
file or send it in an email you have to
create another function so we cannot
reuse this greet function in other
scenarios in contrast this second form
is not tied to printing something on the
terminal it simply returns a value now
we get this value and we can do whatever
we want with it we can print it on the
terminal or we can use the built-in open
function to write this message to a file
so we can create a
like content txt openings for writing
this returns a file object and then we
can call file the right message now
don't worry about these two lines later
in the course I'm gonna talk about
working with files but what I want you
to take away here is that we have this
message variable and we can do whatever
we want with it we can print it on the
terminal write it to a file send it in
an email and so on
and one more thing before we finish this
lecture so here's our greet function and
as you can see we're simply printing a
string now if we call greet give it a
name run the program we get this message
hi Maj but what if we put this inside of
a call to the print function let's see
what we get we get high Marsh followed
by not what is this none is the return
value of the greet function so in Python
all functions by default return the non
value non is an object that represents
the absence of a value later in the
course you're gonna learn more about not
what matters now is that all functions
return non by default unless you
specifically return a value so here if
we return some string
none will no longer be returned now I
just want to clarify something earlier I
told you that we have two types of
functions in programming functions that
carry out the tasks or functions that
calculate and return a value so back to
the code we previously had so even
though this function returns none by
default it is still classified as a
function that carries out a task
let's create another function we call it
increment you want to use this function
to increment a number by a given value
so here we simply return number plus by
now we can call this function like this
increment two and one this returns a
value so we can store it in a variable
like result and then print it on the
terminal let's run the program we get
three beautiful now we can simplify this
code we have used this result variable
only in a single place that is line six
so we don't really need it so on line
six we can replace result with a call to
increment function like this so when
python interpreter executes this code
first it will call the increment
function it will get the result and
temporary store it in a variable for us
we don't see that variable and then it
will pass that variable as an argument
to the print function now if we run this
program we get the exact same result
beautiful now we can make this code more
readable if someone else looks at line
five they may not know exactly what
these arguments are for we can use a
keyword argument to make this code more
readable so this one here is the value
of this by parameter we can prefix it
with the name of the parameter like this
now we can read this code almost like
playing English increment two by one so
if you're calling a function with
multiple arguments and it's not quite
clear what is arguments are for you can
make your code more readable by using
keyword arguments so here y equals one
is a keyword argument
earlier I told you that all the
parameters that you define for a
function are required by default in this
lecture I'm gonna show you how to make
the by parameter optional so let's say
we don't want to explicitly pass y
equals 1 every time we want to call this
increment function we want to use this
function to increment a value by 1 so we
remove the second argument now we need
to give this parameter a default value
so we set it to 1 now if we call this
function and don't supply the second
argument this default value will be used
otherwise the value that we specify here
will be used let me show you so we've
run this program the result is 3 but if
we pass the second argument here we'll
increment 2 by 5 so we'll get 7 so you
can see it's pretty easy to make a
parameter optional just be aware that
all these optional parameters should
come after the required parameters in
other words I cannot add another
required parameter here let's call that
another I cannot add that here if I save
the changes you can see we get a red
underline here so all the optional
parameters should come after the
required parameters now obviously in
this case we don't need the second
parameter so let's delete it
there are times that you may want to
create a function that takes a variable
number of arguments here is an example
let's define this function multiplied
that takes two parameters x and y and
simply returns x times y now we can call
this function like this
so far so good but what if you want to
pass one or two more arguments here that
doesn't work because our multiply
function takes only two parameters to
solve this problem we need to replace
these two parameters with a single
parameter we use a plural name here to
indicate that this is a collection of
arguments and then we prefix it with an
asterisk this is the magical part let me
show you what happens when you use an
asterisk here so temporarily let's
delete this line and simply print
numbers let's see what we get here so
run the program you can see all our
arguments and they're packed in
parentheses what is this well earlier
you learned about lists I briefly
mentioned that you can use square
brackets to create a list of objects
like 2 3 4 5 now later in the course we
have a comprehensive section about lists
so don't worry about the details of
lists and how they work but what I want
you to note here is that the only
difference between this list and what we
have here is in the notation so use
square brackets to create lists and
parentheses to create tuples some people
call it two poles or two poles so a top
pole is similar to a list in that it's a
collection of objects the difference is
that we cannot modify this collection we
cannot add a new object to this topple
once again later in the course we're
going to have a comprehensive section
about lists tuples and other data
structures what matters now is that
these topples
just like lists are iterable so we can
each raid over them which means we can
use them in loops let me show you so
that's right
for number in numbers : let's just print
one number at a time actually we don't
need this line so delete and run the
program so we iterate over this topple
and in each iteration we get one number
and print it on the terminal so now with
a simple change we can calculate the
product of all these numbers
all we have to do is to define a
variable like total initially we set it
to one and then in each iteration we get
total and multiplied by the current
number or we can rewrite this statement
using an Augmented assignment operator
so total times equal number line five
and four are exactly identical so I'm
gonna use line five because it's shorter
and cleaner delete and finally we'll
return the total now one of the issues I
see often in beginners code is that they
don't use this indentation properly so
they put the return statement here and
then they wonder why their function
doesn't work properly if you put the
return statement here it will be part of
the for loop so it will be executed in
each iteration in this case after the
first iteration because of this return
statement we'll return from this
multiply function so the total will not
be calculated properly we need to put
this at the same level of indentation as
other statements in this function so
here we have our for statement we loop
over all the numbers we calculate the
total and then finally return it so with
this implementation we can get the
result and printed on the terminal let's
run the program and you can see the
product of these numbers is 120
so in the last lecture you learned the
syntax to pass a variable number of
arguments to a function we have a
variation of this syntax with double
asterisk and that's what I'm gonna show
you in this lecture so for this demo
let's rename this function to save
underline user and rename the argument
to user so let's imagine we're gonna use
this function to save information about
a user now in this function let's just
print this user argument we're done with
our function let's call it save
underline user now instead of passing
arbitrary arguments here we can pass
arbitrary keyword arguments remember
keyword arguments so we have name equals
value so here we can add multiple
keyword arguments like ID equals 1 name
equals John age equals 22 and so on so
we are passing 3 keyword arguments to
this function now let's run this program
this is what we get look at the syntax
we have these curly braces and in
between them we have multiple key value
pairs so key colon value comma
here's another key value pair and here
is the last one this object you see here
is called a dictionary
it's another complex type or a data
structure in Python and I'm going to
talk about that in detail later in the
course for now all I want you to take
away is that when we use double asterisk
here we can pass multiple key value
pairs or multiple keyword arguments to a
function and Python will automatically
package them into a dictionary so this
user object here is a dictionary now
using the bracket notation we can get
the value of various keys in this
dictionary so we can print user square
brackets we pass a string and this is
the name of our key like ID let's run
the program we get 1 or we can access
the value of name key run
program so name is John so this is how
deeksha Mary's work
in programming we have a very important
concept called scope which refers to the
region of the code where a variable is
defined so in this example we have this
message variable the scope of this
variable is the greet function it only
exists inside of this function so if we
go outside of this function and try to
print message see what happens as soon
as I save the change as we get this red
underlined undefined variable message
and if we run our program we get this
name error named message is not defined
the same rule applies to the parameters
of our functions so if we add a name
parameter here and then try to print it
outside of the greet function we get the
same error so the scope of the name and
message variables are the greet function
and we refer to these variables as local
variables in this function they're local
in this function which means they don't
exist anywhere else and that means we
can have another function let's say send
email with a parameter with the same
name here we can have a message variable
but this message variable is completely
different from the message variable we
have in the greet function and of course
the same rule applies to the named
parameters in these functions they're
completely separate these local
variables have a short lifetime
so when we call let's say the greet
function and pass a name Python
interpreter
will allocate some memory and have the
name and message variables reference
those memory locations when we finish
executing the greet function because
these variables are not referenced or
used anywhere else eventually they get
garbage collector which means Python
interpreter will release the memory that
allocated for these variables so these
are the local variables in contrast to
local variables we have global variables
so if we move this message variable
outside of the
great function now it's a global
variable which means it's accessible
anywhere in this file so the scope of
this variable is this file we can use it
anywhere in this file in any functions
or outside of a function now for this
reason global variables stay in memory
for a longer period of time until they
are garbage collected and you should not
use them that often
in fact global variables are really evil
so as a best practice create functions
with parameters and local variables
now what if here in the greet function
we set message to let's say B now let's
delete this second function we don't
really need it for now so we call the
greet function in this function we
assign a new value to the message
variable now let's print this message
and see what we get what do you think
we're gonna get well let's take a look
we get a but didn't we change the value
of message variable to be not really
because by default python interpreter
treats this message variable as a local
variable in the greet function even
though it has the same name as the
global variable that we have on line one
so these two variables are separate now
I've seen some tutorials or even books
teaching you bad practices for example
they show you how to modify the value of
this global message variable inside of a
function let me show you how to do that
but remember this is a bad practice and
you should avoid it at all times I will
explain the reason in a second so these
tutorials or books teach you to use the
global keyword here and reference the
message variable when python interpreter
sees this line it will realize that in
this function we want to use the global
message variable so it will not define a
local variable in this function now with
this change if we run our program you
can see we get beyond the terminal
because in this function we are
modifying the value of the global
message variable why is this bad because
it is possible that you might have
multiple functions that rely on the
of this global variable if you're
accidentally or deliberately change the
value of this global variable in one
function this might have a side effect
in other functions those functions may
not behave properly and this way we can
create a bug in our program so global
variables have always been bad this is
not a Python thing this is a discussion
that's been going on for decades avoid
them as much as you can or if there are
situations that you really need to
define a variable globally in a file
that's okay but do not modify it in a
function as you see here this is a
really bad practice so that's all about
local and global variables
in this lecture I'm going to show you
how to find and fix bugs in your
programs so here's the multiply function
we wrote earlier let's add a couple of
statements after this function so print
start and then we'll call the multiply
function give it three arguments one two
and three so the result should be six
and here we print the result
on the terminal now to create a bug in
this program I'm going to deliberately
indent this return statement so now when
we run this program instead of six we
get one so we're gonna use a technique
called debugging to find and fix this
bug alright first we need to open the
debugging panel
the first time you want to use debugging
in a Python project you need to click
this icon this would generate a new file
called launch the JSON in this file we
have a bunch of debugging configuration
you never have to touch any of this so
don't worry about it close it you can
see this file is placed inside of this
vs code folder it's right here
launched a JSON now when we have this
file we can go to the debugging panel
and from this list we can select a debug
in configuration some of these
configurations are useful for more
complex applications for example we use
Python Django to debug a web application
built with Python for this course we're
going to use Python current file with
integrated terminal so select this now
to start debugging first we need to add
a breakpoint on one of these statements
so I'm going to put the cursor on line 8
and insert a breakpoint by pressing f9
so this is a breakpoint we can press f9
one more time to remove it if you're on
a Mac keyboard you should press the
function key which is on the bottom left
corner of your keyboard and then press
f9 so here we have a breakpoint now we
can press f5 to run the application up
to this point so f5 so this
automatically opens the integrated
terminal here don't worry about this I'm
going to close it
so you can see our program is running up
to this point this line is highlighted
now we can execute this program line by
line and see exactly what happens at
runtime so to execute one statement at a
time press f10 okay we are done now we
are on line 9
however on line 9 you are calling the
multiply function if we press f10 again
the execution stops so we couldn't
figure out why we got one as the result
of multiplying these numbers so let's
start debugging one more time we press
f5 so once again we are on line 8 let's
step over this line with f10 now this
time we want to step into this multiply
function so we see exactly what is going
on here so instead of f10 press f11 now
we are on line 2 so if you're calling a
function that you have to find you can
step into that function using f11 now
here we are in the multiply function on
the left side inside the variables panel
you can see all the variables that are
meaningful in this function so hungry
locals we have numbers so this is our
numbers argument you can see this is set
to a topple with 3 numbers 1 2 3 right
now our total variable is not in this
list because it's not defined yet the
moment we step over this line with f10
total comes to existence and you can see
initially is set to 1 now we are at the
beginning of our for loop let's press
f10 one more time
here we are we're going to multiply
total by number so let's step over this
line as well now at this point we have a
new variable called number that is our
loop variable initially it's set to 1
now here we are on line 5
if you press f10 we can see we jump out
of this function so our loop did not
execute to completion and that is the
reason our program has a bug so to fix
this I'm gonna stop the debugger with
Shift + f5 now back here let's remove
the indentation save the changes run the
program in debug mode one more time so
we press f5
here we are let's step over this with
f10 now step into this with f11 and step
over these lines with f10 a few more
times so f10 one more time total it's
set now we are in the second iteration
let's press f10 one more time in this
iteration you can see number is set to
two our total is still one so let's step
over this line as well now total is
updated to two here we are at the
beginning of the third iteration let's
step over this line in this iteration
number is three so after we execute this
line because total is currently two when
we multiply it by three we'll get 6 so
f10 one more time now we only have three
iterations in this loop so if you press
f10 one more time our loop completes now
we are ready to return total which is
currently six so f10 we are on line nine
and we're done now one more tip in this
demo I put the breakpoint on the first
line of the program you don't always
have to do this for example here we know
that our multiply function has a bug so
instead of putting the breakpoint on
line eight we could put it on line two
so when we start the program in debug
mode with f5 we immediately start in the
multiply function and one more tip
before we finish this lecture if you
step into a function and you know that
that function works properly we can
immediately step out of that function
with Shift + f11 so you don't have to
execute the entire function line by line
you can press shift and f11 to step out
of that function
alright let's finish up this section by
looking at a few very useful shortcuts
for writing code fast first I'm going to
show you the shortcuts for Windows users
and in the next lecture we will look at
the shortcuts for Mac so if you're a Mac
user feel free to skip this lecture so
here we are on line 9 and my cursor is
right at the beginning of the line let's
say you want to move the cursor to the
end of the line instead of pressing the
right arrow to go all the way to the end
we can simply press the end key and here
is the cursor or if you want to move the
cursor to the beginning of the line
simply press the HOME key there you go
similarly if you want to move the cursor
to the beginning of the file press ctrl
+ home here it is or ctrl + end/2 go to
the end of the file now let's say we
want to move this line up instead of
cutting it from here and then copying it
somewhere else we can simply move it up
by pressing Alt + the up or down arrows
or if you want to move these two lines
up and down simply select them then hold
alt and then up or down very easy now if
you want to duplicate a line or multiple
lines simply select them now hold down
shift alt and then press the down key we
can duplicate it as many times as you
want there you go here's another useful
shortcut if you want to convert this
line or maybe these two lines into a
comment simply hold down control and
press slash using the same shortcut you
can remove the comment so you can toggle
it very easy and finally if you want to
type the name of a variable or a
function like multiplied you don't have
to type all characters here are a few
ways to type this quickly we can just
type the first few characters and here
in the intellisense you can see that so
if you press ENTER this is what we call
auto-completion here's another way so
instead of writing the first few letters
you can just pick any letters in
sequence and type them so I can type mty
or I can just type mpy
or
why there you go here it is so I hope
you enjoyed these shortcuts and thank
you for watching
alright now let's take a look at the
shortcuts for a Mac keyboard so here we
are on line 9 and my cursor is right at
the beginning of the line if you want to
move the cursor to the end of the line
instead of using the right arrow to go
all the way simply hold down the
function key and press right here it is
or you can press function and left to
jump to the beginning of the line
similarly you can press function and up
to go to the top of the file or function
and down to jump to the end of the file
pretty useful now let's say you want to
move this line up instead of cutting it
from here and then copying it somewhere
else you can simply move it up by
holding down alt or option and then
pressing the up arrow or down very easy
or we can select these two lines hold
down the alt or option key move it up or
down here's another useful shortcut we
can convert these two lines into a
comment by pressing command and slash
and then we can remove the comment using
the same shortcut so we can toggle it
and finally if you want to type the name
of a variable or a function like
multiply you don't have to type all the
letters like multiply that is very slow
you can type the first few letters like
mult and here in the intellisense you
can see it's selected so press Enter or
you can pick any characters in sequence
and type them like mty here it is or we
can type an py or m TP so you can
abbreviate it any way you want I hope
you enjoyed these shortcuts and thank
you for watching
one of the questions that often comes in
programming interviews is the fizzbuzz
algorithm you might be surprised that
there are a lot of developers out there
with even years of experience but they
don't know how to solve this simple
programming problem that's why I decided
to include this in my course so let's
see how this algorithm works and then
you can spend 10 to 15 minutes on this
exercise on your own so here we have a
function fizz buzz that takes an input
and depending on the input we give it it
returns different results here are the
rules if the input that we give it is
divisible by 3 it will return the string
fizz
let me show you so we run this program
we get fizz
if the input is divisible by 5 it will
return buzz take a look here's buzz now
the third rule if the input is divisible
by both 3 & 5 it will return fizzbuzz so
let's pass 15 here we'll get fizzbuzz
for any other numbers it will return the
same input so if I pass 7 it's not
divisible by 3 or 5 it will return 7
itself so spend 10 to 15 minutes on this
exercise you will see my solution next
all right let's see how we can solve
this problem so we get the input and
check to see if input is divisible by 3
then we can set a variable like result
to phase
now let me temporarily simplify these
rules because I want to show you a
really cool technique so let's imagine
if the input is divisible by 3
we'll return fizz otherwise we'll return
bus so LS : we set the result to buzz
and finally we'll return this resolved
variable
this is one way to implement these rules
but it's not the best way there is a
better and cleaner way let me show you
so instead of defining this result
variable and then returning it we can
simply return this string here and also
here and then we can get rid of line six
so we remove one unnecessary line of
code this was one technique the other
technique I want to show you is when you
have an if statement and in your if
flock
you're returning a value you don't
really need an else clause because if
this condition is evaluated to false the
control moves to the else clause and all
we're doing here is returning a
different value so this is the only
possible outcome so here we can remove
this else clause and simply return bus
so with this technique I remove an
unnecessary indentation as well I've
made our code more linear okay now let's
go back to our original algorithm so if
the input is divisible by three we'll
return fizz now we check to see if the
input is divisible by five we'll return
buzz so here we don't really need an
Elif because if this condition is false
we'll get here anyway so we can check if
input is divisible by five we will
return buzz once again if this condition
is false the control moves here now we
check the same if the input is divisible
by three and it is also divisible by
five then we will return fizz buzz now
this expression is a little bit long I
would prefer to make it more readable by
putting parentheses around the first and
second parts like this that is cleaner
now if this condition is also false the
control moves here that means our number
is not divisible by three or five so we
should simply return the
input once again we don't need an else
or another if we simply return the input
now let's run this program and see if
it's working properly or not so we call
our function with three and we get fizz
beautiful let's call it with five we get
Buzz perfect what if we call it with 15
we should get fizz bus however we get
fizz
what is going on here the reason this
happened was because when we pass 15
here line two is executed obviously 15
is divisible by three so that is why we
immediately return fizz to solve this
problem we need to move this condition
which is more specific to the top so
I've selected these two lines using alt
+ up I move these lines up beautiful all
right now let's run the program one more
time
so we get fizzbuzz once again let's test
it with three now we get fares let's
test it with five when writing functions
don't assume that your function is
working make sure to test it with all
different kinds of values let's test it
but 5 we get Buzz beautiful what if you
pass 7 which is not divisible by 3 or 5
we get 7 beautiful so what you see here
is the simplest and most elegant
implementation of the fizzbuzz algorithm
and that brings us to the end of this
section in the next lecture we're going
to explore data structures in Python
you're going to learn about lists tuples
sets and dictionaries I hope you enjoyed
this section and thank you for watching
[Music]
you
[Music]
you made it this far and that makes me
think that you're really enthusiastic
about learning Python so I highly
encourage you to enroll in my complete
Python course where we go way beyond
this crash course you will learn how to
use Python in real-world scenarios such
as data analysis and visualization
automating repetitive boring tasks that
involve working with files and folders
spreadsheets PDFs data compression
sending emails web crawling consuming
api's and much much more this course
comes with a 30 day no questions asked
money back guarantee and a certificate
of completion if you're interested click
the link below this video to access the
course once again thank you for watching
please support me by liking and sharing
this video and also subscribe to my
channel to get free new videos every
week thank you and have a great day
[Music]